diff --git a/.changeset/await-current-shared-settle.md b/.changeset/await-current-shared-settle.md new file mode 100644 index 0000000000..724e04a24a --- /dev/null +++ b/.changeset/await-current-shared-settle.md @@ -0,0 +1,5 @@ +--- +'@tanstack/router-core': patch +--- + +Make each load transaction's completion follow its current successor so a burst of back-to-back loads wakes each superseded waiter once instead of once per successor. Previously every superseded `load()` re-polled the current transaction on each later completion, which was quadratic in microtask work. diff --git a/.changeset/calm-errors-listen.md b/.changeset/calm-errors-listen.md new file mode 100644 index 0000000000..029f880dc2 --- /dev/null +++ b/.changeset/calm-errors-listen.md @@ -0,0 +1,10 @@ +--- +'@tanstack/react-router': patch +'@tanstack/router-core': patch +'@tanstack/solid-router': patch +'@tanstack/vue-router': patch +--- + +Preserve falsy thrown values in React and Vue error boundaries. Type React and Vue boundary error components and `onCatch` callbacks as `unknown`. Solid boundary errors remain typed as `Error`; SSR now wraps non-`Error` loader errors to match Solid’s native boundary behavior, preserving the original value in `cause`. Router state and loader `onError` values are unchanged. + +When upgrading React or Vue, narrow boundary errors (for example, with `error instanceof Error`) before reading `message` or `stack`. `ErrorComponentProps` remains available for values narrowed to a specific error type. Route `onError` types are unchanged. diff --git a/.changeset/every-vans-stand.md b/.changeset/every-vans-stand.md new file mode 100644 index 0000000000..b2771abc9b --- /dev/null +++ b/.changeset/every-vans-stand.md @@ -0,0 +1,5 @@ +--- +'@tanstack/router-core': patch +--- + +Avoid quadratic resource handoff scans when navigating with many cached route matches. diff --git a/.changeset/fuzzy-boundaries-remain.md b/.changeset/fuzzy-boundaries-remain.md new file mode 100644 index 0000000000..d8b005f54d --- /dev/null +++ b/.changeset/fuzzy-boundaries-remain.md @@ -0,0 +1,8 @@ +--- +'@tanstack/react-router': patch +'@tanstack/solid-router': patch +'@tanstack/router-core': patch +'@tanstack/vue-router': patch +--- + +Retain successful not-found matches as terminal shared boundaries during client navigation, preserving route context while the destination loads. diff --git a/.changeset/lazy-rspack-guards.md b/.changeset/lazy-rspack-guards.md new file mode 100644 index 0000000000..a1269b9a91 --- /dev/null +++ b/.changeset/lazy-rspack-guards.md @@ -0,0 +1,5 @@ +--- +'@tanstack/start-plugin-core': patch +--- + +Improve Rsbuild import protection performance by scanning the compilation graph once and deferring diagnostic work until a violation is found. diff --git a/.changeset/major-clowns-marry.md b/.changeset/major-clowns-marry.md new file mode 100644 index 0000000000..931b606b43 --- /dev/null +++ b/.changeset/major-clowns-marry.md @@ -0,0 +1,5 @@ +--- +'@tanstack/router-core': patch +--- + +Avoid unnecessary JSON.parse calls for search parameter values that cannot begin valid JSON, while preserving custom parser behavior. diff --git a/.changeset/pink-candies-attack.md b/.changeset/pink-candies-attack.md new file mode 100644 index 0000000000..401860fccc --- /dev/null +++ b/.changeset/pink-candies-attack.md @@ -0,0 +1,10 @@ +--- +'@tanstack/router-core': patch +'@tanstack/react-router': patch +'@tanstack/solid-router': patch +'@tanstack/vue-router': patch +'@tanstack/start-plugin-core': patch +'@tanstack/nitro-v2-vite-plugin': patch +--- + +Use URL.canParse for absolute URL checks in links, navigation, redirects, and build configuration. Preserve a URL constructor fallback for older browsers. diff --git a/.changeset/route-scoped-use-match-should-throw.md b/.changeset/route-scoped-use-match-should-throw.md new file mode 100644 index 0000000000..f45cf7e0db --- /dev/null +++ b/.changeset/route-scoped-use-match-should-throw.md @@ -0,0 +1,7 @@ +--- +'@tanstack/react-router': patch +'@tanstack/solid-router': patch +'@tanstack/vue-router': patch +--- + +Fix route-scoped `useMatch`, `useSearch`, and `useParams` APIs to forward the `shouldThrow` option and preserve optional return types when `shouldThrow: false`. diff --git a/.changeset/rsbuild-manifest-module-chunks-once.md b/.changeset/rsbuild-manifest-module-chunks-once.md deleted file mode 100644 index 02febd9d84..0000000000 --- a/.changeset/rsbuild-manifest-module-chunks-once.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@tanstack/start-plugin-core': patch ---- - -Rsbuild: the Start manifest pass that runs after every client compilation (builds and each dev update) reads an imported module's chunks once per compilation and counts the module once per importing chunk, instead of once per import connection. The manifest is unchanged; the pass takes about 40 % less time (on a 333-route app, tens of milliseconds less per HMR update). diff --git a/.changeset/rsbuild-manifest-own-chunks.md b/.changeset/rsbuild-manifest-own-chunks.md deleted file mode 100644 index 04e8e29928..0000000000 --- a/.changeset/rsbuild-manifest-own-chunks.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@tanstack/start-plugin-core': patch ---- - -Rsbuild: a route's client manifest entry lists only its own chunks and CSS. When two routes shared a module in a chunk of its own, each route's entry also listed the other route's chunk as a preload and its stylesheet. diff --git a/.changeset/rsbuild-rule-use-falsy-loaders.md b/.changeset/rsbuild-rule-use-falsy-loaders.md deleted file mode 100644 index a84a054fbd..0000000000 --- a/.changeset/rsbuild-rule-use-falsy-loaders.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@tanstack/start-plugin-core': patch ---- - -fix: the Rsbuild RSC integration skips falsy entries in a rule's `use` array (Rspack's conditionally disabled loaders) instead of treating them as loaders. diff --git a/.changeset/rsbuild-virtual-modules-build.md b/.changeset/rsbuild-virtual-modules-build.md deleted file mode 100644 index 01a0c5ee6e..0000000000 --- a/.changeset/rsbuild-virtual-modules-build.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@tanstack/start-plugin-core': patch ---- - -Rsbuild: fix the Rsbuild plugin build after two changes to its virtual modules crossed. Without this fix the package does not build, so no release could ship it. The Rsbuild dev manifest is written to its virtual module under the app's root. diff --git a/.changeset/rsbuild-virtual-modules-root.md b/.changeset/rsbuild-virtual-modules-root.md deleted file mode 100644 index 427043a712..0000000000 --- a/.changeset/rsbuild-virtual-modules-root.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@tanstack/start-plugin-core': patch ---- - -Rsbuild: Start writes its virtual modules under the app's root, not the working directory. An app built or served from another directory (`rsbuild build --root ` from a monorepo root) no longer fails with "Module not found" on the packages they import, such as RSC's serialization adapters. diff --git a/.changeset/rsc-security-floor.md b/.changeset/rsc-security-floor.md deleted file mode 100644 index 9c828f13b3..0000000000 --- a/.changeset/rsc-security-floor.md +++ /dev/null @@ -1,8 +0,0 @@ ---- -'@tanstack/react-start-rsc': patch ---- - -Raise the minimum RSC bundler peer dependencies to versions with the React Server Components fixes for GHSA-xqc2-xf4c-x3h3 (CVE-2026-126187, unauthenticated RCE) and GHSA-h3gv-c5rc-p453 (server function DoS): - -- `@vitejs/plugin-rsc` to `>=0.5.38` (GHSA-59pf-q495-3c99), which vendors a fixed `react-server-dom-webpack`. -- `react-server-dom-rspack` to `>=0.1.1`, the first release built from React sources that include the fix. diff --git a/.changeset/sieve-cache.md b/.changeset/sieve-cache.md new file mode 100644 index 0000000000..bd32f43293 --- /dev/null +++ b/.changeset/sieve-cache.md @@ -0,0 +1,5 @@ +--- +'@tanstack/router-core': patch +--- + +Replace the internal LRU cache behind path resolution, route matching and the SSR manifest lookup with a smaller SIEVE cache whose hits no longer relink a list, and fix an eviction edge case in the old implementation. diff --git a/.changeset/start-server-fn-custom-id-check.md b/.changeset/start-server-fn-custom-id-check.md deleted file mode 100644 index 384f0ade06..0000000000 --- a/.changeset/start-server-fn-custom-id-check.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -'@tanstack/start-plugin-core': minor ---- - -A server function id that a custom `serverFns.generateFunctionId` returns and that never worked over HTTP now fails the build, with an error naming the file, the function and the id: whitespace, a control or non-ASCII character, any of `"`, `#`, `/`, `<`, `>`, `?`, `\`, `^`, `` ` ``, `{`, `}`, the ids `.` and `..`, and a percent-encoding the server reads as another id (`%41`, lowercase hex, `%2E`) or rejects. The client puts the id in the URL unencoded, so a `#` or `?` ended the path and a `/` cut the id short (the call silently ran another server function of the file or none), and the other characters reached the server percent-encoded and matched no function. An id embedding a non-ASCII `functionName` is one of these. One case did work and now fails the build: such an id on a server function only SSR code called. - -Ids with `%` or the other characters URLs allow (such as `:`, `@`, `+`, `=`, `,`, `;`, `!`, `*`, `(`, `)`, `&`, `'`, `|`, `[`, `]`) still build and reach their handler, with a deprecation warning (from the Vite plugin; the Rsbuild plugin does not print compiler warnings yet): the next major version rejects them, since proxies and servers may decode or rewrite them (hash the inputs instead, as the documented example does). An id with `'` no longer breaks the server bundle. diff --git a/.changeset/start-vite-root-library-discovery.md b/.changeset/start-vite-root-library-discovery.md deleted file mode 100644 index d4e8221c59..0000000000 --- a/.changeset/start-vite-root-library-discovery.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@tanstack/start-plugin-core': patch ---- - -Vite: Start finds the Start libraries it bundles in the SSR build from Vite's root, not the working directory. A `vite build ` run from another directory (a monorepo root, a script) no longer leaves them external and uncompiled, where their server fns returned `undefined`. diff --git a/.changeset/tame-banks-wear.md b/.changeset/tame-banks-wear.md new file mode 100644 index 0000000000..c4a625802a --- /dev/null +++ b/.changeset/tame-banks-wear.md @@ -0,0 +1,5 @@ +--- +'@tanstack/router-core': patch +--- + +Reduce promise allocations during client navigation when loader data and route components are already available. diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 9dd0def7bd..a33150af03 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -4,14 +4,6 @@ body: - type: markdown attributes: value: | - - Thank you for reporting an issue :pray:. This issue tracker is for reporting bugs found in TanStack Router and/or Start. diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index a5ef10f1ff..1245a0a0fd 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -12,11 +12,3 @@ - [ ] This change affects published code, and I have generated a [changeset](https://github.com/changesets/changesets/blob/main/docs/adding-a-changeset.md). - [ ] This change is docs/CI/dev-only (no release). - - diff --git a/.github/renovate.json b/.github/renovate.json index 6fd5aa1c86..01be1ce5c2 100644 --- a/.github/renovate.json +++ b/.github/renovate.json @@ -21,6 +21,7 @@ "@types/node", "@types/react", "@types/react-dom", + "h3", "node", "react", "react-dom", diff --git a/.github/workflows/bundle-size.yml b/.github/workflows/bundle-size.yml index 51ffa28e4c..23c354e06e 100644 --- a/.github/workflows/bundle-size.yml +++ b/.github/workflows/bundle-size.yml @@ -9,18 +9,12 @@ on: - 'packages/**' - 'benchmarks/**' - 'scripts/benchmarks/bundle-size/**' - - '.nvmrc' - - 'package.json' - - 'pnpm-lock.yaml' push: branches: [main] paths: - 'packages/**' - 'benchmarks/**' - 'scripts/benchmarks/bundle-size/**' - - '.nvmrc' - - 'package.json' - - 'pnpm-lock.yaml' workflow_dispatch: concurrency: @@ -51,7 +45,7 @@ jobs: uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main - name: Measure Bundle Size - run: pnpm benchmark:bundle-size --outputStyle=stream --skipRemoteCache + run: pnpm nx run @benchmarks/bundle-size:build --outputStyle=stream --skipRemoteCache - name: Capture Benchmark Outputs id: capture @@ -109,8 +103,6 @@ jobs: cat benchmarks/bundle-size/results/pr-comment.md - name: Upsert Sticky PR Comment - # Fork PRs have a read-only GITHUB_TOKEN, so they cannot update comments. - if: ${{ github.event.pull_request.head.repo.full_name == github.repository }} env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | @@ -120,7 +112,7 @@ jobs: benchmark-main: name: Publish Bundle Size History - if: (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && github.ref == 'refs/heads/main' && github.repository_owner == 'TanStack' + if: github.event_name == 'push' && github.ref == 'refs/heads/main' && github.repository_owner == 'TanStack' runs-on: ubuntu-latest permissions: contents: write @@ -135,7 +127,7 @@ jobs: uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main - name: Measure Bundle Size - run: pnpm benchmark:bundle-size --outputStyle=stream --skipRemoteCache + run: pnpm nx run @benchmarks/bundle-size:build --outputStyle=stream --skipRemoteCache - name: Publish Benchmark Dashboard uses: benchmark-action/github-action-benchmark@52576c92bccf6ac60c8223ec7eb2565637cae9ba # v1.22.1 with: diff --git a/.github/workflows/benchmarks.yml b/.github/workflows/client-nav-benchmarks.yml similarity index 78% rename from .github/workflows/benchmarks.yml rename to .github/workflows/client-nav-benchmarks.yml index bbc3a1fa24..2045a91a0b 100644 --- a/.github/workflows/benchmarks.yml +++ b/.github/workflows/client-nav-benchmarks.yml @@ -18,15 +18,16 @@ on: pull_request: paths: - 'packages/**' - - '!packages/**/tests/**' - - '!packages/**/__tests__/**' - - '!packages/**/*.test.*' - 'benchmarks/**' - - '.nvmrc' workflow_dispatch: + inputs: + memory-only: + description: Run only the memory benchmarks + type: boolean + default: false concurrency: - group: benchmarks-${{ github.ref }} + group: client-nav-benchmarks-${{ github.ref }} cancel-in-progress: false queue: single @@ -49,20 +50,7 @@ jobs: - react - solid - vue - benchmark: - - client-nav - - ssr - - memory-server - - memory-client - include: - - benchmark: client-nav - mode: simulation - - benchmark: ssr - mode: simulation - - benchmark: memory-server - mode: memory - - benchmark: memory-client - mode: memory + benchmark: ${{ fromJSON(inputs.memory-only && '["memory-server", "memory-client"]' || '["client-nav", "ssr", "memory-server", "memory-client"]') }} runs-on: ubuntu-latest steps: - name: Checkout @@ -81,10 +69,10 @@ jobs: @benchmarks/${{ matrix.benchmark }}:build:${{ matrix.framework }} - name: Run ${{ matrix.benchmark }}:${{ matrix.framework }} CodSpeed benchmark - uses: CodSpeedHQ/action@373d6868929f444bc08d901fd0eb0ad52a8875ea # v5.2.1 + uses: CodSpeedHQ/action@4296e51e7041e24dadb86d1d6e8b9320d223dbe8 # v5.0.3 timeout-minutes: 20 with: - mode: ${{ matrix.mode }} + mode: ${{ startsWith(matrix.benchmark, 'memory-') && 'memory' || 'simulation' }} run: >- WITH_INSTRUMENTATION=1 pnpm nx run diff --git a/.github/workflows/compiler-platforms.yml b/.github/workflows/compiler-platforms.yml deleted file mode 100644 index ad70e39bb6..0000000000 --- a/.github/workflows/compiler-platforms.yml +++ /dev/null @@ -1,101 +0,0 @@ -name: Compiler Platforms - -# The main PR workflow only runs on Linux x64 (glibc). The compilers load a -# native Yuku binary per platform and handle platform-specific paths, so run -# their unit tests and a Vite and Rsbuild production build on the other -# platforms we ship to. - -on: - pull_request: - paths: - - 'packages/router-utils/**' - - 'packages/router-generator/**' - - 'packages/router-plugin/**' - - 'packages/start-plugin-core/**' - - 'pnpm-lock.yaml' - - '.github/workflows/compiler-platforms.yml' - schedule: - # Weekly, to catch new Yuku releases and runner image updates - - cron: '0 6 * * 1' - workflow_dispatch: - -concurrency: - group: ${{ github.workflow }}-${{ github.event.number || github.ref }} - cancel-in-progress: true - -permissions: - contents: read - -env: - NX_DAEMON: 'false' - NX_NO_CLOUD: 'true' - -defaults: - run: - shell: bash - -jobs: - compiler: - name: ${{ matrix.name }} - runs-on: ${{ matrix.os }} - # actions/setup-node only ships glibc builds, so musl uses Alpine's Node image - container: ${{ matrix.container }} - strategy: - fail-fast: false - matrix: - include: - - name: Windows x64 - os: windows-latest - - name: macOS arm64 - os: macos-latest - - name: Linux arm64 - os: ubuntu-24.04-arm - - name: Linux x64 musl - os: ubuntu-latest - container: node:24.8.0-alpine3.22@sha256:3e843c608bb5232f39ecb2b25e41214b958b0795914707374c8acc28487dea17 - steps: - - name: Install system packages - if: ${{ matrix.container }} - shell: sh - run: apk add --no-cache bash git - - name: Keep LF line endings - # Snapshots are stored with LF. Windows runners check out CRLF by default, - # and with `* text=auto` disabling autocrlf alone still uses the native eol - run: | - git config --global core.autocrlf false - git config --global core.eol lf - - name: Checkout - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - persist-credentials: false - - name: Setup pnpm - if: ${{ !matrix.container }} - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 - - name: Setup Node - if: ${{ !matrix.container }} - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 - with: - node-version-file: .nvmrc - package-manager-cache: false - - name: Setup pnpm (container) - if: ${{ matrix.container }} - run: npm install --global "$(node -p "require('./package.json').packageManager")" - - name: Install dependencies - run: >- - pnpm install --frozen-lockfile - --filter . - --filter "@tanstack/router-utils..." - --filter "@tanstack/router-generator..." - --filter "@tanstack/router-plugin..." - --filter "@tanstack/start-plugin-core..." - --filter "tanstack-react-start-e2e-basic..." - - name: Unit tests - run: >- - pnpm nx run-many --targets=test:unit - --projects=@tanstack/router-utils,@tanstack/router-generator,@tanstack/router-plugin,@tanstack/start-plugin-core - --skip-nx-cache --outputStyle=static - - name: Production builds - run: >- - pnpm nx run-many --targets=build:vite:ssr,build:rsbuild:ssr - --projects=tanstack-react-start-e2e-basic - --skip-nx-cache --outputStyle=static diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml index fde1100409..d8c779b170 100644 --- a/.github/workflows/labeler.yml +++ b/.github/workflows/labeler.yml @@ -9,8 +9,6 @@ permissions: jobs: labeler: - # Fork PRs have a read-only GITHUB_TOKEN, so they cannot update labels. - if: ${{ github.event.pull_request.head.repo.full_name == github.repository }} runs-on: ubuntu-latest steps: - name: Labeller diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index ae19b4f0d2..71026a0a92 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -10,13 +10,6 @@ concurrency: env: NX_CLOUD_ACCESS_TOKEN: ${{ secrets.NX_CLOUD_ACCESS_TOKEN }} SERVER_PRESET: 'node-server' - # Enable dynamic task packing for distributed CI. - NX_CLOUD_AGENT_TASK_QUEUE: true - NX_CLOUD_AUTO_TASK_PACKING: true - NX_CLOUD_AGENT_UNCAPPED_GROUP_WORK: true - NX_CLOUD_PACKING_MEM_MULTIPLIER: 1.5 - NX_CLOUD_BUFFER_TASK_COMPLETIONS: true - NX_CLOUD_CONTINUOUS_ASSIGNMENT: true permissions: contents: read @@ -33,8 +26,8 @@ jobs: with: fetch-depth: 0 persist-credentials: false - - name: Start Nx Workers - run: npx nx-cloud start-workers + - name: Start Nx Agents + run: npx nx-cloud start-ci-run --distribute-on=".nx/workflows/dynamic-changesets.yaml" - name: Setup Tools uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main - name: Get base and head commits for `nx affected` @@ -43,9 +36,9 @@ jobs: main-branch-name: main - name: Run Checks run: pnpm run test:pr --parallel=3 - - name: Stop Nx Workers + - name: Stop Nx Agents if: ${{ always() }} - run: npx nx-cloud stop-all-workers + run: npx nx-cloud stop-all-agents preview: name: Preview runs-on: ubuntu-latest diff --git a/.gitignore b/.gitignore index 70028b2860..1699592784 100644 --- a/.gitignore +++ b/.gitignore @@ -66,7 +66,6 @@ nx-cloud.env .nx/workspace-data .nx/polygraph .nx/self-healing -.nx/migrate-runs gpt/db.json diff --git a/.nvmrc b/.nvmrc index 63f87c20ef..b404027604 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -26.12.1 +24.8.0 diff --git a/.nx/ci-config.yaml b/.nx/ci-config.yaml deleted file mode 100644 index 2f0783feb4..0000000000 --- a/.nx/ci-config.yaml +++ /dev/null @@ -1,5 +0,0 @@ -dte: - distribute-on: - small-changeset: 6 linux-medium-js - medium-changeset: 12 linux-medium-js - large-changeset: 18 linux-medium-js diff --git a/.nx/workflows/dynamic-changesets.yaml b/.nx/workflows/dynamic-changesets.yaml new file mode 100644 index 0000000000..39d858d5b2 --- /dev/null +++ b/.nx/workflows/dynamic-changesets.yaml @@ -0,0 +1,4 @@ +distribute-on: + small-changeset: 4 linux-medium-js + medium-changeset: 8 linux-medium-js + large-changeset: 16 linux-medium-js diff --git a/.nx/workflows/sandboxing-config.yaml b/.nx/workflows/sandboxing-config.yaml new file mode 100644 index 0000000000..4fa2634bc3 --- /dev/null +++ b/.nx/workflows/sandboxing-config.yaml @@ -0,0 +1,9 @@ +exclude-reads: + - e2e/.gitignore + - '**/src/routeTree.gen.ts' +exclude-writes: + - '**/src/routeTree.gen.ts' +task-exclusions: + - target: test:build + exclude-reads: + - LICENSE diff --git a/.nx/workflows/ultracache-config.yaml b/.nx/workflows/ultracache-config.yaml deleted file mode 100644 index b3ed223621..0000000000 --- a/.nx/workflows/ultracache-config.yaml +++ /dev/null @@ -1,124 +0,0 @@ -ignore-reads: - - e2e/.gitignore - - '**/src/routeTree.gen.ts' -ignore-writes: - - '**/src/routeTree.gen.ts' -task-exclusions: - - target: test:build - ignore-reads: - - LICENSE - # HMR tests edit these inputs in place and restore their original contents. - # Keep them out of cached outputs so cache replay never overwrites source. - - project: tanstack-react-start-e2e-deferred-hydration - target: test:e2e - ignore-writes: - - e2e/react-start/deferred-hydration/src/routes/components.tsx - - project: tanstack-react-start-e2e-hmr - target: test:e2e - ignore-writes: &hmr-source-writes - - e2e/react-start/hmr/src/components/AliasedRouteImportChildPanel.tsx - - e2e/react-start/hmr/src/components/AliasedRouteImportParentPanel.tsx - - e2e/react-start/hmr/src/hmr/server-fn-hmr-factory.ts - - e2e/react-start/hmr/src/routes/__root.tsx - - e2e/react-start/hmr/src/routes/child.tsx - - e2e/react-start/hmr/src/routes/component-hmr-inline-error-split.tsx - - e2e/react-start/hmr/src/routes/component-hmr-inline-nosplit.tsx - - e2e/react-start/hmr/src/routes/component-hmr-inline-split.tsx - - e2e/react-start/hmr/src/routes/component-hmr-lowercase-named-split.tsx - - e2e/react-start/hmr/src/routes/component-hmr-named-error-split.tsx - - e2e/react-start/hmr/src/routes/component-hmr-named-nosplit.tsx - - e2e/react-start/hmr/src/routes/component-hmr-named-split.tsx - - e2e/react-start/hmr/src/routes/index.tsx - - e2e/react-start/hmr/src/routes/inputs.tsx - - project: tanstack-react-start-e2e-hmr - target: test:e2e--vite-ssr - ignore-writes: *hmr-source-writes - - project: tanstack-react-start-e2e-hmr - target: test:e2e--vite-ssr--bundled-dev - ignore-writes: *hmr-source-writes - - project: tanstack-react-start-e2e-hmr - target: test:e2e--rsbuild-ssr - ignore-writes: *hmr-source-writes - - project: tanstack-react-start-e2e-rsbuild - target: test:e2e--rsbuild-ssr - ignore-writes: - - e2e/react-start/rsbuild/src/routes/index.tsx - - project: tanstack-react-start-e2e-server-functions - target: test:e2e - ignore-writes: - - e2e/react-start/server-functions/src/routes/consistent.tsx - # Scaffolding tests deliberately populate tracked empty route fixtures. - - project: '@tanstack/router-generator' - target: test:unit - ignore-writes: - - packages/router-generator/tests/generator/custom-scaffolding/routes/__root.tsx - - packages/router-generator/tests/generator/custom-scaffolding/routes/api/bar.tsx - - packages/router-generator/tests/generator/custom-scaffolding/routes/foo.lazy.tsx - - packages/router-generator/tests/generator/custom-scaffolding/routes/index.tsx - # These reads are of scratch files created by the same test invocation. - - project: tanstack-solid-start-e2e-basic-auth - target: test:e2e - ignore-reads: - - e2e/solid-start/basic-auth/.tmp/dev.db - - project: tanstack-vue-start-e2e-basic-auth - target: test:e2e - ignore-reads: - - e2e/vue-start/basic-auth/.tmp/dev.db - - project: '@tanstack/router-generator' - target: test:unit - ignore-reads: - - packages/router-generator/tests/generator/file-modification/routes/[(]test[)]/initiallyEmpty.tsx - - packages/router-generator/tests/generator/file-modification/routes/[(]test[)]/initiallyEmpty.lazy.tsx - # Mutable counters are scratch state, not artifacts to replay from cache. - - project: tanstack-react-start-e2e-basic-tsr-config - target: test:e2e - ignore-reads: - - e2e/react-start/basic-tsr-config/count.txt - ignore-writes: - - e2e/react-start/basic-tsr-config/count.txt - - project: tanstack-solid-start-e2e-basic-tsr-config - target: test:e2e - ignore-reads: - - e2e/solid-start/basic-tsr-config/count.txt - ignore-writes: - - e2e/solid-start/basic-tsr-config/count.txt - - project: tanstack-vue-start-e2e-basic-tsr-config - target: test:e2e - ignore-reads: - - e2e/vue-start/basic-tsr-config/count.txt - ignore-writes: - - e2e/vue-start/basic-tsr-config/count.txt - # Paraglide downloads compiler plugins from the URLs in settings.json. - # Ignore warm-cache reads; the settings remain inputs and cache files outputs. - - project: tanstack-react-start-e2e-i18n-paraglide - target: build - ignore-reads: - - e2e/react-start/i18n-paraglide/project.inlang/cache/plugins/* - - project: tanstack-router-e2e-react-i18n-paraglide - target: build - ignore-reads: - - e2e/react-router/i18n-paraglide/project.inlang/cache/plugins/* - - project: tanstack-react-start-e2e-i18n-paraglide - target: test:e2e - ignore-reads: - - e2e/react-start/i18n-paraglide/project.inlang/cache/plugins/* - - project: tanstack-router-e2e-react-i18n-paraglide - target: test:e2e - ignore-reads: - - e2e/react-router/i18n-paraglide/project.inlang/cache/plugins/* - - project: tanstack-router-i18n-paraglide - target: build - ignore-reads: - - examples/react/i18n-paraglide/project.inlang/cache/plugins/* - - project: tanstack-start-i18n-paraglide - target: build - ignore-reads: - - examples/react/start-i18n-paraglide/project.inlang/cache/plugins/* - - project: tanstack-router-solid-i18n-paraglide - target: build - ignore-reads: - - examples/solid/i18n-paraglide/project.inlang/cache/plugins/* - - project: tanstack-solid-start-i18n-paraglide - target: build - ignore-reads: - - examples/solid/start-i18n-paraglide/project.inlang/cache/plugins/* diff --git a/.prettierignore b/.prettierignore index de501452ad..65991e1964 100644 --- a/.prettierignore +++ b/.prettierignore @@ -17,7 +17,4 @@ node_modules /.nx/workspace-data **/src/routeTree.gen.ts packages/router-plugin/tests/**/test-files/** -.nx/self-healing - -# Preserve the pinned upstream URL fixtures byte for byte. -packages/router-core/tests/fixtures/wpt-url/urltestdata*.json +.nx/self-healing \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md index f47b5103e1..3368f3f100 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,41 +1,181 @@ # AGENTS.md -## Scope +Read and follow [`CONTRIBUTING.md`](./CONTRIBUTING.md) before analyzing or +changing this repository. Its contribution and pull request requirements apply +to AI-assisted work. -- Read applicable nested `AGENTS.md` files before editing or testing a subtree. -- Shared routing belongs in `packages/router-core`; check React, Solid, and Vue bindings for shared changes. Shared Start runtime/build logic lives in `packages/start-*-core`. +## Project overview -## Work and validation +TanStack Router is a type-safe router with built-in caching and URL state management for React and Solid applications. This monorepo contains two main products: -- Start bug fixes with a failing regression test that uses only public APIs to reproduce and assert user- or developer-visible behavior. Do not manufacture bugs by mutating internals. Establish whether real usage can reach the failing state before adding runtime handling; simplify handling of states proven unreachable. -- When removing an API, option, or behavior, delete its tests. Never add tests that assert the removed thing is gone, such as `not.toHaveProperty('oldName')`, a type error for the old call, or a runtime throw. -- For suspected dependency issues, verify the upstream root cause, then propose an upstream fix to the user, including for other `@tanstack/*` packages. **Never implement a workaround in this repository unless the user explicitly authorizes it.** -- During debugging/prototyping, keep fixes aligned with the PR's intended architecture. If making a test pass requires another flag, counter, copied deadline, or duplicate completion authority, stop and consolidate state and ownership. Remove superseded paths instead of accumulating patches and bundle growth. -- Use Node from `.nvmrc` and pnpm from root `package.json`. Install at the root with `CI=1 pnpm install --frozen-lockfile`. -- For sandbox-blocked registry/store access, escalate the same command; report the blocker if unavailable. Do not change stores, delete dependencies/lockfiles, use `--force`/`--ignore-scripts`, or weaken workspace trust/build policies to bypass it. -- Never manually edit `pnpm-lock.yaml` or any `routeTree.gen.ts`. Regenerate the lockfile with `pnpm install --no-frozen-lockfile` after intentional dependency changes; regenerate route trees through app builds/dev servers or the generator fixture harness. -- Always use control-flow braces. Run `pnpm format` before validation. -- Use Nx: workspace imports consume built packages, so direct runners can test stale dependencies. Inspect resolved targets with `pnpm nx show project --json`; some are inferred. -- Run finite validation through `run-many` with explicit projects and targets, including a single project/target. Nx automatically selects `summary` output when it detects an AI agent: omit `--outputStyle` for normal runs. Read the reported full log files for failures; use `--outputStyle=summary` if agent detection is unavailable. -- Use `--outputStyle=static` or `pnpm nx run :` only when diagnosing a task and its full output is needed. Continuous/watch targets may use live output. +- **TanStack Router** - Core routing library with type-safe navigation, search params, and path params +- **TanStack Start** - Full-stack framework built on top of TanStack Router -```sh -CI=1 NX_DAEMON=false pnpm nx run-many -p -t --skipRemoteCache -``` +## Setup commands -- Run one Nx command at a time. For a ~20-second startup/graph stall, stop, run `pnpm nx reset`, and retry once, then escalate. Do not apply that timeout to running tests. -- For code changes, run affected packages' `test:unit`, `test:types`, and `test:eslint` where available, including affected consumers; use `test:e2e` for browser/app behavior and `test:build` for exports/build changes. Root `pnpm test` includes the full e2e suite. Published-code changes require `pnpm changeset`. +- Install deps: `pnpm install` +- Setup e2e testing: `pnpm exec playwright install` +- Build packages: `pnpm build` (affected) or `pnpm build:all` (force all) +- Start dev server: `pnpm dev` +- Run tests: `pnpm test` -## Runtime rules +## Code style -- Import `isServer` from `@tanstack/router-core/isServer`. Conditional exports select: `development` → `undefined`; server (`workerd`, `worker`, `deno`, `node`, `bun`) → `true` except `NODE_ENV=test` → `undefined`; browser/fallback → `false`. `development` wins; `NODE_ENV=development` alone does not select it. -- Keep `isServer ?? router.isServer` directly in each branch condition for dead-code elimination; negate the whole expression for client branches. Never extract it into a variable (e.g. `const serverRendering = isServer ?? router.isServer`) or helper. Without a router, inline `isServer ?? typeof window === 'undefined'` (or the existing `document` check). Keep the constant first and use `??`, never `||`. -- **Never create UI/router reactivity on the server, including development/tests.** Branch before reactive setup; use direct reads and core non-reactive stores. Required transport listeners are allowed only with request-scoped lifetimes and cleanup. -- Shared route definitions/build metadata must not acquire request/user data. Keep it on the request's Router, context, or QueryClient. -- HMR can replace code while caches and pending work survive. Invalidate derived state or bypass caching in development; reject stale async results while preserving intentional HMR identities/state. -- Gate developer diagnostics and message construction with direct `process.env.NODE_ENV !== 'production'` checks. Preserve required validation/throws in production (e.g. detailed development error, compact `invariant()` failure). `!== 'development'` also enables the guarded code in tests; preserve existing dev-server mode gates. +- TypeScript strict mode with extensive type safety +- Framework-agnostic core logic separated from React/Solid bindings +- Type-safe routing with search params and path params +- Use workspace protocol for internal dependencies (`workspace:*`) +- Always use curly braces for `if`, `else`, loops, and similar control statements. Never write one-line bodies like `if (foo) x = 1`. -## Performance and final bundle pass +## Dev environment tips -- For runtime/memory changes, compare identical baseline/candidate workloads using the relevant [benchmark guide](benchmarks/AGENTS.md): client navigation, Start SSR, or memory. Add coverage for unmeasured mechanisms. -- **Last phase for every change affecting emitted client JavaScript**, including core/build transforms: complete the full [bundle-size-optimization skill](.agents/skills/bundle-size-optimization/SKILL.md) after correctness and performance validation. The full workflow is mandatory. +- This is a pnpm workspace monorepo with packages organized by functionality +- Nx provides caching, affected testing, targeting, and parallel execution for efficiency +- Use `pnpm nx show projects` to list all available packages +- Target specific packages: `pnpm nx run @tanstack/react-router:test:unit` +- Target multiple packages: `pnpm nx run-many --target=test:eslint --projects=@tanstack/history,@tanstack/router-core` +- Run affected tests only: `pnpm nx affected --target=test:unit` +- Exclude patterns: `pnpm nx run-many --target=test:unit --exclude="examples/**,e2e/**"` +- Navigate to examples and run `pnpm dev` to test changes: `cd examples/react/basic && pnpm dev` +- **Granular unit testing through Nx (recommended):** + - Specific files: `pnpm nx run @tanstack/react-router:test:unit -- tests/link.test.tsx tests/Scripts.test.tsx` + - Test patterns: `pnpm nx run @tanstack/react-router:test:unit -- tests/ClientOnly.test.tsx -t "should render fallback"` + - Name patterns: `pnpm nx run @tanstack/react-router:test:unit -- -t "navigation"` (all tests with "navigation" in name) + - Exclude patterns: `pnpm nx run @tanstack/react-router:test:unit -- --exclude="**/*link*" tests/` + - List tests: `pnpm nx run @tanstack/react-router:test:unit -- list tests/link.test.tsx` (or `-- list` for all) +- **Available test targets per package:** `test:unit`, `test:types`, `test:eslint`, `test:build`, `test:perf`, `build` +- **Testing strategy:** Package level (nx) → File-level args via nx → Test-level args (`-t`) via nx → Pattern-level args (`--exclude`) via nx +- **Agent execution guardrails (important):** + - Always prefer `pnpm nx ...` over `npx nx ...`. + - Prefer Nx targets over direct test runners so task dependencies (including required builds) remain in the graph. + - In sandbox, run Nx with `CI=1 NX_DAEMON=false pnpm nx run : --outputStyle=stream --skipRemoteCache` + - Run only one Nx command at a time. + - If an Nx command shows no output for ~20 seconds, stop, run `pnpm nx reset` once, and retry once. + - Do not loop retries indefinitely. If it still hangs or sandbox blocks graph/daemon behavior, request escalation immediately. + +## Testing instructions + +- **Critical**: Always run unit and type tests during development - do not proceed if they fail +- **Test types:** `pnpm test:unit`, `pnpm test:types`, `pnpm test:eslint`, `pnpm test:e2e`, `pnpm test:build` +- **Full CI suite:** `pnpm test:ci` +- **Fix formatting:** `pnpm format` +- **Efficient targeted testing workflow:** + 1. **Affected only:** `pnpm nx affected --target=test:unit` (compares to main branch) + 2. **Specific packages:** `pnpm nx run @tanstack/react-router:test:unit` + 3. **Specific files:** `pnpm nx run @tanstack/react-router:test:unit -- tests/link.test.tsx` + 4. **Specific patterns:** `pnpm nx run @tanstack/react-router:test:unit -- tests/link.test.tsx -t "preloading"` +- **Pro tips:** + - Use `pnpm nx run @tanstack/react-router:test:unit -- list` to explore available tests before running + - Use `-t "pattern"` to focus on specific functionality during development + - Use `--exclude` patterns to skip unrelated tests + - Keep all test filtering arguments behind `pnpm nx run ... -- ...` for maximum precision while preserving task dependencies +- **Example workflow:** `pnpm nx run @tanstack/react-router:test:unit` → `pnpm nx run @tanstack/react-router:test:unit -- tests/link.test.tsx` → `pnpm nx run @tanstack/react-router:test:unit -- tests/link.test.tsx -t "preloading"` + +## PR instructions + +- Always run `pnpm test:eslint`, `pnpm test:types`, and `pnpm test:unit` before committing +- Test changes in relevant example apps: `cd examples/react/basic && pnpm dev` +- Update corresponding documentation in `docs/` directory when adding features +- Add or update tests for any code changes +- Use internal docs links relative to `docs/` folder (e.g., `./guide/data-loading`) + +## Package structure + +**Core packages:** + +- `packages/router-core/` - Framework-agnostic core router logic +- `packages/react-router/`, `packages/solid-router/` - React/Solid bindings and components +- `packages/history/` - Browser history management + +**Tooling:** + +- `packages/router-cli/` - CLI tools for code generation +- `packages/router-generator/` - Route generation utilities +- `packages/router-plugin/` - Universal bundler plugins (Vite, Webpack, ESBuild, Rspack) +- `packages/virtual-file-routes/` - Virtual file routing system + +**Developer experience:** + +- `packages/router-devtools/`, `packages/*-router-devtools/` - Development tools +- `packages/eslint-plugin-router/` - ESLint rules for router + +**Validation adapters:** + +- `packages/zod-adapter/`, `packages/valibot-adapter/`, `packages/arktype-adapter/` + +**Start framework:** + +- `packages/*-start/`, `packages/start-*/` - Full-stack framework packages + +**Examples & testing:** + +- `examples/react/`, `examples/solid/` - Example applications (test changes here) +- `e2e/` - End-to-end tests (requires Playwright) +- `docs/router/`, `docs/start/` - Documentation with React/Solid subdirectories + +**Dependencies:** Uses workspace protocol (`workspace:*`) - core → framework → start packages + +## Common development tasks + +**Adding new routes:** + +- Use file-based routing in `src/routes/` directories +- Or use code-based routing with route definitions +- Run route generation with CLI tools + +**Testing changes:** + +- Build packages: `pnpm build` or `pnpm dev` (watch mode) +- Run example apps to test functionality +- Use devtools for debugging router state + +**Documentation updates:** + +- Update relevant docs in `docs/` directory +- Ensure examples reflect documentation changes +- Test documentation links and references +- Use relative links to `docs/` folder format + +## Framework-specific notes + +**React:** + +- Uses React Router components and hooks +- Supports React Server Components (RSC) +- Examples include React Query integration +- Package: `@tanstack/react-router` + +**Solid:** + +- Uses Solid Router components and primitives +- Supports Solid Start for full-stack applications +- Examples include Solid Query integration +- Package: `@tanstack/solid-router` + +## Environment requirements + +- **Node.js** - Required for development +- **pnpm** - Package manager (required for workspace features) +- **Playwright** - Required for e2e tests (`pnpm exec playwright install`) + +## Key architecture patterns + +- **Type Safety**: Extensive TypeScript for type-safe routing +- **Framework Agnostic**: Core logic separated from framework bindings +- **Plugin Architecture**: Universal bundler plugins using unplugin +- **File-based Routing**: Support for both code-based and file-based routing +- **Search Params**: First-class support for type-safe search parameters + +## Development workflow + +1. **Setup**: `pnpm install` and `pnpm exec playwright install` +2. **Build**: `pnpm build:all` or `pnpm dev` for watch mode +3. **Test**: Make changes and run relevant tests (use nx for targeted testing) +4. **Examples**: Navigate to examples and run `pnpm dev` to test changes +5. **Quality**: Run `pnpm test:eslint`, `pnpm test:types`, `pnpm test:unit` before committing + +## References + +- **Documentation**: https://tanstack.com/router +- **GitHub**: https://github.com/TanStack/router +- **Discord Community**: https://discord.com/invite/WrRKjPJ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4b6e808af1..ce76a5ba5d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -142,14 +142,6 @@ pnpm dev ## AI-assisted contributions - - AI tools can be useful for exploring the codebase, drafting changes, and writing tests. They do not replace the contributor's responsibility for the result. 1. **Keep the contribution in your own voice**. Review and rewrite generated code comments, issue reports, and pull request descriptions so they reflect what you actually mean. diff --git a/_artifacts/domain_map.yaml b/_artifacts/domain_map.yaml index 0b2672f0c6..4b5d6f8386 100644 --- a/_artifacts/domain_map.yaml +++ b/_artifacts/domain_map.yaml @@ -147,15 +147,13 @@ skills: context types to not flow into loader. wrong_pattern: | createFileRoute('/posts')({ - loader: ({ context }) => - context.queryClient.query({ ...postsQuery, staleTime: 'static' }), + loader: ({ context }) => context.queryClient.ensureQueryData(postsQuery), beforeLoad: ({ context }) => ({ queryClient: context.queryClient }), }) correct_pattern: | createFileRoute('/posts')({ beforeLoad: ({ context }) => ({ queryClient: context.queryClient }), - loader: ({ context }) => - context.queryClient.query({ ...postsQuery, staleTime: 'static' }), + loader: ({ context }) => context.queryClient.ensureQueryData(postsQuery), }) source: 'docs/router/eslint/create-route-property-order.md' priority: HIGH @@ -538,7 +536,7 @@ skills: - '@tanstack/react-router-ssr-query' covers: - External cache coordination pattern - - "queryClient.query with staleTime: 'static' in loader" + - queryClient.ensureQueryData in loader - useSuspenseQuery in components - setupRouterSsrQueryIntegration - defaultPreloadStaleTime @@ -581,11 +579,11 @@ skills: priority: HIGH status: active - - mistake: 'Awaiting a fire-and-forget query in loader blocks rendering' + - mistake: 'Awaiting prefetchQuery in loader blocks rendering' mechanism: >- - For streaming/deferred patterns, start a query without awaiting - it and handle failures with catch(noop) — it starts fetching on - the server and streams without blocking. Awaiting defeats the purpose. + For streaming/deferred patterns, prefetchQuery should NOT + be awaited in the loader — it starts fetching on server + and streams without blocking. Awaiting defeats the purpose. source: 'docs/router/integrations/query.md' priority: MEDIUM status: active diff --git a/_artifacts/skill_spec.md b/_artifacts/skill_spec.md index 7eb9554a42..4503afb48a 100644 --- a/_artifacts/skill_spec.md +++ b/_artifacts/skill_spec.md @@ -83,11 +83,11 @@ TanStack Router is a type-safe router for React and Solid applications with buil ### external-data-loading (3 failure modes) -| # | Mistake | Priority | Source | Cross-skill? | -| --- | ----------------------------------------------------------- | -------- | -------------------------------- | ------------ | -| 1 | Not setting defaultPreloadStaleTime to 0 | HIGH | docs/guide/external-data-loading | — | -| 2 | Creating QueryClient outside createRouter for SSR | HIGH | docs/guide/external-data-loading | — | -| 3 | Awaiting a fire-and-forget query in loader blocks rendering | MEDIUM | docs/integrations/query | — | +| # | Mistake | Priority | Source | Cross-skill? | +| --- | ------------------------------------------------- | -------- | -------------------------------- | ------------ | +| 1 | Not setting defaultPreloadStaleTime to 0 | HIGH | docs/guide/external-data-loading | — | +| 2 | Creating QueryClient outside createRouter for SSR | HIGH | docs/guide/external-data-loading | — | +| 3 | Awaiting prefetchQuery in loader blocks rendering | MEDIUM | docs/integrations/query | — | ### auth-and-guards (3 failure modes) diff --git a/_artifacts/skill_tree.yaml b/_artifacts/skill_tree.yaml index 6f7c4c8742..ec38a04bdd 100644 --- a/_artifacts/skill_tree.yaml +++ b/_artifacts/skill_tree.yaml @@ -246,7 +246,7 @@ skills: package: 'packages/react-router' description: >- Integrating TanStack Router with TanStack Query: queryClient - in router context, static queries and fire-and-forget queries in loaders, + in router context, ensureQueryData/prefetchQuery in loaders, useSuspenseQuery in components, defaultPreloadStaleTime: 0, setupRouterSsrQueryIntegration for SSR dehydration/hydration and streaming, per-request QueryClient isolation. diff --git a/benchmarks/AGENTS.md b/benchmarks/AGENTS.md deleted file mode 100644 index 9d56a2411a..0000000000 --- a/benchmarks/AGENTS.md +++ /dev/null @@ -1,15 +0,0 @@ -# Benchmarks - -Read the relevant README before running benchmarks. Compare baseline and candidate with the same workload and production builds; add a focused case when existing scenarios miss the changed mechanism. Keep workloads and benchmark names stable for historical comparisons. - -| Changed behavior | Guide | Nx project | -| ------------------------------------------ | ---------------------------------- | -------------------------------------------------------- | -| Standalone Router navigation/rendering CPU | [client-nav](client-nav/README.md) | `@benchmarks/client-nav` | -| Start request/SSR CPU | [ssr](ssr/README.md) | `@benchmarks/ssr` | -| Client/server retention and allocations | [memory](memory/README.md) | `@benchmarks/memory-client`, `@benchmarks/memory-server` | - -Use `test:perf:` through Nx. Plain memory runs only smoke-test; memory metrics require CodSpeed. Client navigation benchmarks do not cover Start hydration or client server-function calls. - -Run `vitest bench` directly only with `--mode benchmark`, as the Nx targets do. Vitest 5 otherwise uses Vite's `test` mode, where vite-plugin-solid injects a jest-dom setup file that benchmark packages cannot resolve. - -For bundle-size work, follow the full optimization skill required by the root guide. Full API fixtures are maintained manually: when public hooks/components change, update matching `bundle-size/scenarios/*-full/src/routes/__root.tsx` fixtures. Save baseline results separately because each run overwrites `bundle-size/results/current.json`; report final gzip deltas and explain remaining growth. diff --git a/benchmarks/README.md b/benchmarks/README.md index 94d2f31802..96cd63f850 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -1,7 +1,6 @@ # CPU simulation benchmarks -`client-nav` measures navigation, mounting, and React/Solid hydration in -Node/jsdom; `ssr` measures server requests. +`client-nav` measures navigation in Node/jsdom; `ssr` measures server requests. Both suites run through the CodSpeed Vitest integration in CPU simulation mode. ## Worker runtime @@ -76,13 +75,13 @@ Node and use `setImmediate` directly. Dispatch the existing `Benchmarks` workflow against an unchanged branch: ```sh -gh workflow run benchmarks.yml --ref +gh workflow run client-nav-benchmarks.yml --ref ``` Wait for each workflow run to finish before dispatching the next repetition at the same commit. The workflow also runs memory benchmarks; exclude those results when assessing CPU repeatability. Check that every repetition has all expected -CPU results (currently 134), rather than inherited results from an earlier run. +CPU results (currently 132), rather than inherited results from an earlier run. Compare each benchmark's minimum and maximum across repetitions; keep input data, navigation/request counts, builds, dependencies and Node version fixed when testing runtime configuration changes. diff --git a/benchmarks/bundle-size/README.md b/benchmarks/bundle-size/README.md index 2185d6b43f..c845382fdb 100644 --- a/benchmarks/bundle-size/README.md +++ b/benchmarks/bundle-size/README.md @@ -40,9 +40,7 @@ pnpm benchmark:bundle-size:run --scenario react-router.minimal,react-router.full ``` The runner calls `measure.mjs`, which builds the selected package projects through Nx. Full runs build the package projects for all scenarios. -`pnpm benchmark:bundle-size` uses the Nx build cache for the full benchmark, then generates `current.json` with the current commit, branch, dirty status, and report timestamp. CI uses this command as well. - -Nx caches the bundles, `measurements.json`, and `benchmark-action.json`. Git metadata does not affect the build cache. The report preserves the original `measuredAt` and build duration when measurements come from cache; `generatedAt` records when the report was generated. Running `pnpm nx run @benchmarks/bundle-size:measure` directly produces only the cacheable outputs; run `node scripts/benchmarks/bundle-size/report.mjs` afterward to refresh `current.json`. +The existing `pnpm benchmark:bundle-size` command keeps its CI build graph unchanged. If the required packages are already built and unchanged, skip that step: @@ -52,7 +50,6 @@ pnpm benchmark:bundle-size:run --scenario react-router.minimal --skip-package-bu This writes: -- `benchmarks/bundle-size/results/measurements.json` - `benchmarks/bundle-size/results/current.json` - `benchmarks/bundle-size/results/benchmark-action.json` - `benchmarks/bundle-size/results/measure.log` @@ -65,29 +62,6 @@ Full stdout and stderr stay in the log files. A positive bundle-size delta does For agent runs, use `pnpm --silent benchmark:bundle-size:run ...` to omit the package-manager command echo. -### Phase Timings - -To diagnose measurement time, request a fresh run: - -```bash -pnpm benchmark:bundle-size:run --scenario react-router.minimal --analysis --timings -``` - -The runner directly executes `measure.mjs` on every invocation, rebuilding the selected scenarios and recording fresh timings in `measure.log`. Its package-build step still uses Nx and may restore cached packages. Use `--skip-package-builds` only when those packages are already built and unchanged. - -`measure.mjs` also accepts `--timings` directly. Alternatively, set `BUNDLE_SIZE_TIMINGS=1`. Timing lines go to stderr with the prefix `[bundle-size:timing]` followed by JSON containing `phase`, `durationMs`, and, for scenario phases, `scenario`. They are diagnostics only and do not add fields to the size metrics. - -The cached `pnpm benchmark:bundle-size` / Nx build path can replay terminal output from an earlier execution, including old timing lines. Setting `BUNDLE_SIZE_TIMINGS=1` does not invalidate that cache or guarantee fresh timings. Use the direct runner above for timing investigations; refreshing `current.json` after a cache hit does not remeasure build time. - -- `package-builds`: elapsed time for the package-build invocation, including Nx startup/cache handling; omitted when package builds are skipped. -- `scenario-build`: elapsed time for each scenario's build and cleanup. -- `manifest-resolution`: manifest discovery, parsing, entry selection, and collection of all/initial JS file lists. -- `gzip` / `brotli`: accumulated codec time across distinct files for each scenario, using Node's default compression settings. File reads and summation are excluded; initial files reuse already measured sizes. -- `analysis`: source attribution, when `--analysis` is enabled. -- `overall`: measurement execution through report/history writing. Module imports, process startup, and the outer runner's tests/report command are excluded. - -Phases that start also report elapsed work on failure; compression reports partial accumulated times before propagating the error. Timing records alone do not indicate success. `overall` contains the other phases, so nested timings must not be added to it. The phase breakdown also excludes overhead such as file reads and result writing, so its sum is not expected to equal `overall`. - ## Compare Optimization Candidates Before you change the implementation, save a named baseline: @@ -114,8 +88,6 @@ Without `--name`, runs replace `current.json` and the logs for the steps they ru Emitted bundles still use the shared `dist/` directory. To retain emitted bundles for a candidate, pass a separate `--dist-dir`. `--baseline` accepts a run name or a JSON file path, such as `--baseline ./baseline.json`. -With `--scenario`, the comparison reports only the scenarios measured in the current run, even when the baseline contains more scenarios. Selected scenarios missing from the baseline remain visible with `n/a` for their baseline and deltas. -Without `--scenario`, comparisons include scenarios from either result file. `--results-dir ` changes the results root, including the location of named runs. Use the same scenario selection and measurement flags for the baseline and candidate. @@ -133,8 +105,6 @@ pnpm benchmark:bundle-size:diff --baseline /tmp/base-current.json --id react-rou pnpm benchmark:bundle-size:history --id react-router.minimal --top-deltas 20 ``` -Use `pnpm benchmark:bundle-size:diff --baseline /tmp/base-current.json --current-only` to compare only scenarios present in the current results. This applies to both text and `--json` output; an explicit `--id` takes precedence. - For source attribution, run an analysis build. This uses hidden source maps and writes source estimates into `current.json`; those estimates are for investigation only, not tracking. ```bash diff --git a/benchmarks/bundle-size/package.json b/benchmarks/bundle-size/package.json index ca34cd6cd7..9decbae9da 100644 --- a/benchmarks/bundle-size/package.json +++ b/benchmarks/bundle-size/package.json @@ -3,30 +3,13 @@ "private": true, "type": "module", "scripts": { - "measure": "node ../../scripts/benchmarks/bundle-size/measure.mjs --skip-package-builds --measurements-only", - "test:unit": "node --test ../../scripts/benchmarks/bundle-size/pr-report.test.mjs ../../scripts/benchmarks/bundle-size/run.test.mjs ../../scripts/benchmarks/bundle-size/report.test.mjs ../../scripts/benchmarks/bundle-size/build.test.mjs ../../scripts/benchmarks/bundle-size/compress.test.mjs ../../scripts/benchmarks/bundle-size/timings.test.mjs" + "build": "node ../../scripts/benchmarks/bundle-size/measure.mjs --skip-package-builds", + "test:unit": "node --test ../../scripts/benchmarks/bundle-size/pr-report.test.mjs ../../scripts/benchmarks/bundle-size/run.test.mjs" }, "nx": { "targets": { - "measure": { - "cache": true, - "inputs": [ - "buildProduction", - "^buildProduction", - "dependentTaskOutputs", - "{workspaceRoot}/scripts/benchmarks/bundle-size/measure.mjs", - "{workspaceRoot}/scripts/benchmarks/bundle-size/compress.mjs", - "{workspaceRoot}/scripts/benchmarks/bundle-size/timings.mjs", - "{workspaceRoot}/scripts/benchmarks/bundle-size/report.mjs", - { - "runtime": "node --version" - } - ], - "outputs": [ - "{projectRoot}/dist", - "{projectRoot}/results/measurements.json", - "{projectRoot}/results/benchmark-action.json" - ], + "build": { + "cache": false, "dependsOn": [ { "projects": [ @@ -68,7 +51,7 @@ "vue": "^3.5.16" }, "devDependencies": { - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-react": "^2.0.0", "@tanstack/router-plugin": "workspace:^", "@types/react": "^19.0.8", diff --git a/benchmarks/bundle-size/scenarios/vue-router-full/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/vue-router-full/src/routes/__root.tsx index 0ff40aebfc..d696063083 100644 --- a/benchmarks/bundle-size/scenarios/vue-router-full/src/routes/__root.tsx +++ b/benchmarks/bundle-size/scenarios/vue-router-full/src/routes/__root.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { Asset, Await, @@ -46,151 +45,143 @@ import { useTags, } from '@tanstack/vue-router' -const RootComponent = defineComponent({ - setup() { - const router = useRouter() - const [awaited] = useAwaited({ promise: Promise.resolve('ready') }) - const linkProps = useLinkProps({ to: '/' } as any) - const matchRoute = useMatchRoute() - const matches = useMatches() - const parentMatches = useParentMatches() - const childMatches = useChildMatches() - const match = useMatch({ strict: false, shouldThrow: false } as any) - const loaderDeps = useLoaderDeps({ strict: false } as any) - const loaderData = useLoaderData({ strict: false } as any) - const params = useParams({ strict: false } as any) - const search = useSearch({ strict: false } as any) - const routeContext = useRouteContext({ strict: false } as any) - const routerState = useRouterState({ - select: (state) => state.status, - } as any) - const location = useLocation() - const canGoBack = useCanGoBack() - const navigate = useNavigate() - const scrollEntry = useElementScrollRestoration({ id: 'root-scroll' }) - const tags = useTags() - - useBlocker({ - shouldBlockFn: () => false, - disabled: true, - withResolver: false, - }) - - const linkFactoryResult = linkOptions({ to: '/' } as any) - const routeMatchResult = matchRoute({ to: '/' } as any) - const SvgLink = createLink('svg') - - const hooksAndComponents = [ - useAwaited, - useLinkProps, - useMatchRoute, - useMatches, - useParentMatches, - useChildMatches, - useMatch, - useLoaderDeps, - useLoaderData, - useBlocker, - useNavigate, - useParams, - useSearch, - useRouteContext, - useRouter, - useRouterState, - useLocation, - useCanGoBack, - useElementScrollRestoration, - useTags, - Await, - CatchBoundary, - CatchNotFound, - ClientOnly, - DefaultGlobalNotFound, - ErrorComponent, - Link, - Match, - MatchRoute, - Matches, - Navigate, - Outlet, - RouterContextProvider, - ScrollRestoration, - Block, - ScriptOnce, - Asset, - HeadContent, - Scripts, - Body, - Html, - ] - - ;(globalThis as any).__TANSTACK_BUNDLE_SIZE_KEEP__ = { - hooksAndComponents, - } - - return () => { - void awaited - void linkFactoryResult - void matches.value - void parentMatches.value - void childMatches.value - void match.value - void loaderDeps.value - void loaderData.value - void params.value - void search.value - void routeContext.value - void routerState.value - void location.value - void canGoBack.value - void navigate - void scrollEntry - void tags() - void routeMatchResult.value - - return ( - <> - - {'window.__tsr_bundle_size = true'} - - home - - - - - {() => } - - }> - - - } - /> - false} disabled withResolver={false}> - {() => } - - }> - - - - - - - - -
-
hello world
-
- - ) - } - }, -}) - export const Route = createRootRoute({ component: RootComponent, }) + +function RootComponent() { + const router = useRouter() + const [awaited] = useAwaited({ promise: Promise.resolve('ready') }) + const linkProps = useLinkProps({ to: '/' } as any) + const matchRoute = useMatchRoute() + const matches = useMatches() + const parentMatches = useParentMatches() + const childMatches = useChildMatches() + const match = useMatch({ strict: false, shouldThrow: false } as any) + const loaderDeps = useLoaderDeps({ strict: false } as any) + const loaderData = useLoaderData({ strict: false } as any) + const params = useParams({ strict: false } as any) + const search = useSearch({ strict: false } as any) + const routeContext = useRouteContext({ strict: false } as any) + const routerState = useRouterState({ select: (state) => state.status } as any) + const location = useLocation() + const canGoBack = useCanGoBack() + const navigate = useNavigate() + const scrollEntry = useElementScrollRestoration({ id: 'root-scroll' }) + const tags = useTags() + + useBlocker({ + shouldBlockFn: () => false, + disabled: true, + withResolver: false, + }) + + const linkFactoryResult = linkOptions({ to: '/' } as any) + const routeMatchResult = matchRoute({ to: '/' } as any) + const SvgLink = createLink('svg') + + const hooksAndComponents = [ + useAwaited, + useLinkProps, + useMatchRoute, + useMatches, + useParentMatches, + useChildMatches, + useMatch, + useLoaderDeps, + useLoaderData, + useBlocker, + useNavigate, + useParams, + useSearch, + useRouteContext, + useRouter, + useRouterState, + useLocation, + useCanGoBack, + useElementScrollRestoration, + useTags, + Await, + CatchBoundary, + CatchNotFound, + ClientOnly, + DefaultGlobalNotFound, + ErrorComponent, + Link, + Match, + MatchRoute, + Matches, + Navigate, + Outlet, + RouterContextProvider, + ScrollRestoration, + Block, + ScriptOnce, + Asset, + HeadContent, + Scripts, + Body, + Html, + ] + + ;(globalThis as any).__TANSTACK_BUNDLE_SIZE_KEEP__ = { + hooksAndComponents, + } + + void awaited + void linkFactoryResult + void matches.value + void parentMatches.value + void childMatches.value + void match.value + void loaderDeps.value + void loaderData.value + void params.value + void search.value + void routeContext.value + void routerState.value + void location.value + void canGoBack.value + void navigate + void scrollEntry + void tags() + void routeMatchResult.value + + return ( + <> + + {'window.__tsr_bundle_size = true'} + + home + + + + {() => } + }> + + + } + /> + false} disabled withResolver={false}> + {() => } + + }> + + + + + + + + +
+
hello world
+
+ + ) +} diff --git a/benchmarks/bundle-size/scenarios/vue-start-full/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/vue-start-full/src/routes/__root.tsx index 8e8870a2ce..aa0539fa1a 100644 --- a/benchmarks/bundle-size/scenarios/vue-start-full/src/routes/__root.tsx +++ b/benchmarks/bundle-size/scenarios/vue-start-full/src/routes/__root.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { Asset, Await, @@ -69,159 +68,151 @@ const helloServerFn = createServerFn({ method: 'GET' }) return 'hello from server fn' }) -const RootComponent = defineComponent({ - setup() { - const router = useRouter() - const [awaited] = useAwaited({ promise: Promise.resolve('ready') }) - const linkProps = useLinkProps({ to: '/' } as any) - const matchRoute = useMatchRoute() - const matches = useMatches() - const parentMatches = useParentMatches() - const childMatches = useChildMatches() - const match = useMatch({ strict: false, shouldThrow: false } as any) - const loaderDeps = useLoaderDeps({ strict: false } as any) - const loaderData = useLoaderData({ strict: false } as any) - const params = useParams({ strict: false } as any) - const search = useSearch({ strict: false } as any) - const routeContext = useRouteContext({ strict: false } as any) - const routerState = useRouterState({ - select: (state) => state.status, - } as any) - const location = useLocation() - const canGoBack = useCanGoBack() - const navigate = useNavigate() - const scrollEntry = useElementScrollRestoration({ id: 'root-scroll' }) - const tags = useTags() - const invokeServerFn = useServerFn(helloServerFn) - - useBlocker({ - shouldBlockFn: () => false, - disabled: true, - withResolver: false, - }) - - const linkFactoryResult = linkOptions({ to: '/' } as any) - const routeMatchResult = matchRoute({ to: '/' } as any) - const SvgLink = createLink('svg') - - const startSurface = [createMiddleware, createServerFn, useServerFn] - const hooksAndComponents = [ - useAwaited, - useLinkProps, - useMatchRoute, - useMatches, - useParentMatches, - useChildMatches, - useMatch, - useLoaderDeps, - useLoaderData, - useBlocker, - useNavigate, - useParams, - useSearch, - useRouteContext, - useRouter, - useRouterState, - useLocation, - useCanGoBack, - useElementScrollRestoration, - useTags, - Await, - CatchBoundary, - CatchNotFound, - ClientOnly, - DefaultGlobalNotFound, - ErrorComponent, - Link, - Match, - MatchRoute, - Matches, - Navigate, - Outlet, - RouterContextProvider, - ScrollRestoration, - Block, - ScriptOnce, - Asset, - HeadContent, - Scripts, - Body, - Html, - ] - - ;(globalThis as any).__TANSTACK_BUNDLE_SIZE_KEEP__ = { - hooksAndComponents, - startSurface, - } - - return () => { - void awaited - void linkFactoryResult - void matches.value - void parentMatches.value - void childMatches.value - void match.value - void loaderDeps.value - void loaderData.value - void params.value - void search.value - void routeContext.value - void routerState.value - void location.value - void canGoBack.value - void navigate - void scrollEntry - void tags() - void routeMatchResult.value - void invokeServerFn - - return ( - - - - - - {'window.__tsr_bundle_size = true'} - - home - - - - - {() => } - - }> - - - } - /> - false} disabled withResolver={false}> - {() => } - - }> - - - - - - - - -
-
hello world
-
- - - ) - } - }, -}) - export const Route = createRootRoute({ component: RootComponent, }) + +function RootComponent() { + const router = useRouter() + const [awaited] = useAwaited({ promise: Promise.resolve('ready') }) + const linkProps = useLinkProps({ to: '/' } as any) + const matchRoute = useMatchRoute() + const matches = useMatches() + const parentMatches = useParentMatches() + const childMatches = useChildMatches() + const match = useMatch({ strict: false, shouldThrow: false } as any) + const loaderDeps = useLoaderDeps({ strict: false } as any) + const loaderData = useLoaderData({ strict: false } as any) + const params = useParams({ strict: false } as any) + const search = useSearch({ strict: false } as any) + const routeContext = useRouteContext({ strict: false } as any) + const routerState = useRouterState({ select: (state) => state.status } as any) + const location = useLocation() + const canGoBack = useCanGoBack() + const navigate = useNavigate() + const scrollEntry = useElementScrollRestoration({ id: 'root-scroll' }) + const tags = useTags() + const invokeServerFn = useServerFn(helloServerFn) + + useBlocker({ + shouldBlockFn: () => false, + disabled: true, + withResolver: false, + }) + + const linkFactoryResult = linkOptions({ to: '/' } as any) + const routeMatchResult = matchRoute({ to: '/' } as any) + const SvgLink = createLink('svg') + + const startSurface = [createMiddleware, createServerFn, useServerFn] + const hooksAndComponents = [ + useAwaited, + useLinkProps, + useMatchRoute, + useMatches, + useParentMatches, + useChildMatches, + useMatch, + useLoaderDeps, + useLoaderData, + useBlocker, + useNavigate, + useParams, + useSearch, + useRouteContext, + useRouter, + useRouterState, + useLocation, + useCanGoBack, + useElementScrollRestoration, + useTags, + Await, + CatchBoundary, + CatchNotFound, + ClientOnly, + DefaultGlobalNotFound, + ErrorComponent, + Link, + Match, + MatchRoute, + Matches, + Navigate, + Outlet, + RouterContextProvider, + ScrollRestoration, + Block, + ScriptOnce, + Asset, + HeadContent, + Scripts, + Body, + Html, + ] + + ;(globalThis as any).__TANSTACK_BUNDLE_SIZE_KEEP__ = { + hooksAndComponents, + startSurface, + } + + void awaited + void linkFactoryResult + void matches.value + void parentMatches.value + void childMatches.value + void match.value + void loaderDeps.value + void loaderData.value + void params.value + void search.value + void routeContext.value + void routerState.value + void location.value + void canGoBack.value + void navigate + void scrollEntry + void tags() + void routeMatchResult.value + void invokeServerFn + + return ( + + + + + + {'window.__tsr_bundle_size = true'} + + home + + + + {() => } + }> + + + } + /> + false} disabled withResolver={false}> + {() => } + + }> + + + + + + + + +
+
hello world
+
+ + + ) +} diff --git a/benchmarks/client-nav/README.md b/benchmarks/client-nav/README.md index ec34ecc0c1..6179c7f0b8 100644 --- a/benchmarks/client-nav/README.md +++ b/benchmarks/client-nav/README.md @@ -9,11 +9,10 @@ Cross-framework client-side CPU benchmarks for: The benchmarks run in jsdom against production builds of real apps, and are tracked in CI by CodSpeed (simulation mode). -> **Scope:** these benchmarks cover the client router. The hydration -> scenarios also cover DOM hydration and the Router state-restoration path -> used by Start. Start-specific entry-point initialization, streamed payload -> arrival and client server-function calls are not included. Server request work -> is covered by `benchmarks/ssr`. +> **Scope:** these benchmarks cover the standalone client router only. The +> client side of TanStack Start (hydration of a server-rendered document, +> streamed payload consumption, server-function calls from the client, ...) is +> not covered here; the server side of Start is covered by `benchmarks/ssr`. ## Layout @@ -39,7 +38,7 @@ scenarios/// routes/ ``` -Navigation scenario apps use file-based routing (`@tanstack/router-plugin`) with a +Scenario apps use file-based routing (`@tanstack/router-plugin`) with a generated `routeTree.gen.ts`, like a regular user app. Each scenario uses one app per framework instead of sharing routes in the baseline app. This keeps route-tree size and router options isolated so one scenario cannot shift @@ -58,11 +57,9 @@ be attributed to a specific feature area. | `control-flow` | Loader-thrown `redirect` (including a 2-hop chain), `notFound()` with `notFoundComponent`, loader errors with `errorComponent`, and boundary reset on recovery navigation. | | `head` | `HeadContent` per-navigation work: nested route `head()` evaluation, title/meta/link dedupe across matches, and head tag DOM updates during navigation. | | `history` | History push/replace/back/forward traversal, location masking, registered-but-never-blocking `useBlocker`, and `useCanGoBack`/`useLocation` subscriptions. | -| `hydration` | Initial DOM hydration: execute the SSR payload, restore `beforeLoad` context and loader data, and hydrate 192 ordinary and eight hash-sensitive Links through their follow-up effects in React and Solid. | -| `link-churn` | Links that depart, stay and mount: 30 `/hub` layout Links stay while 100 `/hub/list` leaf Links leave (alone, or with the layout to `/other`) and remount on return; a search-only change rebuilds updater and `to="."` Links. Unlike `links`, whose root-layout Links never depart. | | `links` | Per-navigation cost of ~200 mounted ``s: link prop building, active-state recompute across `activeOptions` variants, `activeProps` swaps, and `useMatchRoute` probes (the `MatchRoute` component is avoided: vue-router's implementation leaks one subscription per render). | | `loaders` | Client loader dispatch: always-stale re-runs (`staleTime: 0`), cached revisits (re-run once per lap by the `invalidate` step), `loaderDeps`-keyed caching, `router.invalidate()`, and `useLoaderData` selectors. | -| `mount` | Cold start: `createRouter` (route-tree processing) + first render + initial `router.load()` + unmount, with a fresh router per mount. | +| `mount` | Cold start: `createRouter` (route-tree processing) + first render + initial `router.load()` + unmount, with a fresh router per mount. The only scenario measuring router creation. | | `nested-params` | Deep nesting (8 dynamic levels): per-level `params.parse`/`stringify`, `beforeLoad` context accumulation across matches, and per-level `useParams`/`useRouteContext` subscriptions. Param values include characters requiring percent-encoding (as do `route-tree-scale`'s), so segment encode/decode paths run on every navigation. | | `preload` | Intent preloading from hover events, programmatic `router.preloadRoute`, deterministic preload cache behavior (`defaultPreloadStaleTime: 0`), and commit-time cache maintenance. | | `rewrites` | Composed client-side location rewrites: router `basepath` plus a locale input/output rewrite pair, running on every href build and location parse (the client analog of the SSR `rewrites` scenario). | @@ -71,14 +68,10 @@ be attributed to a specific feature area. ## Conventions -The hydration scenario has the separate lifecycle described below. The other -scenarios follow these navigation/mount conventions: - - Apps are built with `NODE_ENV=production` (`minify: false`) into `dist/app.js`; benches import the built bundle, so production package builds and production JSX output are measured, not dev transforms. - Scenarios behave like a real user app: navigation happens through `` clicks dispatched on real anchor elements (unless a scenario specifically measures the imperative API), the router uses the default browser history, and `scrollRestoration` is enabled. - Each benchmark iteration advances a fixed, circular sequence of steps; every step awaits the router's `onRendered` event, so render work is included and steps cannot overlap. No two consecutive steps may target the same location, and the sequence ends back on the initial route. - Setup runs one warm-up lap through the sequence and asserts each step's observable output (e.g. `document.title`), so a scenario that silently stops doing its work fails instead of reporting a fast time. -- Apps are mounted and disposed outside timing by `benchLifecycle` (`benchmarks/cpu-simulation.ts`): CodSpeed measures a single invocation, so every invocation gets a freshly mounted app; plain `vitest bench` keeps one app per warmup/run phase. Bench functions must be `async` functions, because CodSpeed's Vitest 5 provider awaits only `AsyncFunction`s. - Determinism: no wall-clock timers (async work is resolved promises or counted `setTimeout(0)` hops), `staleTime`/`gcTime` only ever `0` or effectively-infinite, no `Math.random`/`Date.now` in the measured loop. Scroll restoration uses `getScrollRestorationKey: (location) => location.pathname` so its cache stays bounded (the default random per-entry key grows one cache entry per push navigation). The `mount` scenario opts out of `scrollRestoration` entirely and destroys its history on unmount — both register page-lifetime globals that would leak across its mount/unmount loop. - Push-only step laps grow jsdom's session-history entry list over a run (jsdom never truncates entries behind the current index). Per-push cost stays O(1) so timings are unaffected; only the `history` scenario needs — and has — a lap that is depth-stationary. - Calibration: pick per-iteration step counts so a bench's `vitest bench` run stays roughly between 8 and 30 seconds (long enough to average out, short enough for CI). @@ -103,7 +96,7 @@ Run a single scenario app manually (after building it through Nx): ```bash CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav--:build:client --outputStyle=stream --skipRemoteCache -cd benchmarks/client-nav && NODE_ENV=production vitest bench --mode benchmark --config ./scenarios///vite.config.ts +cd benchmarks/client-nav && NODE_ENV=production vitest bench --config ./scenarios///vite.config.ts ``` Run framework-specific flame benchmarks (10 second loop, profiled with `@platformatic/flame`, forced to `NODE_ENV=production`): @@ -122,186 +115,3 @@ Typecheck benchmark sources (baseline + scenarios): ```bash CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:types --outputStyle=stream --skipRemoteCache ``` - -## Hydration - -`scenarios/hydration/{react,solid}` provide the same initial-hydration -workload: 192 ordinary Links, eight hash-sensitive Links, and three matched -routes with three `beforeLoad` contexts and two loader results. The server URL -has no fragment; the client URL has `#details`, matching half of the hash-sensitive Links. - -```bash -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav-hydration-react:test:perf --outputStyle=stream --skipRemoteCache -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav-hydration-react:test:unit --outputStyle=stream --skipRemoteCache -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav-hydration-react:test:types:client --outputStyle=stream --skipRemoteCache -``` - -Replace `react` with `solid` to run the other adapter. - -The build generates static HTML and its real Router SSR bootstrap scripts once -with `createRequestHandler` and the adapter's streaming renderer. Generation -fully consumes the response and runs outside the CodSpeed action. The measured -worker only reads these artifacts; it does not import a server renderer or start a server. - -Each invocation uses a fresh jsdom window and a fresh evaluation of the complete -production client bundle in that window's realm. HTML parsing, bundle evaluation, -and the initial document lifecycle finish in untimed setup. This resets module -state as well as the DOM, avoiding cached hydration promises and cross-realm -payload objects. The bundle and bootstrap scripts are compiled once, so this -measures a fresh application with warm code, not JavaScript download/parse cost. - -The timed region executes the serialized payload, creates the router and its -small code-based route tree, calls the public client `hydrate` API, and hydrates -the existing DOM with the framework's native renderer: - -- **React:** a separate completion component signals from its post-hydration - effect, after the same snapshot transition as hash-sensitive Links. The harness - awaits that signal and two idle React scheduler turns, then checks the expected - active links. The window's `performance.now()` is frozen, so React's - scheduler yields only to paint after commits, not after 5 ms of wall time, which CPU - instrumentation stretches by a runner-dependent factor. Each sample therefore - uses the same number of scheduler tasks. `Date.now()` is unchanged. A - 60-second watchdog fails a sample that never settles. -- **Solid:** execute the native hydration bootstrap and retain the server's - component/key hierarchy. Wait for mount, the router's rendered event, active-link - effects, and two idle turns. DOM identity assertions include every workload - element so template fallback cannot silently replace server nodes. - -Solid bounds settlement to 100 turns. Ending at the hydration call or the -first mount would miss post-hydration Link updates. -Timer turns use `setImmediate`; scrolling is a no-op -because this is CPU simulation rather than browser layout/paint measurement. - -Untimed assertions verify restored contexts and every loader row, zero client -`beforeLoad`/loader calls, expected hrefs/active state, original DOM-node identity, -working event handlers, and absence of hydration errors. Root unmount, pending -task cancellation, and window disposal also run outside measurement. Diagnostic -tests count Link renders or reactive evaluations and check they stop before the -measured region ends; counting is disabled in the timed workload. - -The bench's own `beforeEach`/`afterEach` hooks prepare and dispose every -sample outside timing, in both CodSpeed and ordinary Vitest runs. Per-phase -setup would let later iterations reuse an already hydrated document. The -hydration unit tests cover repeated fresh-state setup. - -Each scenario is included in its framework's aggregate build and CodSpeed run. -Land the benchmark independently to establish main's baseline before comparing a -hydration optimization. Regenerate each revision's artifacts with identical -fixture data and dependencies; do not pin an old hydration wire format forever. - -## Isolated route-tree construction - -`scenarios/route-tree-scale` measures navigation over an existing tree, not -construction. `scenarios/mount` includes construction but also rendering and -loading. To isolate initialization, use the core construction benchmark: - -```bash -CI=1 NX_DAEMON=false pnpm nx run @tanstack/router-core:test:unit --outputStyle=stream --skipRemoteCache -- bench tests/route-tree-construction.bench.ts --run --testNamePattern=1000.routes --reporter=json --outputFile=/tmp/route-tree-construction.json -``` - -It covers 100, 1,000, and 10,000 static, dynamic, nested, or mixed routes. -The processing-only case creates fresh route objects in an untimed -`beforeEach`, then measures `processRouteTree` and `route.init`. A separate -case includes route-object creation. Neither case measures first interpolation -or navigation. Remove the name filter to run all sizes. Compare identical -benchmark sources in separate checkouts and repeat fresh processes; a cached -router or repeatedly initialized tree is not a construction baseline. - -## Opt-in React Link performance suite - -`link-performance/` contains additional client-navigation and SSR workloads for -focused Link work. They are **not included** in the regular client-nav/SSR -aggregate projects or their CodSpeed build dependencies; they only run through -the dedicated `@benchmarks/react-link-performance` targets below. Use `-t` to -narrow a run to specific cases. - -```bash -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/react-link-performance:test:perf:client --outputStyle=stream --skipRemoteCache -- --run -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/react-link-performance:test:perf:ssr --outputStyle=stream --skipRemoteCache -- --run - -# Select a feature and save the normal Vitest JSON report. -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/react-link-performance:test:perf:client --outputStyle=stream --skipRemoteCache -- --run -t "updater|optional|splat" --reporter=json --outputFile=/tmp/link-perf.json -``` - -The cases cover repeated versus unique destination params, updater functions, -relative/inherited values, search middleware chains, param stringification, -optional and splat segments, encoding, masks, basepath/rewrites, and active -props with structured search. These exercise different costs: cache hits and -misses, parameter cloning, callbacks, middleware traversal, URI encoding, -building masked/public locations, active-state comparisons, and prop merging. -Existing preload, mount, and route-tree-scale scenarios remain responsible for -those separate workloads. - -- **Client:** 200 persistent measured Links, four control Links, and eight - completed navigations per timed batch. The existing client harness checks - hrefs and active state during its untimed warm-up lap. Control navigations - replace the history entry, keeping history size constant. Post-measurement - assertions also check that the measured anchors stayed mounted. -- **SSR:** four fresh-router requests per timed batch, each rendering 200 - measured Links through `RouterProvider` and `renderToString`. Router creation, - `router.load()`, rendering, and history cleanup are included. This isolates - Router SSR Link work, not Start HTTP handling, dehydration, or streaming. - HTML assertions run outside the timed batch. -- Both use the same code-based workload definitions and production JSX/library - builds. The regular Vitest entry points use at least 100 warm-up iterations, - one second of warm-up time, and five-second measurement windows. The client - and server bundles assert their resolved `isServer` environment. React and - React DOM remain external so comparisons can share the same renderer runtime. - These bundles are Node-hosted (jsdom for client mode), not browser deployments. - -Run the gate tests and typecheck separately: - -```bash -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/react-link-performance:test:unit --outputStyle=stream --skipRemoteCache -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/react-link-performance:test:types --outputStyle=stream --skipRemoteCache -``` - -For before/after comparisons, use identical benchmark files and dependencies -on both refs, build each ref through its Nx targets, and alternate fresh -Vitest processes. Report the actual refs, per-case means and relative margins -of error; rerun noisy or borderline results with `-t` rather than interpreting -a small difference as a proven speedup. Client and SSR times have different -batch units and should not be compared directly. - -### Stable paired comparisons - -For regression decisions, prefer the paired runner over a whole-file Vitest -run. It starts a fresh process for every case and repetition, avoiding JIT -feedback from earlier cases. Inside each process, both revisions share the -same production React installation but have separate router/app modules and -router instances. Initialization order alternates between repetitions. -Built snapshots are staged under `node_modules/.cache` so the TypeScript -harness loader does not transpile their emitted JavaScript a second time. - -```bash -# Build the baseline using these same benchmark sources in its own checkout. -# --baseline points to that checkout's link-performance/dist directory. -pnpm nx run @benchmarks/react-link-performance:test:perf:stable -- \ - --baseline /path/to/baseline/benchmarks/client-nav/link-performance/dist \ - --outputJson /tmp/paired-links.json - -# Narrow a comparison, or increase independent process repetitions. -pnpm nx run @benchmarks/react-link-performance:test:perf:stable -- \ - --baseline /path/to/baseline/benchmarks/client-nav/link-performance/dist \ - --mode ssr -t "middleware|unique-params" --repeats 6 \ - --outputJson /tmp/paired-links-ssr.json -``` - -The runner requires Node with `process.threadCpuUsage` (Node 24 works). -It fixes V8 random/hash seeds, warms each variant for at least two seconds -and 100 batches, then alternates ABBA/BAAB blocks calibrated to roughly 500 ms. -Both variants do exactly the same number of batches per block. It records -main-thread CPU time, wall time, and whole-process CPU time; GC during -measurement is not disabled or discarded. - -The default is four independent process repetitions. Reported 95% intervals -use their paired log-ratios, not the many correlated batches as independent -samples. A faster/slower verdict requires CPU and wall intervals to agree. -Intervals overlapping zero or disagreeing metrics are inconclusive; narrow -intervals entirely inside +/-2% are reported separately. - -An A/A calibration uses the current `dist` directory as `--baseline`. Its -intervals should contain zero before trusting similarly sized A/B differences. -Shared-machine contention can still make small changes unresolved. Do not -interpret a point estimate alone, or an inconclusive result, as proof that -a workload is unchanged. diff --git a/benchmarks/client-nav/link-performance/cases.ts b/benchmarks/client-nav/link-performance/cases.ts deleted file mode 100644 index a25eac563b..0000000000 --- a/benchmarks/client-nav/link-performance/cases.ts +++ /dev/null @@ -1,360 +0,0 @@ -export const LINK_CASES = [ - { - id: 'shared-params', - label: 'Shared string params', - description: '200 persistent Links reuse 40 string parameter values.', - }, - { - id: 'unique-params', - label: 'Unique string params', - description: '200 distinct parameter values exceed the 128-result cache.', - }, - { - id: 'param-updaters', - label: 'Parameter updaters', - description: 'Parameter functions derive destinations from current params.', - }, - { - id: 'location-updaters', - label: 'Search, hash and state updaters', - description: - 'Functions derive search, hash and history state from the source.', - }, - { - id: 'relative', - label: 'Relative targets', - description: 'Parent and child targets inherit current params and search.', - }, - { - id: 'middleware', - label: 'Search middleware chain', - description: - 'Retain a tenant, strip a default page and normalize a filter.', - }, - { - id: 'numeric-params', - label: 'Numeric params', - description: 'Parse numbers, update them numerically and stringify them.', - }, - { - id: 'optional-params', - label: 'Optional segments', - description: 'Set, inherit and explicitly clear an optional path segment.', - }, - { - id: 'splats', - label: 'Splat params', - description: 'Empty, multi-segment and encoded splat values.', - }, - { - id: 'encoding', - label: 'Allowed path characters', - description: 'Preserve allowed @, : and + while encoding other characters.', - }, - { - id: 'masks', - label: 'Explicit route masks', - description: - 'Build a different public path and search for each destination.', - }, - { - id: 'rewrites', - label: 'Basepath and rewrites', - description: 'Compose /app with input/output locale path rewrites.', - }, - { - id: 'active', - label: 'Active props and structured search', - description: - 'Exact, fuzzy and search matching with props and render children.', - }, -] as const - -export type LinkCaseId = (typeof LINK_CASES)[number]['id'] - -export const LINK_COUNT = 200 -export const NAVIGATION_STATES = [1, 2, 3, 0] as const -export const LOCALES = ['en', 'fr', 'de', 'es'] as const - -export interface Filter { - tag: string - flags: { open: boolean } - tags: Array -} - -export interface LinkSearch { - page?: number - tenant?: string - filter?: Filter -} - -export function sourceFilter(index: number): Filter { - return { - tag: `group-${index}`, - flags: { open: index % 2 === 0 }, - tags: ['links', `state-${index}`], - } -} - -export function sourceSearch( - caseId: LinkCaseId, - stateIndex: number, -): Partial { - switch (caseId) { - case 'location-updaters': - case 'relative': - case 'middleware': - case 'active': - return { - page: stateIndex + 1, - tenant: `tenant-${stateIndex}`, - filter: sourceFilter(stateIndex), - } - case 'rewrites': - return { tenant: LOCALES[stateIndex] } - default: - return {} - } -} - -export function optionalCategory(stateIndex: number) { - return stateIndex % 2 === 0 ? `category-${stateIndex}` : undefined -} - -export function splatValue(index: number) { - switch (index % 4) { - case 0: - return '' - case 1: - return `folder/sub/file-${index % 40}` - case 2: - return 'a b/100%/caf\u00e9?#' - default: - return 'literal%2F/\u{1f680}' - } -} - -export function encodedValue(index: number) { - return `user-${index % 40}@mail.test:tag+value /?#% caf\u00e9` -} - -function url(pathname: string, search: Partial = {}, hash = '') { - const result = new URL(pathname, 'http://localhost') - for (const [key, value] of Object.entries( - search, - )) { - if (value !== undefined) { - result.searchParams.set( - key, - typeof value === 'object' ? JSON.stringify(value) : String(value), - ) - } - } - result.hash = hash - return result.pathname + result.search + result.hash -} - -function sourcePath(caseId: LinkCaseId, stateIndex: number) { - switch (caseId) { - case 'relative': - return `/teams/team-${stateIndex}/item-${stateIndex}` - case 'numeric-params': - return `/numbers/${stateIndex}` - case 'optional-params': { - const category = optionalCategory(stateIndex) - return `/optional/${category ? `${category}/` : ''}item-${stateIndex}` - } - case 'splats': - return `/files/source/state-${stateIndex}` - case 'encoding': - return `/encoded/source-${stateIndex}` - case 'active': - return `/items/item-${stateIndex}/details` - default: - return `/items/item-${stateIndex}` - } -} - -export function getSourceUrl(caseId: LinkCaseId, stateIndex: number): string { - if (!Number.isInteger(stateIndex) || stateIndex < 0 || stateIndex > 3) { - throw new Error(`Invalid Link performance state: ${stateIndex}`) - } - const pathname = sourcePath(caseId, stateIndex) - if (caseId === 'rewrites') { - return `/app/${LOCALES[stateIndex]}${pathname}` - } - return url( - pathname, - sourceSearch(caseId, stateIndex), - caseId === 'location-updaters' ? `source-${stateIndex}` : '', - ) -} - -// These expectations use fixture values and platform encoding, not router APIs. -function expectedHref(caseId: LinkCaseId, stateIndex: number, index: number) { - const itemId = `item-${index % 40}` - switch (caseId) { - case 'shared-params': - return `/items/${itemId}` - case 'unique-params': - return `/items/item-${index}` - case 'param-updaters': - return `/items/item-${stateIndex}-related-${index % 40}` - case 'location-updaters': - return url( - `/items/item-${stateIndex}`, - { - ...sourceSearch(caseId, stateIndex), - page: stateIndex + 2 + (index % 5), - }, - `source-${stateIndex}-link-${index % 5}`, - ) - case 'relative': - return url( - index % 2 === 0 - ? `/teams/team-${stateIndex}` - : `/teams/team-${stateIndex}/item-${stateIndex}/details`, - sourceSearch(caseId, stateIndex), - ) - case 'middleware': - return url(`/filtered/${itemId}`, { - tenant: `tenant-${stateIndex}`, - page: index % 2 === 0 ? undefined : 2, - filter: { ...sourceFilter(index % 4), tag: `LABEL-${index % 40}` }, - }) - case 'numeric-params': - return `/numbers/${stateIndex + (index % 40)}` - case 'optional-params': { - const category = - index % 3 === 0 - ? 'fixed' - : index % 3 === 1 - ? optionalCategory(stateIndex) - : undefined - return `/optional/${category ? `${category}/` : ''}${itemId}` - } - case 'splats': { - const value = splatValue(index) - return `/files${value ? `/${value.split('/').map(encodeURIComponent).join('/')}` : ''}` - } - case 'encoding': { - const value = encodeURIComponent(encodedValue(index)) - .replaceAll('%40', '@') - .replaceAll('%3A', ':') - .replaceAll('%2B', '+') - return `/encoded/${value}` - } - case 'masks': - return url(`/public/display-${index % 40}`, { - tenant: `mask-${index % 4}`, - }) - case 'rewrites': - return url(`/app/${LOCALES[index % 4]}/items/${itemId}`, { - page: (index % 3) + 1, - }) - case 'active': { - const item = Math.floor(index / 5) - const variant = index % 5 - const search = - variant < 3 - ? { filter: sourceFilter(item % 4) } - : { - ...sourceSearch('active', item % 4), - ...(variant === 4 ? { filter: undefined } : {}), - } - return url(`/items/item-${item}${variant < 2 ? '' : '/details'}`, search) - } - } -} - -function assertUrl( - actualHref: string | null, - expectedHref: string, - label: string, -) { - if (actualHref === null) { - throw new Error(`${label}: missing href`) - } - const actual = new URL(actualHref, 'http://localhost') - const expected = new URL(expectedHref, 'http://localhost') - // Query ordering and the platform's '+' versus '%20' are immaterial here. - const query = (value: URL) => - JSON.stringify([...value.searchParams.entries()].sort()) - if ( - actual.origin !== expected.origin || - actual.pathname !== expected.pathname || - actual.hash !== expected.hash || - query(actual) !== query(expected) - ) { - throw new Error( - `${label}: expected ${expectedHref}, received ${actualHref}`, - ) - } -} - -export function assertScenario( - caseId: LinkCaseId, - stateIndex: number, - root: ParentNode, -): void { - const source = root.querySelector('[data-testid="source-path"]') - if (source?.textContent !== sourcePath(caseId, stateIndex)) { - throw new Error( - `${caseId}/${stateIndex}: unexpected source path ${source?.textContent}`, - ) - } - const links = root.querySelectorAll('a[data-perf-link]') - if (links.length !== LINK_COUNT) { - throw new Error( - `${caseId}: expected ${LINK_COUNT} Links, got ${links.length}`, - ) - } - for (const [index, link] of links.entries()) { - const label = `${caseId}/${stateIndex}/link-${index}` - if (link.getAttribute('data-perf-link') !== String(index)) { - throw new Error(`${label}: unexpected Link order`) - } - assertUrl( - link.getAttribute('href'), - expectedHref(caseId, stateIndex, index), - label, - ) - let active: boolean | undefined - if (caseId === 'shared-params') { - active = index % 40 === stateIndex - } else if (caseId === 'unique-params') { - active = index === stateIndex - } else if (caseId === 'active') { - active = - Math.floor(index / 5) === stateIndex && [0, 2, 3].includes(index % 5) - if ( - link.textContent !== `${index}:${active ? 'active' : 'inactive'}` || - link.getAttribute('title') !== (active ? 'active' : 'inactive') || - !link.classList.contains(active ? 'perf-active' : 'perf-inactive') || - link.style.color !== (active ? 'green' : 'gray') || - link.style.opacity !== '0.8' - ) { - throw new Error( - `${label}: active props or render children are incorrect`, - ) - } - } - if ( - active !== undefined && - (link.getAttribute('data-status') === 'active') !== active - ) { - throw new Error(`${label}: expected active=${active}`) - } - } - for (let state = 0; state < 4; state++) { - const control = root.querySelector(`[data-testid="go-state-${state}"]`) - if (!control || control.hasAttribute('data-perf-link')) { - throw new Error(`${caseId}: missing or measured control Link ${state}`) - } - assertUrl( - control.getAttribute('href'), - getSourceUrl(caseId, state), - `${caseId}/control-${state}`, - ) - } -} diff --git a/benchmarks/client-nav/link-performance/client.bench.ts b/benchmarks/client-nav/link-performance/client.bench.ts deleted file mode 100644 index f819fab52b..0000000000 --- a/benchmarks/client-nav/link-performance/client.bench.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../cpu-simulation' -import { LINK_CASES } from './cases' -import { createClientScenario, samplingOptions } from './scenario' -import type * as App from './src/client' - -const appModulePath = './dist/client/app.js' -const app: typeof App = await import(/* @vite-ignore */ appModulePath) -if (app.serverEnvironment !== false) { - throw new Error('Link client benchmarks must use the production client build') -} - -for (const { id, label } of LINK_CASES) { - test(label, async ({ bench }) => { - const scenario = createClientScenario(app, id) - function finish() { - try { - scenario.check() - } finally { - scenario.teardown() - } - } - - await bench( - `client Links: ${id}`, - benchLifecycle({ before: scenario.setup, after: finish }), - scenario.batch, - ).run(samplingOptions) - }) -} diff --git a/benchmarks/client-nav/link-performance/config.test.ts b/benchmarks/client-nav/link-performance/config.test.ts deleted file mode 100644 index 1a468a3169..0000000000 --- a/benchmarks/client-nav/link-performance/config.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { afterEach, describe, expect, test, vi } from 'vitest' -import { createLinkPerformanceConfig } from './config' - -afterEach(() => vi.unstubAllEnvs()) - -describe.each(['client', 'ssr'] as const)('%s configuration', (target) => { - test('discovers only the requested suite', () => { - const config = createLinkPerformanceConfig(target) - expect(config.test?.benchmark?.include).toEqual([`${target}.bench.ts`]) - }) - - test('builds production code for the correct environment', () => { - const config = createLinkPerformanceConfig(target) - expect(config.define?.['process.env.NODE_ENV']).toBe('"production"') - expect(config.resolve?.conditions).toContain( - target === 'ssr' ? 'node' : 'browser', - ) - expect(config.build?.ssr).toBe(target === 'ssr') - expect(config.build?.outDir).toBe(`./dist/${target}`) - expect(config.build?.rolldownOptions?.platform).toBe('node') - expect(config.build?.rolldownOptions?.external).toEqual([ - 'node:module', - 'module', - /^react(?:\/|$)/, - /^react-dom(?:\/|$)/, - ]) - }) - - test('does not retransform built bundles in the test environment', () => { - vi.stubEnv('VITEST', 'true') - const config = createLinkPerformanceConfig(target) - expect(config.ssr?.noExternal).toBeUndefined() - expect(config.test?.server?.deps?.external).toEqual([ - /\/link-performance\/dist\//, - ]) - }) - - test('bundles router dependencies when building app snapshots', () => { - vi.stubEnv('VITEST', undefined) - expect(createLinkPerformanceConfig(target).ssr?.noExternal).toBe(true) - }) -}) diff --git a/benchmarks/client-nav/link-performance/config.ts b/benchmarks/client-nav/link-performance/config.ts deleted file mode 100644 index 416b027057..0000000000 --- a/benchmarks/client-nav/link-performance/config.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { fileURLToPath } from 'node:url' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import type { UserConfig } from 'vite' - -const root = fileURLToPath(new URL('.', import.meta.url)) - -export function createLinkPerformanceConfig( - target: 'client' | 'ssr', -): UserConfig { - const server = target === 'ssr' - - return { - root, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - react(), - ], - resolve: { - conditions: [server ? 'node' : 'browser', 'production'], - }, - ssr: { - noExternal: process.env.VITEST ? undefined : true, - resolve: { - conditions: ['node', 'production'], - }, - }, - build: { - outDir: `./dist/${target}`, - emptyOutDir: true, - minify: false, - ssr: server, - lib: { - entry: `${root}src/${target}.tsx`, - formats: ['es'], - fileName: 'app', - }, - rolldownOptions: { - platform: 'node', - external: [ - 'node:module', - 'module', - /^react(?:\/|$)/, - /^react-dom(?:\/|$)/, - ], - output: { entryFileNames: 'app.js' }, - }, - }, - test: { - name: `react-link-performance-${target}`, - watch: false, - environment: server ? 'node' : 'jsdom', - setupFiles: server ? [] : ['../vitest.setup.ts'], - server: { - deps: { - external: [/\/link-performance\/dist\//], - }, - }, - include: [], - benchmark: { - include: [`${target}.bench.ts`], - }, - }, - } -} diff --git a/benchmarks/client-nav/link-performance/project.json b/benchmarks/client-nav/link-performance/project.json deleted file mode 100644 index fd1751c081..0000000000 --- a/benchmarks/client-nav/link-performance/project.json +++ /dev/null @@ -1,103 +0,0 @@ -{ - "name": "@benchmarks/react-link-performance", - "projectType": "application", - "tags": ["optional-benchmark"], - "targets": { - "build:client": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config ./link-performance/vite.client.config.ts", - "cwd": "benchmarks/client-nav" - } - }, - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config ./link-performance/vite.ssr.config.ts", - "cwd": "benchmarks/client-nav" - } - }, - "test:perf:client": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": ["build:client"], - "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./link-performance/vite.client.config.ts", - "cwd": "benchmarks/client-nav" - } - }, - "test:perf:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": ["build:ssr"], - "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./link-performance/vite.ssr.config.ts", - "cwd": "benchmarks/client-nav" - } - }, - "test:perf:stable": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": ["build:client", "build:ssr"], - "options": { - "command": "NODE_ENV=production node --import=@swc-node/register/esm-register benchmarks/client-nav/link-performance/stable-runner.ts" - } - }, - "test:unit": { - "executor": "nx:run-commands", - "inputs": [ - "...", - "{workspaceRoot}/benchmarks/client-nav/scenarios/harness.ts", - "{workspaceRoot}/benchmarks/client-nav/scenarios/links/shared.ts", - "{workspaceRoot}/benchmarks/client-nav/setup-helpers.ts", - "{workspaceRoot}/benchmarks/client-nav/tsconfig.json" - ], - "dependsOn": [ - { - "projects": ["@tanstack/history"], - "target": "build" - } - ], - "options": { - "command": "vitest run --config ./link-performance/vitest.config.ts", - "cwd": "benchmarks/client-nav" - } - }, - "test:types": { - "executor": "nx:run-commands", - "inputs": [ - "...", - "{workspaceRoot}/benchmarks/client-nav/jsdom.ts", - "{workspaceRoot}/benchmarks/client-nav/scenarios/harness.ts", - "{workspaceRoot}/benchmarks/client-nav/scenarios/links/shared.ts", - "{workspaceRoot}/benchmarks/client-nav/setup-helpers.ts", - "{workspaceRoot}/benchmarks/client-nav/tsconfig.json", - "{workspaceRoot}/benchmarks/client-nav/vitest.setup.ts" - ], - "dependsOn": [ - { - "projects": ["@tanstack/react-router"], - "target": "build" - } - ], - "options": { - "command": "tsc -p ./link-performance/tsconfig.json --noEmit", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/link-performance/scenario.ts b/benchmarks/client-nav/link-performance/scenario.ts deleted file mode 100644 index f1a3fb6df7..0000000000 --- a/benchmarks/client-nav/link-performance/scenario.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { JSDOM } from 'jsdom' -import { createScenarioSetup } from '../scenarios/harness' -import { ticksPerIteration } from '../scenarios/links/shared' -import { NAVIGATION_STATES, assertScenario, getSourceUrl } from './cases' -import type { LinkCaseId } from './cases' -import type * as ClientApp from './src/client' -import type * as SsrApp from './src/ssr' - -export interface LinkScenario { - setup: () => Promise - batch: () => Promise - check: () => void - teardown: () => void -} - -export const samplingOptions = { - warmupIterations: 100, - warmupTime: 1_000, - time: 5_000, - throws: true, -} - -export function createClientScenario( - app: typeof ClientApp, - id: LinkCaseId, -): LinkScenario { - let mounted: ReturnType | undefined - let container: HTMLElement | undefined - let anchors: Array = [] - const test = createScenarioSetup({ - frameworkLabel: 'React', - mount: (element, history) => { - container = element - mounted = app.mountTestApp(element, history, id) - return mounted - }, - initialUrl: getSourceUrl(id, 0), - steps: NAVIGATION_STATES.map((state) => `go-state-${state}`), - assertAfterStep: (index, element) => { - assertScenario(id, NAVIGATION_STATES[index]!, element) - if (!mounted) { - throw new Error('Link benchmark app was not mounted') - } - mounted.assertStateUpdates() - }, - }) - - return { - async setup() { - await test.before() - if (!container) { - throw new Error('Link benchmark container was not created') - } - anchors = [...container.querySelectorAll('a[data-perf-link]')] - }, - async batch() { - for (let index = 0; index < ticksPerIteration; index++) { - await test.tick() - } - await test.finishBatch() - }, - check() { - if (!container || !mounted) { - throw new Error('Link benchmark app was not mounted') - } - assertScenario(id, 0, container) - mounted.assertStateUpdates() - if (mounted.router.history.length !== 1) { - throw new Error('Link benchmark history must remain bounded') - } - const current = container.querySelectorAll('a[data-perf-link]') - if (anchors.some((anchor, index) => current[index] !== anchor)) { - throw new Error('Measured Links must stay mounted across navigations') - } - }, - teardown: test.after, - } -} - -export function createSsrScenario( - app: typeof SsrApp, - id: LinkCaseId, -): LinkScenario { - let html = '' - let state = 0 - function check() { - const dom = new JSDOM(html) - try { - assertScenario(id, state, dom.window.document) - } finally { - dom.window.close() - } - } - - return { - async setup() { - for (const nextState of NAVIGATION_STATES) { - state = nextState - html = await app.renderScenario(id, state, true) - check() - } - }, - async batch() { - for (const nextState of NAVIGATION_STATES) { - state = nextState - html = await app.renderScenario(id, state) - } - }, - check, - teardown() { - html = '' - }, - } -} diff --git a/benchmarks/client-nav/link-performance/src/client.tsx b/benchmarks/client-nav/link-performance/src/client.tsx deleted file mode 100644 index a187ee8c15..0000000000 --- a/benchmarks/client-nav/link-performance/src/client.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { RouterProvider } from '@tanstack/react-router' -import { isServer } from '@tanstack/router-core/isServer' -import { createRoot } from 'react-dom/client' -import { assertStateUpdates, createLinkRouter } from './workload' -import type { LinkRouter } from './workload' -import type { RouterHistory } from '@tanstack/history' -import type { LinkCaseId } from '../cases' - -export const serverEnvironment: boolean | undefined = isServer - -export function mountTestApp( - container: HTMLElement, - history: RouterHistory, - caseId: LinkCaseId, -): { - router: LinkRouter - unmount: () => void - assertStateUpdates: () => void -} { - const router = createLinkRouter(caseId, history, false) - const root = createRoot(container) - root.render() - - return { - router, - unmount: () => root.unmount(), - assertStateUpdates: () => assertStateUpdates(router), - } -} diff --git a/benchmarks/client-nav/link-performance/src/ssr.tsx b/benchmarks/client-nav/link-performance/src/ssr.tsx deleted file mode 100644 index 491191b1f9..0000000000 --- a/benchmarks/client-nav/link-performance/src/ssr.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { RouterProvider, createMemoryHistory } from '@tanstack/react-router' -import { isServer } from '@tanstack/router-core/isServer' -import { renderToString } from 'react-dom/server' -import { getSourceUrl } from '../cases' -import { assertStateUpdates, createLinkRouter } from './workload' -import type { LinkCaseId } from '../cases' - -export const serverEnvironment: boolean | undefined = isServer - -export async function renderScenario( - caseId: LinkCaseId, - stateIndex: number, - verify = false, -) { - const history = createMemoryHistory({ - initialEntries: [getSourceUrl(caseId, stateIndex)], - }) - const router = createLinkRouter(caseId, history, true) - try { - await router.load() - const html = renderToString() - if (verify) { - assertStateUpdates(router) - } - return html - } finally { - history.destroy() - } -} diff --git a/benchmarks/client-nav/link-performance/src/workload.tsx b/benchmarks/client-nav/link-performance/src/workload.tsx deleted file mode 100644 index 8315b85b8b..0000000000 --- a/benchmarks/client-nav/link-performance/src/workload.tsx +++ /dev/null @@ -1,506 +0,0 @@ -import { - Link, - Outlet, - createRootRouteWithContext, - createRoute, - createRouter, - linkOptions, - retainSearchParams, - stripSearchParams, - useLocation, -} from '@tanstack/react-router' -import { - LINK_COUNT, - LOCALES, - encodedValue, - optionalCategory, - sourceFilter, - sourceSearch, - splatValue, -} from '../cases' -import type { RouterHistory } from '@tanstack/history' -import type { SearchSchemaInput } from '@tanstack/react-router' -import type { Filter, LinkCaseId, LinkSearch } from '../cases' - -interface StateUpdates { - calls: number - verifiedCalls: number - input: number - output: number - offset: number -} - -interface WorkloadContext { - caseId: LinkCaseId - stateUpdates: StateUpdates -} - -function isFilter(value: unknown): value is Filter { - return ( - typeof value === 'object' && - value !== null && - 'tag' in value && - typeof value.tag === 'string' && - 'flags' in value && - typeof value.flags === 'object' && - value.flags !== null && - 'open' in value.flags && - typeof value.flags.open === 'boolean' && - 'tags' in value && - Array.isArray(value.tags) && - value.tags.every((tag: unknown) => typeof tag === 'string') - ) -} - -const rootRoute = createRootRouteWithContext()({ - validateSearch: ( - search: Record & SearchSchemaInput, - ): LinkSearch => ({ - page: typeof search.page === 'number' ? search.page : undefined, - tenant: typeof search.tenant === 'string' ? search.tenant : undefined, - filter: isFilter(search.filter) ? search.filter : undefined, - }), - component: RootLayout, -}) - -const itemsRoute = createRoute({ - getParentRoute: () => rootRoute, - path: 'items/$itemId', -}) -const detailsRoute = createRoute({ - getParentRoute: () => itemsRoute, - path: 'details', -}) -const teamRoute = createRoute({ - getParentRoute: () => rootRoute, - path: 'teams/$teamId', -}) -const teamItemRoute = createRoute({ - getParentRoute: () => teamRoute, - path: '$itemId', -}) -const teamDetailsRoute = createRoute({ - getParentRoute: () => teamItemRoute, - path: 'details', -}) -const filteredRoute = createRoute({ - getParentRoute: () => rootRoute, - path: 'filtered/$itemId', - search: { - middlewares: [ - retainSearchParams(['tenant']), - stripSearchParams({ page: 1 }), - ({ search, next }) => { - const result = next(search) - return { - ...result, - filter: result.filter - ? { ...result.filter, tag: result.filter.tag.trim().toUpperCase() } - : undefined, - } - }, - ], - }, -}) -const numericRoute = createRoute({ - getParentRoute: () => rootRoute, - path: 'numbers/$number', - params: { - parse: ({ number }) => { - const value = Number(number) - if (!Number.isFinite(value)) { - throw new Error(`Invalid number: ${number}`) - } - return { number: value } - }, - stringify: ({ number }) => ({ number: String(number) }), - }, -}) -const optionalRoute = createRoute({ - getParentRoute: () => rootRoute, - path: 'optional/{-$category}/$itemId', -}) -const splatRoute = createRoute({ - getParentRoute: () => rootRoute, - path: 'files/$', -}) -const encodedRoute = createRoute({ - getParentRoute: () => rootRoute, - path: 'encoded/$value', -}) -const publicRoute = createRoute({ - getParentRoute: () => rootRoute, - path: 'public/$itemId', -}) - -const routeTree = rootRoute.addChildren([ - itemsRoute.addChildren([detailsRoute]), - teamRoute.addChildren([teamItemRoute.addChildren([teamDetailsRoute])]), - filteredRoute, - numericRoute, - optionalRoute, - splatRoute, - encodedRoute, - publicRoute, -]) - -const localeRewrite = { - input: ({ url }: { url: URL }) => { - const match = /^\/(en|fr|de|es)(\/.*)$/.exec(url.pathname) - if (match) { - url.pathname = match[2]! - url.searchParams.set('tenant', match[1]!) - } - return url - }, - output: ({ url }: { url: URL }) => { - const locale = url.searchParams.get('tenant') - if (locale) { - url.searchParams.delete('tenant') - url.pathname = `/${locale}${url.pathname}` - } - return url - }, -} - -export function createLinkRouter( - caseId: LinkCaseId, - history: RouterHistory, - isServer: boolean, -) { - const context: WorkloadContext = { - caseId, - stateUpdates: { - calls: 0, - verifiedCalls: 0, - input: 0, - output: 0, - offset: 0, - }, - } - return createRouter({ - routeTree, - history, - isServer, - context, - scrollRestoration: false, - defaultPreload: false, - trailingSlash: 'never', - pathParamsAllowedCharacters: - caseId === 'encoding' ? ['@', ':', '+'] : undefined, - ...(caseId === 'rewrites' - ? { basepath: '/app', rewrite: localeRewrite } - : {}), - }) -} - -export type LinkRouter = ReturnType - -declare module '@tanstack/react-router' { - interface Register { - router: LinkRouter - } -} - -declare module '@tanstack/history' { - interface HistoryState { - linkPerfState?: number - } -} - -// Call alongside DOM assertions, outside the timed loop, after each sample. -export function assertStateUpdates(router: LinkRouter): void { - const { caseId, stateUpdates } = router.options.context - if (caseId !== 'location-updaters') { - return - } - const input = router.state.location.state.linkPerfState ?? 0 - if ( - stateUpdates.calls - stateUpdates.verifiedCalls < LINK_COUNT || - stateUpdates.input !== input || - stateUpdates.output !== input + stateUpdates.offset || - stateUpdates.offset < 1 || - stateUpdates.offset > 40 - ) { - throw new Error( - 'Link history-state updaters did not run with current state', - ) - } - stateUpdates.verifiedCalls = stateUpdates.calls -} - -function sourceOptions(caseId: LinkCaseId, stateIndex: number) { - const itemId = `item-${stateIndex}` - const common = { - search: sourceSearch(caseId, stateIndex), - hash: caseId === 'location-updaters' ? `source-${stateIndex}` : '', - state: { linkPerfState: stateIndex + 10 }, - } - switch (caseId) { - case 'relative': - return linkOptions({ - ...common, - to: '/teams/$teamId/$itemId', - params: { teamId: `team-${stateIndex}`, itemId }, - }) - case 'numeric-params': - return linkOptions({ - ...common, - to: '/numbers/$number', - params: { number: stateIndex }, - }) - case 'optional-params': - return linkOptions({ - ...common, - to: '/optional/{-$category}/$itemId', - params: { category: optionalCategory(stateIndex), itemId }, - }) - case 'splats': - return linkOptions({ - ...common, - to: '/files/$', - params: { _splat: `source/state-${stateIndex}` }, - }) - case 'encoding': - return linkOptions({ - ...common, - to: '/encoded/$value', - params: { value: `source-${stateIndex}` }, - }) - case 'active': - return linkOptions({ - ...common, - to: '/items/$itemId/details', - params: { itemId }, - }) - default: - return linkOptions({ - ...common, - to: '/items/$itemId', - params: { itemId }, - }) - } -} - -const indexes = Array.from({ length: LINK_COUNT }, (_, index) => index) -const controls = [0, 1, 2, 3] as const - -function SourcePath() { - const pathname = useLocation({ select: (location) => location.pathname }) - return {pathname} -} - -function RootLayout() { - const context = rootRoute.useRouteContext() - return ( - <> - - -
- {indexes.map((index) => measuredLink(context, index))} -
- - - ) -} - -function measuredLink( - { caseId, stateUpdates }: WorkloadContext, - index: number, -) { - const common = { - key: index, - 'data-perf-link': index, - preload: false, - children: `Link ${index}`, - } as const - const itemId = `item-${index % 40}` - switch (caseId) { - case 'shared-params': - case 'unique-params': - return ( - - ) - case 'param-updaters': - return ( - ({ - itemId: `${previous.itemId}-related-${index % 40}`, - })} - /> - ) - case 'location-updaters': - return ( - ({ - ...previous, - page: (previous.page ?? 1) + 1 + (index % 5), - })} - hash={(previous) => `${previous}-link-${index % 5}`} - state={(previous) => { - const input = previous.linkPerfState ?? 0 - const offset = (index % 40) + 1 - const output = input + offset - stateUpdates.calls++ - stateUpdates.input = input - stateUpdates.output = output - stateUpdates.offset = offset - return { ...previous, linkPerfState: output } - }} - /> - ) - case 'relative': - return ( - - ) - case 'middleware': - return ( - - ) - case 'numeric-params': - return ( - ({ number: previous.number + (index % 40) })} - /> - ) - case 'optional-params': - return ( - - ) - case 'splats': - return ( - - ) - case 'encoding': - return ( - - ) - case 'masks': - return ( - - ) - case 'rewrites': - return ( - - ) - case 'active': { - const item = Math.floor(index / 5) - const variant = index % 5 - return ( - ({ - className: 'perf-active', - title: 'active', - style: { color: 'green' }, - })} - inactiveProps={() => ({ - className: 'perf-inactive', - title: 'inactive', - style: { color: 'gray' }, - })} - > - {({ isActive }) => `${index}:${isActive ? 'active' : 'inactive'}`} - - ) - } - } -} diff --git a/benchmarks/client-nav/link-performance/ssr.bench.ts b/benchmarks/client-nav/link-performance/ssr.bench.ts deleted file mode 100644 index c30084e510..0000000000 --- a/benchmarks/client-nav/link-performance/ssr.bench.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../cpu-simulation' -import { LINK_CASES } from './cases' -import { createSsrScenario, samplingOptions } from './scenario' -import type * as App from './src/ssr' - -const appUrl = new URL('./dist/ssr/app.js', import.meta.url).href -const app: typeof App = await import(/* @vite-ignore */ appUrl) -if (app.serverEnvironment !== true) { - throw new Error('Link SSR benchmarks must use the production server build') -} - -for (const { id, label } of LINK_CASES) { - test(label, async ({ bench }) => { - const scenario = createSsrScenario(app, id) - function finish() { - try { - scenario.check() - } finally { - scenario.teardown() - } - } - - await bench( - `SSR Links: ${id}`, - benchLifecycle({ before: scenario.setup, after: finish }), - scenario.batch, - ).run(samplingOptions) - }) -} diff --git a/benchmarks/client-nav/link-performance/stable-runner.ts b/benchmarks/client-nav/link-performance/stable-runner.ts deleted file mode 100644 index 59ccfa3cb4..0000000000 --- a/benchmarks/client-nav/link-performance/stable-runner.ts +++ /dev/null @@ -1,269 +0,0 @@ -import { fork } from 'node:child_process' -import { createHash } from 'node:crypto' -import { - copyFileSync, - mkdirSync, - readFileSync, - rmSync, - writeFileSync, -} from 'node:fs' -import { dirname, resolve } from 'node:path' -import { fileURLToPath } from 'node:url' -import { parseArgs } from 'node:util' -import { LINK_CASES } from './cases' -import { createStagingDirectory } from './staging' -import { classify, mean, summarizeRatios } from './statistics' -import type { LinkCaseId } from './cases' -import type { - BlockSample, - Mode, - Variant, - WorkerRequest, - WorkerResponse, -} from './worker-protocol' - -const projectRoot = fileURLToPath(new URL('.', import.meta.url)) -const workspaceRoot = resolve(projectRoot, '../../..') - -function startWorker() { - const child = fork( - fileURLToPath(new URL('./stable-worker.ts', import.meta.url)), - { - cwd: workspaceRoot, - env: { ...process.env, NODE_ENV: 'production' }, - execArgv: [ - '--import=@swc-node/register/esm-register', - '--random-seed=42', - '--hash-seed=42', - ], - stdio: ['ignore', 'ignore', 'pipe', 'ipc'], - }, - ) - let stderr = '' - child.stderr?.on('data', (data: Buffer) => { - stderr = (stderr + data.toString()).slice(-4_096) - }) - - function request(message: WorkerRequest): Promise { - return new Promise((resolveResponse, reject) => { - const timeout = setTimeout(() => { - finish( - new Error(`Sampling worker timed out: ${message.kind}\n${stderr}`), - ) - }, 60_000) - const onExit = (code: number | null) => - finish(new Error(`Sampling worker exited (${code})\n${stderr}`)) - const onError = (error: Error) => finish(error) - const onMessage = (response: WorkerResponse) => { - if (response.kind === 'error') { - finish(new Error(response.message)) - } else { - finish(undefined, response) - } - } - function finish(error?: Error, response?: WorkerResponse) { - clearTimeout(timeout) - child.off('message', onMessage) - child.off('error', onError) - child.off('exit', onExit) - if (error) { - reject(error) - } else if (response) { - resolveResponse(response) - } - } - child.once('message', onMessage) - child.once('error', onError) - child.once('exit', onExit) - child.send(message, (error) => { - if (error) { - finish(error) - } - }) - }) - } - - return { - request, - kill: () => child.kill(), - } -} - -async function sampleReplica( - mode: Mode, - caseId: LinkCaseId, - baseline: string, - current: string, - replica: number, -) { - const worker = startWorker() - const samples: Array> = [[], []] - const ratios: Array<{ cpu: number; wall: number }> = [] - try { - const starts: Array = [] - // Balance module initialization and which variant finishes warming last. - const startupOrder: Array = replica % 2 ? [1, 0] : [0, 1] - for (const index of startupOrder) { - const ready = await worker.request({ - kind: 'init', - mode, - caseId, - bundle: index === 0 ? baseline : current, - variant: index, - }) - if (ready.kind !== 'ready') { - throw new Error('Expected a ready sampling worker') - } - starts[index] = ready.batchMs - } - const iterations = Math.max(1, Math.ceil(500 / Math.min(...starts))) - for (let round = 0; round < 2; round++) { - const block: Array> = [[], []] - const order: Array = - (round + replica) % 2 ? [1, 0, 0, 1] : [0, 1, 1, 0] - for (const index of order) { - const result = await worker.request({ - kind: 'measure', - iterations, - variant: index, - }) - if (result.kind !== 'sample') { - throw new Error('Expected a block measurement') - } - samples[index]!.push(result.sample) - block[index]!.push(result.sample) - } - ratios.push({ - cpu: - mean(block[1]!.map((s) => s.cpuMs)) / - mean(block[0]!.map((s) => s.cpuMs)), - wall: - mean(block[1]!.map((s) => s.wallMs)) / - mean(block[0]!.map((s) => s.wallMs)), - }) - } - const response = await worker.request({ kind: 'stop' }) - if (response.kind !== 'stopped') { - throw new Error('Expected successful post-measurement assertions') - } - return { - iterations, - baseline: samples[0]!, - current: samples[1]!, - cpuRatio: Math.exp(mean(ratios.map((r) => Math.log(r.cpu)))), - wallRatio: Math.exp(mean(ratios.map((r) => Math.log(r.wall)))), - } - } finally { - worker.kill() - } -} - -async function main() { - const { values } = parseArgs({ - options: { - baseline: { type: 'string' }, - current: { type: 'string', default: resolve(projectRoot, 'dist') }, - mode: { type: 'string', default: 'all' }, - repeats: { type: 'string', default: '4' }, - outputJson: { type: 'string' }, - testNamePattern: { type: 'string', short: 't' }, - }, - }) - if (!values.baseline || !values.outputJson) { - throw new Error( - 'Specify --baseline and --outputJson ', - ) - } - const repeats = Number(values.repeats) - if (!Number.isInteger(repeats) || repeats < 3 || repeats > 11) { - throw new Error('--repeats must be an integer between 3 and 11') - } - if (!['all', 'client', 'ssr'].includes(values.mode)) { - throw new Error('--mode must be all, client, or ssr') - } - const modes: Array = - values.mode === 'all' - ? ['client', 'ssr'] - : values.mode === 'client' - ? ['client'] - : ['ssr'] - const pattern = values.testNamePattern - ? new RegExp(values.testNamePattern) - : undefined - const cases = LINK_CASES.filter( - (c) => !pattern || pattern.test(`${c.label} ${c.id}`), - ) - if (!cases.length) { - throw new Error('No Link workloads match the requested pattern') - } - const report: { - protocol: string - node: string - complete: boolean - results: Array<{ - mode: Mode - caseId: LinkCaseId - baselineSha256: string - currentSha256: string - replicas: Array>> - cpu: ReturnType - wall: ReturnType - verdict: ReturnType - }> - } = { - protocol: - 'fresh process per case/replica; shared React runtime; separately loaded router variants; 2 ABBA/BAAB rounds; ~500ms calibrated fixed-work blocks; >=2s/100 batches warmup; main-thread CPU and wall time; fixed V8 random/hash seeds', - node: process.version, - complete: false, - results: [], - } - const output = resolve(values.outputJson) - mkdirSync(dirname(output), { recursive: true }) - const staging = createStagingDirectory() - try { - for (const mode of modes) { - const baselineInput = resolve(values.baseline, mode, 'app.js') - const currentInput = resolve(values.current, mode, 'app.js') - // Both snapshots resolve React from the same package installation. - const baseline = resolve(staging, `baseline-${mode}.mjs`) - const current = resolve(staging, `current-${mode}.mjs`) - copyFileSync(baselineInput, baseline) - copyFileSync(currentInput, current) - const digest = (file: string) => - createHash('sha256').update(readFileSync(file)).digest('hex') - const baselineSha256 = digest(baseline) - const currentSha256 = digest(current) - for (const { id } of cases) { - const replicas = [] - for (let replica = 0; replica < repeats; replica++) { - replicas.push( - await sampleReplica(mode, id, baseline, current, replica), - ) - } - const cpu = summarizeRatios(replicas.map((r) => r.cpuRatio)) - const wall = summarizeRatios(replicas.map((r) => r.wallRatio)) - const verdict = classify(cpu, wall) - report.results.push({ - mode, - caseId: id, - baselineSha256, - currentSha256, - replicas, - cpu, - wall, - verdict, - }) - writeFileSync(output, JSON.stringify(report, null, 2)) - console.log( - `${mode} ${id}: CPU ${cpu.changePercent.toFixed(2)}% [${cpu.low95.toFixed(2)}, ${cpu.high95.toFixed(2)}], wall ${wall.changePercent.toFixed(2)}% [${wall.low95.toFixed(2)}, ${wall.high95.toFixed(2)}] ${verdict}`, - ) - } - } - report.complete = true - writeFileSync(output, JSON.stringify(report, null, 2)) - } finally { - rmSync(staging, { recursive: true }) - } -} - -await main() diff --git a/benchmarks/client-nav/link-performance/stable-worker.test.ts b/benchmarks/client-nav/link-performance/stable-worker.test.ts deleted file mode 100644 index 087b32414a..0000000000 --- a/benchmarks/client-nav/link-performance/stable-worker.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { fork } from 'node:child_process' -import { rmdirSync, unlinkSync, writeFileSync } from 'node:fs' -import { join } from 'node:path' -import { fileURLToPath } from 'node:url' -import { expect, test } from 'vitest' -import { createStagingDirectory } from './staging' -import type { WorkerResponse } from './worker-protocol' - -test('loads emitted JavaScript without retranspiling it through SWC', async () => { - const directory = createStagingDirectory() - const bundle = join(directory, 'app.mjs') - const definition = 'function untouched ( ) { return 1 }' - writeFileSync( - bundle, - `${definition}\nawait Promise.resolve()\nthrow new Error(untouched.toString())`, - ) - const worker = fork( - fileURLToPath(new URL('./stable-worker.ts', import.meta.url)), - { - cwd: fileURLToPath(new URL('../../../', import.meta.url)), - execArgv: ['--import=@swc-node/register/esm-register'], - env: { ...process.env, NODE_ENV: 'production' }, - stdio: ['ignore', 'ignore', 'pipe', 'ipc'], - }, - ) - let stderr = '' - worker.stderr?.on('data', (data: Buffer) => { - stderr += data.toString() - }) - let timeout: ReturnType | undefined - try { - const result = new Promise((resolve, reject) => { - worker.once('message', (message: WorkerResponse) => resolve(message)) - worker.once('error', reject) - worker.once('exit', (code) => { - reject(new Error(`Worker exited (${code}): ${stderr}`)) - }) - timeout = setTimeout(() => { - reject(new Error(`Worker timed out: ${stderr}`)) - }, 5_000) - }) - worker.send({ - kind: 'init', - mode: 'ssr', - caseId: 'shared-params', - bundle, - variant: 0, - }) - const response = await result - expect(response.kind).toBe('error') - if (response.kind === 'error') { - expect(response.message).toContain(`Error: ${definition}`) - } - } finally { - clearTimeout(timeout) - worker.kill() - unlinkSync(bundle) - rmdirSync(directory) - } -}) diff --git a/benchmarks/client-nav/link-performance/stable-worker.ts b/benchmarks/client-nav/link-performance/stable-worker.ts deleted file mode 100644 index d98679dc15..0000000000 --- a/benchmarks/client-nav/link-performance/stable-worker.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { pathToFileURL } from 'node:url' -import { createClientScenario, createSsrScenario } from './scenario' -import type { LinkScenario } from './scenario' -import type { WorkerRequest, WorkerResponse } from './worker-protocol' -import type * as ClientApp from './src/client' -import type * as SsrApp from './src/ssr' - -const scenarios: Array = [] -const creationOrder: Array = [] -let closeWindow = () => {} - -function reply(response: WorkerResponse) { - if (!process.send) { - throw new Error('The Link sampling worker requires an IPC parent') - } - process.send(response) -} - -async function handle(request: WorkerRequest) { - if (request.kind === 'init') { - if (typeof process.threadCpuUsage !== 'function') { - throw new Error( - 'Stable sampling requires Node.js with process.threadCpuUsage', - ) - } - if (scenarios[request.variant]) { - throw new Error('A worker must only initialize each variant once') - } - let scenario: LinkScenario - const bundleUrl = pathToFileURL(request.bundle) - bundleUrl.searchParams.set('linkPerfVariant', String(request.variant)) - if (request.mode === 'client') { - const { window } = await import('../jsdom') - closeWindow = () => window.close() - const app: typeof ClientApp = await import(bundleUrl.href) - if (app.serverEnvironment !== false) { - throw new Error('Expected a production client bundle') - } - scenario = createClientScenario(app, request.caseId) - } else { - const app: typeof SsrApp = await import(bundleUrl.href) - if (app.serverEnvironment !== true) { - throw new Error('Expected a production SSR bundle') - } - scenario = createSsrScenario(app, request.caseId) - } - scenarios[request.variant] = scenario - creationOrder.push(scenario) - await scenario.setup() - const start = performance.now() - let iterations = 0 - do { - await scenario.batch() - iterations++ - } while (iterations < 100 || performance.now() - start < 2_000) - reply({ - kind: 'ready', - batchMs: (performance.now() - start) / iterations, - }) - return - } - if (request.kind === 'measure') { - const scenario = scenarios[request.variant] - if (!scenario) { - throw new Error('The sampling worker has not been initialized') - } - if (!Number.isInteger(request.iterations) || request.iterations < 1) { - throw new Error('Expected a positive batch count') - } - const cpuStart = process.threadCpuUsage() - const processStart = process.cpuUsage() - const start = performance.now() - for (let index = 0; index < request.iterations; index++) { - await scenario.batch() - } - const wallMs = performance.now() - start - const cpu = process.threadCpuUsage(cpuStart) - const processCpu = process.cpuUsage(processStart) - reply({ - kind: 'sample', - sample: { - iterations: request.iterations, - wallMs: wallMs / request.iterations, - cpuMs: (cpu.user + cpu.system) / 1_000 / request.iterations, - processCpuMs: - (processCpu.user + processCpu.system) / 1_000 / request.iterations, - }, - }) - return - } - try { - for (const scenario of creationOrder) { - scenario.check() - } - } finally { - for (const scenario of creationOrder.reverse()) { - scenario.teardown() - } - closeWindow() - } - reply({ kind: 'stopped' }) -} - -process.on('message', (request: WorkerRequest) => { - void handle(request).catch((error: unknown) => { - reply({ - kind: 'error', - message: - error instanceof Error ? error.stack || error.message : String(error), - }) - }) -}) diff --git a/benchmarks/client-nav/link-performance/staging.ts b/benchmarks/client-nav/link-performance/staging.ts deleted file mode 100644 index ac07d34c29..0000000000 --- a/benchmarks/client-nav/link-performance/staging.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { mkdirSync, mkdtempSync } from 'node:fs' -import { resolve } from 'node:path' -import { fileURLToPath } from 'node:url' - -export function createStagingDirectory() { - // SWC skips node_modules, leaving the emitted benchmark JavaScript intact. - const root = fileURLToPath(new URL('./node_modules/.cache/', import.meta.url)) - mkdirSync(root, { recursive: true }) - return mkdtempSync(resolve(root, 'link-performance-')) -} diff --git a/benchmarks/client-nav/link-performance/statistics.test.ts b/benchmarks/client-nav/link-performance/statistics.test.ts deleted file mode 100644 index 8f5f37413b..0000000000 --- a/benchmarks/client-nav/link-performance/statistics.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { expect, test } from 'vitest' -import { classify, mean, summarizeRatios } from './statistics' - -test('summarizes multiplicative paired changes across process replicas', () => { - const result = summarizeRatios([0.9, 0.9, 0.9, 0.9]) - expect(result.changePercent).toBeCloseTo(-10) - expect(result.low95).toBeCloseTo(-10) - expect(result.high95).toBeCloseTo(-10) - expect(result.replicas).toBe(4) -}) - -test('does not turn opposite noisy runs into a conclusive result', () => { - const result = summarizeRatios([0.9, 1.1, 0.95, 1.05]) - expect(result.low95).toBeLessThan(0) - expect(result.high95).toBeGreaterThan(0) - expect(classify(result, result)).toBe('inconclusive') -}) - -test('requires CPU and wall time to corroborate a direction', () => { - const slower = summarizeRatios([1.08, 1.09, 1.08, 1.09]) - const faster = summarizeRatios([0.9, 0.91, 0.9, 0.91]) - expect(classify(slower, slower)).toBe('slower') - expect(classify(faster, faster)).toBe('faster') - expect(classify(slower, faster)).toBe('inconclusive') - expect(classify(summarizeRatios([1, 1, 1]), summarizeRatios([1, 1, 1]))).toBe( - 'within-2%', - ) -}) - -test('rejects incomplete or invalid sampling data', () => { - expect(() => summarizeRatios([1])).toThrow() - expect(() => summarizeRatios([0, 1])).toThrow() - expect(() => summarizeRatios([NaN, 1])).toThrow() - expect(() => mean([])).toThrow() - expect(() => mean([Infinity])).toThrow() -}) diff --git a/benchmarks/client-nav/link-performance/statistics.ts b/benchmarks/client-nav/link-performance/statistics.ts deleted file mode 100644 index 469bdaf65a..0000000000 --- a/benchmarks/client-nav/link-performance/statistics.ts +++ /dev/null @@ -1,57 +0,0 @@ -const critical95 = [ - 12.7062, 4.3027, 3.1824, 2.7764, 2.5706, 2.4469, 2.3646, 2.306, 2.2622, - 2.2281, -] - -export function mean(values: ReadonlyArray) { - if (!values.length || values.some((value) => !Number.isFinite(value))) { - throw new Error('Expected finite, nonempty samples') - } - return values.reduce((sum, value) => sum + value, 0) / values.length -} - -export function summarizeRatios(ratios: ReadonlyArray) { - if ( - ratios.length < 2 || - ratios.length > 11 || - ratios.some((value) => value <= 0) - ) { - throw new Error('Expected 2-11 independent positive process-replica ratios') - } - const logs = ratios.map(Math.log) - const center = mean(logs) - const variance = - logs.reduce((sum, value) => sum + (value - center) ** 2, 0) / - (logs.length - 1) - // Replicas, not the many correlated batches inside a worker, are the samples. - const margin = - critical95[logs.length - 2]! * Math.sqrt(variance / logs.length) - const percent = (value: number) => (Math.exp(value) - 1) * 100 - return { - changePercent: percent(center), - low95: percent(center - margin), - high95: percent(center + margin), - replicas: ratios.length, - } -} - -export function classify( - cpu: ReturnType, - wall: ReturnType, -) { - if (cpu.low95 > 0 && wall.low95 > 0) { - return 'slower' - } - if (cpu.high95 < 0 && wall.high95 < 0) { - return 'faster' - } - if ( - cpu.low95 >= -2 && - cpu.high95 <= 2 && - wall.low95 >= -2 && - wall.high95 <= 2 - ) { - return 'within-2%' - } - return 'inconclusive' -} diff --git a/benchmarks/client-nav/link-performance/tsconfig.json b/benchmarks/client-nav/link-performance/tsconfig.json deleted file mode 100644 index fbf230c977..0000000000 --- a/benchmarks/client-nav/link-performance/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "./**/*.ts", - "./**/*.tsx", - "../scenarios/harness.ts", - "../setup-helpers.ts", - "../vitest.setup.ts" - ] -} diff --git a/benchmarks/client-nav/link-performance/vite.client.config.ts b/benchmarks/client-nav/link-performance/vite.client.config.ts deleted file mode 100644 index 1cd45fc45e..0000000000 --- a/benchmarks/client-nav/link-performance/vite.client.config.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { createLinkPerformanceConfig } from './config' - -export default createLinkPerformanceConfig('client') diff --git a/benchmarks/client-nav/link-performance/vite.ssr.config.ts b/benchmarks/client-nav/link-performance/vite.ssr.config.ts deleted file mode 100644 index f59148eaf6..0000000000 --- a/benchmarks/client-nav/link-performance/vite.ssr.config.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { createLinkPerformanceConfig } from './config' - -export default createLinkPerformanceConfig('ssr') diff --git a/benchmarks/client-nav/link-performance/worker-protocol.ts b/benchmarks/client-nav/link-performance/worker-protocol.ts deleted file mode 100644 index 474858a529..0000000000 --- a/benchmarks/client-nav/link-performance/worker-protocol.ts +++ /dev/null @@ -1,28 +0,0 @@ -import type { LinkCaseId } from './cases' - -export type Mode = 'client' | 'ssr' -export type Variant = 0 | 1 - -export type WorkerRequest = - | { - kind: 'init' - mode: Mode - caseId: LinkCaseId - bundle: string - variant: Variant - } - | { kind: 'measure'; iterations: number; variant: Variant } - | { kind: 'stop' } - -export interface BlockSample { - wallMs: number - cpuMs: number - processCpuMs: number - iterations: number -} - -export type WorkerResponse = - | { kind: 'ready'; batchMs: number } - | { kind: 'sample'; sample: BlockSample } - | { kind: 'stopped' } - | { kind: 'error'; message: string } diff --git a/benchmarks/client-nav/package.json b/benchmarks/client-nav/package.json index 1f878adc67..1b42e8fc87 100644 --- a/benchmarks/client-nav/package.json +++ b/benchmarks/client-nav/package.json @@ -9,10 +9,10 @@ "test:flame:react": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./react/speed.flame.ts", "test:flame:solid": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./solid/speed.flame.ts", "test:flame:vue": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./vue/speed.flame.ts", - "test:perf": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.config.ts", - "test:perf:react": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.react.config.ts", - "test:perf:solid": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.solid.config.ts", - "test:perf:vue": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.vue.config.ts", + "test:perf": "NODE_ENV=production vitest bench --config ./vitest.config.ts", + "test:perf:react": "NODE_ENV=production vitest bench --config ./vitest.react.config.ts", + "test:perf:solid": "NODE_ENV=production vitest bench --config ./vitest.solid.config.ts", + "test:perf:vue": "NODE_ENV=production vitest bench --config ./vitest.vue.config.ts", "test:types": "pnpm run test:types:react && pnpm run test:types:solid && pnpm run test:types:vue", "test:types:react": "tsc -p ./react/tsconfig.json --noEmit", "test:types:solid": "tsc -p ./solid/tsconfig.json --noEmit", @@ -31,7 +31,7 @@ }, "devDependencies": { "@platformatic/flame": "^1.6.0", - "@codspeed/vitest-plugin": "^6.0.1", + "@codspeed/vitest-plugin": "^5.5.0", "@tanstack/router-plugin": "workspace:^", "@testing-library/react": "^16.2.0", "@vitejs/plugin-react": "^6.0.1", @@ -64,8 +64,6 @@ "@benchmarks/client-nav-control-flow-react", "@benchmarks/client-nav-head-react", "@benchmarks/client-nav-history-react", - "@benchmarks/client-nav-hydration-react", - "@benchmarks/client-nav-link-churn-react", "@benchmarks/client-nav-links-react", "@benchmarks/client-nav-loaders-react", "@benchmarks/client-nav-mount-react", @@ -94,8 +92,6 @@ "@benchmarks/client-nav-control-flow-solid", "@benchmarks/client-nav-head-solid", "@benchmarks/client-nav-history-solid", - "@benchmarks/client-nav-hydration-solid", - "@benchmarks/client-nav-link-churn-solid", "@benchmarks/client-nav-links-solid", "@benchmarks/client-nav-loaders-solid", "@benchmarks/client-nav-mount-solid", @@ -124,7 +120,6 @@ "@benchmarks/client-nav-control-flow-vue", "@benchmarks/client-nav-head-vue", "@benchmarks/client-nav-history-vue", - "@benchmarks/client-nav-link-churn-vue", "@benchmarks/client-nav-links-vue", "@benchmarks/client-nav-loaders-vue", "@benchmarks/client-nav-mount-vue", @@ -183,13 +178,7 @@ ] }, "test:types": { - "inputs": [ - "default", - "^production", - "{workspaceRoot}/eslint.config.js", - "{workspaceRoot}/benchmarks/cpu-simulation.ts", - "dependentTaskOutputs" - ], + "cache": false, "dependsOn": [ "^build", { @@ -206,13 +195,8 @@ "@benchmarks/client-nav-history-react", "@benchmarks/client-nav-history-solid", "@benchmarks/client-nav-history-vue", - "@benchmarks/client-nav-hydration-react", - "@benchmarks/client-nav-hydration-solid", - "@benchmarks/client-nav-link-churn-react", "@benchmarks/client-nav-links-react", - "@benchmarks/client-nav-link-churn-solid", "@benchmarks/client-nav-links-solid", - "@benchmarks/client-nav-link-churn-vue", "@benchmarks/client-nav-links-vue", "@benchmarks/client-nav-loaders-react", "@benchmarks/client-nav-loaders-solid", diff --git a/benchmarks/client-nav/react/speed.bench.ts b/benchmarks/client-nav/react/speed.bench.ts index 944f182734..fcc15b5fbc 100644 --- a/benchmarks/client-nav/react/speed.bench.ts +++ b/benchmarks/client-nav/react/speed.bench.ts @@ -1,19 +1,34 @@ -import { test } from 'vitest' +import { afterAll, beforeAll, bench, describe } from 'vitest' import { setup } from './setup' -test('client-nav', async ({ bench }) => { - const scenario = setup() +describe('client-nav', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, + * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. + * + * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, + * but it does support `beforeAll` and `afterAll`. + * + * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. + */ + + beforeAll(test.before) + afterAll(test.after) + + bench( 'client-side navigation loop (react)', - { beforeAll: scenario.before, afterAll: scenario.after }, async () => { for (let i = 0; i < 10; i++) { - await scenario.tick() + await test.tick() } }, - ).run({ - warmupIterations: 100, - time: 10_000, - }) + { + warmupIterations: 100, + time: 10_000, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/react/vite.config.ts b/benchmarks/client-nav/react/vite.config.ts index 7df3f80e71..ea85a49a21 100644 --- a/benchmarks/client-nav/react/vite.config.ts +++ b/benchmarks/client-nav/react/vite.config.ts @@ -34,6 +34,5 @@ export default defineConfig({ watch: false, environment: 'jsdom', setupFiles: [`${rootDir}vitest.setup.ts`], - benchmark: { include: ['react/speed.bench.ts'] }, }, }) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/speed.bench.ts b/benchmarks/client-nav/scenarios/async-pipeline/react/speed.bench.ts index 65dab0781e..c3f4c5231c 100644 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-async-pipeline', async ({ bench }) => { - const scenario = setup() +describe('client-async-pipeline', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-async-pipeline navigation loop (react)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.bench.ts index acef710469..96082e9963 100644 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-async-pipeline', async ({ bench }) => { - const scenario = setup() +describe('client-async-pipeline', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-async-pipeline navigation loop (solid)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routeTree.gen.ts index 27b9498b11..7c15baf4e9 100644 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routeTree.gen.ts @@ -9,25 +9,25 @@ // 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 NestedRouteImport } from './routes/nested' -import { Route as CtxIdRouteImport } from './routes/ctx.$id' -import { Route as NestedIdRouteImport } from './routes/nested.$id' +import { Route as IndexRouteImport } from './routes/index' import { Route as SlowIdRouteImport } from './routes/slow.$id' +import { Route as NestedIdRouteImport } from './routes/nested.$id' +import { Route as CtxIdRouteImport } from './routes/ctx.$id' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const NestedRoute = NestedRouteImport.update({ id: '/nested', path: '/nested', getParentRoute: () => rootRouteImport, } as any) -const CtxIdRoute = CtxIdRouteImport.update({ - id: '/ctx/$id', - path: '/ctx/$id', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const SlowIdRoute = SlowIdRouteImport.update({ + id: '/slow/$id', + path: '/slow/$id', getParentRoute: () => rootRouteImport, } as any) const NestedIdRoute = NestedIdRouteImport.update({ @@ -35,9 +35,9 @@ const NestedIdRoute = NestedIdRouteImport.update({ path: '/$id', getParentRoute: () => NestedRoute, } as any) -const SlowIdRoute = SlowIdRouteImport.update({ - id: '/slow/$id', - path: '/slow/$id', +const CtxIdRoute = CtxIdRouteImport.update({ + id: '/ctx/$id', + path: '/ctx/$id', getParentRoute: () => rootRouteImport, } as any) @@ -80,13 +80,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/nested': { id: '/nested' path: '/nested' @@ -94,11 +87,18 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof NestedRouteImport parentRoute: typeof rootRouteImport } - '/ctx/$id': { - id: '/ctx/$id' - path: '/ctx/$id' - fullPath: '/ctx/$id' - preLoaderRoute: typeof CtxIdRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/slow/$id': { + id: '/slow/$id' + path: '/slow/$id' + fullPath: '/slow/$id' + preLoaderRoute: typeof SlowIdRouteImport parentRoute: typeof rootRouteImport } '/nested/$id': { @@ -108,11 +108,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof NestedIdRouteImport parentRoute: typeof NestedRoute } - '/slow/$id': { - id: '/slow/$id' - path: '/slow/$id' - fullPath: '/slow/$id' - preLoaderRoute: typeof SlowIdRouteImport + '/ctx/$id': { + id: '/ctx/$id' + path: '/ctx/$id' + fullPath: '/ctx/$id' + preLoaderRoute: typeof CtxIdRouteImport parentRoute: typeof rootRouteImport } } diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.bench.ts index f0fd3e58df..193a3837df 100644 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-async-pipeline', async ({ bench }) => { - const scenario = setup() +describe('client-async-pipeline', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-async-pipeline navigation loop (vue)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routeTree.gen.ts index 66b9efd7aa..ce26dc62d1 100644 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routeTree.gen.ts @@ -9,25 +9,25 @@ // 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 NestedRouteImport } from './routes/nested' -import { Route as CtxIdRouteImport } from './routes/ctx.$id' -import { Route as NestedIdRouteImport } from './routes/nested.$id' +import { Route as IndexRouteImport } from './routes/index' import { Route as SlowIdRouteImport } from './routes/slow.$id' +import { Route as NestedIdRouteImport } from './routes/nested.$id' +import { Route as CtxIdRouteImport } from './routes/ctx.$id' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const NestedRoute = NestedRouteImport.update({ id: '/nested', path: '/nested', getParentRoute: () => rootRouteImport, } as any) -const CtxIdRoute = CtxIdRouteImport.update({ - id: '/ctx/$id', - path: '/ctx/$id', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const SlowIdRoute = SlowIdRouteImport.update({ + id: '/slow/$id', + path: '/slow/$id', getParentRoute: () => rootRouteImport, } as any) const NestedIdRoute = NestedIdRouteImport.update({ @@ -35,9 +35,9 @@ const NestedIdRoute = NestedIdRouteImport.update({ path: '/$id', getParentRoute: () => NestedRoute, } as any) -const SlowIdRoute = SlowIdRouteImport.update({ - id: '/slow/$id', - path: '/slow/$id', +const CtxIdRoute = CtxIdRouteImport.update({ + id: '/ctx/$id', + path: '/ctx/$id', getParentRoute: () => rootRouteImport, } as any) @@ -80,13 +80,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/nested': { id: '/nested' path: '/nested' @@ -94,11 +87,18 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof NestedRouteImport parentRoute: typeof rootRouteImport } - '/ctx/$id': { - id: '/ctx/$id' - path: '/ctx/$id' - fullPath: '/ctx/$id' - preLoaderRoute: typeof CtxIdRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/slow/$id': { + id: '/slow/$id' + path: '/slow/$id' + fullPath: '/slow/$id' + preLoaderRoute: typeof SlowIdRouteImport parentRoute: typeof rootRouteImport } '/nested/$id': { @@ -108,11 +108,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof NestedIdRouteImport parentRoute: typeof NestedRoute } - '/slow/$id': { - id: '/slow/$id' - path: '/slow/$id' - fullPath: '/slow/$id' - preLoaderRoute: typeof SlowIdRouteImport + '/ctx/$id': { + id: '/ctx/$id' + path: '/ctx/$id' + fullPath: '/ctx/$id' + preLoaderRoute: typeof CtxIdRouteImport parentRoute: typeof rootRouteImport } } diff --git a/benchmarks/client-nav/scenarios/control-flow/react/speed.bench.ts b/benchmarks/client-nav/scenarios/control-flow/react/speed.bench.ts index d6f2190be7..7f1153021f 100644 --- a/benchmarks/client-nav/scenarios/control-flow/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/control-flow/react/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-control-flow', async ({ bench }) => { - const scenario = setup() +describe('client-control-flow', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-control-flow navigation loop (react)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/control-flow/solid/speed.bench.ts index d803d2a313..a88093ca52 100644 --- a/benchmarks/client-nav/scenarios/control-flow/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/control-flow/solid/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-control-flow', async ({ bench }) => { - const scenario = setup() +describe('client-control-flow', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-control-flow navigation loop (solid)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/control-flow/solid/src/routeTree.gen.ts index cd84f99d5d..44d88e9f8d 100644 --- a/benchmarks/client-nav/scenarios/control-flow/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/control-flow/solid/src/routeTree.gen.ts @@ -9,26 +9,16 @@ // 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 BrokenRouteImport } from './routes/broken' -import { Route as Hop1RouteImport } from './routes/hop1' -import { Route as Hop2RouteImport } from './routes/hop2' import { Route as TargetRouteImport } from './routes/target' +import { Route as Hop2RouteImport } from './routes/hop2' +import { Route as Hop1RouteImport } from './routes/hop1' +import { Route as BrokenRouteImport } from './routes/broken' +import { Route as IndexRouteImport } from './routes/index' import { Route as MissingIdRouteImport } from './routes/missing.$id' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const BrokenRoute = BrokenRouteImport.update({ - id: '/broken', - path: '/broken', - getParentRoute: () => rootRouteImport, -} as any) -const Hop1Route = Hop1RouteImport.update({ - id: '/hop1', - path: '/hop1', +const TargetRoute = TargetRouteImport.update({ + id: '/target', + path: '/target', getParentRoute: () => rootRouteImport, } as any) const Hop2Route = Hop2RouteImport.update({ @@ -36,9 +26,19 @@ const Hop2Route = Hop2RouteImport.update({ path: '/hop2', getParentRoute: () => rootRouteImport, } as any) -const TargetRoute = TargetRouteImport.update({ - id: '/target', - path: '/target', +const Hop1Route = Hop1RouteImport.update({ + id: '/hop1', + path: '/hop1', + getParentRoute: () => rootRouteImport, +} as any) +const BrokenRoute = BrokenRouteImport.update({ + id: '/broken', + path: '/broken', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const MissingIdRoute = MissingIdRouteImport.update({ @@ -98,25 +98,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/broken': { - id: '/broken' - path: '/broken' - fullPath: '/broken' - preLoaderRoute: typeof BrokenRouteImport - parentRoute: typeof rootRouteImport - } - '/hop1': { - id: '/hop1' - path: '/hop1' - fullPath: '/hop1' - preLoaderRoute: typeof Hop1RouteImport + '/target': { + id: '/target' + path: '/target' + fullPath: '/target' + preLoaderRoute: typeof TargetRouteImport parentRoute: typeof rootRouteImport } '/hop2': { @@ -126,11 +112,25 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof Hop2RouteImport parentRoute: typeof rootRouteImport } - '/target': { - id: '/target' - path: '/target' - fullPath: '/target' - preLoaderRoute: typeof TargetRouteImport + '/hop1': { + id: '/hop1' + path: '/hop1' + fullPath: '/hop1' + preLoaderRoute: typeof Hop1RouteImport + parentRoute: typeof rootRouteImport + } + '/broken': { + id: '/broken' + path: '/broken' + fullPath: '/broken' + preLoaderRoute: typeof BrokenRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/missing/$id': { diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/control-flow/vue/speed.bench.ts index 8a019945c7..9a335cfb87 100644 --- a/benchmarks/client-nav/scenarios/control-flow/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/control-flow/vue/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-control-flow', async ({ bench }) => { - const scenario = setup() +describe('client-control-flow', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-control-flow navigation loop (vue)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/control-flow/vue/src/routeTree.gen.ts index 6b53a6a203..60fc846f89 100644 --- a/benchmarks/client-nav/scenarios/control-flow/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/control-flow/vue/src/routeTree.gen.ts @@ -9,26 +9,16 @@ // 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 BrokenRouteImport } from './routes/broken' -import { Route as Hop1RouteImport } from './routes/hop1' -import { Route as Hop2RouteImport } from './routes/hop2' import { Route as TargetRouteImport } from './routes/target' +import { Route as Hop2RouteImport } from './routes/hop2' +import { Route as Hop1RouteImport } from './routes/hop1' +import { Route as BrokenRouteImport } from './routes/broken' +import { Route as IndexRouteImport } from './routes/index' import { Route as MissingIdRouteImport } from './routes/missing.$id' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const BrokenRoute = BrokenRouteImport.update({ - id: '/broken', - path: '/broken', - getParentRoute: () => rootRouteImport, -} as any) -const Hop1Route = Hop1RouteImport.update({ - id: '/hop1', - path: '/hop1', +const TargetRoute = TargetRouteImport.update({ + id: '/target', + path: '/target', getParentRoute: () => rootRouteImport, } as any) const Hop2Route = Hop2RouteImport.update({ @@ -36,9 +26,19 @@ const Hop2Route = Hop2RouteImport.update({ path: '/hop2', getParentRoute: () => rootRouteImport, } as any) -const TargetRoute = TargetRouteImport.update({ - id: '/target', - path: '/target', +const Hop1Route = Hop1RouteImport.update({ + id: '/hop1', + path: '/hop1', + getParentRoute: () => rootRouteImport, +} as any) +const BrokenRoute = BrokenRouteImport.update({ + id: '/broken', + path: '/broken', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const MissingIdRoute = MissingIdRouteImport.update({ @@ -98,25 +98,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/broken': { - id: '/broken' - path: '/broken' - fullPath: '/broken' - preLoaderRoute: typeof BrokenRouteImport - parentRoute: typeof rootRouteImport - } - '/hop1': { - id: '/hop1' - path: '/hop1' - fullPath: '/hop1' - preLoaderRoute: typeof Hop1RouteImport + '/target': { + id: '/target' + path: '/target' + fullPath: '/target' + preLoaderRoute: typeof TargetRouteImport parentRoute: typeof rootRouteImport } '/hop2': { @@ -126,11 +112,25 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof Hop2RouteImport parentRoute: typeof rootRouteImport } - '/target': { - id: '/target' - path: '/target' - fullPath: '/target' - preLoaderRoute: typeof TargetRouteImport + '/hop1': { + id: '/hop1' + path: '/hop1' + fullPath: '/hop1' + preLoaderRoute: typeof Hop1RouteImport + parentRoute: typeof rootRouteImport + } + '/broken': { + id: '/broken' + path: '/broken' + fullPath: '/broken' + preLoaderRoute: typeof BrokenRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/missing/$id': { diff --git a/benchmarks/client-nav/scenarios/head/react/speed.bench.ts b/benchmarks/client-nav/scenarios/head/react/speed.bench.ts index d0d731a09f..97c76a1a11 100644 --- a/benchmarks/client-nav/scenarios/head/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/head/react/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-head', async ({ bench }) => { - const scenario = setup() +describe('client-head', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-head navigation loop (react)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/head/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/head/solid/speed.bench.ts index ca156c950b..075e7673de 100644 --- a/benchmarks/client-nav/scenarios/head/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/head/solid/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-head', async ({ bench }) => { - const scenario = setup() +describe('client-head', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-head navigation loop (solid)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/head/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/head/solid/src/routeTree.gen.ts index b6f217e527..ead6a4436a 100644 --- a/benchmarks/client-nav/scenarios/head/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/head/solid/src/routeTree.gen.ts @@ -9,15 +9,15 @@ // 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 DocsRouteImport } from './routes/docs' import { Route as SettingsRouteImport } from './routes/settings' -import { Route as ArticlesIdRouteImport } from './routes/articles.$id' +import { Route as DocsRouteImport } from './routes/docs' +import { Route as IndexRouteImport } from './routes/index' import { Route as DocsSectionRouteImport } from './routes/docs.$section' +import { Route as ArticlesIdRouteImport } from './routes/articles.$id' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const SettingsRoute = SettingsRouteImport.update({ + id: '/settings', + path: '/settings', getParentRoute: () => rootRouteImport, } as any) const DocsRoute = DocsRouteImport.update({ @@ -25,14 +25,9 @@ const DocsRoute = DocsRouteImport.update({ path: '/docs', getParentRoute: () => rootRouteImport, } as any) -const SettingsRoute = SettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => rootRouteImport, -} as any) -const ArticlesIdRoute = ArticlesIdRouteImport.update({ - id: '/articles/$id', - path: '/articles/$id', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const DocsSectionRoute = DocsSectionRouteImport.update({ @@ -40,6 +35,11 @@ const DocsSectionRoute = DocsSectionRouteImport.update({ path: '/$section', getParentRoute: () => DocsRoute, } as any) +const ArticlesIdRoute = ArticlesIdRouteImport.update({ + id: '/articles/$id', + path: '/articles/$id', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -86,11 +86,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/settings': { + id: '/settings' + path: '/settings' + fullPath: '/settings' + preLoaderRoute: typeof SettingsRouteImport parentRoute: typeof rootRouteImport } '/docs': { @@ -100,18 +100,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DocsRouteImport parentRoute: typeof rootRouteImport } - '/settings': { - id: '/settings' - path: '/settings' - fullPath: '/settings' - preLoaderRoute: typeof SettingsRouteImport - parentRoute: typeof rootRouteImport - } - '/articles/$id': { - id: '/articles/$id' - path: '/articles/$id' - fullPath: '/articles/$id' - preLoaderRoute: typeof ArticlesIdRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/docs/$section': { @@ -121,6 +114,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DocsSectionRouteImport parentRoute: typeof DocsRoute } + '/articles/$id': { + id: '/articles/$id' + path: '/articles/$id' + fullPath: '/articles/$id' + preLoaderRoute: typeof ArticlesIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/client-nav/scenarios/head/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/head/vue/speed.bench.ts index d188a9dd7a..7080b4ea7d 100644 --- a/benchmarks/client-nav/scenarios/head/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/head/vue/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-head', async ({ bench }) => { - const scenario = setup() +describe('client-head', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-head navigation loop (vue)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/head/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/head/vue/src/routeTree.gen.ts index 161f99a65c..b115854c26 100644 --- a/benchmarks/client-nav/scenarios/head/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/head/vue/src/routeTree.gen.ts @@ -9,15 +9,15 @@ // 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 DocsRouteImport } from './routes/docs' import { Route as SettingsRouteImport } from './routes/settings' -import { Route as ArticlesIdRouteImport } from './routes/articles.$id' +import { Route as DocsRouteImport } from './routes/docs' +import { Route as IndexRouteImport } from './routes/index' import { Route as DocsSectionRouteImport } from './routes/docs.$section' +import { Route as ArticlesIdRouteImport } from './routes/articles.$id' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const SettingsRoute = SettingsRouteImport.update({ + id: '/settings', + path: '/settings', getParentRoute: () => rootRouteImport, } as any) const DocsRoute = DocsRouteImport.update({ @@ -25,14 +25,9 @@ const DocsRoute = DocsRouteImport.update({ path: '/docs', getParentRoute: () => rootRouteImport, } as any) -const SettingsRoute = SettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => rootRouteImport, -} as any) -const ArticlesIdRoute = ArticlesIdRouteImport.update({ - id: '/articles/$id', - path: '/articles/$id', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const DocsSectionRoute = DocsSectionRouteImport.update({ @@ -40,6 +35,11 @@ const DocsSectionRoute = DocsSectionRouteImport.update({ path: '/$section', getParentRoute: () => DocsRoute, } as any) +const ArticlesIdRoute = ArticlesIdRouteImport.update({ + id: '/articles/$id', + path: '/articles/$id', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -86,11 +86,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/settings': { + id: '/settings' + path: '/settings' + fullPath: '/settings' + preLoaderRoute: typeof SettingsRouteImport parentRoute: typeof rootRouteImport } '/docs': { @@ -100,18 +100,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof DocsRouteImport parentRoute: typeof rootRouteImport } - '/settings': { - id: '/settings' - path: '/settings' - fullPath: '/settings' - preLoaderRoute: typeof SettingsRouteImport - parentRoute: typeof rootRouteImport - } - '/articles/$id': { - id: '/articles/$id' - path: '/articles/$id' - fullPath: '/articles/$id' - preLoaderRoute: typeof ArticlesIdRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/docs/$section': { @@ -121,6 +114,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof DocsSectionRouteImport parentRoute: typeof DocsRoute } + '/articles/$id': { + id: '/articles/$id' + path: '/articles/$id' + fullPath: '/articles/$id' + preLoaderRoute: typeof ArticlesIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/client-nav/scenarios/history/react/speed.bench.ts b/benchmarks/client-nav/scenarios/history/react/speed.bench.ts index 6ec7031857..9192258b66 100644 --- a/benchmarks/client-nav/scenarios/history/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/history/react/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-history', async ({ bench }) => { - const scenario = setup() +describe('client-history', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-history navigation loop (react)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/history/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/history/solid/speed.bench.ts index 56af035b2b..d7f4fd898d 100644 --- a/benchmarks/client-nav/scenarios/history/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/history/solid/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-history', async ({ bench }) => { - const scenario = setup() +describe('client-history', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-history navigation loop (solid)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/history/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/history/solid/src/routeTree.gen.ts index af253f4a15..a6ab2a4fc8 100644 --- a/benchmarks/client-nav/scenarios/history/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/history/solid/src/routeTree.gen.ts @@ -9,24 +9,19 @@ // 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 GalleryRouteImport } from './routes/gallery' -import { Route as PagesNRouteImport } from './routes/pages.$n' +import { Route as IndexRouteImport } from './routes/index' import { Route as PhotosPhotoIdRouteImport } from './routes/photos.$photoId' +import { Route as PagesNRouteImport } from './routes/pages.$n' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const GalleryRoute = GalleryRouteImport.update({ id: '/gallery', path: '/gallery', getParentRoute: () => rootRouteImport, } as any) -const PagesNRoute = PagesNRouteImport.update({ - id: '/pages/$n', - path: '/pages/$n', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const PhotosPhotoIdRoute = PhotosPhotoIdRouteImport.update({ @@ -34,6 +29,11 @@ const PhotosPhotoIdRoute = PhotosPhotoIdRouteImport.update({ path: '/photos/$photoId', getParentRoute: () => rootRouteImport, } as any) +const PagesNRoute = PagesNRouteImport.update({ + id: '/pages/$n', + path: '/pages/$n', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -71,13 +71,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/gallery': { id: '/gallery' path: '/gallery' @@ -85,11 +78,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof GalleryRouteImport parentRoute: typeof rootRouteImport } - '/pages/$n': { - id: '/pages/$n' - path: '/pages/$n' - fullPath: '/pages/$n' - preLoaderRoute: typeof PagesNRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/photos/$photoId': { @@ -99,6 +92,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PhotosPhotoIdRouteImport parentRoute: typeof rootRouteImport } + '/pages/$n': { + id: '/pages/$n' + path: '/pages/$n' + fullPath: '/pages/$n' + preLoaderRoute: typeof PagesNRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/client-nav/scenarios/history/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/history/vue/speed.bench.ts index 3d36ac4cfa..a378e45ac5 100644 --- a/benchmarks/client-nav/scenarios/history/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/history/vue/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-history', async ({ bench }) => { - const scenario = setup() +describe('client-history', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-history navigation loop (vue)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/history/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/history/vue/src/routeTree.gen.ts index 519aef7c8f..cee1b68870 100644 --- a/benchmarks/client-nav/scenarios/history/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/history/vue/src/routeTree.gen.ts @@ -9,24 +9,19 @@ // 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 GalleryRouteImport } from './routes/gallery' -import { Route as PagesNRouteImport } from './routes/pages.$n' +import { Route as IndexRouteImport } from './routes/index' import { Route as PhotosPhotoIdRouteImport } from './routes/photos.$photoId' +import { Route as PagesNRouteImport } from './routes/pages.$n' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const GalleryRoute = GalleryRouteImport.update({ id: '/gallery', path: '/gallery', getParentRoute: () => rootRouteImport, } as any) -const PagesNRoute = PagesNRouteImport.update({ - id: '/pages/$n', - path: '/pages/$n', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const PhotosPhotoIdRoute = PhotosPhotoIdRouteImport.update({ @@ -34,6 +29,11 @@ const PhotosPhotoIdRoute = PhotosPhotoIdRouteImport.update({ path: '/photos/$photoId', getParentRoute: () => rootRouteImport, } as any) +const PagesNRoute = PagesNRouteImport.update({ + id: '/pages/$n', + path: '/pages/$n', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -71,13 +71,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/gallery': { id: '/gallery' path: '/gallery' @@ -85,11 +78,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof GalleryRouteImport parentRoute: typeof rootRouteImport } - '/pages/$n': { - id: '/pages/$n' - path: '/pages/$n' - fullPath: '/pages/$n' - preLoaderRoute: typeof PagesNRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/photos/$photoId': { @@ -99,6 +92,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PhotosPhotoIdRouteImport parentRoute: typeof rootRouteImport } + '/pages/$n': { + id: '/pages/$n' + path: '/pages/$n' + fullPath: '/pages/$n' + preLoaderRoute: typeof PagesNRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/client-nav/scenarios/hydration/react/fixture.ts b/benchmarks/client-nav/scenarios/hydration/react/fixture.ts deleted file mode 100644 index 950c870a1c..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/fixture.ts +++ /dev/null @@ -1,31 +0,0 @@ -export const ordinaryLinkCount = 192 -export const hashLinkCount = 8 -export const serverUrl = '/teams/team-7/items/item-42?view=summary' -export const clientUrl = `${serverUrl}#details` - -export interface Diagnostics { - beforeLoads: number - loaders: number - mounted: boolean - clicks: number - ordinaryRenders: number - hashRenders: number - countRenders: boolean -} - -export function createDiagnostics(countRenders = false): Diagnostics { - return { - beforeLoads: 0, - loaders: 0, - mounted: false, - clicks: 0, - ordinaryRenders: 0, - hashRenders: 0, - countRenders, - } -} - -export interface FixtureArtifact { - html: string - scripts: Array -} diff --git a/benchmarks/client-nav/scenarios/hydration/react/generate-fixture.mjs b/benchmarks/client-nav/scenarios/hydration/react/generate-fixture.mjs deleted file mode 100644 index fbc67c5a08..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/generate-fixture.mjs +++ /dev/null @@ -1,23 +0,0 @@ -import assert from 'node:assert/strict' -import { writeFile } from 'node:fs/promises' -import { JSDOM } from 'jsdom' - -if (process.env.NODE_ENV !== 'production') { - throw new Error('Generate the hydration fixture in production mode') -} -const { renderFixture } = await import('./dist/server/server.js') -const html = await renderFixture() -const dom = new JSDOM(html) -try { - const scriptElements = [...dom.window.document.querySelectorAll('script')] - assert.ok(scriptElements.length > 0) - assert.ok(scriptElements.every((script) => !script.src)) - const scripts = scriptElements.map((script) => script.textContent) - assert.ok(scripts.some((script) => script.includes('$_TSR'))) - await writeFile( - new URL('./dist/fixture.json', import.meta.url), - JSON.stringify({ html, scripts }), - ) -} finally { - dom.window.close() -} diff --git a/benchmarks/client-nav/scenarios/hydration/react/hydration.test.ts b/benchmarks/client-nav/scenarios/hydration/react/hydration.test.ts deleted file mode 100644 index 7e466cbaed..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/hydration.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { expect, test } from 'vitest' -import { hashLinkCount, ordinaryLinkCount } from './fixture' -import { setup } from './setup' -import { settleHydration } from './settle' - -const turn = () => new Promise((resolve) => setImmediate(resolve)) - -test('restores data and context into fresh DOMs and includes follow-up renders', async () => { - const scenario = setup({ countRenders: true }) - const schedulerTasks = new Set() - for (let iteration = 0; iteration < 3; iteration++) { - await scenario.before() - try { - expect(scenario.snapshot().diagnostics.mounted).toBe(false) - expect(scenario.snapshot().matches).toBeUndefined() - await scenario.run() - schedulerTasks.add(scenario.schedulerTasks()) - const completed = scenario.snapshot() - // Supports both main's extra Link update and the optimized snapshot. - expect([ordinaryLinkCount, ordinaryLinkCount * 2]).toContain( - completed.diagnostics.ordinaryRenders, - ) - expect(completed.diagnostics.hashRenders).toBeGreaterThanOrEqual( - hashLinkCount + hashLinkCount / 2, - ) - for (let index = 0; index < 4; index++) { - await turn() - } - expect(scenario.snapshot()).toEqual(completed) - await expect(scenario.run()).rejects.toThrow('newly prepared sample') - } finally { - await scenario.after() - } - } - // React yields on its pinned clock, never on wall time spent hydrating. - expect(schedulerTasks.size).toBe(1) -}) - -test('rejects an empty measurement and still releases its sample', async () => { - const scenario = setup() - await scenario.before() - await expect(scenario.after()).rejects.toThrow( - 'Hydration sample was not completed', - ) - await scenario.before() - try { - await scenario.run() - } finally { - await scenario.after() - } -}) - -test('waits for a commit and scheduler work lasting more than 100 turns', async () => { - let committed = false - const commit = (async () => { - for (let index = 0; index < 150; index++) { - await turn() - } - committed = true - })() - let remainingCallbacks = 150 - await settleHydration( - commit, - () => { - expect(committed).toBe(true) - return remainingCallbacks-- <= 0 - }, - () => 'delayed commit', - ) - expect(remainingCallbacks).toBeLessThan(0) -}) - -test('retains a watchdog for a commit that never completes', async () => { - await expect( - settleHydration( - new Promise(() => {}), - () => true, - () => 'commit pending', - 10, - ), - ).rejects.toThrow('Hydration did not settle within 10ms: commit pending') -}) - -test('retains a watchdog when scheduler work never becomes idle', async () => { - await expect( - settleHydration( - Promise.resolve(), - () => false, - () => 'callbacks pending', - 10, - ), - ).rejects.toThrow('Hydration did not settle within 10ms: callbacks pending') -}) diff --git a/benchmarks/client-nav/scenarios/hydration/react/project.json b/benchmarks/client-nav/scenarios/hydration/react/project.json deleted file mode 100644 index ca23838c0f..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-hydration-react", - "projectType": "application", - "targets": { - "build:client": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { "projects": ["@tanstack/react-router"], "target": "build" } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.server.config.ts && NODE_ENV=production node {projectRoot}/generate-fixture.mjs && NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:unit": { - "executor": "nx:run-commands", - "dependsOn": ["build:client"], - "options": { - "command": "vitest run --config ./scenarios/hydration/react/vite.config.ts", - "cwd": "benchmarks/client-nav" - } - }, - "test:perf": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": ["build:client"], - "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --run --config ./scenarios/hydration/react/vite.config.ts", - "cwd": "benchmarks/client-nav" - } - }, - "test:types:client": { - "executor": "nx:run-commands", - "dependsOn": [ - { "projects": ["@tanstack/react-router"], "target": "build" } - ], - "options": { "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" } - } - } -} diff --git a/benchmarks/client-nav/scenarios/hydration/react/settle.ts b/benchmarks/client-nav/scenarios/hydration/react/settle.ts deleted file mode 100644 index cc4c09a72d..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/settle.ts +++ /dev/null @@ -1,35 +0,0 @@ -const turn = () => new Promise((resolve) => setImmediate(resolve)) - -export async function settleHydration( - committed: Promise, - isIdle: () => boolean, - describeProgress: () => string, - timeoutMs = 60_000, -) { - let timeoutError: Error | undefined - let watchdog: ReturnType | undefined - const timeout = new Promise((_, reject) => { - watchdog = setTimeout(() => { - timeoutError = new Error( - `Hydration did not settle within ${timeoutMs}ms: ${describeProgress()}`, - ) - reject(timeoutError) - }, timeoutMs) - }) - try { - // Concurrent hydration can need many more scheduler turns under CPU - // instrumentation. Await its commit instead of limiting successful work - // to an arbitrary number of event-loop polls. - await Promise.race([committed, timeout]) - let idleTurns = 0 - while (idleTurns < 2) { - await turn() - if (timeoutError) { - throw timeoutError - } - idleTurns = isIdle() ? idleTurns + 1 : 0 - } - } finally { - clearTimeout(watchdog) - } -} diff --git a/benchmarks/client-nav/scenarios/hydration/react/setup.ts b/benchmarks/client-nav/scenarios/hydration/react/setup.ts deleted file mode 100644 index 7c588af3fd..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/setup.ts +++ /dev/null @@ -1,316 +0,0 @@ -import assert from 'node:assert/strict' -import { readFileSync } from 'node:fs' -import { fileURLToPath } from 'node:url' -import { Script } from 'node:vm' -import { JSDOM, VirtualConsole } from 'jsdom' -import { clientUrl, hashLinkCount, ordinaryLinkCount } from './fixture' -import { settleHydration } from './settle' -import type { FixtureArtifact } from './fixture' -import type * as Client from './src/client' - -type ClientApp = typeof Client -const turn = () => new Promise((resolve) => setImmediate(resolve)) - -// React's scheduler ends a time slice once performance.now() has advanced 5 ms. -// Under CodSpeed's CPU simulation the wall clock advances much further per -// instruction, by a runner-dependent factor, so real time turned identical -// samples into different numbers of yields, scheduler tasks and event-loop -// turns. With a frozen clock React yields only to paint after a commit, as on -// a fast host. 1 s is past React's initial 300 ms fallback throttle. Only the -// window's performance clock is pinned: Date.now(), which the Router uses for -// match timestamps, is unchanged. -const schedulerTime = 1_000 - -export function setup({ countRenders = false } = {}) { - // Compile once, outside measurement. Evaluation below creates fresh objects - // in each window's realm; neither the payload nor module state is reused. - const artifact: FixtureArtifact = JSON.parse( - readFileSync(new URL('./dist/fixture.json', import.meta.url), 'utf8'), - ) - const clientPath = new URL('./dist/client/client.js', import.meta.url) - const clientScript = new Script(readFileSync(clientPath, 'utf8'), { - filename: fileURLToPath(clientPath), - }) - const bootstrapScripts = artifact.scripts.map( - (source, index) => - new Script(source, { - filename: `hydration-bootstrap-${index}.js`, - }), - ) - let current: Awaited> | undefined - - async function prepare() { - const errors: Array = [] - const virtualConsole = new VirtualConsole() - virtualConsole.on('jsdomError', (error) => errors.push(String(error))) - virtualConsole.on('error', (...args) => - errors.push(args.map(String).join(' ')), - ) - const dom = new JSDOM(artifact.html, { - url: `http://localhost${clientUrl}`, - runScripts: 'outside-only', - virtualConsole, - }) - const immediates = new Set() - const scheduler = { tasks: 0 } - try { - Object.assign(dom.window, { - TextEncoder, - TextDecoder, - ReadableStream, - WritableStream, - TransformStream, - // Let React's production scheduler use the same task-turn primitive as - // the existing Node client benchmarks, without a real-delay timer. - setImmediate( - callback: (...args: Array) => void, - ...args: Array - ) { - scheduler.tasks++ - const handle = setImmediate(() => { - immediates.delete(handle) - callback(...args) - }) - immediates.add(handle) - return handle - }, - clearImmediate(handle: NodeJS.Immediate) { - immediates.delete(handle) - clearImmediate(handle) - }, - fetch() { - throw new Error('Hydration attempted a network request') - }, - scrollTo() {}, - }) - dom.window.performance.now = () => schedulerTime - const context = dom.getInternalVMContext() - // jsdom has no layout/scroll implementation; only hydration CPU is measured. - dom.window.HTMLElement.prototype.scrollIntoView = () => {} - clientScript.runInContext(context) - const app = (dom.window as unknown as { HydrationBenchmark: ClientApp }) - .HydrationBenchmark - assert.equal(app.serverEnvironment, false) - const anchors = Array.from(dom.window.document.querySelectorAll('a')) - const scriptElements = Array.from( - dom.window.document.querySelectorAll('script'), - ) - const executingScript = { current: null as HTMLScriptElement | null } - Object.defineProperty(dom.window.document, 'currentScript', { - configurable: true, - get: () => executingScript.current, - }) - assert.equal(anchors.length, ordinaryLinkCount + hashLinkCount) - const content = dom.window.document.getElementById('hydration-content') - assert.ok(content) - // Finish jsdom's initial document lifecycle before opening the measure. - await turn() - assert.equal(dom.window.document.readyState, 'complete') - assert.equal(app.ready(), false) - return { - dom, - context, - app, - anchors, - content, - scriptElements, - executingScript, - immediates, - scheduler, - errors, - started: false, - completed: false, - failed: false, - } - } catch (error) { - for (const handle of immediates) { - clearImmediate(handle) - } - dom.window.close() - throw error - } - } - - async function before() { - if (current) { - throw new Error('Previous hydration sample was not disposed') - } - current = await prepare() - } - - async function run() { - const sample = current - if (!sample || sample.started) { - throw new Error('Hydration requires a newly prepared sample') - } - sample.started = true - try { - // HTML parsing/module evaluation are already done. Payload execution, - // router initialization/restoration and React hydration are measured. - for (let index = 0; index < bootstrapScripts.length; index++) { - // SSR bootstrap scripts remove their own script element after running. - sample.executingScript.current = sample.scriptElements[index]! - try { - bootstrapScripts[index]!.runInContext(sample.context) - } finally { - sample.executingScript.current = null - } - } - await settleHydration( - sample.app.start(countRenders), - () => sample.immediates.size === 0, - () => { - const progress = sample.app.snapshot() - return JSON.stringify({ - diagnostics: progress.diagnostics, - errors: [...sample.errors, ...progress.errors], - restoredMatches: progress.matches?.length, - pendingSchedulerCallbacks: sample.immediates.size, - }) - }, - ) - if (sample.errors.length) { - throw new Error(sample.errors.join('\n')) - } - assert.ok( - sample.app.ready(), - 'Hydration committed without the expected active links', - ) - sample.completed = true - } catch (error) { - sample.failed = true - throw error - } - } - - function snapshot() { - if (!current) { - throw new Error('No hydration sample') - } - // Normalize realm prototypes only for untimed assertions. - return JSON.parse(JSON.stringify(current.app.snapshot())) as ReturnType< - ClientApp['snapshot'] - > - } - - function schedulerTasks() { - if (!current) { - throw new Error('No hydration sample') - } - return current.scheduler.tasks - } - - function validate() { - assert.ok(current?.started) - const { dom, anchors, content, errors } = current - const doc = dom.window.document - const result = snapshot() - assert.deepEqual(errors, []) - assert.deepEqual(result.errors, []) - assert.equal(result.diagnostics.beforeLoads, 0) - assert.equal(result.diagnostics.loaders, 0) - assert.equal(result.diagnostics.mounted, true) - assert.equal(result.location, clientUrl) - assert.equal(result.matches?.length, 3) - for (const match of result.matches) { - assert.equal(match.status, 'success') - assert.deepEqual(match.context.viewer, { - id: 'viewer-3', - name: 'Ada', - role: 'editor', - }) - } - assert.deepEqual(result.matches[1]!.context.team, { - id: 'team-7', - member: 'viewer-3', - }) - assert.deepEqual(result.matches[2]!.context.permissions, { edit: true }) - assert.deepEqual(result.matches[1]!.loaderData, { - title: 'Team team-7', - categories: ['open', 'closed'], - }) - const data = result.matches[2]!.loaderData as { - owner: string - selected: string - rows: Array<{ - id: string - label: string - details: { score: number; open: boolean } - }> - } - assert.equal(data.owner, 'viewer-3') - assert.equal(data.selected, 'item-42') - assert.equal(data.rows.length, ordinaryLinkCount) - assert.equal(doc.getElementById('hydration-content'), content) - assert.equal(doc.querySelectorAll('a').length, anchors.length) - assert.equal(doc.getElementById('viewer')?.textContent, 'Ada') - assert.equal(doc.getElementById('permission')?.textContent, 'Editable') - for (const anchor of anchors) { - assert.equal(doc.getElementById(anchor.id), anchor) - } - for (let index = 0; index < ordinaryLinkCount; index++) { - const anchor = doc.getElementById(`ordinary-item-${index}`)! - assert.equal( - anchor.getAttribute('href'), - `/teams/team-7/items/item-${index}?view=summary`, - ) - assert.equal(anchor.textContent, `Item ${index}`) - assert.equal( - anchor.getAttribute('data-status'), - index === 42 ? 'active' : null, - ) - assert.deepEqual(data.rows[index], { - id: `item-${index}`, - label: `Item ${index}`, - details: { score: index * 3, open: index % 2 === 0 }, - }) - } - for (let index = 0; index < hashLinkCount; index++) { - assert.equal( - doc.getElementById(`hash-${index}`)?.getAttribute('data-status'), - index % 2 === 0 ? 'active' : null, - ) - } - doc - .getElementById('interactive')! - .dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true })) - assert.equal( - current.app.snapshot().diagnostics.clicks, - result.diagnostics.clicks + 1, - ) - } - - async function after() { - const sample = current - if (!sample) { - return - } - try { - if (!sample.failed) { - assert.ok(sample.completed, 'Hydration sample was not completed') - validate() - } - } finally { - current = undefined - try { - sample.app.dispose() - // Unmount work and its scheduled effects stay outside the measure. - await turn() - await turn() - } finally { - for (const handle of sample.immediates) { - clearImmediate(handle) - } - sample.dom.window.close() - } - } - } - - return { - before, - run, - after, - snapshot, - schedulerTasks, - } -} diff --git a/benchmarks/client-nav/scenarios/hydration/react/speed.bench.ts b/benchmarks/client-nav/scenarios/hydration/react/speed.bench.ts deleted file mode 100644 index 643877760e..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { setup } from './setup' - -test('client-hydration', async ({ bench }) => { - const scenario = setup() - - await bench( - 'hydrate restored route state and mixed Links (react)', - { beforeEach: scenario.before, afterEach: scenario.after }, - async () => { - await scenario.run() - }, - ).run({ - time: 5000, - warmupTime: 1000, - warmupIterations: 20, - throws: true, - }) -}) diff --git a/benchmarks/client-nav/scenarios/hydration/react/src/app.tsx b/benchmarks/client-nav/scenarios/hydration/react/src/app.tsx deleted file mode 100644 index e9797f71fa..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/src/app.tsx +++ /dev/null @@ -1,216 +0,0 @@ -import { useEffect } from 'react' -import { - HeadContent, - Link, - Outlet, - Scripts, - createMemoryHistory, - createRootRoute, - createRoute, - createRouter, - useHydrated, -} from '@tanstack/react-router' -import { - clientUrl, - hashLinkCount, - ordinaryLinkCount, - serverUrl, -} from '../fixture' -import type { ReactNode } from 'react' -import type { Diagnostics } from '../fixture' - -export function createFixtureRouter( - server: boolean, - diagnostics: Diagnostics, - onHydrated: () => void = () => {}, -) { - function beforeLoad() { - diagnostics.beforeLoads++ - if (!server) { - throw new Error('Hydration reran beforeLoad instead of restoring context') - } - } - - function loader() { - diagnostics.loaders++ - if (!server) { - throw new Error('Hydration reran a loader instead of restoring data') - } - } - - const root = createRootRoute({ - beforeLoad: () => { - beforeLoad() - return { viewer: { id: 'viewer-3', name: 'Ada', role: 'editor' } } - }, - head: () => ({ - meta: [{ charSet: 'utf-8' }, { title: 'Hydration benchmark' }], - }), - shellComponent: Document, - }) - const team = createRoute({ - getParentRoute: () => root, - path: '/teams/$teamId', - beforeLoad: ({ context, params }) => { - beforeLoad() - return { team: { id: params.teamId, member: context.viewer.id } } - }, - loader: ({ context }) => { - loader() - return { - title: `Team ${context.team.id}`, - categories: ['open', 'closed'], - } - }, - component: Team, - }) - const items = createRoute({ - getParentRoute: () => team, - path: 'items/$itemId', - validateSearch: (search: Record) => ({ - view: search.view === 'details' ? 'details' : 'summary', - }), - beforeLoad: ({ context }) => { - beforeLoad() - return { permissions: { edit: context.viewer.role === 'editor' } } - }, - loader: ({ context, params }) => { - loader() - return { - selected: params.itemId, - owner: context.team.member, - rows: Array.from({ length: ordinaryLinkCount }, (_, index) => ({ - id: `item-${index}`, - label: `Item ${index}`, - details: { score: index * 3, open: index % 2 === 0 }, - })), - } - }, - component: Items, - }) - - function Document({ children }: { children: ReactNode }) { - return ( - - - - - - {children} - - - - ) - } - - function Team() { - const context = team.useRouteContext() - const data = team.useLoaderData() - return ( -
-

{data.title}

-

{context.viewer.name}

- -
- ) - } - - function Items() { - const data = items.useLoaderData() - const context = items.useRouteContext() - useEffect(() => { - diagnostics.mounted = true - }, []) - return ( - <> -

- {context.permissions.edit ? 'Editable' : 'Read only'} -

- - - - {data.rows.map((row) => ( - - - - - - ))} - -
{row.id}{row.details.score} - - {diagnostics.countRenders - ? () => { - diagnostics.ordinaryRenders++ - return row.label - } - : row.label} - -
- -
Details
- - - ) - } - - function HydrationComplete() { - const hydrated = useHydrated() - useEffect(() => { - if (hydrated) { - onHydrated() - } - }, [hydrated]) - return null - } - - return createRouter({ - routeTree: root.addChildren([team.addChildren([items])]), - history: createMemoryHistory({ - initialEntries: [server ? serverUrl : clientUrl], - }), - isServer: server, - scrollRestoration: false, - defaultHashScrollIntoView: false, - defaultPreload: false, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/client-nav/scenarios/hydration/react/src/client.tsx b/benchmarks/client-nav/scenarios/hydration/react/src/client.tsx deleted file mode 100644 index 42c5a5104e..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/src/client.tsx +++ /dev/null @@ -1,83 +0,0 @@ -import { startTransition } from 'react' -import { hydrateRoot } from 'react-dom/client' -import { RouterProvider } from '@tanstack/react-router' -import { hydrate } from '@tanstack/react-router/ssr/client' -import { isServer } from '@tanstack/router-core/isServer' -import { createDiagnostics, hashLinkCount } from '../fixture' -import { createFixtureRouter } from './app' - -export const serverEnvironment = isServer -let router: ReturnType | undefined -let root: ReturnType | undefined -let diagnostics = createDiagnostics() -const errors: Array = [] - -export async function start(countRenders = false) { - if (router) { - throw new Error('A hydration sample must use a fresh client realm') - } - if (!window.$_TSR?.router) { - throw new Error('Missing SSR hydration payload') - } - diagnostics = createDiagnostics(countRenders) - let resolveHydrated!: () => void - let rejectHydrated!: (error: unknown) => void - const hydrated = new Promise((resolve, reject) => { - resolveHydrated = resolve - rejectHydrated = reject - }) - router = createFixtureRouter(false, diagnostics, resolveHydrated) - // This is the same restoration path used by Start, without a module-cached - // RouterClient/StartClient promise or a live server in the worker. - await hydrate(router) - window.$_TSR.h() - startTransition(() => { - root = hydrateRoot(document, , { - onRecoverableError: (error) => { - errors.push(String(error)) - rejectHydrated(error) - }, - onUncaughtError: (error) => { - errors.push(String(error)) - rejectHydrated(error) - }, - }) - }) - await hydrated -} - -export function ready() { - if (!diagnostics.mounted) { - return false - } - // Matching hash Links only become active in the follow-up hydration commit. - // Ending at the first mount effect would miss the work this scenario targets. - for (let index = 0; index < hashLinkCount; index += 2) { - if ( - document.getElementById(`hash-${index}`)?.getAttribute('data-status') !== - 'active' - ) { - return false - } - } - return true -} - -export function snapshot() { - const matches = router?.stores.matches.get() - return { - diagnostics: { ...diagnostics }, - errors: [...errors], - location: router?.stores.location.get().href, - matches: matches?.map((match) => ({ - status: match.status, - context: match.context, - loaderData: match.loaderData, - })), - } -} - -export function dispose() { - root?.unmount() - router?.history.destroy() -} diff --git a/benchmarks/client-nav/scenarios/hydration/react/src/server.tsx b/benchmarks/client-nav/scenarios/hydration/react/src/server.tsx deleted file mode 100644 index 713b0a77f2..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/src/server.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { - createRequestHandler, - defaultStreamHandler, -} from '@tanstack/react-router/ssr/server' -import { isServer } from '@tanstack/router-core/isServer' -import { createDiagnostics, serverUrl } from '../fixture' -import { createFixtureRouter } from './app' - -export async function renderFixture() { - if ((isServer as boolean | undefined) !== true) { - throw new Error('Fixture generation requires the production server build') - } - const diagnostics = createDiagnostics() - const response = await createRequestHandler({ - createRouter: () => createFixtureRouter(true, diagnostics), - request: new Request(`http://localhost${serverUrl}`), - })(defaultStreamHandler) - const html = await response.text() - if ( - response.status !== 200 || - diagnostics.beforeLoads !== 3 || - diagnostics.loaders !== 2 - ) { - throw new Error( - 'SSR fixture did not execute its beforeLoad and loader functions', - ) - } - return html -} diff --git a/benchmarks/client-nav/scenarios/hydration/react/tsconfig.json b/benchmarks/client-nav/scenarios/hydration/react/tsconfig.json deleted file mode 100644 index 23dd08de8b..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/tsconfig.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": ["./*.ts", "./src/**/*"] -} diff --git a/benchmarks/client-nav/scenarios/hydration/react/vite.config.ts b/benchmarks/client-nav/scenarios/hydration/react/vite.config.ts deleted file mode 100644 index 62ab87115b..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/vite.config.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -export default defineConfig({ - root: fileURLToPath(new URL('.', import.meta.url)), - define: { 'process.env.NODE_ENV': JSON.stringify('production') }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - react(), - ], - resolve: { conditions: ['browser', 'production'] }, - build: { - outDir: './dist/client', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/client.tsx', - name: 'HydrationBenchmark', - formats: ['iife'], - fileName: () => 'client.js', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav hydration (react)', - watch: false, - environment: 'node', - isolate: true, - include: ['hydration.test.ts'], - benchmark: { include: ['speed.bench.ts'] }, - }, -}) diff --git a/benchmarks/client-nav/scenarios/hydration/react/vite.server.config.ts b/benchmarks/client-nav/scenarios/hydration/react/vite.server.config.ts deleted file mode 100644 index fbf6a149b9..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/vite.server.config.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vite' -import react from '@vitejs/plugin-react' - -export default defineConfig({ - root: fileURLToPath(new URL('.', import.meta.url)), - define: { 'process.env.NODE_ENV': JSON.stringify('production') }, - plugins: [react()], - resolve: { conditions: ['node', 'production'] }, - ssr: { noExternal: true }, - build: { - ssr: true, - outDir: './dist/server', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/server.tsx', - formats: ['es'], - fileName: () => 'server.js', - }, - rolldownOptions: { - platform: 'node', - external: [/^node:/, /^react(?:\/|$)/, /^react-dom(?:\/|$)/], - }, - }, -}) diff --git a/benchmarks/client-nav/scenarios/hydration/solid/fixture.ts b/benchmarks/client-nav/scenarios/hydration/solid/fixture.ts deleted file mode 100644 index 4c86d0e2f4..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/solid/fixture.ts +++ /dev/null @@ -1,35 +0,0 @@ -export { - clientUrl, - hashLinkCount, - ordinaryLinkCount, - serverUrl, -} from '../react/fixture' -export type { FixtureArtifact } from '../react/fixture' - -export interface Diagnostics { - beforeLoads: number - loaders: number - mounted: boolean - rendered: number - clicks: number - countUpdates: boolean - ordinaryEvaluations: number - hashEvaluations: number - initialHashStates: Array - hashStates: Array -} - -export function createDiagnostics(countUpdates = false): Diagnostics { - return { - beforeLoads: 0, - loaders: 0, - mounted: false, - rendered: 0, - clicks: 0, - countUpdates, - ordinaryEvaluations: 0, - hashEvaluations: 0, - initialHashStates: [], - hashStates: [], - } -} diff --git a/benchmarks/client-nav/scenarios/hydration/solid/generate-fixture.mjs b/benchmarks/client-nav/scenarios/hydration/solid/generate-fixture.mjs deleted file mode 100644 index 63647e1be7..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/solid/generate-fixture.mjs +++ /dev/null @@ -1,30 +0,0 @@ -import assert from 'node:assert/strict' -import { writeFile } from 'node:fs/promises' -import { JSDOM } from 'jsdom' - -if (process.env.NODE_ENV !== 'production') { - throw new Error('Generate the hydration fixture in production mode') -} -const { renderFixture } = await import('./dist/server/server.js') -const html = await renderFixture() -const dom = new JSDOM(html) -try { - const doc = dom.window.document - const scriptElements = [...doc.querySelectorAll('script')] - assert.ok(scriptElements.length > 0) - assert.ok(scriptElements.every((script) => !script.src)) - const scripts = scriptElements.map((script) => script.textContent) - assert.ok(scripts.some((script) => script.includes('$_TSR'))) - assert.ok(scripts.some((script) => script.includes('_$HY'))) - assert.ok(doc.documentElement.hasAttribute('data-hk')) - assert.ok(doc.getElementById('hydration-content')?.hasAttribute('data-hk')) - assert.ok( - [...doc.querySelectorAll('a')].every((a) => a.hasAttribute('data-hk')), - ) - await writeFile( - new URL('./dist/fixture.json', import.meta.url), - JSON.stringify({ html, scripts }), - ) -} finally { - dom.window.close() -} diff --git a/benchmarks/client-nav/scenarios/hydration/solid/hydration.test.ts b/benchmarks/client-nav/scenarios/hydration/solid/hydration.test.ts deleted file mode 100644 index 4e5f3208ca..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/solid/hydration.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { expect, test } from 'vitest' -import { hashLinkCount, ordinaryLinkCount } from './fixture' -import { setup } from './setup' - -const turn = () => new Promise((resolve) => setImmediate(resolve)) - -test('restores fresh DOMs and route state and completes hash-link reactivity', async () => { - const scenario = setup({ countUpdates: true }) - let previous: ReturnType | undefined - for (let iteration = 0; iteration < 3; iteration++) { - await scenario.before() - try { - const initial = scenario.snapshot() - expect(initial.matches).toBeUndefined() - expect(initial.diagnostics.mounted).toBe(false) - expect(initial.diagnostics.rendered).toBe(0) - expect(initial.diagnostics.clicks).toBe(0) - expect(initial.diagnostics.ordinaryEvaluations).toBe(0) - expect(initial.diagnostics.hashEvaluations).toBe(0) - expect(initial.diagnostics.initialHashStates).toEqual([]) - await scenario.run() - const completed = scenario.snapshot() - expect(completed.diagnostics.ordinaryEvaluations).toBeGreaterThanOrEqual( - ordinaryLinkCount, - ) - expect(completed.diagnostics.initialHashStates).toEqual( - Array.from({ length: hashLinkCount }, () => false), - ) - expect(completed.diagnostics.hashStates).toEqual( - Array.from({ length: hashLinkCount }, (_, index) => index % 2 === 0), - ) - expect(completed.diagnostics.hashEvaluations).toBeGreaterThanOrEqual( - hashLinkCount + hashLinkCount / 2, - ) - expect(completed.hydrating).toBe(false) - for (let index = 0; index < 4; index++) { - await turn() - } - expect(scenario.snapshot()).toEqual(completed) - if (previous) { - expect(completed).toEqual(previous) - } - previous = completed - await expect(scenario.run()).rejects.toThrow('newly prepared sample') - } finally { - // Untimed assertions include DOM identity, all restored data/context, - // native event handling, and the absence of hydration diagnostics. - await scenario.after() - } - } -}) - -test('prepares every sample without counting diagnostics', async () => { - const scenario = setup() - for (let iteration = 0; iteration < 2; iteration++) { - await scenario.before() - try { - expect(scenario.snapshot().diagnostics.mounted).toBe(false) - expect(scenario.snapshot().diagnostics.clicks).toBe(0) - await scenario.run() - expect(scenario.snapshot().diagnostics.hashEvaluations).toBe(0) - } finally { - await scenario.after() - } - } -}) - -test('rejects an empty measurement and still releases its sample', async () => { - const scenario = setup() - await scenario.before() - await expect(scenario.after()).rejects.toThrow( - 'Hydration sample was not completed', - ) - await scenario.before() - try { - await expect(scenario.before()).rejects.toThrow('was not disposed') - await scenario.run() - } finally { - await scenario.after() - } -}) diff --git a/benchmarks/client-nav/scenarios/hydration/solid/project.json b/benchmarks/client-nav/scenarios/hydration/solid/project.json deleted file mode 100644 index 1fa162771b..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/solid/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-hydration-solid", - "projectType": "application", - "targets": { - "build:client": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { "projects": ["@tanstack/solid-router"], "target": "build" } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.server.config.ts && NODE_ENV=production node {projectRoot}/generate-fixture.mjs && NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:unit": { - "executor": "nx:run-commands", - "dependsOn": ["build:client"], - "options": { - "command": "vitest run --config ./scenarios/hydration/solid/vite.config.ts", - "cwd": "benchmarks/client-nav" - } - }, - "test:perf": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": ["build:client"], - "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --run --config ./scenarios/hydration/solid/vite.config.ts", - "cwd": "benchmarks/client-nav" - } - }, - "test:types:client": { - "executor": "nx:run-commands", - "dependsOn": [ - { "projects": ["@tanstack/solid-router"], "target": "build" } - ], - "options": { "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" } - } - } -} diff --git a/benchmarks/client-nav/scenarios/hydration/solid/setup.ts b/benchmarks/client-nav/scenarios/hydration/solid/setup.ts deleted file mode 100644 index ebdbc8e9b2..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/solid/setup.ts +++ /dev/null @@ -1,326 +0,0 @@ -import assert from 'node:assert/strict' -import { readFileSync } from 'node:fs' -import { fileURLToPath } from 'node:url' -import { Script } from 'node:vm' -import { JSDOM, VirtualConsole } from 'jsdom' -import { clientUrl, hashLinkCount, ordinaryLinkCount } from './fixture' -import type { FixtureArtifact } from './fixture' -import type * as Client from './src/client' - -type ClientApp = typeof Client -const turn = () => new Promise((resolve) => setImmediate(resolve)) -const maxSettleTurns = 100 - -export function setup({ countUpdates = false } = {}) { - // Compile once, outside measurement; evaluate the entire production bundle - // anew in every window, including Solid's module-level hydration state. - const artifact: FixtureArtifact = JSON.parse( - readFileSync(new URL('./dist/fixture.json', import.meta.url), 'utf8'), - ) - const clientPath = new URL('./dist/client/client.js', import.meta.url) - const clientScript = new Script(readFileSync(clientPath, 'utf8'), { - filename: fileURLToPath(clientPath), - }) - const bootstrapScripts = artifact.scripts.map( - (source, index) => - new Script(source, { - filename: `solid-hydration-bootstrap-${index}.js`, - }), - ) - let current: Awaited> | undefined - - async function prepare() { - const errors: Array = [] - const virtualConsole = new VirtualConsole() - virtualConsole.on('jsdomError', (error) => errors.push(String(error))) - for (const event of ['error', 'warn'] as const) { - virtualConsole.on(event, (...args) => - errors.push(args.map(String).join(' ')), - ) - } - const dom = new JSDOM(artifact.html, { - url: `http://localhost${clientUrl}`, - runScripts: 'outside-only', - virtualConsole, - }) - const immediates = new Set() - try { - Object.assign(dom.window, { - TextEncoder, - TextDecoder, - ReadableStream, - WritableStream, - TransformStream, - setImmediate( - callback: (...args: Array) => void, - ...args: Array - ) { - const handle = setImmediate(() => { - immediates.delete(handle) - callback(...args) - }) - immediates.add(handle) - return handle - }, - clearImmediate(handle: NodeJS.Immediate) { - immediates.delete(handle) - clearImmediate(handle) - }, - fetch() { - throw new Error('Hydration attempted a network request') - }, - scrollTo() {}, - }) - dom.window.addEventListener('unhandledrejection', (event) => { - errors.push(String(event.reason)) - }) - dom.window.HTMLElement.prototype.scrollIntoView = () => {} - const context = dom.getInternalVMContext() - clientScript.runInContext(context) - const app = (dom.window as unknown as { HydrationBenchmark: ClientApp }) - .HydrationBenchmark - assert.equal(app.serverEnvironment, false) - assert.equal(app.solidServerEnvironment, false) - const doc = dom.window.document - const anchors = Array.from(doc.querySelectorAll('a')) - const scriptElements = Array.from(doc.querySelectorAll('script')) - assert.equal(scriptElements.length, bootstrapScripts.length) - const executingScript = { current: null as HTMLScriptElement | null } - Object.defineProperty(doc, 'currentScript', { - configurable: true, - get: () => executingScript.current, - }) - assert.equal(anchors.length, ordinaryLinkCount + hashLinkCount) - const content = doc.getElementById('hydration-content') - assert.ok(content) - assert.ok(content.hasAttribute('data-hk')) - assert.ok(anchors.every((anchor) => anchor.hasAttribute('data-hk'))) - for (let index = 0; index < hashLinkCount; index++) { - assert.equal( - doc.getElementById(`hash-${index}`)?.getAttribute('data-status'), - null, - ) - } - // Production Solid can fall back to templates for missing hydration keys. - // Retain every workload element, not only the parent and the anchors. - const elements = Array.from(content.querySelectorAll('*')) - const documentElement = doc.documentElement - await turn() - assert.equal(doc.readyState, 'complete') - assert.equal(app.ready(), false) - assert.deepEqual(errors, []) - return { - dom, - context, - app, - anchors, - content, - elements, - documentElement, - scriptElements, - executingScript, - immediates, - errors, - started: false, - completed: false, - failed: false, - } - } catch (error) { - for (const handle of immediates) { - clearImmediate(handle) - } - dom.window.close() - throw error - } - } - - async function before() { - if (current) { - throw new Error('Previous hydration sample was not disposed') - } - current = await prepare() - } - - async function run() { - const sample = current - if (!sample || sample.started) { - throw new Error('Hydration requires a newly prepared sample') - } - sample.started = true - try { - // Parsing/evaluation are done. Execute both native Solid bootstrap and - // Router payload, then create/restore the router and hydrate the DOM. - for (let index = 0; index < bootstrapScripts.length; index++) { - // Router scripts remove document.currentScript. Keep the original - // script nodes and order, including Solid's bootstrap and markers. - sample.executingScript.current = sample.scriptElements[index]! - try { - bootstrapScripts[index]!.runInContext(sample.context) - } finally { - sample.executingScript.current = null - } - } - await sample.app.start(countUpdates) - let idleTurns = 0 - for (let index = 0; index < maxSettleTurns; index++) { - await turn() - if (sample.errors.length) { - throw new Error(sample.errors.join('\n')) - } - if (sample.app.ready() && sample.immediates.size === 0) { - if (++idleTurns === 2) { - sample.completed = true - return - } - } else { - idleTurns = 0 - } - } - throw new Error( - `Hydration did not settle: ${JSON.stringify(sample.app.snapshot())}`, - ) - } catch (error) { - sample.failed = true - throw error - } - } - - function snapshot() { - if (!current) { - throw new Error('No hydration sample') - } - // Normalize realm prototypes only for untimed assertions. - return JSON.parse(JSON.stringify(current.app.snapshot())) as ReturnType< - ClientApp['snapshot'] - > - } - - function validate() { - assert.ok(current?.started) - const { dom, anchors, content, elements, documentElement, errors } = current - const doc = dom.window.document - const result = snapshot() - assert.deepEqual(errors, []) - assert.equal(result.diagnostics.beforeLoads, 0) - assert.equal(result.diagnostics.loaders, 0) - assert.equal(result.diagnostics.mounted, true) - assert.ok(result.diagnostics.rendered > 0) - assert.equal(result.hydrating, false) - assert.equal(result.location, clientUrl) - assert.equal(result.resolvedLocation, clientUrl) - assert.equal(result.matches?.length, 3) - for (const match of result.matches) { - assert.equal(match.status, 'success') - assert.deepEqual(match.context.viewer, { - id: 'viewer-3', - name: 'Ada', - role: 'editor', - }) - } - const teamContext = { id: 'team-7', member: 'viewer-3' } - assert.deepEqual(result.matches[1]!.context.team, teamContext) - assert.deepEqual(result.matches[2]!.context.team, teamContext) - assert.deepEqual(result.matches[2]!.context.permissions, { edit: true }) - assert.deepEqual(result.matches[1]!.loaderData, { - title: 'Team team-7', - categories: ['open', 'closed'], - }) - const data = result.matches[2]!.loaderData as { - owner: string - selected: string - rows: Array<{ - id: string - label: string - details: { score: number; open: boolean } - }> - } - assert.equal(data.owner, 'viewer-3') - assert.equal(data.selected, 'item-42') - assert.equal(data.rows.length, ordinaryLinkCount) - assert.equal(doc.documentElement, documentElement) - assert.equal(doc.getElementById('hydration-content'), content) - const hydratedElements = Array.from(content.querySelectorAll('*')) - assert.equal(hydratedElements.length, elements.length) - elements.forEach((element, index) => { - assert.equal(hydratedElements[index], element) - }) - assert.equal(doc.querySelectorAll('a').length, anchors.length) - assert.equal(doc.title, 'Hydration benchmark') - assert.equal(content.querySelector('h1')?.textContent, 'Team team-7') - assert.equal(doc.getElementById('viewer')?.textContent, 'Ada') - assert.equal(doc.getElementById('permission')?.textContent, 'Editable') - for (const anchor of anchors) { - assert.equal(doc.getElementById(anchor.id), anchor) - } - for (let index = 0; index < ordinaryLinkCount; index++) { - const anchor = doc.getElementById(`ordinary-item-${index}`)! - assert.equal( - anchor.getAttribute('href'), - `/teams/team-7/items/item-${index}?view=summary`, - ) - assert.equal(anchor.textContent, `Item ${index}`) - assert.equal( - anchor.getAttribute('data-status'), - index === 42 ? 'active' : null, - ) - assert.deepEqual(data.rows[index], { - id: `item-${index}`, - label: `Item ${index}`, - details: { score: index * 3, open: index % 2 === 0 }, - }) - } - for (let index = 0; index < hashLinkCount; index++) { - const anchor = doc.getElementById(`hash-${index}`)! - assert.equal( - anchor.getAttribute('data-status'), - index % 2 === 0 ? 'active' : null, - ) - assert.equal( - anchor.getAttribute('href'), - `/teams/team-7/items/item-42?view=summary#${index % 2 === 0 ? 'details' : 'other'}`, - ) - assert.equal(anchor.textContent, `Section ${index}`) - } - assert.equal(result.diagnostics.clicks, 0) - doc - .getElementById('interactive')! - .dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true })) - assert.equal(current.app.snapshot().diagnostics.clicks, 1) - assert.deepEqual(errors, []) - } - - async function after() { - const sample = current - if (!sample) { - return - } - try { - if (!sample.failed) { - assert.ok(sample.completed, 'Hydration sample was not completed') - validate() - } - } finally { - current = undefined - try { - sample.app.dispose() - await turn() - await turn() - if (!sample.failed) { - assert.deepEqual(sample.errors, []) - } - } finally { - for (const handle of sample.immediates) { - clearImmediate(handle) - } - sample.dom.window.close() - } - } - } - - return { - before, - run, - after, - snapshot, - } -} diff --git a/benchmarks/client-nav/scenarios/hydration/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/hydration/solid/speed.bench.ts deleted file mode 100644 index b386cb8215..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { setup } from './setup' - -test('client-hydration', async ({ bench }) => { - const scenario = setup() - - await bench( - 'hydrate restored route state and mixed Links (solid)', - { beforeEach: scenario.before, afterEach: scenario.after }, - async () => { - await scenario.run() - }, - ).run({ - time: 5000, - warmupTime: 1000, - warmupIterations: 20, - throws: true, - }) -}) diff --git a/benchmarks/client-nav/scenarios/hydration/solid/src/app.tsx b/benchmarks/client-nav/scenarios/hydration/solid/src/app.tsx deleted file mode 100644 index cb772d6b5b..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/solid/src/app.tsx +++ /dev/null @@ -1,213 +0,0 @@ -import { For, onMount } from 'solid-js' -import { HydrationScript } from 'solid-js/web' -import { - HeadContent, - Link, - Outlet, - Scripts, - createMemoryHistory, - createRootRoute, - createRoute, - createRouter, -} from '@tanstack/solid-router' -import { - clientUrl, - hashLinkCount, - ordinaryLinkCount, - serverUrl, -} from '../fixture' -import type { JSX } from 'solid-js' -import type { Diagnostics } from '../fixture' - -export function createFixtureRouter(server: boolean, diagnostics: Diagnostics) { - function beforeLoad() { - diagnostics.beforeLoads++ - if (!server) { - throw new Error('Hydration reran beforeLoad instead of restoring context') - } - } - - function loader() { - diagnostics.loaders++ - if (!server) { - throw new Error('Hydration reran a loader instead of restoring data') - } - } - - const root = createRootRoute({ - beforeLoad: () => { - beforeLoad() - return { viewer: { id: 'viewer-3', name: 'Ada', role: 'editor' } } - }, - head: () => ({ - meta: [{ charset: 'utf-8' }, { title: 'Hydration benchmark' }], - }), - shellComponent: Document, - }) - const team = createRoute({ - getParentRoute: () => root, - path: '/teams/$teamId', - beforeLoad: ({ context, params }) => { - beforeLoad() - return { team: { id: params.teamId, member: context.viewer.id } } - }, - loader: ({ context }) => { - loader() - return { - title: `Team ${context.team.id}`, - categories: ['open', 'closed'], - } - }, - component: Team, - }) - const items = createRoute({ - getParentRoute: () => team, - path: 'items/$itemId', - validateSearch: (search: Record) => ({ - view: search.view === 'details' ? 'details' : 'summary', - }), - beforeLoad: ({ context }) => { - beforeLoad() - return { permissions: { edit: context.viewer.role === 'editor' } } - }, - loader: ({ context, params }) => { - loader() - return { - selected: params.itemId, - owner: context.team.member, - rows: Array.from({ length: ordinaryLinkCount }, (_, index) => ({ - id: `item-${index}`, - label: `Item ${index}`, - details: { score: index * 3, open: index % 2 === 0 }, - })), - } - }, - component: Items, - }) - - function Document(props: { children: JSX.Element }) { - return ( - - - - - - - {props.children} - - - - ) - } - - function Team() { - const context = team.useRouteContext() - const data = team.useLoaderData() - return ( -
-

{data().title}

-

{context().viewer.name}

- -
- ) - } - - function Items() { - const data = items.useLoaderData() - const context = items.useRouteContext() - onMount(() => { - diagnostics.mounted = true - }) - return ( - <> -

- {context().permissions.edit ? 'Editable' : 'Read only'} -

- - - - - {(row) => ( - - - - - - )} - - -
{row.id}{row.details.score} - - {diagnostics.countUpdates - ? (state) => { - // Read the getter so this unit-only probe observes - // Link reactivity, rather than component execution. - void state.isActive - diagnostics.ordinaryEvaluations++ - return row.label - } - : row.label} - -
- -
Details
- - ) - } - - return createRouter({ - routeTree: root.addChildren([team.addChildren([items])]), - history: createMemoryHistory({ - initialEntries: [server ? serverUrl : clientUrl], - }), - isServer: server, - scrollRestoration: false, - defaultHashScrollIntoView: false, - defaultPreload: false, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/client-nav/scenarios/hydration/solid/src/client.tsx b/benchmarks/client-nav/scenarios/hydration/solid/src/client.tsx deleted file mode 100644 index ef0f5268d6..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/solid/src/client.tsx +++ /dev/null @@ -1,91 +0,0 @@ -import { sharedConfig } from 'solid-js' -import { hydrate as hydrateDOM, isServer as solidIsServer } from 'solid-js/web' -import { RouterProvider } from '@tanstack/solid-router' -import { hydrate } from '@tanstack/router-core/ssr/client' -import { isServer } from '@tanstack/router-core/isServer' -import { createDiagnostics, hashLinkCount } from '../fixture' -import { createFixtureRouter } from './app' - -export const serverEnvironment = isServer -export const solidServerEnvironment = solidIsServer -let router: ReturnType | undefined -let disposeRoot: (() => void) | undefined -let unsubscribe: (() => void) | undefined -let diagnostics = createDiagnostics() - -type HydrationWindow = Window & { - _$HY?: { done?: boolean; events?: Array; r: object } -} - -export async function start(countUpdates = false) { - if (router) { - throw new Error('A hydration sample must use a fresh client realm') - } - if (!window.$_TSR?.router) { - throw new Error('Missing SSR hydration payload') - } - const bootstrap = (window as HydrationWindow)._$HY - if (!bootstrap || bootstrap.done || sharedConfig.context) { - throw new Error('Missing or already consumed Solid hydration bootstrap') - } - diagnostics = createDiagnostics(countUpdates) - router = createFixtureRouter(false, diagnostics) - unsubscribe = router.subscribe('onRendered', () => { - diagnostics.rendered++ - }) - // Solid's RouterClient uses this core restoration API. Await it directly so - // the shell has the same component/key hierarchy as the server provider. - await hydrate(router) - window.$_TSR.h() - disposeRoot = hydrateDOM(() => , document) -} - -export function ready() { - if ( - !diagnostics.mounted || - !diagnostics.rendered || - sharedConfig.context || - router?.stores.status.get() === 'pending' - ) { - return false - } - // Each Link's onMount updates its hydration signal. Solid updates attributes - // through fine-grained effects, without rerendering the route components. - for (let index = 0; index < hashLinkCount; index++) { - const anchor = document.getElementById(`hash-${index}`) - if ( - !anchor || - anchor.getAttribute('data-status') !== (index % 2 === 0 ? 'active' : null) - ) { - return false - } - } - return true -} - -export function snapshot() { - return { - diagnostics: { - ...diagnostics, - initialHashStates: [...diagnostics.initialHashStates], - hashStates: [...diagnostics.hashStates], - }, - hydrating: !!sharedConfig.context, - location: router?.stores.location.get().href, - resolvedLocation: router?.stores.resolvedLocation.get()?.href, - matches: router?.stores.matches.get().map((match) => ({ - status: match.status, - context: match.context, - loaderData: match.loaderData, - })), - } -} - -export function dispose() { - try { - disposeRoot?.() - } finally { - unsubscribe?.() - router?.history.destroy() - } -} diff --git a/benchmarks/client-nav/scenarios/hydration/solid/src/server.tsx b/benchmarks/client-nav/scenarios/hydration/solid/src/server.tsx deleted file mode 100644 index 6052c48eac..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/solid/src/server.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import { RouterProvider } from '@tanstack/solid-router' -import { - createRequestHandler, - renderRouterToStream, -} from '@tanstack/solid-router/ssr/server' -import { isServer } from '@tanstack/router-core/isServer' -import { isServer as solidIsServer } from 'solid-js/web' -import { createDiagnostics, serverUrl } from '../fixture' -import { createFixtureRouter } from './app' - -export async function renderFixture() { - if ((isServer as boolean | undefined) !== true || !solidIsServer) { - throw new Error('Fixture generation requires the production server build') - } - const diagnostics = createDiagnostics() - const response = await createRequestHandler({ - createRouter: () => createFixtureRouter(true, diagnostics), - request: new Request(`http://localhost${serverUrl}`), - })(({ request, router, responseHeaders }) => - renderRouterToStream({ - request, - router, - responseHeaders, - // The route shell owns the document, as in Solid Start. Using the same - // provider tree on both sides preserves Solid's hydration key sequence. - children: () => , - }), - ) - const html = await response.text() - if ( - response.status !== 200 || - diagnostics.beforeLoads !== 3 || - diagnostics.loaders !== 2 - ) { - throw new Error( - 'SSR fixture did not execute its beforeLoad and loader functions', - ) - } - return html -} diff --git a/benchmarks/client-nav/scenarios/hydration/solid/tsconfig.json b/benchmarks/client-nav/scenarios/hydration/solid/tsconfig.json deleted file mode 100644 index daf27ddf12..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/solid/tsconfig.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": ["./*.ts", "./src/**/*"] -} diff --git a/benchmarks/client-nav/scenarios/hydration/solid/vite.config.ts b/benchmarks/client-nav/scenarios/hydration/solid/vite.config.ts deleted file mode 100644 index 16e5ff95aa..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/solid/vite.config.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import solid from 'vite-plugin-solid' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -export default defineConfig({ - root: fileURLToPath(new URL('.', import.meta.url)), - define: { 'process.env.NODE_ENV': JSON.stringify('production') }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - // The Node worker evaluates the prebuilt bundle and needs no JSX transform - // or browser test setup injected by vite-plugin-solid. - !process.env.VITEST && solid({ ssr: true, hot: false, dev: false }), - ], - resolve: { conditions: ['solid', 'browser', 'production'] }, - build: { - outDir: './dist/client', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/client.tsx', - name: 'HydrationBenchmark', - formats: ['iife'], - fileName: () => 'client.js', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav hydration (solid)', - watch: false, - environment: 'node', - isolate: true, - include: ['hydration.test.ts'], - benchmark: { include: ['speed.bench.ts'] }, - }, -}) diff --git a/benchmarks/client-nav/scenarios/hydration/solid/vite.server.config.ts b/benchmarks/client-nav/scenarios/hydration/solid/vite.server.config.ts deleted file mode 100644 index 9787cbb4e2..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/solid/vite.server.config.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vite' -import solid from 'vite-plugin-solid' - -export default defineConfig({ - root: fileURLToPath(new URL('.', import.meta.url)), - define: { 'process.env.NODE_ENV': JSON.stringify('production') }, - plugins: [solid({ ssr: true, hot: false, dev: false })], - resolve: { conditions: ['solid', 'node', 'production'] }, - ssr: { - noExternal: true, - resolve: { conditions: ['solid', 'node', 'production'] }, - }, - build: { - ssr: true, - outDir: './dist/server', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/server.tsx', - formats: ['es'], - fileName: () => 'server.js', - }, - rolldownOptions: { - platform: 'node', - external: [/^node:/], - }, - }, -}) diff --git a/benchmarks/client-nav/scenarios/link-churn/react/project.json b/benchmarks/client-nav/scenarios/link-churn/react/project.json deleted file mode 100644 index 1606b2c456..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-link-churn-react", - "projectType": "application", - "targets": { - "build:client": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-router", "@tanstack/router-plugin"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:client": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/react-router", "@tanstack/router-plugin"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": ["build:client"], - "options": { - "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/link-churn/react/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/link-churn/react/setup.ts b/benchmarks/client-nav/scenarios/link-churn/react/setup.ts deleted file mode 100644 index 59221603da..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/react/setup.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, initialUrl, scenarioSteps } from '../shared' -import type * as App from './src/main' - -const appModulePath = './dist/app.js' -const { mountTestApp } = (await import( - /* @vite-ignore */ appModulePath -)) as typeof App - -export function setup() { - return createScenarioSetup({ - frameworkLabel: 'React', - mount: mountTestApp, - steps: scenarioSteps, - assertAfterStep: assertStepResult, - initialUrl, - }) -} diff --git a/benchmarks/client-nav/scenarios/link-churn/react/speed.bench.ts b/benchmarks/client-nav/scenarios/link-churn/react/speed.bench.ts deleted file mode 100644 index ca0b370528..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-link-churn', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-link-churn navigation loop (react)', - benchLifecycle(scenario), - async () => { - for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() - } - await scenario.finishBatch() - }, - ).run(benchOptions) -}) diff --git a/benchmarks/client-nav/scenarios/link-churn/react/speed.flame.ts b/benchmarks/client-nav/scenarios/link-churn/react/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/react/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/link-churn/react/src/main.tsx b/benchmarks/client-nav/scenarios/link-churn/react/src/main.tsx deleted file mode 100644 index 5febd6f795..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/react/src/main.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { RouterProvider, createRouter } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const reactRoot = createRoot(container) - reactRoot.render() - - return { - router, - unmount() { - reactRoot.unmount() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/link-churn/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/link-churn/react/src/routeTree.gen.ts deleted file mode 100644 index 4535430b61..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/react/src/routeTree.gen.ts +++ /dev/null @@ -1,121 +0,0 @@ -/* 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 HubRouteImport } from './routes/hub' -import { Route as OtherRouteImport } from './routes/other' -import { Route as HubListRouteImport } from './routes/hub.list' -import { Route as HubDetailIdRouteImport } from './routes/hub.detail.$id' - -const HubRoute = HubRouteImport.update({ - id: '/hub', - path: '/hub', - getParentRoute: () => rootRouteImport, -} as any) -const OtherRoute = OtherRouteImport.update({ - id: '/other', - path: '/other', - getParentRoute: () => rootRouteImport, -} as any) -const HubListRoute = HubListRouteImport.update({ - id: '/list', - path: '/list', - getParentRoute: () => HubRoute, -} as any) -const HubDetailIdRoute = HubDetailIdRouteImport.update({ - id: '/detail/$id', - path: '/detail/$id', - getParentRoute: () => HubRoute, -} as any) - -export interface FileRoutesByFullPath { - '/hub': typeof HubRouteWithChildren - '/other': typeof OtherRoute - '/hub/list': typeof HubListRoute - '/hub/detail/$id': typeof HubDetailIdRoute -} -export interface FileRoutesByTo { - '/hub': typeof HubRouteWithChildren - '/other': typeof OtherRoute - '/hub/list': typeof HubListRoute - '/hub/detail/$id': typeof HubDetailIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/hub': typeof HubRouteWithChildren - '/other': typeof OtherRoute - '/hub/list': typeof HubListRoute - '/hub/detail/$id': typeof HubDetailIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/hub' | '/other' | '/hub/list' | '/hub/detail/$id' - fileRoutesByTo: FileRoutesByTo - to: '/hub' | '/other' | '/hub/list' | '/hub/detail/$id' - id: '__root__' | '/hub' | '/other' | '/hub/list' | '/hub/detail/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - HubRoute: typeof HubRouteWithChildren - OtherRoute: typeof OtherRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/hub': { - id: '/hub' - path: '/hub' - fullPath: '/hub' - preLoaderRoute: typeof HubRouteImport - parentRoute: typeof rootRouteImport - } - '/other': { - id: '/other' - path: '/other' - fullPath: '/other' - preLoaderRoute: typeof OtherRouteImport - parentRoute: typeof rootRouteImport - } - '/hub/list': { - id: '/hub/list' - path: '/list' - fullPath: '/hub/list' - preLoaderRoute: typeof HubListRouteImport - parentRoute: typeof HubRoute - } - '/hub/detail/$id': { - id: '/hub/detail/$id' - path: '/detail/$id' - fullPath: '/hub/detail/$id' - preLoaderRoute: typeof HubDetailIdRouteImport - parentRoute: typeof HubRoute - } - } -} - -interface HubRouteChildren { - HubListRoute: typeof HubListRoute - HubDetailIdRoute: typeof HubDetailIdRoute -} - -const HubRouteChildren: HubRouteChildren = { - HubListRoute: HubListRoute, - HubDetailIdRoute: HubDetailIdRoute, -} - -const HubRouteWithChildren = HubRoute._addFileChildren(HubRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - HubRoute: HubRouteWithChildren, - OtherRoute: OtherRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/link-churn/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/link-churn/react/src/routes/__root.tsx deleted file mode 100644 index 199cf1ff73..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/react/src/routes/__root.tsx +++ /dev/null @@ -1,39 +0,0 @@ -import { Link, Outlet, createRootRoute } from '@tanstack/react-router' -import { sortedSearch } from '../../../shared' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - <> - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/link-churn/react/src/routes/hub.detail.$id.tsx b/benchmarks/client-nav/scenarios/link-churn/react/src/routes/hub.detail.$id.tsx deleted file mode 100644 index 143cb39a7a..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/react/src/routes/hub.detail.$id.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import { Link, createFileRoute } from '@tanstack/react-router' -import { detailMarker } from '../../../shared' - -export const Route = createFileRoute('/hub/detail/$id')({ - component: DetailPage, -}) - -function DetailPage() { - const params = Route.useParams() - - return ( -
-

{detailMarker(params.id)}

- Back to list - - Next - - Elsewhere -
- ) -} diff --git a/benchmarks/client-nav/scenarios/link-churn/react/src/routes/hub.list.tsx b/benchmarks/client-nav/scenarios/link-churn/react/src/routes/hub.list.tsx deleted file mode 100644 index 5aa37b20a7..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/react/src/routes/hub.list.tsx +++ /dev/null @@ -1,65 +0,0 @@ -import { Link, createFileRoute } from '@tanstack/react-router' -import { - listItemIds, - listMarker, - listRelativeTestId, - listSortedMarker, -} from '../../../shared' - -export const Route = createFileRoute('/hub/list')({ - component: ListPage, -}) - -const ascSearch = { sort: 'asc' } as const - -// List Links depart whenever the list leaf is left. -function ListLinks() { - return ( -
    - {listItemIds.map((id) => { - const page = Number(id) - return ( -
  • - - {`Item ${id}`} - - - {`Item ${id} asc`} - - - {`Item ${id} exact`} - - ({ ...prev, page })}> - {`Page ${id}`} - - ({ ...prev, page, sort: 'asc' as const })} - data-testid={id === '1' ? listRelativeTestId : undefined} - > - {`Page ${id} asc`} - -
  • - ) - })} -
- ) -} - -function ListPage() { - const sort = Route.useSearch({ select: (search) => search.sort }) - - return ( -
-

- {sort === 'desc' ? listSortedMarker : listMarker} -

- -
- ) -} diff --git a/benchmarks/client-nav/scenarios/link-churn/react/src/routes/hub.tsx b/benchmarks/client-nav/scenarios/link-churn/react/src/routes/hub.tsx deleted file mode 100644 index ac12eae2da..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/react/src/routes/hub.tsx +++ /dev/null @@ -1,64 +0,0 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' -import { - hubItemIds, - hubRelativeTestId, - validateHubSearch, -} from '../../../shared' - -export const Route = createFileRoute('/hub')({ - validateSearch: validateHubSearch, - component: HubLayout, -}) - -// Layout Links stay mounted while the hub leaves change. -function HubLinks() { - return ( -
- {hubItemIds.map((id) => { - const page = Number(id) - return ( -
- - {`Detail ${id}`} - - - {`Detail ${id} exact`} - - - {`List page ${id}`} - - ({ ...prev, page })}> - {`List keep ${id}`} - - ({ ...prev, page })} - data-testid={id === '1' ? hubRelativeTestId : undefined} - > - {`Here page ${id}`} - -
- ) - })} -
- ) -} - -function HubLayout() { - return ( -
- - -
- ) -} diff --git a/benchmarks/client-nav/scenarios/link-churn/react/src/routes/other.tsx b/benchmarks/client-nav/scenarios/link-churn/react/src/routes/other.tsx deleted file mode 100644 index 1f146b789f..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/react/src/routes/other.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { otherMarker } from '../../../shared' - -export const Route = createFileRoute('/other')({ - component: OtherPage, -}) - -function OtherPage() { - return ( -
-

{otherMarker}

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/link-churn/react/tsconfig.json b/benchmarks/client-nav/scenarios/link-churn/react/tsconfig.json deleted file mode 100644 index 1d59cbb450..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/react/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/link-churn/react/vite.config.ts b/benchmarks/client-nav/scenarios/link-churn/react/vite.config.ts deleted file mode 100644 index 344974ebf9..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/react/vite.config.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'react', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav link-churn (react)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - }, -}) diff --git a/benchmarks/client-nav/scenarios/link-churn/shared.ts b/benchmarks/client-nav/scenarios/link-churn/shared.ts deleted file mode 100644 index d936af35cc..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/shared.ts +++ /dev/null @@ -1,178 +0,0 @@ -/** - * Shared definition of the `link-churn` scenario: Links that leave, stay and - * arrive across navigations. A `/hub` layout renders Links that stay mounted - * while its leaves change; the `/hub/list` leaf renders Links that depart when - * leaving it and mount again when returning; `/other` sits outside the layout - * so leaving the list there unmounts layout and leaf Links together. The - * existing `links` scenario keeps all its Links in the root layout, so none of - * them ever departs or remounts. The three framework apps consume these - * constants so the workload is identical modulo the rendering layer. - */ -import type { ScenarioStep } from '../harness' - -// Layout (staying) Links: HUB_ITEM_COUNT ids x 5 variants. -export const HUB_ITEM_COUNT = 6 -// List leaf (departing) Links: LIST_ITEM_COUNT ids x 5 variants. -export const LIST_ITEM_COUNT = 20 - -const ids = (count: number) => - Array.from({ length: count }, (_, index) => String(index + 1)) - -export const hubItemIds = ids(HUB_ITEM_COUNT) -export const listItemIds = ids(LIST_ITEM_COUNT) - -export interface HubSearch { - page?: number - sort?: 'asc' | 'desc' -} - -/** Search validation of the `/hub` layout, inherited by its leaves. */ -export function validateHubSearch(search: Record): HubSearch { - const result: HubSearch = {} - if (typeof search.page === 'number') { - result.page = search.page - } - if (search.sort === 'asc' || search.sort === 'desc') { - result.sort = search.sort - } - return result -} - -export const sortedSearch = { sort: 'desc' } as const - -export function detailMarker(id: string) { - return `detail-${id}` -} - -export const listMarker = 'list' -export const listSortedMarker = 'list-desc' -export const otherMarker = 'other' - -// Sampled Links whose href depends on the current location: the first layout -// `to="."` updater Link and the first list `to="."` updater Link. -export const hubRelativeTestId = 'hub-relative-1' -export const listRelativeTestId = 'list-relative-1' - -interface StepDef { - testId: string - marker: string - /** Expected number of `.active-link` elements after the step. */ - activeCount: number - /** Expected href of the sampled layout updater Link (null: not mounted). */ - hubRelativeHref: string | null - /** Expected href of the sampled list updater Link (null: not mounted). */ - listRelativeHref: string | null -} - -// On the list, every layout `includeSearch: false` Link to the list is active. -const listActiveCount = HUB_ITEM_COUNT - -export const stepDefs: ReadonlyArray = [ - // 1. list -> detail/1: list Links depart, layout Links stay and update. - { - testId: 'go-detail-1', - marker: detailMarker('1'), - activeCount: 1, - hubRelativeHref: '/hub/detail/1?page=1', - listRelativeHref: null, - }, - // 2. detail/1 -> detail/2: same route, new param; every Link stays. - { - testId: 'go-detail-2', - marker: detailMarker('2'), - activeCount: 1, - hubRelativeHref: '/hub/detail/2?page=1', - listRelativeHref: null, - }, - // 3. detail/2 -> list: list Links mount. - { - testId: 'go-list', - marker: listMarker, - activeCount: listActiveCount, - hubRelativeHref: '/hub/list?page=1', - listRelativeHref: '/hub/list?page=1&sort=asc', - }, - // 4. list -> other: layout and list Links depart together. - { - testId: 'go-other', - marker: otherMarker, - activeCount: 0, - hubRelativeHref: null, - listRelativeHref: null, - }, - // 5. other -> list: layout and list Links all mount. - { - testId: 'go-list', - marker: listMarker, - activeCount: listActiveCount, - hubRelativeHref: '/hub/list?page=1', - listRelativeHref: '/hub/list?page=1&sort=asc', - }, - // 6a. list -> list?sort=desc: nothing departs, updater Links rebuild. - { - testId: 'go-list-sorted', - marker: listSortedMarker, - activeCount: listActiveCount, - hubRelativeHref: '/hub/list?sort=desc&page=1', - listRelativeHref: '/hub/list?sort=asc&page=1', - }, - // 6b. back to the plain list so the lap ends on the initial location. - { - testId: 'go-list', - marker: listMarker, - activeCount: listActiveCount, - hubRelativeHref: '/hub/list?page=1', - listRelativeHref: '/hub/list?page=1&sort=asc', - }, -] - -export const initialUrl = '/hub/list' - -export const scenarioSteps: ReadonlyArray = stepDefs.map( - (step) => step.testId, -) - -function assertHref( - container: HTMLElement, - testId: string, - expected: string | null, - stepIndex: number, -) { - const link = container.querySelector(`[data-testid="${testId}"]`) - const href = link ? link.getAttribute('href') : null - if (href !== expected) { - throw new Error( - `Expected "${testId}" href ${JSON.stringify(expected)} after step ${stepIndex}, received ${JSON.stringify(href)}`, - ) - } -} - -export function assertStepResult(stepIndex: number, container: HTMLElement) { - const step = stepDefs[stepIndex]! - - const marker = container.querySelector('[data-testid="page-state"]') - if (marker?.textContent !== step.marker) { - throw new Error( - `Expected page marker "${step.marker}" after step ${stepIndex}, received "${marker?.textContent}"`, - ) - } - - const activeLinks = container.querySelectorAll('a.active-link') - if (activeLinks.length !== step.activeCount) { - throw new Error( - `Expected ${step.activeCount} active link(s) after step ${stepIndex}, received ${activeLinks.length}`, - ) - } - - assertHref(container, hubRelativeTestId, step.hubRelativeHref, stepIndex) - assertHref(container, listRelativeTestId, step.listRelativeHref, stepIndex) -} - -// One lap through the 7-step sequence per benchmark iteration. -export const ticksPerIteration = stepDefs.length - -export const benchOptions = { - warmupIterations: 50, - time: 10_000, - throws: true, -} diff --git a/benchmarks/client-nav/scenarios/link-churn/solid/project.json b/benchmarks/client-nav/scenarios/link-churn/solid/project.json deleted file mode 100644 index 4e46143b32..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/solid/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-link-churn-solid", - "projectType": "application", - "targets": { - "build:client": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-router", "@tanstack/router-plugin"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:client": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/solid-router", "@tanstack/router-plugin"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": ["build:client"], - "options": { - "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/link-churn/solid/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/link-churn/solid/setup.ts b/benchmarks/client-nav/scenarios/link-churn/solid/setup.ts deleted file mode 100644 index a2a024341d..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/solid/setup.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, initialUrl, scenarioSteps } from '../shared' -import type * as App from './src/main' - -const appModulePath = './dist/app.js' -const { mountTestApp } = (await import( - /* @vite-ignore */ appModulePath -)) as typeof App - -export function setup() { - return createScenarioSetup({ - frameworkLabel: 'Solid', - mount: mountTestApp, - steps: scenarioSteps, - assertAfterStep: assertStepResult, - initialUrl, - }) -} diff --git a/benchmarks/client-nav/scenarios/link-churn/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/link-churn/solid/speed.bench.ts deleted file mode 100644 index 80c4aaa6fd..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-link-churn', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-link-churn navigation loop (solid)', - benchLifecycle(scenario), - async () => { - for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() - } - await scenario.finishBatch() - }, - ).run(benchOptions) -}) diff --git a/benchmarks/client-nav/scenarios/link-churn/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/link-churn/solid/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/solid/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/link-churn/solid/src/main.tsx b/benchmarks/client-nav/scenarios/link-churn/solid/src/main.tsx deleted file mode 100644 index fa9d239418..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/solid/src/main.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { render } from 'solid-js/web' -import { RouterProvider, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const unmount = render(() => , container) - - return { - router, - unmount, - } -} diff --git a/benchmarks/client-nav/scenarios/link-churn/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/link-churn/solid/src/routeTree.gen.ts deleted file mode 100644 index e3cb546963..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,121 +0,0 @@ -/* 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 HubRouteImport } from './routes/hub' -import { Route as OtherRouteImport } from './routes/other' -import { Route as HubListRouteImport } from './routes/hub.list' -import { Route as HubDetailIdRouteImport } from './routes/hub.detail.$id' - -const HubRoute = HubRouteImport.update({ - id: '/hub', - path: '/hub', - getParentRoute: () => rootRouteImport, -} as any) -const OtherRoute = OtherRouteImport.update({ - id: '/other', - path: '/other', - getParentRoute: () => rootRouteImport, -} as any) -const HubListRoute = HubListRouteImport.update({ - id: '/list', - path: '/list', - getParentRoute: () => HubRoute, -} as any) -const HubDetailIdRoute = HubDetailIdRouteImport.update({ - id: '/detail/$id', - path: '/detail/$id', - getParentRoute: () => HubRoute, -} as any) - -export interface FileRoutesByFullPath { - '/hub': typeof HubRouteWithChildren - '/other': typeof OtherRoute - '/hub/list': typeof HubListRoute - '/hub/detail/$id': typeof HubDetailIdRoute -} -export interface FileRoutesByTo { - '/hub': typeof HubRouteWithChildren - '/other': typeof OtherRoute - '/hub/list': typeof HubListRoute - '/hub/detail/$id': typeof HubDetailIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/hub': typeof HubRouteWithChildren - '/other': typeof OtherRoute - '/hub/list': typeof HubListRoute - '/hub/detail/$id': typeof HubDetailIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/hub' | '/other' | '/hub/list' | '/hub/detail/$id' - fileRoutesByTo: FileRoutesByTo - to: '/hub' | '/other' | '/hub/list' | '/hub/detail/$id' - id: '__root__' | '/hub' | '/other' | '/hub/list' | '/hub/detail/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - HubRoute: typeof HubRouteWithChildren - OtherRoute: typeof OtherRoute -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/hub': { - id: '/hub' - path: '/hub' - fullPath: '/hub' - preLoaderRoute: typeof HubRouteImport - parentRoute: typeof rootRouteImport - } - '/other': { - id: '/other' - path: '/other' - fullPath: '/other' - preLoaderRoute: typeof OtherRouteImport - parentRoute: typeof rootRouteImport - } - '/hub/list': { - id: '/hub/list' - path: '/list' - fullPath: '/hub/list' - preLoaderRoute: typeof HubListRouteImport - parentRoute: typeof HubRoute - } - '/hub/detail/$id': { - id: '/hub/detail/$id' - path: '/detail/$id' - fullPath: '/hub/detail/$id' - preLoaderRoute: typeof HubDetailIdRouteImport - parentRoute: typeof HubRoute - } - } -} - -interface HubRouteChildren { - HubListRoute: typeof HubListRoute - HubDetailIdRoute: typeof HubDetailIdRoute -} - -const HubRouteChildren: HubRouteChildren = { - HubListRoute: HubListRoute, - HubDetailIdRoute: HubDetailIdRoute, -} - -const HubRouteWithChildren = HubRoute._addFileChildren(HubRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - HubRoute: HubRouteWithChildren, - OtherRoute: OtherRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/__root.tsx deleted file mode 100644 index a9de4ea356..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/__root.tsx +++ /dev/null @@ -1,39 +0,0 @@ -import { Link, Outlet, createRootRoute } from '@tanstack/solid-router' -import { sortedSearch } from '../../../shared' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - <> - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/hub.detail.$id.tsx b/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/hub.detail.$id.tsx deleted file mode 100644 index 7aca4a9935..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/hub.detail.$id.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { Link, createFileRoute } from '@tanstack/solid-router' -import { detailMarker } from '../../../shared' - -export const Route = createFileRoute('/hub/detail/$id')({ - component: DetailPage, -}) - -function DetailPage() { - const params = Route.useParams() - - return ( -
-

{detailMarker(params().id)}

- Back to list - - Next - - Elsewhere -
- ) -} diff --git a/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/hub.list.tsx b/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/hub.list.tsx deleted file mode 100644 index 5796a50b02..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/hub.list.tsx +++ /dev/null @@ -1,68 +0,0 @@ -import { For } from 'solid-js' -import { Link, createFileRoute } from '@tanstack/solid-router' -import { - listItemIds, - listMarker, - listRelativeTestId, - listSortedMarker, -} from '../../../shared' - -export const Route = createFileRoute('/hub/list')({ - component: ListPage, -}) - -const ascSearch = { sort: 'asc' } as const - -// List Links depart whenever the list leaf is left. -function ListLinks() { - return ( -
    - - {(id) => { - const page = Number(id) - return ( -
  • - - {`Item ${id}`} - - - {`Item ${id} asc`} - - - {`Item ${id} exact`} - - ({ ...prev, page })}> - {`Page ${id}`} - - ({ ...prev, page, sort: 'asc' as const })} - data-testid={id === '1' ? listRelativeTestId : undefined} - > - {`Page ${id} asc`} - -
  • - ) - }} -
    -
- ) -} - -function ListPage() { - const sort = Route.useSearch({ select: (search) => search.sort }) - - return ( -
-

- {sort() === 'desc' ? listSortedMarker : listMarker} -

- -
- ) -} diff --git a/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/hub.tsx b/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/hub.tsx deleted file mode 100644 index 4682f85aae..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/hub.tsx +++ /dev/null @@ -1,67 +0,0 @@ -import { For } from 'solid-js' -import { Link, Outlet, createFileRoute } from '@tanstack/solid-router' -import { - hubItemIds, - hubRelativeTestId, - validateHubSearch, -} from '../../../shared' - -export const Route = createFileRoute('/hub')({ - validateSearch: validateHubSearch, - component: HubLayout, -}) - -// Layout Links stay mounted while the hub leaves change. -function HubLinks() { - return ( -
- - {(id) => { - const page = Number(id) - return ( -
- - {`Detail ${id}`} - - - {`Detail ${id} exact`} - - - {`List page ${id}`} - - ({ ...prev, page })}> - {`List keep ${id}`} - - ({ ...prev, page })} - data-testid={id === '1' ? hubRelativeTestId : undefined} - > - {`Here page ${id}`} - -
- ) - }} -
-
- ) -} - -function HubLayout() { - return ( -
- - -
- ) -} diff --git a/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/other.tsx b/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/other.tsx deleted file mode 100644 index 2606089113..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/other.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { otherMarker } from '../../../shared' - -export const Route = createFileRoute('/other')({ - component: OtherPage, -}) - -function OtherPage() { - return ( -
-

{otherMarker}

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/link-churn/solid/tsconfig.json b/benchmarks/client-nav/scenarios/link-churn/solid/tsconfig.json deleted file mode 100644 index 98d76ad6b8..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/solid/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/link-churn/solid/vite.config.ts b/benchmarks/client-nav/scenarios/link-churn/solid/vite.config.ts deleted file mode 100644 index 37718a2d6a..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/solid/vite.config.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import solid from 'vite-plugin-solid' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'solid', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - resolve: { - conditions: ['solid', 'browser'], - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav link-churn (solid)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/project.json b/benchmarks/client-nav/scenarios/link-churn/vue/project.json deleted file mode 100644 index fb890ddfb8..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-link-churn-vue", - "projectType": "application", - "targets": { - "build:client": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-router", "@tanstack/router-plugin"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:client": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/vue-router", "@tanstack/router-plugin"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": ["build:client"], - "options": { - "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/link-churn/vue/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/setup.ts b/benchmarks/client-nav/scenarios/link-churn/vue/setup.ts deleted file mode 100644 index 95cacb9ea8..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/setup.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, initialUrl, scenarioSteps } from '../shared' -import type * as App from './src/main' - -const appModulePath = './dist/app.js' -const { mountTestApp } = (await import( - /* @vite-ignore */ appModulePath -)) as typeof App - -export function setup() { - return createScenarioSetup({ - frameworkLabel: 'Vue', - mount: mountTestApp, - steps: scenarioSteps, - assertAfterStep: assertStepResult, - initialUrl, - }) -} diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/link-churn/vue/speed.bench.ts deleted file mode 100644 index dea511c24c..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-link-churn', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-link-churn navigation loop (vue)', - benchLifecycle(scenario), - async () => { - for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() - } - await scenario.finishBatch() - }, - ).run(benchOptions) -}) diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/link-churn/vue/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/src/main.tsx b/benchmarks/client-nav/scenarios/link-churn/vue/src/main.tsx deleted file mode 100644 index cae9b54f1d..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/src/main.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import * as Vue from 'vue' -import { RouterProvider, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const component = - const app = Vue.createApp({ - render: () => component, - }) - - app.mount(container) - - return { - router, - unmount() { - app.unmount() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/link-churn/vue/src/routeTree.gen.ts deleted file mode 100644 index 9327bbc01d..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,121 +0,0 @@ -/* 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 HubRouteImport } from './routes/hub' -import { Route as OtherRouteImport } from './routes/other' -import { Route as HubListRouteImport } from './routes/hub.list' -import { Route as HubDetailIdRouteImport } from './routes/hub.detail.$id' - -const HubRoute = HubRouteImport.update({ - id: '/hub', - path: '/hub', - getParentRoute: () => rootRouteImport, -} as any) -const OtherRoute = OtherRouteImport.update({ - id: '/other', - path: '/other', - getParentRoute: () => rootRouteImport, -} as any) -const HubListRoute = HubListRouteImport.update({ - id: '/list', - path: '/list', - getParentRoute: () => HubRoute, -} as any) -const HubDetailIdRoute = HubDetailIdRouteImport.update({ - id: '/detail/$id', - path: '/detail/$id', - getParentRoute: () => HubRoute, -} as any) - -export interface FileRoutesByFullPath { - '/hub': typeof HubRouteWithChildren - '/other': typeof OtherRoute - '/hub/list': typeof HubListRoute - '/hub/detail/$id': typeof HubDetailIdRoute -} -export interface FileRoutesByTo { - '/hub': typeof HubRouteWithChildren - '/other': typeof OtherRoute - '/hub/list': typeof HubListRoute - '/hub/detail/$id': typeof HubDetailIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/hub': typeof HubRouteWithChildren - '/other': typeof OtherRoute - '/hub/list': typeof HubListRoute - '/hub/detail/$id': typeof HubDetailIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/hub' | '/other' | '/hub/list' | '/hub/detail/$id' - fileRoutesByTo: FileRoutesByTo - to: '/hub' | '/other' | '/hub/list' | '/hub/detail/$id' - id: '__root__' | '/hub' | '/other' | '/hub/list' | '/hub/detail/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - HubRoute: typeof HubRouteWithChildren - OtherRoute: typeof OtherRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/hub': { - id: '/hub' - path: '/hub' - fullPath: '/hub' - preLoaderRoute: typeof HubRouteImport - parentRoute: typeof rootRouteImport - } - '/other': { - id: '/other' - path: '/other' - fullPath: '/other' - preLoaderRoute: typeof OtherRouteImport - parentRoute: typeof rootRouteImport - } - '/hub/list': { - id: '/hub/list' - path: '/list' - fullPath: '/hub/list' - preLoaderRoute: typeof HubListRouteImport - parentRoute: typeof HubRoute - } - '/hub/detail/$id': { - id: '/hub/detail/$id' - path: '/detail/$id' - fullPath: '/hub/detail/$id' - preLoaderRoute: typeof HubDetailIdRouteImport - parentRoute: typeof HubRoute - } - } -} - -interface HubRouteChildren { - HubListRoute: typeof HubListRoute - HubDetailIdRoute: typeof HubDetailIdRoute -} - -const HubRouteChildren: HubRouteChildren = { - HubListRoute: HubListRoute, - HubDetailIdRoute: HubDetailIdRoute, -} - -const HubRouteWithChildren = HubRoute._addFileChildren(HubRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - HubRoute: HubRouteWithChildren, - OtherRoute: OtherRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/__root.tsx deleted file mode 100644 index a4f7985c5a..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/__root.tsx +++ /dev/null @@ -1,46 +0,0 @@ -import * as Vue from 'vue' -import { Link, Outlet, createRootRoute } from '@tanstack/vue-router' -import { sortedSearch } from '../../../shared' - -const RootComponent = Vue.defineComponent({ - setup() { - return () => ( - <> - - - - ) - }, -}) - -export const Route = createRootRoute({ - component: RootComponent, -}) diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/hub.detail.$id.tsx b/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/hub.detail.$id.tsx deleted file mode 100644 index 4701ab44eb..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/hub.detail.$id.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import * as Vue from 'vue' -import { Link, createFileRoute } from '@tanstack/vue-router' -import { detailMarker } from '../../../shared' - -const DetailPage = Vue.defineComponent({ - setup() { - const params = Route.useParams() - - return () => ( -
-

{detailMarker(params.value.id)}

- Back to list - - Next - - Elsewhere -
- ) - }, -}) - -export const Route = createFileRoute('/hub/detail/$id')({ - component: DetailPage, -}) diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/hub.list.tsx b/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/hub.list.tsx deleted file mode 100644 index 02abd6db1b..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/hub.list.tsx +++ /dev/null @@ -1,74 +0,0 @@ -import * as Vue from 'vue' -import { Link, createFileRoute } from '@tanstack/vue-router' -import { - listItemIds, - listMarker, - listRelativeTestId, - listSortedMarker, -} from '../../../shared' - -const ascSearch = { sort: 'asc' } as const - -// List Links depart whenever the list leaf is left. -const ListLinks = Vue.defineComponent({ - setup() { - return () => ( -
    - {listItemIds.map((id) => { - const page = Number(id) - return ( -
  • - - {`Item ${id}`} - - - {`Item ${id} asc`} - - - {`Item ${id} exact`} - - ({ ...prev, page })}> - {`Page ${id}`} - - ({ - ...prev, - page, - sort: 'asc' as const, - })} - data-testid={id === '1' ? listRelativeTestId : undefined} - > - {`Page ${id} asc`} - -
  • - ) - })} -
- ) - }, -}) - -const ListPage = Vue.defineComponent({ - setup() { - const sort = Route.useSearch({ select: (search) => search.sort }) - - return () => ( -
-

- {sort.value === 'desc' ? listSortedMarker : listMarker} -

- -
- ) - }, -}) - -export const Route = createFileRoute('/hub/list')({ - component: ListPage, -}) diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/hub.tsx b/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/hub.tsx deleted file mode 100644 index 5be17f3350..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/hub.tsx +++ /dev/null @@ -1,69 +0,0 @@ -import * as Vue from 'vue' -import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' -import { - hubItemIds, - hubRelativeTestId, - validateHubSearch, -} from '../../../shared' - -// Layout Links stay mounted while the hub leaves change. -const HubLinks = Vue.defineComponent({ - setup() { - return () => ( -
- {hubItemIds.map((id) => { - const page = Number(id) - return ( -
- - {`Detail ${id}`} - - - {`Detail ${id} exact`} - - - {`List page ${id}`} - - ({ ...prev, page })}> - {`List keep ${id}`} - - ({ ...prev, page })} - data-testid={id === '1' ? hubRelativeTestId : undefined} - > - {`Here page ${id}`} - -
- ) - })} -
- ) - }, -}) - -const HubLayout = Vue.defineComponent({ - setup() { - return () => ( -
- - -
- ) - }, -}) - -export const Route = createFileRoute('/hub')({ - validateSearch: validateHubSearch, - component: HubLayout, -}) diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/other.tsx b/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/other.tsx deleted file mode 100644 index 08dec586fa..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/other.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' -import { otherMarker } from '../../../shared' - -const OtherPage = Vue.defineComponent({ - setup() { - return () => ( -
-

{otherMarker}

-
- ) - }, -}) - -export const Route = createFileRoute('/other')({ - component: OtherPage, -}) diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/tsconfig.json b/benchmarks/client-nav/scenarios/link-churn/vue/tsconfig.json deleted file mode 100644 index 7786fc3da9..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/vite.config.ts b/benchmarks/client-nav/scenarios/link-churn/vue/vite.config.ts deleted file mode 100644 index 8f56734e04..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/vite.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'vue', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav link-churn (vue)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - }, -}) diff --git a/benchmarks/client-nav/scenarios/links/react/speed.bench.ts b/benchmarks/client-nav/scenarios/links/react/speed.bench.ts index 75f5f725d4..0892308901 100644 --- a/benchmarks/client-nav/scenarios/links/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/links/react/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-links', async ({ bench }) => { - const scenario = setup() +describe('client-links', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-links navigation loop (react)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/links/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/links/solid/speed.bench.ts index fc7f3e71e7..a3d690b423 100644 --- a/benchmarks/client-nav/scenarios/links/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/links/solid/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-links', async ({ bench }) => { - const scenario = setup() +describe('client-links', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-links navigation loop (solid)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/links/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/links/solid/src/routeTree.gen.ts index 0da70513e8..b61431e40d 100644 --- a/benchmarks/client-nav/scenarios/links/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/links/solid/src/routeTree.gen.ts @@ -9,20 +9,20 @@ // 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 AboutRouteImport } from './routes/about' +import { Route as IndexRouteImport } from './routes/index' import { Route as ItemsIdRouteImport } from './routes/items.$id' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const AboutRoute = AboutRouteImport.update({ id: '/about', path: '/about', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const ItemsIdRoute = ItemsIdRouteImport.update({ id: '/items/$id', path: '/items/$id', @@ -61,13 +61,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/about': { id: '/about' path: '/about' @@ -75,6 +68,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/items/$id': { id: '/items/$id' path: '/items/$id' diff --git a/benchmarks/client-nav/scenarios/links/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/links/vue/speed.bench.ts index 2ace7a8409..e2d3f7c47a 100644 --- a/benchmarks/client-nav/scenarios/links/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/links/vue/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-links', async ({ bench }) => { - const scenario = setup() +describe('client-links', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-links navigation loop (vue)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/links/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/links/vue/src/routeTree.gen.ts index 7d2b1e9bbb..cee64be43c 100644 --- a/benchmarks/client-nav/scenarios/links/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/links/vue/src/routeTree.gen.ts @@ -9,20 +9,20 @@ // 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 AboutRouteImport } from './routes/about' +import { Route as IndexRouteImport } from './routes/index' import { Route as ItemsIdRouteImport } from './routes/items.$id' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const AboutRoute = AboutRouteImport.update({ id: '/about', path: '/about', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const ItemsIdRoute = ItemsIdRouteImport.update({ id: '/items/$id', path: '/items/$id', @@ -61,13 +61,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/about': { id: '/about' path: '/about' @@ -75,6 +68,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/items/$id': { id: '/items/$id' path: '/items/$id' diff --git a/benchmarks/client-nav/scenarios/loaders/react/speed.bench.ts b/benchmarks/client-nav/scenarios/loaders/react/speed.bench.ts index 8bcc53b88e..f5a51b29be 100644 --- a/benchmarks/client-nav/scenarios/loaders/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/loaders/react/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-loaders', async ({ bench }) => { - const scenario = setup() +describe('client-loaders', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-loaders navigation loop (react)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/loaders/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/loaders/solid/speed.bench.ts index 953a17b31a..9f3bd397db 100644 --- a/benchmarks/client-nav/scenarios/loaders/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/loaders/solid/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-loaders', async ({ bench }) => { - const scenario = setup() +describe('client-loaders', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-loaders navigation loop (solid)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/loaders/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/loaders/solid/src/routeTree.gen.ts index fa5d032141..bdec400237 100644 --- a/benchmarks/client-nav/scenarios/loaders/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/loaders/solid/src/routeTree.gen.ts @@ -9,24 +9,19 @@ // 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 DepsRouteImport } from './routes/deps' -import { Route as CachedIdRouteImport } from './routes/cached.$id' +import { Route as IndexRouteImport } from './routes/index' import { Route as FreshIdRouteImport } from './routes/fresh.$id' +import { Route as CachedIdRouteImport } from './routes/cached.$id' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const DepsRoute = DepsRouteImport.update({ id: '/deps', path: '/deps', getParentRoute: () => rootRouteImport, } as any) -const CachedIdRoute = CachedIdRouteImport.update({ - id: '/cached/$id', - path: '/cached/$id', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const FreshIdRoute = FreshIdRouteImport.update({ @@ -34,6 +29,11 @@ const FreshIdRoute = FreshIdRouteImport.update({ path: '/fresh/$id', getParentRoute: () => rootRouteImport, } as any) +const CachedIdRoute = CachedIdRouteImport.update({ + id: '/cached/$id', + path: '/cached/$id', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -71,13 +71,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/deps': { id: '/deps' path: '/deps' @@ -85,11 +78,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DepsRouteImport parentRoute: typeof rootRouteImport } - '/cached/$id': { - id: '/cached/$id' - path: '/cached/$id' - fullPath: '/cached/$id' - preLoaderRoute: typeof CachedIdRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/fresh/$id': { @@ -99,6 +92,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof FreshIdRouteImport parentRoute: typeof rootRouteImport } + '/cached/$id': { + id: '/cached/$id' + path: '/cached/$id' + fullPath: '/cached/$id' + preLoaderRoute: typeof CachedIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/client-nav/scenarios/loaders/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/loaders/vue/speed.bench.ts index 1ae2f89a56..819fe020b0 100644 --- a/benchmarks/client-nav/scenarios/loaders/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/loaders/vue/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-loaders', async ({ bench }) => { - const scenario = setup() +describe('client-loaders', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-loaders navigation loop (vue)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/loaders/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/loaders/vue/src/routeTree.gen.ts index 10cb8f2aca..25a82df477 100644 --- a/benchmarks/client-nav/scenarios/loaders/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/loaders/vue/src/routeTree.gen.ts @@ -9,24 +9,19 @@ // 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 DepsRouteImport } from './routes/deps' -import { Route as CachedIdRouteImport } from './routes/cached.$id' +import { Route as IndexRouteImport } from './routes/index' import { Route as FreshIdRouteImport } from './routes/fresh.$id' +import { Route as CachedIdRouteImport } from './routes/cached.$id' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const DepsRoute = DepsRouteImport.update({ id: '/deps', path: '/deps', getParentRoute: () => rootRouteImport, } as any) -const CachedIdRoute = CachedIdRouteImport.update({ - id: '/cached/$id', - path: '/cached/$id', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const FreshIdRoute = FreshIdRouteImport.update({ @@ -34,6 +29,11 @@ const FreshIdRoute = FreshIdRouteImport.update({ path: '/fresh/$id', getParentRoute: () => rootRouteImport, } as any) +const CachedIdRoute = CachedIdRouteImport.update({ + id: '/cached/$id', + path: '/cached/$id', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -71,13 +71,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/deps': { id: '/deps' path: '/deps' @@ -85,11 +78,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof DepsRouteImport parentRoute: typeof rootRouteImport } - '/cached/$id': { - id: '/cached/$id' - path: '/cached/$id' - fullPath: '/cached/$id' - preLoaderRoute: typeof CachedIdRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/fresh/$id': { @@ -99,6 +92,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof FreshIdRouteImport parentRoute: typeof rootRouteImport } + '/cached/$id': { + id: '/cached/$id' + path: '/cached/$id' + fullPath: '/cached/$id' + preLoaderRoute: typeof CachedIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/client-nav/scenarios/mount/react/speed.bench.ts b/benchmarks/client-nav/scenarios/mount/react/speed.bench.ts index 6c3a64b026..2d675ff259 100644 --- a/benchmarks/client-nav/scenarios/mount/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/mount/react/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-mount', async ({ bench }) => { - const scenario = setup() +describe('client-mount', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-mount loop (react)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/mount/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/mount/solid/speed.bench.ts index 236f875f57..eaf7f1ed34 100644 --- a/benchmarks/client-nav/scenarios/mount/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/mount/solid/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-mount', async ({ bench }) => { - const scenario = setup() +describe('client-mount', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-mount loop (solid)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/mount/solid/src/routeTree.gen.ts index 30247636dd..dc0acc183d 100644 --- a/benchmarks/client-nav/scenarios/mount/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/mount/solid/src/routeTree.gen.ts @@ -9,35 +9,20 @@ // 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 AboutRouteImport } from './routes/about' -import { Route as BlogRouteImport } from './routes/blog' -import { Route as SearchRouteImport } from './routes/search' -import { Route as SettingsRouteImport } from './routes/settings' import { Route as ShopRouteImport } from './routes/shop' -import { Route as BlogIndexRouteImport } from './routes/blog.index' -import { Route as BlogSlugRouteImport } from './routes/blog.$slug' +import { Route as SettingsRouteImport } from './routes/settings' +import { Route as SearchRouteImport } from './routes/search' +import { Route as BlogRouteImport } from './routes/blog' +import { Route as AboutRouteImport } from './routes/about' +import { Route as IndexRouteImport } from './routes/index' import { Route as ShopIndexRouteImport } from './routes/shop.index' +import { Route as BlogIndexRouteImport } from './routes/blog.index' import { Route as ShopProductIdRouteImport } from './routes/shop.$productId' +import { Route as BlogSlugRouteImport } from './routes/blog.$slug' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) -const BlogRoute = BlogRouteImport.update({ - id: '/blog', - path: '/blog', - getParentRoute: () => rootRouteImport, -} as any) -const SearchRoute = SearchRouteImport.update({ - id: '/search', - path: '/search', +const ShopRoute = ShopRouteImport.update({ + id: '/shop', + path: '/shop', getParentRoute: () => rootRouteImport, } as any) const SettingsRoute = SettingsRouteImport.update({ @@ -45,31 +30,46 @@ const SettingsRoute = SettingsRouteImport.update({ path: '/settings', getParentRoute: () => rootRouteImport, } as any) -const ShopRoute = ShopRouteImport.update({ - id: '/shop', - path: '/shop', +const SearchRoute = SearchRouteImport.update({ + id: '/search', + path: '/search', getParentRoute: () => rootRouteImport, } as any) -const BlogIndexRoute = BlogIndexRouteImport.update({ +const BlogRoute = BlogRouteImport.update({ + id: '/blog', + path: '/blog', + getParentRoute: () => rootRouteImport, +} as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => BlogRoute, -} as any) -const BlogSlugRoute = BlogSlugRouteImport.update({ - id: '/$slug', - path: '/$slug', - getParentRoute: () => BlogRoute, + getParentRoute: () => rootRouteImport, } as any) const ShopIndexRoute = ShopIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => ShopRoute, } as any) +const BlogIndexRoute = BlogIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => BlogRoute, +} as any) const ShopProductIdRoute = ShopProductIdRouteImport.update({ id: '/$productId', path: '/$productId', getParentRoute: () => ShopRoute, } as any) +const BlogSlugRoute = BlogSlugRouteImport.update({ + id: '/$slug', + path: '/$slug', + getParentRoute: () => BlogRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -154,32 +154,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } - '/blog': { - id: '/blog' - path: '/blog' - fullPath: '/blog' - preLoaderRoute: typeof BlogRouteImport - parentRoute: typeof rootRouteImport - } - '/search': { - id: '/search' - path: '/search' - fullPath: '/search' - preLoaderRoute: typeof SearchRouteImport + '/shop': { + id: '/shop' + path: '/shop' + fullPath: '/shop' + preLoaderRoute: typeof ShopRouteImport parentRoute: typeof rootRouteImport } '/settings': { @@ -189,26 +168,33 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof SettingsRouteImport parentRoute: typeof rootRouteImport } - '/shop': { - id: '/shop' - path: '/shop' - fullPath: '/shop' - preLoaderRoute: typeof ShopRouteImport + '/search': { + id: '/search' + path: '/search' + fullPath: '/search' + preLoaderRoute: typeof SearchRouteImport parentRoute: typeof rootRouteImport } - '/blog/': { - id: '/blog/' - path: '/' - fullPath: '/blog/' - preLoaderRoute: typeof BlogIndexRouteImport - parentRoute: typeof BlogRoute + '/blog': { + id: '/blog' + path: '/blog' + fullPath: '/blog' + preLoaderRoute: typeof BlogRouteImport + parentRoute: typeof rootRouteImport } - '/blog/$slug': { - id: '/blog/$slug' - path: '/$slug' - fullPath: '/blog/$slug' - preLoaderRoute: typeof BlogSlugRouteImport - parentRoute: typeof BlogRoute + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/shop/': { id: '/shop/' @@ -217,6 +203,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ShopIndexRouteImport parentRoute: typeof ShopRoute } + '/blog/': { + id: '/blog/' + path: '/' + fullPath: '/blog/' + preLoaderRoute: typeof BlogIndexRouteImport + parentRoute: typeof BlogRoute + } '/shop/$productId': { id: '/shop/$productId' path: '/$productId' @@ -224,6 +217,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ShopProductIdRouteImport parentRoute: typeof ShopRoute } + '/blog/$slug': { + id: '/blog/$slug' + path: '/$slug' + fullPath: '/blog/$slug' + preLoaderRoute: typeof BlogSlugRouteImport + parentRoute: typeof BlogRoute + } } } diff --git a/benchmarks/client-nav/scenarios/mount/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/mount/vue/speed.bench.ts index d9268ba91b..f5538dd49c 100644 --- a/benchmarks/client-nav/scenarios/mount/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/mount/vue/speed.bench.ts @@ -1,15 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-mount', async ({ bench }) => { - const scenario = setup() +describe('client-mount', () => { + const test = setup() - await bench('client-mount loop (vue)', benchLifecycle(scenario), async () => { - for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() - } - await scenario.finishBatch() - }).run(benchOptions) + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( + 'client-mount loop (vue)', + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await test.tick() + } + await test.finishBatch() + }, + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/mount/vue/src/routeTree.gen.ts index cd27c917e1..98643d63c9 100644 --- a/benchmarks/client-nav/scenarios/mount/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/mount/vue/src/routeTree.gen.ts @@ -9,35 +9,20 @@ // 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 AboutRouteImport } from './routes/about' -import { Route as BlogRouteImport } from './routes/blog' -import { Route as SearchRouteImport } from './routes/search' -import { Route as SettingsRouteImport } from './routes/settings' import { Route as ShopRouteImport } from './routes/shop' -import { Route as BlogIndexRouteImport } from './routes/blog.index' -import { Route as BlogSlugRouteImport } from './routes/blog.$slug' +import { Route as SettingsRouteImport } from './routes/settings' +import { Route as SearchRouteImport } from './routes/search' +import { Route as BlogRouteImport } from './routes/blog' +import { Route as AboutRouteImport } from './routes/about' +import { Route as IndexRouteImport } from './routes/index' import { Route as ShopIndexRouteImport } from './routes/shop.index' +import { Route as BlogIndexRouteImport } from './routes/blog.index' import { Route as ShopProductIdRouteImport } from './routes/shop.$productId' +import { Route as BlogSlugRouteImport } from './routes/blog.$slug' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) -const BlogRoute = BlogRouteImport.update({ - id: '/blog', - path: '/blog', - getParentRoute: () => rootRouteImport, -} as any) -const SearchRoute = SearchRouteImport.update({ - id: '/search', - path: '/search', +const ShopRoute = ShopRouteImport.update({ + id: '/shop', + path: '/shop', getParentRoute: () => rootRouteImport, } as any) const SettingsRoute = SettingsRouteImport.update({ @@ -45,31 +30,46 @@ const SettingsRoute = SettingsRouteImport.update({ path: '/settings', getParentRoute: () => rootRouteImport, } as any) -const ShopRoute = ShopRouteImport.update({ - id: '/shop', - path: '/shop', +const SearchRoute = SearchRouteImport.update({ + id: '/search', + path: '/search', getParentRoute: () => rootRouteImport, } as any) -const BlogIndexRoute = BlogIndexRouteImport.update({ +const BlogRoute = BlogRouteImport.update({ + id: '/blog', + path: '/blog', + getParentRoute: () => rootRouteImport, +} as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => BlogRoute, -} as any) -const BlogSlugRoute = BlogSlugRouteImport.update({ - id: '/$slug', - path: '/$slug', - getParentRoute: () => BlogRoute, + getParentRoute: () => rootRouteImport, } as any) const ShopIndexRoute = ShopIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => ShopRoute, } as any) +const BlogIndexRoute = BlogIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => BlogRoute, +} as any) const ShopProductIdRoute = ShopProductIdRouteImport.update({ id: '/$productId', path: '/$productId', getParentRoute: () => ShopRoute, } as any) +const BlogSlugRoute = BlogSlugRouteImport.update({ + id: '/$slug', + path: '/$slug', + getParentRoute: () => BlogRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -154,32 +154,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } - '/blog': { - id: '/blog' - path: '/blog' - fullPath: '/blog' - preLoaderRoute: typeof BlogRouteImport - parentRoute: typeof rootRouteImport - } - '/search': { - id: '/search' - path: '/search' - fullPath: '/search' - preLoaderRoute: typeof SearchRouteImport + '/shop': { + id: '/shop' + path: '/shop' + fullPath: '/shop' + preLoaderRoute: typeof ShopRouteImport parentRoute: typeof rootRouteImport } '/settings': { @@ -189,26 +168,33 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof SettingsRouteImport parentRoute: typeof rootRouteImport } - '/shop': { - id: '/shop' - path: '/shop' - fullPath: '/shop' - preLoaderRoute: typeof ShopRouteImport + '/search': { + id: '/search' + path: '/search' + fullPath: '/search' + preLoaderRoute: typeof SearchRouteImport parentRoute: typeof rootRouteImport } - '/blog/': { - id: '/blog/' - path: '/' - fullPath: '/blog/' - preLoaderRoute: typeof BlogIndexRouteImport - parentRoute: typeof BlogRoute + '/blog': { + id: '/blog' + path: '/blog' + fullPath: '/blog' + preLoaderRoute: typeof BlogRouteImport + parentRoute: typeof rootRouteImport } - '/blog/$slug': { - id: '/blog/$slug' - path: '/$slug' - fullPath: '/blog/$slug' - preLoaderRoute: typeof BlogSlugRouteImport - parentRoute: typeof BlogRoute + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/shop/': { id: '/shop/' @@ -217,6 +203,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ShopIndexRouteImport parentRoute: typeof ShopRoute } + '/blog/': { + id: '/blog/' + path: '/' + fullPath: '/blog/' + preLoaderRoute: typeof BlogIndexRouteImport + parentRoute: typeof BlogRoute + } '/shop/$productId': { id: '/shop/$productId' path: '/$productId' @@ -224,6 +217,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ShopProductIdRouteImport parentRoute: typeof ShopRoute } + '/blog/$slug': { + id: '/blog/$slug' + path: '/$slug' + fullPath: '/blog/$slug' + preLoaderRoute: typeof BlogSlugRouteImport + parentRoute: typeof BlogRoute + } } } diff --git a/benchmarks/client-nav/scenarios/nested-params/react/speed.bench.ts b/benchmarks/client-nav/scenarios/nested-params/react/speed.bench.ts index fa5809c1fd..3dfe93c117 100644 --- a/benchmarks/client-nav/scenarios/nested-params/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/nested-params/react/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-nested-params', async ({ bench }) => { - const scenario = setup() +describe('client-nested-params', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-nested-params navigation loop (react)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/nested-params/solid/speed.bench.ts index 2c64d9a221..dc7ec11f6b 100644 --- a/benchmarks/client-nav/scenarios/nested-params/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/nested-params/solid/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-nested-params', async ({ bench }) => { - const scenario = setup() +describe('client-nested-params', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-nested-params navigation loop (solid)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/nested-params/vue/speed.bench.ts index bd3e82e070..fcb336d1db 100644 --- a/benchmarks/client-nav/scenarios/nested-params/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/nested-params/vue/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-nested-params', async ({ bench }) => { - const scenario = setup() +describe('client-nested-params', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-nested-params navigation loop (vue)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/preload/react/speed.bench.ts b/benchmarks/client-nav/scenarios/preload/react/speed.bench.ts index 5c210b2fd7..5b188a0a0b 100644 --- a/benchmarks/client-nav/scenarios/preload/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/preload/react/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-preload', async ({ bench }) => { - const scenario = setup() +describe('client-preload', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-preload interaction loop (react)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/preload/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/preload/solid/speed.bench.ts index f835b4a7b9..267c9fd41d 100644 --- a/benchmarks/client-nav/scenarios/preload/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/preload/solid/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-preload', async ({ bench }) => { - const scenario = setup() +describe('client-preload', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-preload interaction loop (solid)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/preload/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/preload/solid/src/routeTree.gen.ts index 97e215b6da..645d925238 100644 --- a/benchmarks/client-nav/scenarios/preload/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/preload/solid/src/routeTree.gen.ts @@ -9,20 +9,20 @@ // 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 DocsRouteImport } from './routes/docs' +import { Route as IndexRouteImport } from './routes/index' import { Route as SectionsSectionRouteImport } from './routes/sections.$section' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const DocsRoute = DocsRouteImport.update({ id: '/docs', path: '/docs', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const SectionsSectionRoute = SectionsSectionRouteImport.update({ id: '/sections/$section', path: '/sections/$section', @@ -61,13 +61,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/docs': { id: '/docs' path: '/docs' @@ -75,6 +68,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DocsRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/sections/$section': { id: '/sections/$section' path: '/sections/$section' diff --git a/benchmarks/client-nav/scenarios/preload/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/preload/vue/speed.bench.ts index e0ec83619b..38a2e9e664 100644 --- a/benchmarks/client-nav/scenarios/preload/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/preload/vue/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-preload', async ({ bench }) => { - const scenario = setup() +describe('client-preload', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-preload interaction loop (vue)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/preload/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/preload/vue/src/routeTree.gen.ts index 5f95d09da0..05a751060b 100644 --- a/benchmarks/client-nav/scenarios/preload/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/preload/vue/src/routeTree.gen.ts @@ -9,20 +9,20 @@ // 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 DocsRouteImport } from './routes/docs' +import { Route as IndexRouteImport } from './routes/index' import { Route as SectionsSectionRouteImport } from './routes/sections.$section' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const DocsRoute = DocsRouteImport.update({ id: '/docs', path: '/docs', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const SectionsSectionRoute = SectionsSectionRouteImport.update({ id: '/sections/$section', path: '/sections/$section', @@ -61,13 +61,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/docs': { id: '/docs' path: '/docs' @@ -75,6 +68,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof DocsRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/sections/$section': { id: '/sections/$section' path: '/sections/$section' diff --git a/benchmarks/client-nav/scenarios/rewrites/react/speed.bench.ts b/benchmarks/client-nav/scenarios/rewrites/react/speed.bench.ts index dd1b6f3686..8e79c6db7e 100644 --- a/benchmarks/client-nav/scenarios/rewrites/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/rewrites/react/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-rewrites', async ({ bench }) => { - const scenario = setup() +describe('client-rewrites', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-rewrites navigation loop (react)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/rewrites/solid/speed.bench.ts index 9c4313e2ff..cf70bcaa40 100644 --- a/benchmarks/client-nav/scenarios/rewrites/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/rewrites/solid/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-rewrites', async ({ bench }) => { - const scenario = setup() +describe('client-rewrites', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-rewrites navigation loop (solid)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/rewrites/vue/speed.bench.ts index e96aff39eb..2dc9eb2679 100644 --- a/benchmarks/client-nav/scenarios/rewrites/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/rewrites/vue/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-rewrites', async ({ bench }) => { - const scenario = setup() +describe('client-rewrites', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-rewrites navigation loop (vue)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/speed.bench.ts b/benchmarks/client-nav/scenarios/route-tree-scale/react/speed.bench.ts index 6f4b448775..337ba35b73 100644 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-route-tree-scale', async ({ bench }) => { - const scenario = setup() +describe('client-route-tree-scale', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-route-tree-scale navigation loop (react)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/route-tree-scale/solid/speed.bench.ts index 9244ef1350..545b501617 100644 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-route-tree-scale', async ({ bench }) => { - const scenario = setup() +describe('client-route-tree-scale', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-route-tree-scale navigation loop (solid)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routeTree.gen.ts index e6f3596562..20b4af6146 100644 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routeTree.gen.ts @@ -9,72 +9,48 @@ // 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 LayoutRouteImport } from './routes/_layout' -import { Route as SecARouteImport } from './routes/sec-a' -import { Route as SecBRouteImport } from './routes/sec-b' -import { Route as SecCRouteImport } from './routes/sec-c' -import { Route as SecDRouteImport } from './routes/sec-d' -import { Route as SecERouteImport } from './routes/sec-e' import { Route as SecFRouteImport } from './routes/sec-f' -import { Route as marketingPricingRouteImport } from './routes/(marketing)/pricing' -import { Route as marketingPromoRouteImport } from './routes/(marketing)/promo' -import { Route as LayoutAlphaRouteImport } from './routes/_layout.alpha' -import { Route as LayoutBetaRouteImport } from './routes/_layout.beta' -import { Route as FilesSplatRouteImport } from './routes/files.$' -import { Route as ReleaseVChar123versionChar125RouteImport } from './routes/release.v{$version}' -import { Route as SecAIndexRouteImport } from './routes/sec-a.index' -import { Route as SecAIdRouteImport } from './routes/sec-a.$id' -import { Route as SecAAboutRouteImport } from './routes/sec-a.about' -import { Route as SecASettingsRouteImport } from './routes/sec-a.settings' -import { Route as SecBIndexRouteImport } from './routes/sec-b.index' -import { Route as SecBIdRouteImport } from './routes/sec-b.$id' -import { Route as SecBAboutRouteImport } from './routes/sec-b.about' -import { Route as SecBSettingsRouteImport } from './routes/sec-b.settings' -import { Route as SecCIndexRouteImport } from './routes/sec-c.index' -import { Route as SecCIdRouteImport } from './routes/sec-c.$id' -import { Route as SecCAboutRouteImport } from './routes/sec-c.about' -import { Route as SecCSettingsRouteImport } from './routes/sec-c.settings' -import { Route as SecDIndexRouteImport } from './routes/sec-d.index' -import { Route as SecDIdRouteImport } from './routes/sec-d.$id' -import { Route as SecDAboutRouteImport } from './routes/sec-d.about' -import { Route as SecDSettingsRouteImport } from './routes/sec-d.settings' -import { Route as SecEIndexRouteImport } from './routes/sec-e.index' -import { Route as SecEIdRouteImport } from './routes/sec-e.$id' -import { Route as SecEAboutRouteImport } from './routes/sec-e.about' -import { Route as SecESettingsRouteImport } from './routes/sec-e.settings' +import { Route as SecERouteImport } from './routes/sec-e' +import { Route as SecDRouteImport } from './routes/sec-d' +import { Route as SecCRouteImport } from './routes/sec-c' +import { Route as SecBRouteImport } from './routes/sec-b' +import { Route as SecARouteImport } from './routes/sec-a' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as IndexRouteImport } from './routes/index' import { Route as SecFIndexRouteImport } from './routes/sec-f.index' -import { Route as SecFIdRouteImport } from './routes/sec-f.$id' -import { Route as SecFAboutRouteImport } from './routes/sec-f.about' +import { Route as SecEIndexRouteImport } from './routes/sec-e.index' +import { Route as SecDIndexRouteImport } from './routes/sec-d.index' +import { Route as SecCIndexRouteImport } from './routes/sec-c.index' +import { Route as SecBIndexRouteImport } from './routes/sec-b.index' +import { Route as SecAIndexRouteImport } from './routes/sec-a.index' import { Route as SecFSettingsRouteImport } from './routes/sec-f.settings' +import { Route as SecFAboutRouteImport } from './routes/sec-f.about' +import { Route as SecFIdRouteImport } from './routes/sec-f.$id' +import { Route as SecESettingsRouteImport } from './routes/sec-e.settings' +import { Route as SecEAboutRouteImport } from './routes/sec-e.about' +import { Route as SecEIdRouteImport } from './routes/sec-e.$id' +import { Route as SecDSettingsRouteImport } from './routes/sec-d.settings' +import { Route as SecDAboutRouteImport } from './routes/sec-d.about' +import { Route as SecDIdRouteImport } from './routes/sec-d.$id' +import { Route as SecCSettingsRouteImport } from './routes/sec-c.settings' +import { Route as SecCAboutRouteImport } from './routes/sec-c.about' +import { Route as SecCIdRouteImport } from './routes/sec-c.$id' +import { Route as SecBSettingsRouteImport } from './routes/sec-b.settings' +import { Route as SecBAboutRouteImport } from './routes/sec-b.about' +import { Route as SecBIdRouteImport } from './routes/sec-b.$id' +import { Route as SecASettingsRouteImport } from './routes/sec-a.settings' +import { Route as SecAAboutRouteImport } from './routes/sec-a.about' +import { Route as SecAIdRouteImport } from './routes/sec-a.$id' +import { Route as ReleaseVChar123versionChar125RouteImport } from './routes/release.v{$version}' +import { Route as FilesSplatRouteImport } from './routes/files.$' +import { Route as LayoutBetaRouteImport } from './routes/_layout.beta' +import { Route as LayoutAlphaRouteImport } from './routes/_layout.alpha' +import { Route as marketingPromoRouteImport } from './routes/(marketing)/promo' +import { Route as marketingPricingRouteImport } from './routes/(marketing)/pricing' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', - getParentRoute: () => rootRouteImport, -} as any) -const SecARoute = SecARouteImport.update({ - id: '/sec-a', - path: '/sec-a', - getParentRoute: () => rootRouteImport, -} as any) -const SecBRoute = SecBRouteImport.update({ - id: '/sec-b', - path: '/sec-b', - getParentRoute: () => rootRouteImport, -} as any) -const SecCRoute = SecCRouteImport.update({ - id: '/sec-c', - path: '/sec-c', - getParentRoute: () => rootRouteImport, -} as any) -const SecDRoute = SecDRouteImport.update({ - id: '/sec-d', - path: '/sec-d', +const SecFRoute = SecFRouteImport.update({ + id: '/sec-f', + path: '/sec-f', getParentRoute: () => rootRouteImport, } as any) const SecERoute = SecERouteImport.update({ @@ -82,150 +58,68 @@ const SecERoute = SecERouteImport.update({ path: '/sec-e', getParentRoute: () => rootRouteImport, } as any) -const SecFRoute = SecFRouteImport.update({ - id: '/sec-f', - path: '/sec-f', +const SecDRoute = SecDRouteImport.update({ + id: '/sec-d', + path: '/sec-d', getParentRoute: () => rootRouteImport, } as any) -const marketingPricingRoute = marketingPricingRouteImport.update({ - id: '/(marketing)/pricing', - path: '/pricing', +const SecCRoute = SecCRouteImport.update({ + id: '/sec-c', + path: '/sec-c', getParentRoute: () => rootRouteImport, } as any) -const marketingPromoRoute = marketingPromoRouteImport.update({ - id: '/(marketing)/promo', - path: '/promo', +const SecBRoute = SecBRouteImport.update({ + id: '/sec-b', + path: '/sec-b', getParentRoute: () => rootRouteImport, } as any) -const LayoutAlphaRoute = LayoutAlphaRouteImport.update({ - id: '/alpha', - path: '/alpha', - getParentRoute: () => LayoutRoute, -} as any) -const LayoutBetaRoute = LayoutBetaRouteImport.update({ - id: '/beta', - path: '/beta', - getParentRoute: () => LayoutRoute, -} as any) -const FilesSplatRoute = FilesSplatRouteImport.update({ - id: '/files/$', - path: '/files/$', +const SecARoute = SecARouteImport.update({ + id: '/sec-a', + path: '/sec-a', getParentRoute: () => rootRouteImport, } as any) -const ReleaseVChar123versionChar125Route = - ReleaseVChar123versionChar125RouteImport.update({ - id: '/release/v{$version}', - path: '/release/v{$version}', - getParentRoute: () => rootRouteImport, - } as any) -const SecAIndexRoute = SecAIndexRouteImport.update({ +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => SecARoute, -} as any) -const SecAIdRoute = SecAIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecARoute, -} as any) -const SecAAboutRoute = SecAAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecARoute, -} as any) -const SecASettingsRoute = SecASettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecARoute, -} as any) -const SecBIndexRoute = SecBIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecBRoute, -} as any) -const SecBIdRoute = SecBIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecBRoute, -} as any) -const SecBAboutRoute = SecBAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecBRoute, -} as any) -const SecBSettingsRoute = SecBSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecBRoute, -} as any) -const SecCIndexRoute = SecCIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecCRoute, -} as any) -const SecCIdRoute = SecCIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecCRoute, -} as any) -const SecCAboutRoute = SecCAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecCRoute, -} as any) -const SecCSettingsRoute = SecCSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecCRoute, -} as any) -const SecDIndexRoute = SecDIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecDRoute, -} as any) -const SecDIdRoute = SecDIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecDRoute, -} as any) -const SecDAboutRoute = SecDAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecDRoute, -} as any) -const SecDSettingsRoute = SecDSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecDRoute, -} as any) -const SecEIndexRoute = SecEIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecERoute, -} as any) -const SecEIdRoute = SecEIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecERoute, -} as any) -const SecEAboutRoute = SecEAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecERoute, -} as any) -const SecESettingsRoute = SecESettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecERoute, + getParentRoute: () => rootRouteImport, } as any) const SecFIndexRoute = SecFIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => SecFRoute, } as any) -const SecFIdRoute = SecFIdRouteImport.update({ - id: '/$id', - path: '/$id', +const SecEIndexRoute = SecEIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecERoute, +} as any) +const SecDIndexRoute = SecDIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecDRoute, +} as any) +const SecCIndexRoute = SecCIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecCRoute, +} as any) +const SecBIndexRoute = SecBIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecBRoute, +} as any) +const SecAIndexRoute = SecAIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecARoute, +} as any) +const SecFSettingsRoute = SecFSettingsRouteImport.update({ + id: '/settings', + path: '/settings', getParentRoute: () => SecFRoute, } as any) const SecFAboutRoute = SecFAboutRouteImport.update({ @@ -233,10 +127,116 @@ const SecFAboutRoute = SecFAboutRouteImport.update({ path: '/about', getParentRoute: () => SecFRoute, } as any) -const SecFSettingsRoute = SecFSettingsRouteImport.update({ +const SecFIdRoute = SecFIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecFRoute, +} as any) +const SecESettingsRoute = SecESettingsRouteImport.update({ id: '/settings', path: '/settings', - getParentRoute: () => SecFRoute, + getParentRoute: () => SecERoute, +} as any) +const SecEAboutRoute = SecEAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecERoute, +} as any) +const SecEIdRoute = SecEIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecERoute, +} as any) +const SecDSettingsRoute = SecDSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecDRoute, +} as any) +const SecDAboutRoute = SecDAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecDRoute, +} as any) +const SecDIdRoute = SecDIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecDRoute, +} as any) +const SecCSettingsRoute = SecCSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecCRoute, +} as any) +const SecCAboutRoute = SecCAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecCRoute, +} as any) +const SecCIdRoute = SecCIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecCRoute, +} as any) +const SecBSettingsRoute = SecBSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecBRoute, +} as any) +const SecBAboutRoute = SecBAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecBRoute, +} as any) +const SecBIdRoute = SecBIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecBRoute, +} as any) +const SecASettingsRoute = SecASettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecARoute, +} as any) +const SecAAboutRoute = SecAAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecARoute, +} as any) +const SecAIdRoute = SecAIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecARoute, +} as any) +const ReleaseVChar123versionChar125Route = + ReleaseVChar123versionChar125RouteImport.update({ + id: '/release/v{$version}', + path: '/release/v{$version}', + getParentRoute: () => rootRouteImport, + } as any) +const FilesSplatRoute = FilesSplatRouteImport.update({ + id: '/files/$', + path: '/files/$', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutBetaRoute = LayoutBetaRouteImport.update({ + id: '/beta', + path: '/beta', + getParentRoute: () => LayoutRoute, +} as any) +const LayoutAlphaRoute = LayoutAlphaRouteImport.update({ + id: '/alpha', + path: '/alpha', + getParentRoute: () => LayoutRoute, +} as any) +const marketingPromoRoute = marketingPromoRouteImport.update({ + id: '/(marketing)/promo', + path: '/promo', + getParentRoute: () => rootRouteImport, +} as any) +const marketingPricingRoute = marketingPricingRouteImport.update({ + id: '/(marketing)/pricing', + path: '/pricing', + getParentRoute: () => rootRouteImport, } as any) export interface FileRoutesByFullPath { @@ -484,46 +484,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout': { - id: '/_layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-a': { - id: '/sec-a' - path: '/sec-a' - fullPath: '/sec-a' - preLoaderRoute: typeof SecARouteImport - parentRoute: typeof rootRouteImport - } - '/sec-b': { - id: '/sec-b' - path: '/sec-b' - fullPath: '/sec-b' - preLoaderRoute: typeof SecBRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-c': { - id: '/sec-c' - path: '/sec-c' - fullPath: '/sec-c' - preLoaderRoute: typeof SecCRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-d': { - id: '/sec-d' - path: '/sec-d' - fullPath: '/sec-d' - preLoaderRoute: typeof SecDRouteImport + '/sec-f': { + id: '/sec-f' + path: '/sec-f' + fullPath: '/sec-f' + preLoaderRoute: typeof SecFRouteImport parentRoute: typeof rootRouteImport } '/sec-e': { @@ -533,194 +498,47 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof SecERouteImport parentRoute: typeof rootRouteImport } - '/sec-f': { - id: '/sec-f' - path: '/sec-f' - fullPath: '/sec-f' - preLoaderRoute: typeof SecFRouteImport + '/sec-d': { + id: '/sec-d' + path: '/sec-d' + fullPath: '/sec-d' + preLoaderRoute: typeof SecDRouteImport parentRoute: typeof rootRouteImport } - '/(marketing)/pricing': { - id: '/(marketing)/pricing' - path: '/pricing' - fullPath: '/pricing' - preLoaderRoute: typeof marketingPricingRouteImport + '/sec-c': { + id: '/sec-c' + path: '/sec-c' + fullPath: '/sec-c' + preLoaderRoute: typeof SecCRouteImport parentRoute: typeof rootRouteImport } - '/(marketing)/promo': { - id: '/(marketing)/promo' - path: '/promo' - fullPath: '/promo' - preLoaderRoute: typeof marketingPromoRouteImport + '/sec-b': { + id: '/sec-b' + path: '/sec-b' + fullPath: '/sec-b' + preLoaderRoute: typeof SecBRouteImport parentRoute: typeof rootRouteImport } - '/_layout/alpha': { - id: '/_layout/alpha' - path: '/alpha' - fullPath: '/alpha' - preLoaderRoute: typeof LayoutAlphaRouteImport - parentRoute: typeof LayoutRoute - } - '/_layout/beta': { - id: '/_layout/beta' - path: '/beta' - fullPath: '/beta' - preLoaderRoute: typeof LayoutBetaRouteImport - parentRoute: typeof LayoutRoute - } - '/files/$': { - id: '/files/$' - path: '/files/$' - fullPath: '/files/$' - preLoaderRoute: typeof FilesSplatRouteImport + '/sec-a': { + id: '/sec-a' + path: '/sec-a' + fullPath: '/sec-a' + preLoaderRoute: typeof SecARouteImport parentRoute: typeof rootRouteImport } - '/release/v{$version}': { - id: '/release/v{$version}' - path: '/release/v{$version}' - fullPath: '/release/v{$version}' - preLoaderRoute: typeof ReleaseVChar123versionChar125RouteImport + '/_layout': { + id: '/_layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/sec-a/': { - id: '/sec-a/' + '/': { + id: '/' path: '/' - fullPath: '/sec-a/' - preLoaderRoute: typeof SecAIndexRouteImport - parentRoute: typeof SecARoute - } - '/sec-a/$id': { - id: '/sec-a/$id' - path: '/$id' - fullPath: '/sec-a/$id' - preLoaderRoute: typeof SecAIdRouteImport - parentRoute: typeof SecARoute - } - '/sec-a/about': { - id: '/sec-a/about' - path: '/about' - fullPath: '/sec-a/about' - preLoaderRoute: typeof SecAAboutRouteImport - parentRoute: typeof SecARoute - } - '/sec-a/settings': { - id: '/sec-a/settings' - path: '/settings' - fullPath: '/sec-a/settings' - preLoaderRoute: typeof SecASettingsRouteImport - parentRoute: typeof SecARoute - } - '/sec-b/': { - id: '/sec-b/' - path: '/' - fullPath: '/sec-b/' - preLoaderRoute: typeof SecBIndexRouteImport - parentRoute: typeof SecBRoute - } - '/sec-b/$id': { - id: '/sec-b/$id' - path: '/$id' - fullPath: '/sec-b/$id' - preLoaderRoute: typeof SecBIdRouteImport - parentRoute: typeof SecBRoute - } - '/sec-b/about': { - id: '/sec-b/about' - path: '/about' - fullPath: '/sec-b/about' - preLoaderRoute: typeof SecBAboutRouteImport - parentRoute: typeof SecBRoute - } - '/sec-b/settings': { - id: '/sec-b/settings' - path: '/settings' - fullPath: '/sec-b/settings' - preLoaderRoute: typeof SecBSettingsRouteImport - parentRoute: typeof SecBRoute - } - '/sec-c/': { - id: '/sec-c/' - path: '/' - fullPath: '/sec-c/' - preLoaderRoute: typeof SecCIndexRouteImport - parentRoute: typeof SecCRoute - } - '/sec-c/$id': { - id: '/sec-c/$id' - path: '/$id' - fullPath: '/sec-c/$id' - preLoaderRoute: typeof SecCIdRouteImport - parentRoute: typeof SecCRoute - } - '/sec-c/about': { - id: '/sec-c/about' - path: '/about' - fullPath: '/sec-c/about' - preLoaderRoute: typeof SecCAboutRouteImport - parentRoute: typeof SecCRoute - } - '/sec-c/settings': { - id: '/sec-c/settings' - path: '/settings' - fullPath: '/sec-c/settings' - preLoaderRoute: typeof SecCSettingsRouteImport - parentRoute: typeof SecCRoute - } - '/sec-d/': { - id: '/sec-d/' - path: '/' - fullPath: '/sec-d/' - preLoaderRoute: typeof SecDIndexRouteImport - parentRoute: typeof SecDRoute - } - '/sec-d/$id': { - id: '/sec-d/$id' - path: '/$id' - fullPath: '/sec-d/$id' - preLoaderRoute: typeof SecDIdRouteImport - parentRoute: typeof SecDRoute - } - '/sec-d/about': { - id: '/sec-d/about' - path: '/about' - fullPath: '/sec-d/about' - preLoaderRoute: typeof SecDAboutRouteImport - parentRoute: typeof SecDRoute - } - '/sec-d/settings': { - id: '/sec-d/settings' - path: '/settings' - fullPath: '/sec-d/settings' - preLoaderRoute: typeof SecDSettingsRouteImport - parentRoute: typeof SecDRoute - } - '/sec-e/': { - id: '/sec-e/' - path: '/' - fullPath: '/sec-e/' - preLoaderRoute: typeof SecEIndexRouteImport - parentRoute: typeof SecERoute - } - '/sec-e/$id': { - id: '/sec-e/$id' - path: '/$id' - fullPath: '/sec-e/$id' - preLoaderRoute: typeof SecEIdRouteImport - parentRoute: typeof SecERoute - } - '/sec-e/about': { - id: '/sec-e/about' - path: '/about' - fullPath: '/sec-e/about' - preLoaderRoute: typeof SecEAboutRouteImport - parentRoute: typeof SecERoute - } - '/sec-e/settings': { - id: '/sec-e/settings' - path: '/settings' - fullPath: '/sec-e/settings' - preLoaderRoute: typeof SecESettingsRouteImport - parentRoute: typeof SecERoute + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/sec-f/': { id: '/sec-f/' @@ -729,11 +547,46 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof SecFIndexRouteImport parentRoute: typeof SecFRoute } - '/sec-f/$id': { - id: '/sec-f/$id' - path: '/$id' - fullPath: '/sec-f/$id' - preLoaderRoute: typeof SecFIdRouteImport + '/sec-e/': { + id: '/sec-e/' + path: '/' + fullPath: '/sec-e/' + preLoaderRoute: typeof SecEIndexRouteImport + parentRoute: typeof SecERoute + } + '/sec-d/': { + id: '/sec-d/' + path: '/' + fullPath: '/sec-d/' + preLoaderRoute: typeof SecDIndexRouteImport + parentRoute: typeof SecDRoute + } + '/sec-c/': { + id: '/sec-c/' + path: '/' + fullPath: '/sec-c/' + preLoaderRoute: typeof SecCIndexRouteImport + parentRoute: typeof SecCRoute + } + '/sec-b/': { + id: '/sec-b/' + path: '/' + fullPath: '/sec-b/' + preLoaderRoute: typeof SecBIndexRouteImport + parentRoute: typeof SecBRoute + } + '/sec-a/': { + id: '/sec-a/' + path: '/' + fullPath: '/sec-a/' + preLoaderRoute: typeof SecAIndexRouteImport + parentRoute: typeof SecARoute + } + '/sec-f/settings': { + id: '/sec-f/settings' + path: '/settings' + fullPath: '/sec-f/settings' + preLoaderRoute: typeof SecFSettingsRouteImport parentRoute: typeof SecFRoute } '/sec-f/about': { @@ -743,13 +596,160 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof SecFAboutRouteImport parentRoute: typeof SecFRoute } - '/sec-f/settings': { - id: '/sec-f/settings' - path: '/settings' - fullPath: '/sec-f/settings' - preLoaderRoute: typeof SecFSettingsRouteImport + '/sec-f/$id': { + id: '/sec-f/$id' + path: '/$id' + fullPath: '/sec-f/$id' + preLoaderRoute: typeof SecFIdRouteImport parentRoute: typeof SecFRoute } + '/sec-e/settings': { + id: '/sec-e/settings' + path: '/settings' + fullPath: '/sec-e/settings' + preLoaderRoute: typeof SecESettingsRouteImport + parentRoute: typeof SecERoute + } + '/sec-e/about': { + id: '/sec-e/about' + path: '/about' + fullPath: '/sec-e/about' + preLoaderRoute: typeof SecEAboutRouteImport + parentRoute: typeof SecERoute + } + '/sec-e/$id': { + id: '/sec-e/$id' + path: '/$id' + fullPath: '/sec-e/$id' + preLoaderRoute: typeof SecEIdRouteImport + parentRoute: typeof SecERoute + } + '/sec-d/settings': { + id: '/sec-d/settings' + path: '/settings' + fullPath: '/sec-d/settings' + preLoaderRoute: typeof SecDSettingsRouteImport + parentRoute: typeof SecDRoute + } + '/sec-d/about': { + id: '/sec-d/about' + path: '/about' + fullPath: '/sec-d/about' + preLoaderRoute: typeof SecDAboutRouteImport + parentRoute: typeof SecDRoute + } + '/sec-d/$id': { + id: '/sec-d/$id' + path: '/$id' + fullPath: '/sec-d/$id' + preLoaderRoute: typeof SecDIdRouteImport + parentRoute: typeof SecDRoute + } + '/sec-c/settings': { + id: '/sec-c/settings' + path: '/settings' + fullPath: '/sec-c/settings' + preLoaderRoute: typeof SecCSettingsRouteImport + parentRoute: typeof SecCRoute + } + '/sec-c/about': { + id: '/sec-c/about' + path: '/about' + fullPath: '/sec-c/about' + preLoaderRoute: typeof SecCAboutRouteImport + parentRoute: typeof SecCRoute + } + '/sec-c/$id': { + id: '/sec-c/$id' + path: '/$id' + fullPath: '/sec-c/$id' + preLoaderRoute: typeof SecCIdRouteImport + parentRoute: typeof SecCRoute + } + '/sec-b/settings': { + id: '/sec-b/settings' + path: '/settings' + fullPath: '/sec-b/settings' + preLoaderRoute: typeof SecBSettingsRouteImport + parentRoute: typeof SecBRoute + } + '/sec-b/about': { + id: '/sec-b/about' + path: '/about' + fullPath: '/sec-b/about' + preLoaderRoute: typeof SecBAboutRouteImport + parentRoute: typeof SecBRoute + } + '/sec-b/$id': { + id: '/sec-b/$id' + path: '/$id' + fullPath: '/sec-b/$id' + preLoaderRoute: typeof SecBIdRouteImport + parentRoute: typeof SecBRoute + } + '/sec-a/settings': { + id: '/sec-a/settings' + path: '/settings' + fullPath: '/sec-a/settings' + preLoaderRoute: typeof SecASettingsRouteImport + parentRoute: typeof SecARoute + } + '/sec-a/about': { + id: '/sec-a/about' + path: '/about' + fullPath: '/sec-a/about' + preLoaderRoute: typeof SecAAboutRouteImport + parentRoute: typeof SecARoute + } + '/sec-a/$id': { + id: '/sec-a/$id' + path: '/$id' + fullPath: '/sec-a/$id' + preLoaderRoute: typeof SecAIdRouteImport + parentRoute: typeof SecARoute + } + '/release/v{$version}': { + id: '/release/v{$version}' + path: '/release/v{$version}' + fullPath: '/release/v{$version}' + preLoaderRoute: typeof ReleaseVChar123versionChar125RouteImport + parentRoute: typeof rootRouteImport + } + '/files/$': { + id: '/files/$' + path: '/files/$' + fullPath: '/files/$' + preLoaderRoute: typeof FilesSplatRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout/beta': { + id: '/_layout/beta' + path: '/beta' + fullPath: '/beta' + preLoaderRoute: typeof LayoutBetaRouteImport + parentRoute: typeof LayoutRoute + } + '/_layout/alpha': { + id: '/_layout/alpha' + path: '/alpha' + fullPath: '/alpha' + preLoaderRoute: typeof LayoutAlphaRouteImport + parentRoute: typeof LayoutRoute + } + '/(marketing)/promo': { + id: '/(marketing)/promo' + path: '/promo' + fullPath: '/promo' + preLoaderRoute: typeof marketingPromoRouteImport + parentRoute: typeof rootRouteImport + } + '/(marketing)/pricing': { + id: '/(marketing)/pricing' + path: '/pricing' + fullPath: '/pricing' + preLoaderRoute: typeof marketingPricingRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/route-tree-scale/vue/speed.bench.ts index 331e8e008f..9365231579 100644 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-route-tree-scale', async ({ bench }) => { - const scenario = setup() +describe('client-route-tree-scale', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-route-tree-scale navigation loop (vue)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routeTree.gen.ts index a12f981bb4..a03c051a79 100644 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routeTree.gen.ts @@ -9,72 +9,48 @@ // 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 LayoutRouteImport } from './routes/_layout' -import { Route as SecARouteImport } from './routes/sec-a' -import { Route as SecBRouteImport } from './routes/sec-b' -import { Route as SecCRouteImport } from './routes/sec-c' -import { Route as SecDRouteImport } from './routes/sec-d' -import { Route as SecERouteImport } from './routes/sec-e' import { Route as SecFRouteImport } from './routes/sec-f' -import { Route as marketingPricingRouteImport } from './routes/(marketing)/pricing' -import { Route as marketingPromoRouteImport } from './routes/(marketing)/promo' -import { Route as LayoutAlphaRouteImport } from './routes/_layout.alpha' -import { Route as LayoutBetaRouteImport } from './routes/_layout.beta' -import { Route as FilesSplatRouteImport } from './routes/files.$' -import { Route as ReleaseVChar123versionChar125RouteImport } from './routes/release.v{$version}' -import { Route as SecAIndexRouteImport } from './routes/sec-a.index' -import { Route as SecAIdRouteImport } from './routes/sec-a.$id' -import { Route as SecAAboutRouteImport } from './routes/sec-a.about' -import { Route as SecASettingsRouteImport } from './routes/sec-a.settings' -import { Route as SecBIndexRouteImport } from './routes/sec-b.index' -import { Route as SecBIdRouteImport } from './routes/sec-b.$id' -import { Route as SecBAboutRouteImport } from './routes/sec-b.about' -import { Route as SecBSettingsRouteImport } from './routes/sec-b.settings' -import { Route as SecCIndexRouteImport } from './routes/sec-c.index' -import { Route as SecCIdRouteImport } from './routes/sec-c.$id' -import { Route as SecCAboutRouteImport } from './routes/sec-c.about' -import { Route as SecCSettingsRouteImport } from './routes/sec-c.settings' -import { Route as SecDIndexRouteImport } from './routes/sec-d.index' -import { Route as SecDIdRouteImport } from './routes/sec-d.$id' -import { Route as SecDAboutRouteImport } from './routes/sec-d.about' -import { Route as SecDSettingsRouteImport } from './routes/sec-d.settings' -import { Route as SecEIndexRouteImport } from './routes/sec-e.index' -import { Route as SecEIdRouteImport } from './routes/sec-e.$id' -import { Route as SecEAboutRouteImport } from './routes/sec-e.about' -import { Route as SecESettingsRouteImport } from './routes/sec-e.settings' +import { Route as SecERouteImport } from './routes/sec-e' +import { Route as SecDRouteImport } from './routes/sec-d' +import { Route as SecCRouteImport } from './routes/sec-c' +import { Route as SecBRouteImport } from './routes/sec-b' +import { Route as SecARouteImport } from './routes/sec-a' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as IndexRouteImport } from './routes/index' import { Route as SecFIndexRouteImport } from './routes/sec-f.index' -import { Route as SecFIdRouteImport } from './routes/sec-f.$id' -import { Route as SecFAboutRouteImport } from './routes/sec-f.about' +import { Route as SecEIndexRouteImport } from './routes/sec-e.index' +import { Route as SecDIndexRouteImport } from './routes/sec-d.index' +import { Route as SecCIndexRouteImport } from './routes/sec-c.index' +import { Route as SecBIndexRouteImport } from './routes/sec-b.index' +import { Route as SecAIndexRouteImport } from './routes/sec-a.index' import { Route as SecFSettingsRouteImport } from './routes/sec-f.settings' +import { Route as SecFAboutRouteImport } from './routes/sec-f.about' +import { Route as SecFIdRouteImport } from './routes/sec-f.$id' +import { Route as SecESettingsRouteImport } from './routes/sec-e.settings' +import { Route as SecEAboutRouteImport } from './routes/sec-e.about' +import { Route as SecEIdRouteImport } from './routes/sec-e.$id' +import { Route as SecDSettingsRouteImport } from './routes/sec-d.settings' +import { Route as SecDAboutRouteImport } from './routes/sec-d.about' +import { Route as SecDIdRouteImport } from './routes/sec-d.$id' +import { Route as SecCSettingsRouteImport } from './routes/sec-c.settings' +import { Route as SecCAboutRouteImport } from './routes/sec-c.about' +import { Route as SecCIdRouteImport } from './routes/sec-c.$id' +import { Route as SecBSettingsRouteImport } from './routes/sec-b.settings' +import { Route as SecBAboutRouteImport } from './routes/sec-b.about' +import { Route as SecBIdRouteImport } from './routes/sec-b.$id' +import { Route as SecASettingsRouteImport } from './routes/sec-a.settings' +import { Route as SecAAboutRouteImport } from './routes/sec-a.about' +import { Route as SecAIdRouteImport } from './routes/sec-a.$id' +import { Route as ReleaseVChar123versionChar125RouteImport } from './routes/release.v{$version}' +import { Route as FilesSplatRouteImport } from './routes/files.$' +import { Route as LayoutBetaRouteImport } from './routes/_layout.beta' +import { Route as LayoutAlphaRouteImport } from './routes/_layout.alpha' +import { Route as marketingPromoRouteImport } from './routes/(marketing)/promo' +import { Route as marketingPricingRouteImport } from './routes/(marketing)/pricing' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', - getParentRoute: () => rootRouteImport, -} as any) -const SecARoute = SecARouteImport.update({ - id: '/sec-a', - path: '/sec-a', - getParentRoute: () => rootRouteImport, -} as any) -const SecBRoute = SecBRouteImport.update({ - id: '/sec-b', - path: '/sec-b', - getParentRoute: () => rootRouteImport, -} as any) -const SecCRoute = SecCRouteImport.update({ - id: '/sec-c', - path: '/sec-c', - getParentRoute: () => rootRouteImport, -} as any) -const SecDRoute = SecDRouteImport.update({ - id: '/sec-d', - path: '/sec-d', +const SecFRoute = SecFRouteImport.update({ + id: '/sec-f', + path: '/sec-f', getParentRoute: () => rootRouteImport, } as any) const SecERoute = SecERouteImport.update({ @@ -82,150 +58,68 @@ const SecERoute = SecERouteImport.update({ path: '/sec-e', getParentRoute: () => rootRouteImport, } as any) -const SecFRoute = SecFRouteImport.update({ - id: '/sec-f', - path: '/sec-f', +const SecDRoute = SecDRouteImport.update({ + id: '/sec-d', + path: '/sec-d', getParentRoute: () => rootRouteImport, } as any) -const marketingPricingRoute = marketingPricingRouteImport.update({ - id: '/(marketing)/pricing', - path: '/pricing', +const SecCRoute = SecCRouteImport.update({ + id: '/sec-c', + path: '/sec-c', getParentRoute: () => rootRouteImport, } as any) -const marketingPromoRoute = marketingPromoRouteImport.update({ - id: '/(marketing)/promo', - path: '/promo', +const SecBRoute = SecBRouteImport.update({ + id: '/sec-b', + path: '/sec-b', getParentRoute: () => rootRouteImport, } as any) -const LayoutAlphaRoute = LayoutAlphaRouteImport.update({ - id: '/alpha', - path: '/alpha', - getParentRoute: () => LayoutRoute, -} as any) -const LayoutBetaRoute = LayoutBetaRouteImport.update({ - id: '/beta', - path: '/beta', - getParentRoute: () => LayoutRoute, -} as any) -const FilesSplatRoute = FilesSplatRouteImport.update({ - id: '/files/$', - path: '/files/$', +const SecARoute = SecARouteImport.update({ + id: '/sec-a', + path: '/sec-a', getParentRoute: () => rootRouteImport, } as any) -const ReleaseVChar123versionChar125Route = - ReleaseVChar123versionChar125RouteImport.update({ - id: '/release/v{$version}', - path: '/release/v{$version}', - getParentRoute: () => rootRouteImport, - } as any) -const SecAIndexRoute = SecAIndexRouteImport.update({ +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => SecARoute, -} as any) -const SecAIdRoute = SecAIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecARoute, -} as any) -const SecAAboutRoute = SecAAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecARoute, -} as any) -const SecASettingsRoute = SecASettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecARoute, -} as any) -const SecBIndexRoute = SecBIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecBRoute, -} as any) -const SecBIdRoute = SecBIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecBRoute, -} as any) -const SecBAboutRoute = SecBAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecBRoute, -} as any) -const SecBSettingsRoute = SecBSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecBRoute, -} as any) -const SecCIndexRoute = SecCIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecCRoute, -} as any) -const SecCIdRoute = SecCIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecCRoute, -} as any) -const SecCAboutRoute = SecCAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecCRoute, -} as any) -const SecCSettingsRoute = SecCSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecCRoute, -} as any) -const SecDIndexRoute = SecDIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecDRoute, -} as any) -const SecDIdRoute = SecDIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecDRoute, -} as any) -const SecDAboutRoute = SecDAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecDRoute, -} as any) -const SecDSettingsRoute = SecDSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecDRoute, -} as any) -const SecEIndexRoute = SecEIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecERoute, -} as any) -const SecEIdRoute = SecEIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecERoute, -} as any) -const SecEAboutRoute = SecEAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecERoute, -} as any) -const SecESettingsRoute = SecESettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecERoute, + getParentRoute: () => rootRouteImport, } as any) const SecFIndexRoute = SecFIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => SecFRoute, } as any) -const SecFIdRoute = SecFIdRouteImport.update({ - id: '/$id', - path: '/$id', +const SecEIndexRoute = SecEIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecERoute, +} as any) +const SecDIndexRoute = SecDIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecDRoute, +} as any) +const SecCIndexRoute = SecCIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecCRoute, +} as any) +const SecBIndexRoute = SecBIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecBRoute, +} as any) +const SecAIndexRoute = SecAIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecARoute, +} as any) +const SecFSettingsRoute = SecFSettingsRouteImport.update({ + id: '/settings', + path: '/settings', getParentRoute: () => SecFRoute, } as any) const SecFAboutRoute = SecFAboutRouteImport.update({ @@ -233,10 +127,116 @@ const SecFAboutRoute = SecFAboutRouteImport.update({ path: '/about', getParentRoute: () => SecFRoute, } as any) -const SecFSettingsRoute = SecFSettingsRouteImport.update({ +const SecFIdRoute = SecFIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecFRoute, +} as any) +const SecESettingsRoute = SecESettingsRouteImport.update({ id: '/settings', path: '/settings', - getParentRoute: () => SecFRoute, + getParentRoute: () => SecERoute, +} as any) +const SecEAboutRoute = SecEAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecERoute, +} as any) +const SecEIdRoute = SecEIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecERoute, +} as any) +const SecDSettingsRoute = SecDSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecDRoute, +} as any) +const SecDAboutRoute = SecDAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecDRoute, +} as any) +const SecDIdRoute = SecDIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecDRoute, +} as any) +const SecCSettingsRoute = SecCSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecCRoute, +} as any) +const SecCAboutRoute = SecCAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecCRoute, +} as any) +const SecCIdRoute = SecCIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecCRoute, +} as any) +const SecBSettingsRoute = SecBSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecBRoute, +} as any) +const SecBAboutRoute = SecBAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecBRoute, +} as any) +const SecBIdRoute = SecBIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecBRoute, +} as any) +const SecASettingsRoute = SecASettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecARoute, +} as any) +const SecAAboutRoute = SecAAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecARoute, +} as any) +const SecAIdRoute = SecAIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecARoute, +} as any) +const ReleaseVChar123versionChar125Route = + ReleaseVChar123versionChar125RouteImport.update({ + id: '/release/v{$version}', + path: '/release/v{$version}', + getParentRoute: () => rootRouteImport, + } as any) +const FilesSplatRoute = FilesSplatRouteImport.update({ + id: '/files/$', + path: '/files/$', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutBetaRoute = LayoutBetaRouteImport.update({ + id: '/beta', + path: '/beta', + getParentRoute: () => LayoutRoute, +} as any) +const LayoutAlphaRoute = LayoutAlphaRouteImport.update({ + id: '/alpha', + path: '/alpha', + getParentRoute: () => LayoutRoute, +} as any) +const marketingPromoRoute = marketingPromoRouteImport.update({ + id: '/(marketing)/promo', + path: '/promo', + getParentRoute: () => rootRouteImport, +} as any) +const marketingPricingRoute = marketingPricingRouteImport.update({ + id: '/(marketing)/pricing', + path: '/pricing', + getParentRoute: () => rootRouteImport, } as any) export interface FileRoutesByFullPath { @@ -484,46 +484,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout': { - id: '/_layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-a': { - id: '/sec-a' - path: '/sec-a' - fullPath: '/sec-a' - preLoaderRoute: typeof SecARouteImport - parentRoute: typeof rootRouteImport - } - '/sec-b': { - id: '/sec-b' - path: '/sec-b' - fullPath: '/sec-b' - preLoaderRoute: typeof SecBRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-c': { - id: '/sec-c' - path: '/sec-c' - fullPath: '/sec-c' - preLoaderRoute: typeof SecCRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-d': { - id: '/sec-d' - path: '/sec-d' - fullPath: '/sec-d' - preLoaderRoute: typeof SecDRouteImport + '/sec-f': { + id: '/sec-f' + path: '/sec-f' + fullPath: '/sec-f' + preLoaderRoute: typeof SecFRouteImport parentRoute: typeof rootRouteImport } '/sec-e': { @@ -533,194 +498,47 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof SecERouteImport parentRoute: typeof rootRouteImport } - '/sec-f': { - id: '/sec-f' - path: '/sec-f' - fullPath: '/sec-f' - preLoaderRoute: typeof SecFRouteImport + '/sec-d': { + id: '/sec-d' + path: '/sec-d' + fullPath: '/sec-d' + preLoaderRoute: typeof SecDRouteImport parentRoute: typeof rootRouteImport } - '/(marketing)/pricing': { - id: '/(marketing)/pricing' - path: '/pricing' - fullPath: '/pricing' - preLoaderRoute: typeof marketingPricingRouteImport + '/sec-c': { + id: '/sec-c' + path: '/sec-c' + fullPath: '/sec-c' + preLoaderRoute: typeof SecCRouteImport parentRoute: typeof rootRouteImport } - '/(marketing)/promo': { - id: '/(marketing)/promo' - path: '/promo' - fullPath: '/promo' - preLoaderRoute: typeof marketingPromoRouteImport + '/sec-b': { + id: '/sec-b' + path: '/sec-b' + fullPath: '/sec-b' + preLoaderRoute: typeof SecBRouteImport parentRoute: typeof rootRouteImport } - '/_layout/alpha': { - id: '/_layout/alpha' - path: '/alpha' - fullPath: '/alpha' - preLoaderRoute: typeof LayoutAlphaRouteImport - parentRoute: typeof LayoutRoute - } - '/_layout/beta': { - id: '/_layout/beta' - path: '/beta' - fullPath: '/beta' - preLoaderRoute: typeof LayoutBetaRouteImport - parentRoute: typeof LayoutRoute - } - '/files/$': { - id: '/files/$' - path: '/files/$' - fullPath: '/files/$' - preLoaderRoute: typeof FilesSplatRouteImport + '/sec-a': { + id: '/sec-a' + path: '/sec-a' + fullPath: '/sec-a' + preLoaderRoute: typeof SecARouteImport parentRoute: typeof rootRouteImport } - '/release/v{$version}': { - id: '/release/v{$version}' - path: '/release/v{$version}' - fullPath: '/release/v{$version}' - preLoaderRoute: typeof ReleaseVChar123versionChar125RouteImport + '/_layout': { + id: '/_layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/sec-a/': { - id: '/sec-a/' + '/': { + id: '/' path: '/' - fullPath: '/sec-a/' - preLoaderRoute: typeof SecAIndexRouteImport - parentRoute: typeof SecARoute - } - '/sec-a/$id': { - id: '/sec-a/$id' - path: '/$id' - fullPath: '/sec-a/$id' - preLoaderRoute: typeof SecAIdRouteImport - parentRoute: typeof SecARoute - } - '/sec-a/about': { - id: '/sec-a/about' - path: '/about' - fullPath: '/sec-a/about' - preLoaderRoute: typeof SecAAboutRouteImport - parentRoute: typeof SecARoute - } - '/sec-a/settings': { - id: '/sec-a/settings' - path: '/settings' - fullPath: '/sec-a/settings' - preLoaderRoute: typeof SecASettingsRouteImport - parentRoute: typeof SecARoute - } - '/sec-b/': { - id: '/sec-b/' - path: '/' - fullPath: '/sec-b/' - preLoaderRoute: typeof SecBIndexRouteImport - parentRoute: typeof SecBRoute - } - '/sec-b/$id': { - id: '/sec-b/$id' - path: '/$id' - fullPath: '/sec-b/$id' - preLoaderRoute: typeof SecBIdRouteImport - parentRoute: typeof SecBRoute - } - '/sec-b/about': { - id: '/sec-b/about' - path: '/about' - fullPath: '/sec-b/about' - preLoaderRoute: typeof SecBAboutRouteImport - parentRoute: typeof SecBRoute - } - '/sec-b/settings': { - id: '/sec-b/settings' - path: '/settings' - fullPath: '/sec-b/settings' - preLoaderRoute: typeof SecBSettingsRouteImport - parentRoute: typeof SecBRoute - } - '/sec-c/': { - id: '/sec-c/' - path: '/' - fullPath: '/sec-c/' - preLoaderRoute: typeof SecCIndexRouteImport - parentRoute: typeof SecCRoute - } - '/sec-c/$id': { - id: '/sec-c/$id' - path: '/$id' - fullPath: '/sec-c/$id' - preLoaderRoute: typeof SecCIdRouteImport - parentRoute: typeof SecCRoute - } - '/sec-c/about': { - id: '/sec-c/about' - path: '/about' - fullPath: '/sec-c/about' - preLoaderRoute: typeof SecCAboutRouteImport - parentRoute: typeof SecCRoute - } - '/sec-c/settings': { - id: '/sec-c/settings' - path: '/settings' - fullPath: '/sec-c/settings' - preLoaderRoute: typeof SecCSettingsRouteImport - parentRoute: typeof SecCRoute - } - '/sec-d/': { - id: '/sec-d/' - path: '/' - fullPath: '/sec-d/' - preLoaderRoute: typeof SecDIndexRouteImport - parentRoute: typeof SecDRoute - } - '/sec-d/$id': { - id: '/sec-d/$id' - path: '/$id' - fullPath: '/sec-d/$id' - preLoaderRoute: typeof SecDIdRouteImport - parentRoute: typeof SecDRoute - } - '/sec-d/about': { - id: '/sec-d/about' - path: '/about' - fullPath: '/sec-d/about' - preLoaderRoute: typeof SecDAboutRouteImport - parentRoute: typeof SecDRoute - } - '/sec-d/settings': { - id: '/sec-d/settings' - path: '/settings' - fullPath: '/sec-d/settings' - preLoaderRoute: typeof SecDSettingsRouteImport - parentRoute: typeof SecDRoute - } - '/sec-e/': { - id: '/sec-e/' - path: '/' - fullPath: '/sec-e/' - preLoaderRoute: typeof SecEIndexRouteImport - parentRoute: typeof SecERoute - } - '/sec-e/$id': { - id: '/sec-e/$id' - path: '/$id' - fullPath: '/sec-e/$id' - preLoaderRoute: typeof SecEIdRouteImport - parentRoute: typeof SecERoute - } - '/sec-e/about': { - id: '/sec-e/about' - path: '/about' - fullPath: '/sec-e/about' - preLoaderRoute: typeof SecEAboutRouteImport - parentRoute: typeof SecERoute - } - '/sec-e/settings': { - id: '/sec-e/settings' - path: '/settings' - fullPath: '/sec-e/settings' - preLoaderRoute: typeof SecESettingsRouteImport - parentRoute: typeof SecERoute + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/sec-f/': { id: '/sec-f/' @@ -729,11 +547,46 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof SecFIndexRouteImport parentRoute: typeof SecFRoute } - '/sec-f/$id': { - id: '/sec-f/$id' - path: '/$id' - fullPath: '/sec-f/$id' - preLoaderRoute: typeof SecFIdRouteImport + '/sec-e/': { + id: '/sec-e/' + path: '/' + fullPath: '/sec-e/' + preLoaderRoute: typeof SecEIndexRouteImport + parentRoute: typeof SecERoute + } + '/sec-d/': { + id: '/sec-d/' + path: '/' + fullPath: '/sec-d/' + preLoaderRoute: typeof SecDIndexRouteImport + parentRoute: typeof SecDRoute + } + '/sec-c/': { + id: '/sec-c/' + path: '/' + fullPath: '/sec-c/' + preLoaderRoute: typeof SecCIndexRouteImport + parentRoute: typeof SecCRoute + } + '/sec-b/': { + id: '/sec-b/' + path: '/' + fullPath: '/sec-b/' + preLoaderRoute: typeof SecBIndexRouteImport + parentRoute: typeof SecBRoute + } + '/sec-a/': { + id: '/sec-a/' + path: '/' + fullPath: '/sec-a/' + preLoaderRoute: typeof SecAIndexRouteImport + parentRoute: typeof SecARoute + } + '/sec-f/settings': { + id: '/sec-f/settings' + path: '/settings' + fullPath: '/sec-f/settings' + preLoaderRoute: typeof SecFSettingsRouteImport parentRoute: typeof SecFRoute } '/sec-f/about': { @@ -743,13 +596,160 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof SecFAboutRouteImport parentRoute: typeof SecFRoute } - '/sec-f/settings': { - id: '/sec-f/settings' - path: '/settings' - fullPath: '/sec-f/settings' - preLoaderRoute: typeof SecFSettingsRouteImport + '/sec-f/$id': { + id: '/sec-f/$id' + path: '/$id' + fullPath: '/sec-f/$id' + preLoaderRoute: typeof SecFIdRouteImport parentRoute: typeof SecFRoute } + '/sec-e/settings': { + id: '/sec-e/settings' + path: '/settings' + fullPath: '/sec-e/settings' + preLoaderRoute: typeof SecESettingsRouteImport + parentRoute: typeof SecERoute + } + '/sec-e/about': { + id: '/sec-e/about' + path: '/about' + fullPath: '/sec-e/about' + preLoaderRoute: typeof SecEAboutRouteImport + parentRoute: typeof SecERoute + } + '/sec-e/$id': { + id: '/sec-e/$id' + path: '/$id' + fullPath: '/sec-e/$id' + preLoaderRoute: typeof SecEIdRouteImport + parentRoute: typeof SecERoute + } + '/sec-d/settings': { + id: '/sec-d/settings' + path: '/settings' + fullPath: '/sec-d/settings' + preLoaderRoute: typeof SecDSettingsRouteImport + parentRoute: typeof SecDRoute + } + '/sec-d/about': { + id: '/sec-d/about' + path: '/about' + fullPath: '/sec-d/about' + preLoaderRoute: typeof SecDAboutRouteImport + parentRoute: typeof SecDRoute + } + '/sec-d/$id': { + id: '/sec-d/$id' + path: '/$id' + fullPath: '/sec-d/$id' + preLoaderRoute: typeof SecDIdRouteImport + parentRoute: typeof SecDRoute + } + '/sec-c/settings': { + id: '/sec-c/settings' + path: '/settings' + fullPath: '/sec-c/settings' + preLoaderRoute: typeof SecCSettingsRouteImport + parentRoute: typeof SecCRoute + } + '/sec-c/about': { + id: '/sec-c/about' + path: '/about' + fullPath: '/sec-c/about' + preLoaderRoute: typeof SecCAboutRouteImport + parentRoute: typeof SecCRoute + } + '/sec-c/$id': { + id: '/sec-c/$id' + path: '/$id' + fullPath: '/sec-c/$id' + preLoaderRoute: typeof SecCIdRouteImport + parentRoute: typeof SecCRoute + } + '/sec-b/settings': { + id: '/sec-b/settings' + path: '/settings' + fullPath: '/sec-b/settings' + preLoaderRoute: typeof SecBSettingsRouteImport + parentRoute: typeof SecBRoute + } + '/sec-b/about': { + id: '/sec-b/about' + path: '/about' + fullPath: '/sec-b/about' + preLoaderRoute: typeof SecBAboutRouteImport + parentRoute: typeof SecBRoute + } + '/sec-b/$id': { + id: '/sec-b/$id' + path: '/$id' + fullPath: '/sec-b/$id' + preLoaderRoute: typeof SecBIdRouteImport + parentRoute: typeof SecBRoute + } + '/sec-a/settings': { + id: '/sec-a/settings' + path: '/settings' + fullPath: '/sec-a/settings' + preLoaderRoute: typeof SecASettingsRouteImport + parentRoute: typeof SecARoute + } + '/sec-a/about': { + id: '/sec-a/about' + path: '/about' + fullPath: '/sec-a/about' + preLoaderRoute: typeof SecAAboutRouteImport + parentRoute: typeof SecARoute + } + '/sec-a/$id': { + id: '/sec-a/$id' + path: '/$id' + fullPath: '/sec-a/$id' + preLoaderRoute: typeof SecAIdRouteImport + parentRoute: typeof SecARoute + } + '/release/v{$version}': { + id: '/release/v{$version}' + path: '/release/v{$version}' + fullPath: '/release/v{$version}' + preLoaderRoute: typeof ReleaseVChar123versionChar125RouteImport + parentRoute: typeof rootRouteImport + } + '/files/$': { + id: '/files/$' + path: '/files/$' + fullPath: '/files/$' + preLoaderRoute: typeof FilesSplatRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout/beta': { + id: '/_layout/beta' + path: '/beta' + fullPath: '/beta' + preLoaderRoute: typeof LayoutBetaRouteImport + parentRoute: typeof LayoutRoute + } + '/_layout/alpha': { + id: '/_layout/alpha' + path: '/alpha' + fullPath: '/alpha' + preLoaderRoute: typeof LayoutAlphaRouteImport + parentRoute: typeof LayoutRoute + } + '/(marketing)/promo': { + id: '/(marketing)/promo' + path: '/promo' + fullPath: '/promo' + preLoaderRoute: typeof marketingPromoRouteImport + parentRoute: typeof rootRouteImport + } + '/(marketing)/pricing': { + id: '/(marketing)/pricing' + path: '/pricing' + fullPath: '/pricing' + preLoaderRoute: typeof marketingPricingRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/client-nav/scenarios/search-params/react/speed.bench.ts b/benchmarks/client-nav/scenarios/search-params/react/speed.bench.ts index 0b38f7bddb..5bdd994e32 100644 --- a/benchmarks/client-nav/scenarios/search-params/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/search-params/react/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-search-params', async ({ bench }) => { - const scenario = setup() +describe('client-search-params', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-search-params navigation loop (react)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/search-params/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/search-params/solid/speed.bench.ts index caa626c596..ea0baa1098 100644 --- a/benchmarks/client-nav/scenarios/search-params/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/search-params/solid/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-search-params', async ({ bench }) => { - const scenario = setup() +describe('client-search-params', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-search-params navigation loop (solid)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/search-params/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/search-params/solid/src/routeTree.gen.ts index b15beed09b..96d211d64c 100644 --- a/benchmarks/client-nav/scenarios/search-params/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/search-params/solid/src/routeTree.gen.ts @@ -9,13 +9,13 @@ // 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 CatalogRouteImport } from './routes/catalog' import { Route as ProductsRouteImport } from './routes/products' +import { Route as CatalogRouteImport } from './routes/catalog' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const ProductsRoute = ProductsRouteImport.update({ + id: '/products', + path: '/products', getParentRoute: () => rootRouteImport, } as any) const CatalogRoute = CatalogRouteImport.update({ @@ -23,9 +23,9 @@ const CatalogRoute = CatalogRouteImport.update({ path: '/catalog', getParentRoute: () => rootRouteImport, } as any) -const ProductsRoute = ProductsRouteImport.update({ - id: '/products', - path: '/products', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) @@ -61,11 +61,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/products': { + id: '/products' + path: '/products' + fullPath: '/products' + preLoaderRoute: typeof ProductsRouteImport parentRoute: typeof rootRouteImport } '/catalog': { @@ -75,11 +75,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof CatalogRouteImport parentRoute: typeof rootRouteImport } - '/products': { - id: '/products' - path: '/products' - fullPath: '/products' - preLoaderRoute: typeof ProductsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } } diff --git a/benchmarks/client-nav/scenarios/search-params/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/search-params/vue/speed.bench.ts index 728d2779e8..c82efd49c9 100644 --- a/benchmarks/client-nav/scenarios/search-params/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/search-params/vue/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-search-params', async ({ bench }) => { - const scenario = setup() +describe('client-search-params', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-search-params navigation loop (vue)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/search-params/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/search-params/vue/src/routeTree.gen.ts index f73b84ebe7..b95b667803 100644 --- a/benchmarks/client-nav/scenarios/search-params/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/search-params/vue/src/routeTree.gen.ts @@ -9,13 +9,13 @@ // 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 CatalogRouteImport } from './routes/catalog' import { Route as ProductsRouteImport } from './routes/products' +import { Route as CatalogRouteImport } from './routes/catalog' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const ProductsRoute = ProductsRouteImport.update({ + id: '/products', + path: '/products', getParentRoute: () => rootRouteImport, } as any) const CatalogRoute = CatalogRouteImport.update({ @@ -23,9 +23,9 @@ const CatalogRoute = CatalogRouteImport.update({ path: '/catalog', getParentRoute: () => rootRouteImport, } as any) -const ProductsRoute = ProductsRouteImport.update({ - id: '/products', - path: '/products', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) @@ -61,11 +61,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/products': { + id: '/products' + path: '/products' + fullPath: '/products' + preLoaderRoute: typeof ProductsRouteImport parentRoute: typeof rootRouteImport } '/catalog': { @@ -75,11 +75,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof CatalogRouteImport parentRoute: typeof rootRouteImport } - '/products': { - id: '/products' - path: '/products' - fullPath: '/products' - preLoaderRoute: typeof ProductsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } } diff --git a/benchmarks/client-nav/solid/speed.bench.ts b/benchmarks/client-nav/solid/speed.bench.ts index d629da17a8..34791180ce 100644 --- a/benchmarks/client-nav/solid/speed.bench.ts +++ b/benchmarks/client-nav/solid/speed.bench.ts @@ -1,19 +1,34 @@ -import { test } from 'vitest' +import { afterAll, beforeAll, bench, describe } from 'vitest' import { setup } from './setup' -test('client-nav', async ({ bench }) => { - const scenario = setup() +describe('client-nav', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, + * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. + * + * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, + * but it does support `beforeAll` and `afterAll`. + * + * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. + */ + + beforeAll(test.before) + afterAll(test.after) + + bench( 'client-side navigation loop (solid)', - { beforeAll: scenario.before, afterAll: scenario.after }, async () => { for (let i = 0; i < 10; i++) { - await scenario.tick() + await test.tick() } }, - ).run({ - warmupIterations: 100, - time: 10_000, - }) + { + warmupIterations: 100, + time: 10_000, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/solid/vite.config.ts b/benchmarks/client-nav/solid/vite.config.ts index 0c26b32f5f..1dd8e1e15c 100644 --- a/benchmarks/client-nav/solid/vite.config.ts +++ b/benchmarks/client-nav/solid/vite.config.ts @@ -37,7 +37,6 @@ export default defineConfig({ watch: false, environment: 'jsdom', setupFiles: [`${rootDir}vitest.setup.ts`], - benchmark: { include: ['solid/speed.bench.ts'] }, server: { deps: { inline: [/@solidjs/, /@tanstack\/solid-store/], diff --git a/benchmarks/client-nav/vue/speed.bench.ts b/benchmarks/client-nav/vue/speed.bench.ts index 503e91e7b7..f9e532f5ba 100644 --- a/benchmarks/client-nav/vue/speed.bench.ts +++ b/benchmarks/client-nav/vue/speed.bench.ts @@ -1,19 +1,34 @@ -import { test } from 'vitest' +import { afterAll, beforeAll, bench, describe } from 'vitest' import { setup } from './setup' -test('client-nav', async ({ bench }) => { - const scenario = setup() +describe('client-nav', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, + * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. + * + * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, + * but it does support `beforeAll` and `afterAll`. + * + * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. + */ + + beforeAll(test.before) + afterAll(test.after) + + bench( 'client-side navigation loop (vue)', - { beforeAll: scenario.before, afterAll: scenario.after }, async () => { for (let i = 0; i < 10; i++) { - await scenario.tick() + await test.tick() } }, - ).run({ - warmupIterations: 100, - time: 10_000, - }) + { + warmupIterations: 100, + time: 10_000, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/vue/vite.config.ts b/benchmarks/client-nav/vue/vite.config.ts index 78d8ae5638..7abe24b455 100644 --- a/benchmarks/client-nav/vue/vite.config.ts +++ b/benchmarks/client-nav/vue/vite.config.ts @@ -36,6 +36,5 @@ export default defineConfig({ watch: false, environment: 'jsdom', setupFiles: [`${rootDir}vitest.setup.ts`], - benchmark: { include: ['vue/speed.bench.ts'] }, }, }) diff --git a/benchmarks/cpu-simulation.ts b/benchmarks/cpu-simulation.ts index 9b8859f74d..7e16bf4c5a 100644 --- a/benchmarks/cpu-simulation.ts +++ b/benchmarks/cpu-simulation.ts @@ -1,23 +1,9 @@ -function codspeedRunnerMode() { - return process.env.CODSPEED_ENV === undefined - ? undefined - : process.env.CODSPEED_RUNNER_MODE -} - -/** - * Whether CodSpeed's simulation or memory instrument drives the run. Both - * measure one invocation after a few warmup calls instead of sampling. - */ -export function isCodSpeedAnalysis() { - const mode = codspeedRunnerMode() - return ( - mode === 'simulation' || mode === 'instrumentation' || mode === 'memory' - ) -} - /** Extra worker flags for CodSpeed CPU simulation, not walltime benchmarks. */ export function cpuSimulationExecArgv() { - const mode = codspeedRunnerMode() + const mode = + process.env.CODSPEED_ENV === undefined + ? undefined + : process.env.CODSPEED_RUNNER_MODE if (mode === 'simulation' || mode === 'instrumentation') { // CodSpeed supplies --no-opt, which only disables TurboFan on Node 24. // Maglev can still compile and inline hot functions between measured runs. @@ -36,18 +22,3 @@ export function cpuSimulationExecArgv() { } return [] } - -/** - * Per-bench lifecycle for apps that a bench prepares and disposes outside - * timing. CodSpeed measures one invocation, so each invocation gets fresh - * state. Tinybench samples thousands of iterations and keeps one instance per - * warmup/run phase instead of preparing it for every iteration. - */ -export function benchLifecycle(hooks: { - before: () => Promise | void - after: () => Promise | void -}) { - return isCodSpeedAnalysis() - ? { beforeEach: hooks.before, afterEach: hooks.after } - : { beforeAll: hooks.before, afterAll: hooks.after } -} diff --git a/benchmarks/memory/README.md b/benchmarks/memory/README.md index 18b68768f9..cf871f3439 100644 --- a/benchmarks/memory/README.md +++ b/benchmarks/memory/README.md @@ -2,7 +2,7 @@ Dedicated memory benchmarks for TanStack Router / Start, measured with the CodSpeed **memory instrument** (`mode: memory` in -`.github/workflows/benchmarks.yml`). The workflow runs on every +`.github/workflows/client-nav-benchmarks.yml`). The workflow runs on every push to `main` except docs/examples/e2e-only pushes: CodSpeed compares a PR against the run on its merge-base commit, and a main commit without a run makes CodSpeed silently fall back to an older base — a single outlier base run then @@ -34,8 +34,8 @@ benchmarks/memory// One app per scenario; apps and bench names are stable once landed (CodSpeed continuity). Never grow an existing scenario for a new case — add a scenario. `setup.ts` imports the built app and exports the concrete workload; -`memory.bench.ts` registers it with Vitest's `bench` test fixture, and -`memory.flame.ts` runs the same workload through the Flame profiler. +`memory.bench.ts` registers `bench(...)` directly, and `memory.flame.ts` runs the +same workload through the Flame profiler. ## How the memory instrument executes a bench @@ -43,98 +43,40 @@ continuity). Never grow an existing scenario for a new case — add a scenario. after a forced GC. Under plain `vitest bench` the suites only smoke-test: timing output is meaningless; real numbers come from CodSpeed. - Under CodSpeed the bench fn runs several warmup invocations plus the - measured one. The bench's `beforeEach`/`afterEach` hooks - (`memoryBenchHooks`) run around every invocation, outside the measurement - window: client workloads mount a fresh app before each invocation and tear - it down afterward. This prevents warmup navigation history and caches from - changing the starting state. Plain `vitest bench` runs the same hooks around - its warmup and measured iteration. Module-level counters/LCGs keep generated - URLs unique across invocations. -- Workload `run` functions must be `async` functions. CodSpeed's Vitest 5 - provider awaits only `AsyncFunction`s; a plain function that returns a - promise would be measured only up to its first suspension. -- Worker flags live in `runtime.ts` and apply only to the CodSpeed memory - instrument. They supplement the integration's predictable execution flags; - the retained overrides are described below. -- Before each CodSpeed invocation, the `beforeEach` hook yields to the event - loop, outside the measurement marker and before CodSpeed forces GC. Promise-only - warmup chains can keep WeakRef targets alive through a collection in the same - job. Client app setup also runs before the forced GC. -- Do not force GC inside a measured request loop or poll `heapUsed` to choose - how much work to do. Both introduce allocator activity from the harness into - the measurement. Footprint scenarios run exactly one large request per - invocation; churn scenarios retain their fixed sequential request counts. -- Error-path cases use separate isolated workers so one case's module and - allocator history cannot contaminate the next case. + measured one **on the same mount**, so bench fns must be idempotent and + module-level counters/LCGs are used where ids must never repeat across + invocations. +- Plain `vitest bench` never runs suite hooks (`beforeAll`/`afterAll`) and + only honors tinybench's `setup`/`teardown` options; the CodSpeed runner + does the exact opposite. Client benches therefore register **both** — in + any given mode exactly one pair runs. +- The process runs with V8 determinism flags (predictable GC schedule, + `--no-opt`). Never call `global.gc()` manually in **churn** scenarios — + their signal is accumulation across iterations, which a forced collection + masks. **Peak** scenarios do the opposite: they set + `pinGcBetweenIterations` on the request loop so a collection runs between + iterations. Their signal is the footprint of a single request, and without + pinned GC points the measured peak flips by a whole payload depending on + whether iteration i's garbage is collected before iteration i+1 allocates. + Because of `--no-opt`, allocation counts overstate production; numbers are + for regression tracking, not absolute claims. - Keep each bench under **~1.5M allocations** (instrument overhead grows past 2M); this is the main constraint when tuning iteration counts. -## Worker settings - -All scenarios use [`memoryConfig`](./runtime.ts). It adds these flags only in -memory mode: - -- `--no-maglev` -- `--no-flush-bytecode` -- `--no-minor-gc-task` -- `--no-incremental-marking` -- `--initial-old-space-size=512` - -`--jitless` was removed after repeated CI comparisons. Ten unchanged-commit -repetitions with the last four flags kept all 48 peak-memory results within 1% -(worst spread: 0.834%). With JIT enabled, all 16 subsets of the four flags were -tested. Removing bytecode, minor-GC-task, incremental-marking, or heap-budget -overrides from this profile produced worst client peak spreads of 6.616%, 2.714%, -2.109%, and 10.669%, respectively. Smaller combinations also exceeded 1% in at -least one tracked metric. This supports retaining the four-flag profile; it does -not establish that every override is required in every individual scenario. - -A server-only heap-budget profile initially passed five repetitions, but further -confirmation produced a 24.46% server peak outlier. That configuration was -rejected. Allocated bytes and allocation counts remain imperfectly repeatable: -a client confirmation with the retained four flags showed a 6.77% allocated-byte -spread and a 5.91% allocation-count spread. Client peaks remained within 0.834% -across all 15 observations with the retained profile. Experiment details and CI runs are recorded in -[PR #8260](https://github.com/TanStack/router/pull/8260). - -These settings trade production GC behavior for repeatable regression signals. -They suppress bytecode reclamation and change collection scheduling. The 512 MiB -initial/minimum old-generation allocation budget can postpone automatic full -collections. This does not preallocate 512 MiB, and the smallest sufficient budget -was not determined. Results describe this controlled worker profile, not a -production application's absolute memory footprint. - -CodSpeed's `--no-opt` only disables TurboFan on Node 24 (V8 13); Maglev still -compiles. Under CodSpeed's `--predictable` there is no background compilation, -so Maglev compiles run synchronously inside whichever request triggers them, and -the forced GC before the measured call can discard optimized code so recompiles -land inside the measured window. Maglev's malloc'd Zone scratch (32 KiB -segments) then dominates allocation metrics, and its size depends on -per-process feedback state. `--no-maglev` was added for this: the bimodal -+32,792 B / +1 allocation in `mem server error-paths unmatched (react)` was one -Maglev Zone segment allocated while compiling React Fizz's per-request stream -`write` closure, and compiler scratch made up ~97% of that bench's allocated -bytes. Retained-object measurements are unaffected because Zone memory is freed -after each compile. The repeatability figures above predate this flag. - ## Bench shapes and signals -- **Churn:** a fixed number of sequential operations, measuring native - allocation activity and peak outstanding native allocations. -- **Peak (footprint):** one large operation, measuring its native footprint. - -CodSpeed reports native allocator activity, not individual JavaScript object -allocations or retained JS heap size. V8 can reuse heap pages without a visible -native allocation. These benchmarks can detect native buffering and allocator -regressions, but a flat graph does not establish that route data or JS objects -are collectable. Absolute numbers include Node/framework/jsdom activity under -benchmark-specific V8 settings; compare identical harness versions. +- **Churn (leak detector):** N sequential iterations at steady state. If one + iteration leaks L bytes, peak grows by ~N·L; healthy builds show a flat + timeline floor independent of N. Tuning check: doubling N must leave peak + roughly unchanged. +- **Peak (footprint):** one (or very few) large operations; peak memory + scaling with the workload is the signal. ## Scenarios ### Server -| Scenario | Shape | Exercises | +| Scenario | Shape | Guards against | | ----------------------- | ----- | --------------------------------------------------------- | | `request-churn` | churn | cross-request retention in document SSR (unique URLs) | | `server-fn-churn` | churn | retention in the server-function RPC path | @@ -146,7 +88,7 @@ benchmark-specific V8 settings; compare identical harness versions. ### Client -| Scenario | Shape | Exercises | +| Scenario | Shape | Guards against | | ------------------------- | ----- | -------------------------------------------------------- | | `navigation-churn` | churn | per-navigation retention at steady state | | `unique-location-churn` | churn | unbounded href/search-keyed caches (never-repeated URLs) | @@ -161,10 +103,14 @@ benchmark-specific V8 settings; compare identical harness versions. server response is fully consumed before the next request. Pairing a single navigation with its render signal via `Promise.all([navigate, rendered])` is fine — never overlap distinct work items. -- Randomness only via the seeded LCG in `bench-utils.ts`. Deferred streaming - uses counted zero-delay timer hops to stage work. Timers still depend on the - event loop, so validate repeatability on CI instead of assuming deterministic - ordering from a zero delay alone. +- Randomness only via the seeded LCG in `bench-utils.ts`; no `Math.random`, + `Date.now`, or timers with a nonzero delay — anywhere async ordering must be + staged (`streaming-peak`'s deferred sections, `aborted-requests`' deferred + loader data and post-abort drain), chain **0ms `setTimeout` hops** and count + event-loop turns instead. A wall-clock delay races renderer work differently + depending on runner load and instrumentation overhead, which makes the + single measured run non-reproducible; 0ms hops fire in registration order in + the timers phase, so the interleaving is a pure function of the schedule. - Sanity assertions run once at module load and throw on wrong status/markers, so a bench can never silently measure the wrong thing. - Server requests follow `benchmarks/ssr` conventions: document GETs send @@ -238,7 +184,7 @@ pnpm --filter @benchmarks/memory-client clean:profiles ``` Client memory benches are useful for regression tracking of router/React/jsdom -integration behavior and native allocation activity. They are not pure +integration behavior, especially retained route/cache data. They are not pure browser-memory measurements, and local Flame attribution can include jsdom, React DOM, and profiler shutdown frames. @@ -254,20 +200,3 @@ WITH_INSTRUMENTATION=1 codspeed run --mode memory -- pnpm nx run @benchmarks/mem WITH_INSTRUMENTATION=1 codspeed run --mode memory -- pnpm nx run @benchmarks/memory-client:test:perf:solid WITH_INSTRUMENTATION=1 codspeed run --mode memory -- pnpm nx run @benchmarks/memory-client:test:perf:vue ``` - -Run the benchmark workflow on an experiment branch: - -```bash -gh workflow run benchmarks.yml --ref -``` - -Repeat at the same commit, using distinct branch names if runs should overlap -(the workflow serializes runs on the same ref). Compare all 48 fresh memory -results: 18 client and 30 server. Exclude CPU simulation results, inherited -CodSpeed results, and failed or incomplete repetitions. For each workload, calculate -`100 * (max / min - 1)` across runs for peak bytes, allocated bytes, and -allocation counts; aggregate averages hide unstable cases. - -Observed spreads below 1% establish repeatability in the tested sample, not a -bound on future runs. Changes to worker flags or workload lifecycles establish -new measurement baselines. diff --git a/benchmarks/memory/client/bench-utils.ts b/benchmarks/memory/client/bench-utils.ts index 785e8fac7f..0cbaedbd71 100644 --- a/benchmarks/memory/client/bench-utils.ts +++ b/benchmarks/memory/client/bench-utils.ts @@ -1,5 +1,3 @@ -export { memoryBenchHooks } from '../turn' - export const memoryBenchOptions = { iterations: 1, warmupIterations: 1, diff --git a/benchmarks/memory/client/benchmark.ts b/benchmarks/memory/client/benchmark.ts index 463047f4d9..8b877b0740 100644 --- a/benchmarks/memory/client/benchmark.ts +++ b/benchmarks/memory/client/benchmark.ts @@ -1,10 +1,6 @@ export interface ClientMemoryWorkload { name: string before?: () => Promise | void - /** - * Must be an `async` function: CodSpeed's Vitest 5 provider awaits only - * `AsyncFunction`s and otherwise measures just the synchronous part. - */ run: () => Promise | void sanity: () => Promise | void after?: () => Promise | void diff --git a/benchmarks/memory/client/package.json b/benchmarks/memory/client/package.json index 4dc6246183..5bc11e053b 100644 --- a/benchmarks/memory/client/package.json +++ b/benchmarks/memory/client/package.json @@ -22,7 +22,7 @@ "vue": "^3.5.16" }, "devDependencies": { - "@codspeed/vitest-plugin": "^6.0.1", + "@codspeed/vitest-plugin": "^5.5.0", "@datadog/pprof": "^5.13.2", "@platformatic/flame": "^1.6.0", "@testing-library/react": "^16.2.0", @@ -202,7 +202,7 @@ "build:react" ], "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.react.config.ts", + "command": "NODE_ENV=production vitest bench --config ./vitest.react.config.ts", "cwd": "benchmarks/memory/client" } }, @@ -214,7 +214,7 @@ "build:solid" ], "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.solid.config.ts", + "command": "NODE_ENV=production vitest bench --config ./vitest.solid.config.ts", "cwd": "benchmarks/memory/client" } }, @@ -226,12 +226,12 @@ "build:vue" ], "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.vue.config.ts", + "command": "NODE_ENV=production vitest bench --config ./vitest.vue.config.ts", "cwd": "benchmarks/memory/client" } }, "test:types": { - "executor": "nx:run-commands", + "executor": "nx:noop", "dependsOn": [ { "projects": [ @@ -256,17 +256,6 @@ ], "target": "test:types:client" } - ], - "options": { - "command": "tsc -p ./tsconfig.json --noEmit", - "cwd": "benchmarks/memory/client" - }, - "inputs": [ - "default", - "^production", - "{workspaceRoot}/eslint.config.js", - "dependentTaskOutputs", - "{workspaceRoot}/benchmarks/memory/*.ts" ] } } diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/react/memory.bench.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/react/memory.bench.ts index 43ab822de3..e645ab38f1 100644 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/react/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterAll, beforeAll, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeAll(workload.before) + afterAll(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/react/vite.config.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/react/vite.config.ts index 0f05cedf40..5910981796 100644 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/vite.config.ts +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/react/vite.config.ts @@ -2,7 +2,7 @@ import { fileURLToPath } from 'node:url' import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import react from '@vitejs/plugin-react' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -27,9 +27,10 @@ export default defineConfig({ }, }, test: { - ...memoryConfig('client'), + execArgv: memoryExecArgv(), name: '@benchmarks/memory-client interrupted-navigations (react)', watch: false, environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/memory.bench.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/memory.bench.ts index 43ab822de3..e645ab38f1 100644 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterAll, beforeAll, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeAll(workload.before) + afterAll(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/vite.config.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/vite.config.ts index 26ff0b5c8c..fbdfe6b8ea 100644 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/vite.config.ts +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/vite.config.ts @@ -2,7 +2,7 @@ import { fileURLToPath } from 'node:url' import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import solid from 'vite-plugin-solid' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -27,9 +27,10 @@ export default defineConfig({ }, }, test: { - ...memoryConfig('client'), + execArgv: memoryExecArgv(), name: '@benchmarks/memory-client interrupted-navigations (solid)', watch: false, environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/memory.bench.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/memory.bench.ts index 43ab822de3..e645ab38f1 100644 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterAll, beforeAll, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeAll(workload.before) + afterAll(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/fast.$id.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/fast.$id.tsx index f6dc9ac3bd..3bd820bd07 100644 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/fast.$id.tsx +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/fast.$id.tsx @@ -1,19 +1,6 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { fixedTimestamp } from '../../../slow-loaders' -const FastComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () => ( -
- {`${data.value.kind}:${data.value.id}:${data.value.ts}`} -
- ) - }, -}) - export const Route = createFileRoute('/fast/$id')({ loader: ({ params }: { params: { id: string } }) => ({ id: params.id, @@ -22,3 +9,13 @@ export const Route = createFileRoute('/fast/$id')({ }), component: FastComponent, }) + +function FastComponent() { + const data = Route.useLoaderData() + + return ( +
+ {`${data.value.kind}:${data.value.id}:${data.value.ts}`} +
+ ) +} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/slow.$id.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/slow.$id.tsx index 3b5bb75ede..68885fb918 100644 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/slow.$id.tsx +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/slow.$id.tsx @@ -1,19 +1,6 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { getSlowLoaderDeferred } from '../../../slow-loaders' -const SlowComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () => ( -
- {`${data.value.kind}:${data.value.id}:${data.value.ts}`} -
- ) - }, -}) - export const Route = createFileRoute('/slow/$id')({ loader: async ({ params }: { params: { id: string } }) => { const deferred = getSlowLoaderDeferred(params.id) @@ -22,3 +9,13 @@ export const Route = createFileRoute('/slow/$id')({ }, component: SlowComponent, }) + +function SlowComponent() { + const data = Route.useLoaderData() + + return ( +
+ {`${data.value.kind}:${data.value.id}:${data.value.ts}`} +
+ ) +} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/vite.config.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/vite.config.ts index 02574908d2..a9814eace8 100644 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/vite.config.ts +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/vite.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -29,9 +29,10 @@ export default defineConfig({ }, }, test: { - ...memoryConfig('client'), + execArgv: memoryExecArgv(), name: '@benchmarks/memory-client interrupted-navigations (vue)', watch: false, environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/react/memory.bench.ts b/benchmarks/memory/client/scenarios/loader-data-retention/react/memory.bench.ts index 43ab822de3..e645ab38f1 100644 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/loader-data-retention/react/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterAll, beforeAll, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeAll(workload.before) + afterAll(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/react/vite.config.ts b/benchmarks/memory/client/scenarios/loader-data-retention/react/vite.config.ts index 8630417936..e0e31c1fca 100644 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/vite.config.ts +++ b/benchmarks/memory/client/scenarios/loader-data-retention/react/vite.config.ts @@ -2,7 +2,7 @@ import { fileURLToPath } from 'node:url' import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import react from '@vitejs/plugin-react' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -27,9 +27,10 @@ export default defineConfig({ }, }, test: { - ...memoryConfig('client'), + execArgv: memoryExecArgv(), name: '@benchmarks/memory-client loader-data-retention (react)', watch: false, environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/solid/memory.bench.ts b/benchmarks/memory/client/scenarios/loader-data-retention/solid/memory.bench.ts index 43ab822de3..e645ab38f1 100644 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/loader-data-retention/solid/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterAll, beforeAll, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeAll(workload.before) + afterAll(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/solid/vite.config.ts b/benchmarks/memory/client/scenarios/loader-data-retention/solid/vite.config.ts index 5dfd5b53fe..4011ff34ce 100644 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/vite.config.ts +++ b/benchmarks/memory/client/scenarios/loader-data-retention/solid/vite.config.ts @@ -2,7 +2,7 @@ import { fileURLToPath } from 'node:url' import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import solid from 'vite-plugin-solid' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -27,9 +27,10 @@ export default defineConfig({ }, }, test: { - ...memoryConfig('client'), + execArgv: memoryExecArgv(), name: '@benchmarks/memory-client loader-data-retention (solid)', watch: false, environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/vue/memory.bench.ts b/benchmarks/memory/client/scenarios/loader-data-retention/vue/memory.bench.ts index 43ab822de3..e645ab38f1 100644 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/loader-data-retention/vue/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterAll, beforeAll, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeAll(workload.before) + afterAll(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/page.$id.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/page.$id.tsx index 38f1d2614c..9f4b3c4470 100644 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/page.$id.tsx +++ b/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/page.$id.tsx @@ -1,25 +1,22 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { createLoaderData } from '../../../loader-data' -const PageComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () => ( -
- {`${data.value.id}:${data.value.records.length}`} -
- ) - }, -}) - export const Route = createFileRoute('/page/$id')({ loader: ({ params }: { params: { id: string } }) => createLoaderData(params.id), component: PageComponent, }) + +function PageComponent() { + const data = Route.useLoaderData() + + return ( +
+ {`${data.value.id}:${data.value.records.length}`} +
+ ) +} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/vue/vite.config.ts b/benchmarks/memory/client/scenarios/loader-data-retention/vue/vite.config.ts index 006636eaa0..97c5bd726b 100644 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/vite.config.ts +++ b/benchmarks/memory/client/scenarios/loader-data-retention/vue/vite.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -29,9 +29,10 @@ export default defineConfig({ }, }, test: { - ...memoryConfig('client'), + execArgv: memoryExecArgv(), name: '@benchmarks/memory-client loader-data-retention (vue)', watch: false, environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/react/memory.bench.ts b/benchmarks/memory/client/scenarios/mount-unmount/react/memory.bench.ts index 43ab822de3..e645ab38f1 100644 --- a/benchmarks/memory/client/scenarios/mount-unmount/react/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/mount-unmount/react/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterAll, beforeAll, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeAll(workload.before) + afterAll(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/react/vite.config.ts b/benchmarks/memory/client/scenarios/mount-unmount/react/vite.config.ts index a08352a837..020d1115c5 100644 --- a/benchmarks/memory/client/scenarios/mount-unmount/react/vite.config.ts +++ b/benchmarks/memory/client/scenarios/mount-unmount/react/vite.config.ts @@ -2,7 +2,7 @@ import { fileURLToPath } from 'node:url' import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import react from '@vitejs/plugin-react' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -27,9 +27,10 @@ export default defineConfig({ }, }, test: { - ...memoryConfig('client'), + execArgv: memoryExecArgv(), name: '@benchmarks/memory-client mount-unmount (react)', watch: false, environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/solid/memory.bench.ts b/benchmarks/memory/client/scenarios/mount-unmount/solid/memory.bench.ts index 43ab822de3..e645ab38f1 100644 --- a/benchmarks/memory/client/scenarios/mount-unmount/solid/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/mount-unmount/solid/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterAll, beforeAll, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeAll(workload.before) + afterAll(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/solid/vite.config.ts b/benchmarks/memory/client/scenarios/mount-unmount/solid/vite.config.ts index 33699639de..94774af226 100644 --- a/benchmarks/memory/client/scenarios/mount-unmount/solid/vite.config.ts +++ b/benchmarks/memory/client/scenarios/mount-unmount/solid/vite.config.ts @@ -2,7 +2,7 @@ import { fileURLToPath } from 'node:url' import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import solid from 'vite-plugin-solid' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -27,9 +27,10 @@ export default defineConfig({ }, }, test: { - ...memoryConfig('client'), + execArgv: memoryExecArgv(), name: '@benchmarks/memory-client mount-unmount (solid)', watch: false, environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/vue/memory.bench.ts b/benchmarks/memory/client/scenarios/mount-unmount/vue/memory.bench.ts index 43ab822de3..e645ab38f1 100644 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/mount-unmount/vue/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterAll, beforeAll, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeAll(workload.before) + afterAll(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/vue/src/routes/a.tsx b/benchmarks/memory/client/scenarios/mount-unmount/vue/src/routes/a.tsx index 0dd650e1dd..cbcd543ce5 100644 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/src/routes/a.tsx +++ b/benchmarks/memory/client/scenarios/mount-unmount/vue/src/routes/a.tsx @@ -1,15 +1,12 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' -const AComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () =>
{data.value.id}
- }, -}) - export const Route = createFileRoute('/a')({ loader: () => ({ id: 'a' }), component: AComponent, }) + +function AComponent() { + const data = Route.useLoaderData() + + return
{data.value.id}
+} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/vue/vite.config.ts b/benchmarks/memory/client/scenarios/mount-unmount/vue/vite.config.ts index a3f0eeaa8c..d5ac1a6793 100644 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/vite.config.ts +++ b/benchmarks/memory/client/scenarios/mount-unmount/vue/vite.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -29,9 +29,10 @@ export default defineConfig({ }, }, test: { - ...memoryConfig('client'), + execArgv: memoryExecArgv(), name: '@benchmarks/memory-client mount-unmount (vue)', watch: false, environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/react/memory.bench.ts b/benchmarks/memory/client/scenarios/navigation-churn/react/memory.bench.ts index 43ab822de3..e645ab38f1 100644 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/navigation-churn/react/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterAll, beforeAll, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeAll(workload.before) + afterAll(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/react/vite.config.ts b/benchmarks/memory/client/scenarios/navigation-churn/react/vite.config.ts index eef60a658e..d2881ea8ac 100644 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/vite.config.ts +++ b/benchmarks/memory/client/scenarios/navigation-churn/react/vite.config.ts @@ -2,7 +2,7 @@ import { fileURLToPath } from 'node:url' import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import react from '@vitejs/plugin-react' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -27,9 +27,10 @@ export default defineConfig({ }, }, test: { - ...memoryConfig('client'), + execArgv: memoryExecArgv(), name: '@benchmarks/memory-client navigation-churn (react)', watch: false, environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/solid/memory.bench.ts b/benchmarks/memory/client/scenarios/navigation-churn/solid/memory.bench.ts index 43ab822de3..e645ab38f1 100644 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/navigation-churn/solid/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterAll, beforeAll, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeAll(workload.before) + afterAll(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/solid/vite.config.ts b/benchmarks/memory/client/scenarios/navigation-churn/solid/vite.config.ts index 7dfb186b2e..32b6b7b583 100644 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/vite.config.ts +++ b/benchmarks/memory/client/scenarios/navigation-churn/solid/vite.config.ts @@ -2,7 +2,7 @@ import { fileURLToPath } from 'node:url' import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import solid from 'vite-plugin-solid' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -27,9 +27,10 @@ export default defineConfig({ }, }, test: { - ...memoryConfig('client'), + execArgv: memoryExecArgv(), name: '@benchmarks/memory-client navigation-churn (solid)', watch: false, environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/vue/memory.bench.ts b/benchmarks/memory/client/scenarios/navigation-churn/vue/memory.bench.ts index 43ab822de3..e645ab38f1 100644 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/navigation-churn/vue/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterAll, beforeAll, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeAll(workload.before) + afterAll(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/a.tsx b/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/a.tsx index c1a9cfb244..183228e748 100644 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/a.tsx +++ b/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/a.tsx @@ -1,19 +1,16 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' const fixedTimestamp = 1_700_000_000_000 -const AComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () => ( -
{`${data.value.name}:${data.value.ts}`}
- ) - }, -}) - export const Route = createFileRoute('/a')({ loader: () => ({ name: 'a', ts: fixedTimestamp }), component: AComponent, }) + +function AComponent() { + const data = Route.useLoaderData() + + return ( +
{`${data.value.name}:${data.value.ts}`}
+ ) +} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/b.tsx b/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/b.tsx index 3a20799f3b..3a18ec97a9 100644 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/b.tsx +++ b/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/b.tsx @@ -1,19 +1,16 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' const fixedTimestamp = 1_700_000_000_000 -const BComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () => ( -
{`${data.value.name}:${data.value.ts}`}
- ) - }, -}) - export const Route = createFileRoute('/b')({ loader: () => ({ name: 'b', ts: fixedTimestamp }), component: BComponent, }) + +function BComponent() { + const data = Route.useLoaderData() + + return ( +
{`${data.value.name}:${data.value.ts}`}
+ ) +} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/vue/vite.config.ts b/benchmarks/memory/client/scenarios/navigation-churn/vue/vite.config.ts index b3bdd39dd2..defc633ff4 100644 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/vite.config.ts +++ b/benchmarks/memory/client/scenarios/navigation-churn/vue/vite.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -29,9 +29,10 @@ export default defineConfig({ }, }, test: { - ...memoryConfig('client'), + execArgv: memoryExecArgv(), name: '@benchmarks/memory-client navigation-churn (vue)', watch: false, environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/preload-churn/react/memory.bench.ts b/benchmarks/memory/client/scenarios/preload-churn/react/memory.bench.ts index 43ab822de3..e645ab38f1 100644 --- a/benchmarks/memory/client/scenarios/preload-churn/react/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/preload-churn/react/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterAll, beforeAll, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeAll(workload.before) + afterAll(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/client/scenarios/preload-churn/react/vite.config.ts b/benchmarks/memory/client/scenarios/preload-churn/react/vite.config.ts index c12995f68e..0d792a669a 100644 --- a/benchmarks/memory/client/scenarios/preload-churn/react/vite.config.ts +++ b/benchmarks/memory/client/scenarios/preload-churn/react/vite.config.ts @@ -2,7 +2,7 @@ import { fileURLToPath } from 'node:url' import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import react from '@vitejs/plugin-react' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -27,9 +27,10 @@ export default defineConfig({ }, }, test: { - ...memoryConfig('client'), + execArgv: memoryExecArgv(), name: '@benchmarks/memory-client preload-churn (react)', watch: false, environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/preload-churn/shared.ts b/benchmarks/memory/client/scenarios/preload-churn/shared.ts index 68fdfedd3f..8cea4aca81 100644 --- a/benchmarks/memory/client/scenarios/preload-churn/shared.ts +++ b/benchmarks/memory/client/scenarios/preload-churn/shared.ts @@ -35,14 +35,18 @@ type PreloadRouter = { subscribe: (event: 'onRendered', listener: () => void) => () => void } -// Reuse one navigation target while evicting the distinct preloaded routes. +// Fixed id for the eviction navigations interleaved into the bench loop; its +// payload is a constant-size steady-state resident, never part of the signal. const evictionItemId = 'nav-evict' const preloadChurnIterations = 200 // A navigation commit is what triggers the router's clearExpiredCache -- // preloaded matches (defaultPreloadGcTime: 0) are only evicted then, never -// during a preload-only loop. Interleave navigation to exercise eviction. +// during a preload-only loop. Interleaving a navigation every few preloads is +// what makes the flat floor assert "eviction releases preloaded payloads". const preloadsPerEvictionNavigation = 10 -// Keep generated URLs unique across warmup and measured invocations. +// Module-level so ids stay unique across runner invocations on one mount; a +// per-invocation LCG would replay identical ids, and every preload after the +// first invocation would dedupe against cachedMatches instead of doing work. const benchmarkRandom = createDeterministicRandom(0x706c6f61) let preloadCounter = 0 diff --git a/benchmarks/memory/client/scenarios/preload-churn/solid/memory.bench.ts b/benchmarks/memory/client/scenarios/preload-churn/solid/memory.bench.ts index 43ab822de3..e645ab38f1 100644 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/preload-churn/solid/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterAll, beforeAll, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeAll(workload.before) + afterAll(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/client/scenarios/preload-churn/solid/vite.config.ts b/benchmarks/memory/client/scenarios/preload-churn/solid/vite.config.ts index efc75d2b93..23fa994bd9 100644 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/vite.config.ts +++ b/benchmarks/memory/client/scenarios/preload-churn/solid/vite.config.ts @@ -2,7 +2,7 @@ import { fileURLToPath } from 'node:url' import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import solid from 'vite-plugin-solid' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -27,9 +27,10 @@ export default defineConfig({ }, }, test: { - ...memoryConfig('client'), + execArgv: memoryExecArgv(), name: '@benchmarks/memory-client preload-churn (solid)', watch: false, environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/preload-churn/vue/memory.bench.ts b/benchmarks/memory/client/scenarios/preload-churn/vue/memory.bench.ts index 43ab822de3..e645ab38f1 100644 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/preload-churn/vue/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterAll, beforeAll, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeAll(workload.before) + afterAll(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/client/scenarios/preload-churn/vue/src/routes/items.$id.tsx b/benchmarks/memory/client/scenarios/preload-churn/vue/src/routes/items.$id.tsx index 08254e173e..2a29245926 100644 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/src/routes/items.$id.tsx +++ b/benchmarks/memory/client/scenarios/preload-churn/vue/src/routes/items.$id.tsx @@ -1,19 +1,6 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { createItemPayload, trackItemLoaderCall } from '../../../item-payload' -const ItemComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () => ( -
- {`${data.value.id}:${data.value.byteLength}`} -
- ) - }, -}) - export const Route = createFileRoute('/items/$id')({ loader: ({ params }: { params: { id: string } }) => { trackItemLoaderCall(params.id) @@ -21,3 +8,13 @@ export const Route = createFileRoute('/items/$id')({ }, component: ItemComponent, }) + +function ItemComponent() { + const data = Route.useLoaderData() + + return ( +
+ {`${data.value.id}:${data.value.byteLength}`} +
+ ) +} diff --git a/benchmarks/memory/client/scenarios/preload-churn/vue/vite.config.ts b/benchmarks/memory/client/scenarios/preload-churn/vue/vite.config.ts index 3d56089ba7..a2d39c12de 100644 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/vite.config.ts +++ b/benchmarks/memory/client/scenarios/preload-churn/vue/vite.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -29,9 +29,10 @@ export default defineConfig({ }, }, test: { - ...memoryConfig('client'), + execArgv: memoryExecArgv(), name: '@benchmarks/memory-client preload-churn (vue)', watch: false, environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/react/memory.bench.ts b/benchmarks/memory/client/scenarios/unique-location-churn/react/memory.bench.ts index 43ab822de3..e645ab38f1 100644 --- a/benchmarks/memory/client/scenarios/unique-location-churn/react/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/unique-location-churn/react/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterAll, beforeAll, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeAll(workload.before) + afterAll(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/react/vite.config.ts b/benchmarks/memory/client/scenarios/unique-location-churn/react/vite.config.ts index 7ee67bfe30..4d6359c2ab 100644 --- a/benchmarks/memory/client/scenarios/unique-location-churn/react/vite.config.ts +++ b/benchmarks/memory/client/scenarios/unique-location-churn/react/vite.config.ts @@ -2,7 +2,7 @@ import { fileURLToPath } from 'node:url' import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import react from '@vitejs/plugin-react' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -27,9 +27,10 @@ export default defineConfig({ }, }, test: { - ...memoryConfig('client'), + execArgv: memoryExecArgv(), name: '@benchmarks/memory-client unique-location-churn (react)', watch: false, environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/solid/memory.bench.ts b/benchmarks/memory/client/scenarios/unique-location-churn/solid/memory.bench.ts index 43ab822de3..e645ab38f1 100644 --- a/benchmarks/memory/client/scenarios/unique-location-churn/solid/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/unique-location-churn/solid/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterAll, beforeAll, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeAll(workload.before) + afterAll(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/solid/vite.config.ts b/benchmarks/memory/client/scenarios/unique-location-churn/solid/vite.config.ts index 4db90da2d2..58abb71a63 100644 --- a/benchmarks/memory/client/scenarios/unique-location-churn/solid/vite.config.ts +++ b/benchmarks/memory/client/scenarios/unique-location-churn/solid/vite.config.ts @@ -2,7 +2,7 @@ import { fileURLToPath } from 'node:url' import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import solid from 'vite-plugin-solid' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -27,9 +27,10 @@ export default defineConfig({ }, }, test: { - ...memoryConfig('client'), + execArgv: memoryExecArgv(), name: '@benchmarks/memory-client unique-location-churn (solid)', watch: false, environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/vue/memory.bench.ts b/benchmarks/memory/client/scenarios/unique-location-churn/vue/memory.bench.ts index 43ab822de3..e645ab38f1 100644 --- a/benchmarks/memory/client/scenarios/unique-location-churn/vue/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/unique-location-churn/vue/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterAll, beforeAll, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeAll(workload.before) + afterAll(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/routes/items.$id.tsx b/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/routes/items.$id.tsx index e796ee14d1..1854367142 100644 --- a/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/routes/items.$id.tsx +++ b/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/routes/items.$id.tsx @@ -1,22 +1,9 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' type ItemSearch = { q: string } -const ItemComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () => ( -
{`${data.value.id}:${data.value.q}:${data.value.checksum}`}
- ) - }, -}) - export const Route = createFileRoute('/items/$id')({ validateSearch: (search: Record): ItemSearch => ({ q: typeof search.q === 'string' ? search.q : '', @@ -35,3 +22,13 @@ export const Route = createFileRoute('/items/$id')({ }), component: ItemComponent, }) + +function ItemComponent() { + const data = Route.useLoaderData() + + return ( +
{`${data.value.id}:${data.value.q}:${data.value.checksum}`}
+ ) +} diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/vue/vite.config.ts b/benchmarks/memory/client/scenarios/unique-location-churn/vue/vite.config.ts index d074d571b9..edcfd3fa10 100644 --- a/benchmarks/memory/client/scenarios/unique-location-churn/vue/vite.config.ts +++ b/benchmarks/memory/client/scenarios/unique-location-churn/vue/vite.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -29,9 +29,10 @@ export default defineConfig({ }, }, test: { - ...memoryConfig('client'), + execArgv: memoryExecArgv(), name: '@benchmarks/memory-client unique-location-churn (vue)', watch: false, environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/tsconfig.json b/benchmarks/memory/client/tsconfig.json index eefc5c581e..9280d5c42f 100644 --- a/benchmarks/memory/client/tsconfig.json +++ b/benchmarks/memory/client/tsconfig.json @@ -3,10 +3,5 @@ "compilerOptions": { "types": ["node", "vite/client", "vitest/globals"] }, - "include": [ - "bench-utils.ts", - "lifecycle.ts", - "vitest.setup.ts", - "scenarios/*/shared.ts" - ] + "include": ["bench-utils.ts", "lifecycle.ts", "vitest.setup.ts"] } diff --git a/benchmarks/memory/runtime.ts b/benchmarks/memory/runtime.ts index 010149b4df..941de2dfe5 100644 --- a/benchmarks/memory/runtime.ts +++ b/benchmarks/memory/runtime.ts @@ -1,36 +1,18 @@ -import { fileURLToPath } from 'node:url' -import { isMemoryInstrumented } from './turn' - /** Worker settings for the CodSpeed memory instrument. */ export function memoryExecArgv() { - if (!isMemoryInstrumented()) { + if ( + process.env.CODSPEED_ENV === undefined || + process.env.CODSPEED_RUNNER_MODE !== 'memory' + ) { return [] } - // CodSpeed supplies --no-opt, which only disables TurboFan on Node 24. - // Under --predictable, Maglev compilations run synchronously inside the - // request that triggers them, and the forced GC before the measured call can - // discard optimized code so recompiles land in the measured window. Their - // malloc'd Zone scratch (32 KiB segments) then dominates allocation metrics - // and depends on per-process feedback state. - // Limit variation from GC scheduling and bytecode reclamation; keep a - // fixed initial old-generation budget. + // Node 24 still enables Maglev under CodSpeed's --no-opt. Compile baseline + // code eagerly and keep minor GC tied to allocations instead of tasks. return [ '--no-maglev', - '--no-flush-bytecode', + '--always-sparkplug', '--no-minor-gc-task', - '--no-incremental-marking', '--initial-old-space-size=512', ] } - -export function memoryConfig(side: 'client' | 'server') { - const execArgv = memoryExecArgv() - return { - execArgv, - setupFiles: - side === 'client' - ? [fileURLToPath(new URL('./client/vitest.setup.ts', import.meta.url))] - : [], - } -} diff --git a/benchmarks/memory/server/bench-utils.test.ts b/benchmarks/memory/server/bench-utils.test.ts new file mode 100644 index 0000000000..6ea717ae24 --- /dev/null +++ b/benchmarks/memory/server/bench-utils.test.ts @@ -0,0 +1,62 @@ +import { afterEach, expect, it, vi } from 'vitest' +import { runSequentialRequestLoop } from './bench-utils' + +afterEach(() => { + vi.useRealTimers() + vi.unstubAllGlobals() +}) + +it('drains each response before starting the next request', async () => { + vi.useFakeTimers() + const events: Array = [] + let index = 0 + const run = runSequentialRequestLoop( + { + fetch() { + const current = index++ + events.push(`fetch ${current}`) + return new Response( + new ReadableStream({ + start(controller) { + setTimeout(() => { + events.push(`body ${current}`) + controller.enqueue(new Uint8Array([1])) + controller.close() + }, 0) + }, + }), + ) + }, + }, + { + seed: 1, + iterations: 2, + buildRequest: () => new Request('http://localhost/'), + }, + ) + await vi.runAllTimersAsync() + await run + expect(events).toEqual(['fetch 0', 'body 0', 'fetch 1', 'body 1']) +}) + +it('releases a failed response reader and does not start another request', async () => { + const failure = new Error('stream failed') + const body = new ReadableStream({ + start(controller) { + controller.error(failure) + }, + }) + const fetch = vi.fn(() => new Response(body)) + await expect( + runSequentialRequestLoop( + { fetch }, + { + seed: 1, + iterations: 2, + buildRequest: () => new Request('http://localhost/'), + }, + ), + ).rejects.toBe(failure) + expect(body.locked).toBe(false) + expect(fetch).toHaveBeenCalledTimes(1) +}) diff --git a/benchmarks/memory/server/bench-utils.ts b/benchmarks/memory/server/bench-utils.ts index 9caaf63384..8893d5be4b 100644 --- a/benchmarks/memory/server/bench-utils.ts +++ b/benchmarks/memory/server/bench-utils.ts @@ -1,5 +1,3 @@ -export { memoryBenchHooks } from '../turn' - export interface StartRequestHandler { fetch: (request: Request) => Promise | Response } diff --git a/benchmarks/memory/server/benchmark.ts b/benchmarks/memory/server/benchmark.ts index 9b8dc2c76f..301a9f956d 100644 --- a/benchmarks/memory/server/benchmark.ts +++ b/benchmarks/memory/server/benchmark.ts @@ -1,9 +1,5 @@ export interface ServerMemoryWorkload { name: string - /** - * Must be an `async` function: CodSpeed's Vitest 5 provider awaits only - * `AsyncFunction`s and otherwise measures just the synchronous part. - */ run: () => Promise | void } diff --git a/benchmarks/memory/server/package.json b/benchmarks/memory/server/package.json index d09343c7b6..b3774a2778 100644 --- a/benchmarks/memory/server/package.json +++ b/benchmarks/memory/server/package.json @@ -23,7 +23,7 @@ "vue": "^3.5.16" }, "devDependencies": { - "@codspeed/vitest-plugin": "^6.0.1", + "@codspeed/vitest-plugin": "^5.5.0", "@datadog/pprof": "^5.13.2", "@platformatic/flame": "^1.6.0", "@vitejs/plugin-react": "^6.0.1", @@ -208,7 +208,7 @@ "build:react" ], "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.react.config.ts", + "command": "NODE_ENV=production vitest bench --config ./vitest.react.config.ts", "cwd": "benchmarks/memory/server" } }, @@ -220,7 +220,7 @@ "build:solid" ], "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.solid.config.ts", + "command": "NODE_ENV=production vitest bench --config ./vitest.solid.config.ts", "cwd": "benchmarks/memory/server" } }, @@ -232,7 +232,7 @@ "build:vue" ], "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.vue.config.ts", + "command": "NODE_ENV=production vitest bench --config ./vitest.vue.config.ts", "cwd": "benchmarks/memory/server" } }, @@ -269,13 +269,18 @@ "options": { "command": "tsc -p ./tsconfig.json --noEmit", "cwd": "benchmarks/memory/server" + } + }, + "test:unit": { + "executor": "nx:run-commands", + "options": { + "command": "vitest run --config ./vitest.unit.config.ts", + "cwd": "benchmarks/memory/server" }, "inputs": [ "default", "^production", - "{workspaceRoot}/eslint.config.js", - "dependentTaskOutputs", - "{workspaceRoot}/benchmarks/memory/*.ts" + "{workspaceRoot}/benchmarks/memory/runtime.ts" ] } } diff --git a/benchmarks/memory/server/runtime.test.ts b/benchmarks/memory/server/runtime.test.ts new file mode 100644 index 0000000000..d4bcccd745 --- /dev/null +++ b/benchmarks/memory/server/runtime.test.ts @@ -0,0 +1,62 @@ +import { execFileSync } from 'node:child_process' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { resolveConfig } from 'vite' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { memoryExecArgv } from '../runtime' + +afterEach(() => { + vi.unstubAllEnvs() +}) + +describe('memory worker configuration', () => { + it('preserves CodSpeed instrumentation flags in a runnable worker', async () => { + vi.stubEnv('CODSPEED_ENV', 'test') + vi.stubEnv('CODSPEED_RUNNER_MODE', 'memory') + + const config = await resolveConfig( + { + configFile: false, + plugins: [codspeedPlugin()], + test: { execArgv: memoryExecArgv() }, + }, + 'serve', + 'benchmark', + ) + const flags = config.test!.execArgv! + expect(flags).toContain('--expose-gc') + expect(flags).toContain('--predictable') + expect(flags).toContain('--hash-seed=1') + + const output = execFileSync( + process.execPath, + [ + ...flags, + '--trace-opt', + '--eval', + ` + if (typeof global.gc !== 'function') { + throw new Error('Missing GC instrumentation') + } + function hot(value) { return value + 1 } + let total = 0 + for (let index = 0; index < 100000; index++) { + total += hot(index) + } + console.log(total) + `, + ], + { encoding: 'utf8' }, + ) + expect(output).toContain('5000050000') + expect(output).not.toMatch(/MAGLEV/) + }) + + it.each([undefined, 'simulation', 'instrumentation', 'walltime'])( + 'does not change %s workers', + (mode) => { + vi.stubEnv('CODSPEED_ENV', 'test') + vi.stubEnv('CODSPEED_RUNNER_MODE', mode) + expect(memoryExecArgv()).toEqual([]) + }, + ) +}) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/deferred-records.ts b/benchmarks/memory/server/scenarios/aborted-requests/deferred-records.ts index 7a1cd6d254..4886e3ee80 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/deferred-records.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/deferred-records.ts @@ -16,42 +16,3 @@ export function makeAbortedRequestRecords( label: `deferred-${group}-${id}-${index}`, })) } - -// Abort probes keep their deferred payload pending until the request is -// cancelled. Timer chains can outlive cancellation and spill into the next -// measured request; route-loader signals stop observing the request after load. -export function makeDeferredRecords( - id: string, - group: RecordGroup, - signal: AbortSignal, -): Promise> { - return new Promise((resolve) => { - if (signal.aborted) { - resolve([]) - return - } - - let timeoutId: ReturnType | undefined - const onAbort = () => { - clearTimeout(timeoutId) - resolve([]) - } - signal.addEventListener('abort', onAbort, { once: true }) - - if (id === 'sanity-mid-stream' || id.startsWith('abort-')) { - return - } - - let remaining = group === 'alpha' ? 4 : 6 - const step = () => { - remaining -= 1 - if (remaining === 0) { - signal.removeEventListener('abort', onAbort) - resolve(makeAbortedRequestRecords(id, group)) - return - } - timeoutId = setTimeout(step, 0) - } - timeoutId = setTimeout(step, 0) - }) -} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/react/memory.bench.ts b/benchmarks/memory/server/scenarios/aborted-requests/react/memory.bench.ts index 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/react/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/react/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/react/vite.config.ts b/benchmarks/memory/server/scenarios/aborted-requests/react/vite.config.ts index eff0d0e043..7a0d8ea3a1 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/react/vite.config.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/react/vite.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -23,7 +23,16 @@ export default defineConfig({ minify: false, }, test: { - ...memoryConfig('server'), + // Keep lazily-compiled code alive for the whole run: the pinned + // collections age code fast enough for V8 to flush unused bytecode, + // and the mid-measurement recompile injects a multi-MB allocation + // burst at a run-dependent time. + execArgv: [ + ...memoryExecArgv(), + '--no-flush-bytecode', + '--min-semi-space-size=16', + '--max-semi-space-size=16', + ], name: '@benchmarks/memory-server aborted-requests (react)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/aborted-requests/shared.ts b/benchmarks/memory/server/scenarios/aborted-requests/shared.ts index 29eca99e00..dfd064cd63 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/shared.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/shared.ts @@ -6,6 +6,13 @@ export type { StartRequestHandler } type Framework = 'react' | 'solid' | 'vue' type AbortedRequestReadMode = 'first-chunk' | 'shell-before-deferred' +type AbortedRequestCancelMode = 'plain' | 'swallow-abort-error' + +type AbortedRequestMode = { + readMode: AbortedRequestReadMode + cancelMode: AbortedRequestCancelMode +} + const abortedRequestIterations = 40 let abortedRequestCounter = 0 const eagerMarker = 'data-bench="aborted-requests-eager"' @@ -17,10 +24,19 @@ const betaFirstRecord = (id: string) => `deferred-beta-${id}-0` const betaLastRecord = (id: string) => `deferred-beta-${id}-19` const textDecoder = new TextDecoder() -const abortedRequestModes: Record = { - react: 'first-chunk', - solid: 'first-chunk', - vue: 'shell-before-deferred', +const abortedRequestModes: Record = { + react: { + readMode: 'first-chunk', + cancelMode: 'swallow-abort-error', + }, + solid: { + readMode: 'first-chunk', + cancelMode: 'swallow-abort-error', + }, + vue: { + readMode: 'shell-before-deferred', + cancelMode: 'swallow-abort-error', + }, } const documentRequestInit = { @@ -121,10 +137,10 @@ async function readShellBeforeDeferred( async function readSanityStream( response: Response, request: Request, - mode: AbortedRequestReadMode, + mode: AbortedRequestMode, id: string, ) { - if (mode === 'shell-before-deferred') { + if (mode.readMode === 'shell-before-deferred') { return readShellBeforeDeferred(response, request, id) } @@ -149,19 +165,33 @@ function readLoopStream( return readFirstChunk(response, request) } -async function cancelReader(reader: ReadableStreamDefaultReader) { - try { - await reader.cancel() - } catch (error) { - if (!(error instanceof DOMException && error.name === 'AbortError')) { - throw error +async function cancelReader( + reader: ReadableStreamDefaultReader, + mode: AbortedRequestCancelMode, +) { + if (mode === 'swallow-abort-error') { + try { + await reader.cancel() + } catch (error) { + if (!(error instanceof DOMException && error.name === 'AbortError')) { + throw error + } } + + return } + + await reader.cancel() +} + +// Let deferred loaders and renderer teardown finish after cancellation. +async function drainCancellation() { + await settle() } async function assertAbortedRequestsSanity( handler: StartRequestHandler, - mode: AbortedRequestReadMode, + mode: AbortedRequestMode, ) { const fullId = 'sanity-full' const fullRequest = buildStreamRequest(fullId) @@ -194,13 +224,13 @@ async function assertAbortedRequestsSanity( // reader.cancel() is the response-stream cancellation path if the handler // does not observe Request.signal for this in-process request. controller.abort() - await cancelReader(reader) - await settle() + await cancelReader(reader, mode.cancelMode) + await drainCancellation() } async function runAbortedRequestLoop( handler: StartRequestHandler, - mode: AbortedRequestReadMode, + mode: AbortedRequestMode, ) { for (let index = 0; index < abortedRequestIterations; index++) { const controller = new AbortController() @@ -209,10 +239,15 @@ async function runAbortedRequestLoop( const response = await handler.fetch(request) validateDocumentResponse(response, request) - const { reader } = await readLoopStream(mode, response, request, id) + const { reader } = await readLoopStream( + mode.readMode, + response, + request, + id, + ) controller.abort() - await cancelReader(reader) - await settle() + await cancelReader(reader, mode.cancelMode) + await drainCancellation() } } @@ -221,7 +256,7 @@ export function createWorkloadGroup( handler: StartRequestHandler, ) { const mode = abortedRequestModes[framework] - const run = async () => runAbortedRequestLoop(handler, mode) + const run = () => runAbortedRequestLoop(handler, mode) return { sanity: () => assertAbortedRequestsSanity(handler, mode), diff --git a/benchmarks/memory/server/scenarios/aborted-requests/solid/memory.bench.ts b/benchmarks/memory/server/scenarios/aborted-requests/solid/memory.bench.ts index 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/solid/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routes/stream.$id.tsx b/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routes/stream.$id.tsx index bf6af17f31..b47f25a405 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routes/stream.$id.tsx +++ b/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routes/stream.$id.tsx @@ -1,17 +1,90 @@ -import { createServerOnlyFn } from '@tanstack/solid-start' -import { getRequest } from '@tanstack/solid-start/server' import { createFileRoute } from '@tanstack/solid-router' import { Show, Suspense, createResource } from 'solid-js' -import { makeDeferredRecords } from '../../../deferred-records' -import type { DeferredRecord } from '../../../deferred-records' +import { + makeAbortedRequestRecords, + type DeferredRecord, + type RecordGroup, +} from '../../../deferred-records' -const getRequestSignal = createServerOnlyFn(() => getRequest().signal) +const alphaResolveTicks = 4 +const betaResolveTicks = 6 +const abortProbeAlphaResolveTicks = 40 +const abortProbeBetaResolveTicks = 60 + +function isAbortProbeId(id: string) { + return id === 'sanity-mid-stream' || id.startsWith('abort-') +} + +function getResolveTicks(id: string, group: RecordGroup) { + if (isAbortProbeId(id)) { + return group === 'alpha' + ? abortProbeAlphaResolveTicks + : abortProbeBetaResolveTicks + } + + return group === 'alpha' ? alphaResolveTicks : betaResolveTicks +} + +// One tick = one 0ms timers-phase hop. Counting event-loop turns instead of +// milliseconds keeps the resolve/abort interleaving a pure function of the +// event-loop schedule: a wall-clock delay races the abort differently +// depending on runner load and instrumentation overhead, which made this +// benchmark's single measured run swing between runs. +function resolveAfterTicks( + ticks: number, + signal: AbortSignal, + value: () => T, + abortedValue: () => T, +) { + return new Promise((resolve) => { + if (signal.aborted) { + resolve(abortedValue()) + return + } + + let remaining = ticks + let timeoutId: ReturnType + + const onAbort = () => { + clearTimeout(timeoutId) + resolve(abortedValue()) + } + + const step = () => { + remaining -= 1 + + if (remaining <= 0) { + signal.removeEventListener('abort', onAbort) + resolve(value()) + return + } + + timeoutId = setTimeout(step, 0) + } + + signal.addEventListener('abort', onAbort, { once: true }) + timeoutId = setTimeout(step, 0) + }) +} + +function makeDeferredRecords( + id: string, + group: RecordGroup, + signal: AbortSignal, +) { + return resolveAfterTicks( + getResolveTicks(id, group), + signal, + () => makeAbortedRequestRecords(id, group), + () => [], + ) +} export const Route = createFileRoute('/stream/$id')({ - loader: ({ params }) => ({ + loader: ({ params, abortController }) => ({ eager: `eager-${params.id}`, - alpha: makeDeferredRecords(params.id, 'alpha', getRequestSignal()), - beta: makeDeferredRecords(params.id, 'beta', getRequestSignal()), + alpha: makeDeferredRecords(params.id, 'alpha', abortController.signal), + beta: makeDeferredRecords(params.id, 'beta', abortController.signal), }), component: StreamComponent, }) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/solid/vite.config.ts b/benchmarks/memory/server/scenarios/aborted-requests/solid/vite.config.ts index d7fd3459ee..6729a10f5b 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/vite.config.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/solid/vite.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import solid from 'vite-plugin-solid' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -23,7 +23,16 @@ export default defineConfig({ minify: false, }, test: { - ...memoryConfig('server'), + // Keep lazily-compiled code alive for the whole run: the pinned + // collections age code fast enough for V8 to flush unused bytecode, + // and the mid-measurement recompile injects a multi-MB allocation + // burst at a run-dependent time. + execArgv: [ + ...memoryExecArgv(), + '--no-flush-bytecode', + '--min-semi-space-size=16', + '--max-semi-space-size=16', + ], name: '@benchmarks/memory-server aborted-requests (solid)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/aborted-requests/vue/memory.bench.ts b/benchmarks/memory/server/scenarios/aborted-requests/vue/memory.bench.ts index 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/vue/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routes/stream.$id.tsx b/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routes/stream.$id.tsx index e41af03c16..b723c7f69e 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routes/stream.$id.tsx +++ b/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routes/stream.$id.tsx @@ -1,65 +1,136 @@ -import { createServerOnlyFn } from '@tanstack/vue-start' -import { getRequest } from '@tanstack/vue-start/server' import { Await, createFileRoute } from '@tanstack/vue-router' -import { Suspense, defineComponent } from 'vue' -import { makeDeferredRecords } from '../../../deferred-records' -import type { DeferredRecord } from '../../../deferred-records' +import { Suspense } from 'vue' +import { + makeAbortedRequestRecords, + type DeferredRecord, + type RecordGroup, +} from '../../../deferred-records' -const getRequestSignal = createServerOnlyFn(() => getRequest().signal) +const alphaResolveTicks = 4 +const betaResolveTicks = 6 +const abortProbeAlphaResolveTicks = 40 +const abortProbeBetaResolveTicks = 60 -const StreamComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() +function isAbortProbeId(id: string) { + return id === 'sanity-mid-stream' || id.startsWith('abort-') +} - return () => ( -
-

{data.value.eager}

-

loading-alpha

-

loading-beta

- - {{ - default: () => ( - ) => ( -
    - {records.map((record) => ( -
  • {record.label}
  • - ))} -
- )} - /> - ), - fallback: () => null, - }} -
- - {{ - default: () => ( - ) => ( -
    - {records.map((record) => ( -
  • {record.label}
  • - ))} -
- )} - /> - ), - fallback: () => null, - }} -
-
- ) - }, -}) +function getResolveTicks(id: string, group: RecordGroup) { + if (isAbortProbeId(id)) { + return group === 'alpha' + ? abortProbeAlphaResolveTicks + : abortProbeBetaResolveTicks + } + + return group === 'alpha' ? alphaResolveTicks : betaResolveTicks +} + +// One tick = one 0ms timers-phase hop. Counting event-loop turns instead of +// milliseconds keeps the resolve/abort interleaving a pure function of the +// event-loop schedule: a wall-clock delay races the abort differently +// depending on runner load and instrumentation overhead, which made this +// benchmark's single measured run swing between runs. +function resolveAfterTicks( + ticks: number, + signal: AbortSignal, + value: () => T, + abortedValue: () => T, +) { + return new Promise((resolve) => { + if (signal.aborted) { + resolve(abortedValue()) + return + } + + let remaining = ticks + let timeoutId: ReturnType + + const onAbort = () => { + clearTimeout(timeoutId) + resolve(abortedValue()) + } + + const step = () => { + remaining -= 1 + + if (remaining <= 0) { + signal.removeEventListener('abort', onAbort) + resolve(value()) + return + } + + timeoutId = setTimeout(step, 0) + } + + signal.addEventListener('abort', onAbort, { once: true }) + timeoutId = setTimeout(step, 0) + }) +} + +function makeDeferredRecords( + id: string, + group: RecordGroup, + signal: AbortSignal, +) { + return resolveAfterTicks( + getResolveTicks(id, group), + signal, + () => makeAbortedRequestRecords(id, group), + () => [], + ) +} export const Route = createFileRoute('/stream/$id')({ - loader: ({ params }) => ({ + loader: ({ params, abortController }) => ({ eager: `eager-${params.id}`, - alpha: makeDeferredRecords(params.id, 'alpha', getRequestSignal()), - beta: makeDeferredRecords(params.id, 'beta', getRequestSignal()), + alpha: makeDeferredRecords(params.id, 'alpha', abortController.signal), + beta: makeDeferredRecords(params.id, 'beta', abortController.signal), }), component: StreamComponent, }) + +function StreamComponent() { + const data = Route.useLoaderData() + + return ( +
+

{data.value.eager}

+

loading-alpha

+

loading-beta

+ + {{ + default: () => ( + ) => ( +
    + {records.map((record) => ( +
  • {record.label}
  • + ))} +
+ )} + /> + ), + fallback: () => null, + }} +
+ + {{ + default: () => ( + ) => ( +
    + {records.map((record) => ( +
  • {record.label}
  • + ))} +
+ )} + /> + ), + fallback: () => null, + }} +
+
+ ) +} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/vue/vite.config.ts b/benchmarks/memory/server/scenarios/aborted-requests/vue/vite.config.ts index e4e1eb66d4..011e60e6a8 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/vite.config.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/vue/vite.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -23,7 +23,16 @@ export default defineConfig({ minify: false, }, test: { - ...memoryConfig('server'), + // Keep lazily-compiled code alive for the whole run: the pinned + // collections age code fast enough for V8 to flush unused bytecode, + // and the mid-measurement recompile injects a multi-MB allocation + // burst at a run-dependent time. + execArgv: [ + ...memoryExecArgv(), + '--no-flush-bytecode', + '--min-semi-space-size=16', + '--max-semi-space-size=16', + ], name: '@benchmarks/memory-server aborted-requests (vue)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/error-paths/react/memory.bench.ts b/benchmarks/memory/server/scenarios/error-paths/react/memory.bench.ts index a6f07b97be..2780830cb2 100644 --- a/benchmarks/memory/server/scenarios/error-paths/react/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/error-paths/react/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() const workload = workloadGroup.workloads[0]! -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/server/scenarios/error-paths/react/memory.error.bench.ts b/benchmarks/memory/server/scenarios/error-paths/react/memory.error.bench.ts index 89071137c3..d41877e6ce 100644 --- a/benchmarks/memory/server/scenarios/error-paths/react/memory.error.bench.ts +++ b/benchmarks/memory/server/scenarios/error-paths/react/memory.error.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() const workload = workloadGroup.workloads[2]! -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/server/scenarios/error-paths/react/memory.not-found.bench.ts b/benchmarks/memory/server/scenarios/error-paths/react/memory.not-found.bench.ts index fa6a6693ed..42d67b1164 100644 --- a/benchmarks/memory/server/scenarios/error-paths/react/memory.not-found.bench.ts +++ b/benchmarks/memory/server/scenarios/error-paths/react/memory.not-found.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() const workload = workloadGroup.workloads[1]! -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/server/scenarios/error-paths/react/memory.unmatched.bench.ts b/benchmarks/memory/server/scenarios/error-paths/react/memory.unmatched.bench.ts index b2c3d24200..6179e469dd 100644 --- a/benchmarks/memory/server/scenarios/error-paths/react/memory.unmatched.bench.ts +++ b/benchmarks/memory/server/scenarios/error-paths/react/memory.unmatched.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() const workload = workloadGroup.workloads[3]! -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/server/scenarios/error-paths/react/vite.config.ts b/benchmarks/memory/server/scenarios/error-paths/react/vite.config.ts index c00de7727a..f1e6b78c30 100644 --- a/benchmarks/memory/server/scenarios/error-paths/react/vite.config.ts +++ b/benchmarks/memory/server/scenarios/error-paths/react/vite.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -24,7 +24,16 @@ export default defineConfig({ }, test: { isolate: true, - ...memoryConfig('server'), + // Keep lazily-compiled code alive for the whole run: the pinned + // collections age code fast enough for V8 to flush unused bytecode, + // and the mid-measurement recompile injects a multi-MB allocation + // burst at a run-dependent time. + execArgv: [ + ...memoryExecArgv(), + '--no-flush-bytecode', + '--min-semi-space-size=16', + '--max-semi-space-size=16', + ], name: '@benchmarks/memory-server error-paths (react)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/error-paths/shared.ts b/benchmarks/memory/server/scenarios/error-paths/shared.ts index 11ed293d22..966505f3a0 100644 --- a/benchmarks/memory/server/scenarios/error-paths/shared.ts +++ b/benchmarks/memory/server/scenarios/error-paths/shared.ts @@ -136,7 +136,7 @@ export function createWorkloadGroup( framework: Framework, handler: StartRequestHandler, ) { - const runRedirect = async () => + const runRedirect = () => runSequentialRequestLoop(handler, { random: redirectRandom, iterations: errorPathsIterations, @@ -144,7 +144,7 @@ export function createWorkloadGroup( validateResponse: validateRedirectResponse, }) - const runNotFound = async () => + const runNotFound = () => runSequentialRequestLoop(handler, { random: notFoundRandom, iterations: errorPathsIterations, @@ -152,7 +152,7 @@ export function createWorkloadGroup( validateResponse: validateNotFoundResponse, }) - const runError = async () => + const runError = () => runSequentialRequestLoop(handler, { random: errorRandom, iterations: errorPathsIterations, @@ -160,7 +160,7 @@ export function createWorkloadGroup( validateResponse: validateErrorResponse, }) - const runUnmatched = async () => + const runUnmatched = () => runSequentialRequestLoop(handler, { random: unmatchedRandom, iterations: errorPathsIterations, diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/memory.bench.ts b/benchmarks/memory/server/scenarios/error-paths/solid/memory.bench.ts index a6f07b97be..2780830cb2 100644 --- a/benchmarks/memory/server/scenarios/error-paths/solid/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/error-paths/solid/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() const workload = workloadGroup.workloads[0]! -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/memory.error.bench.ts b/benchmarks/memory/server/scenarios/error-paths/solid/memory.error.bench.ts index 89071137c3..d41877e6ce 100644 --- a/benchmarks/memory/server/scenarios/error-paths/solid/memory.error.bench.ts +++ b/benchmarks/memory/server/scenarios/error-paths/solid/memory.error.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() const workload = workloadGroup.workloads[2]! -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/memory.not-found.bench.ts b/benchmarks/memory/server/scenarios/error-paths/solid/memory.not-found.bench.ts index fa6a6693ed..42d67b1164 100644 --- a/benchmarks/memory/server/scenarios/error-paths/solid/memory.not-found.bench.ts +++ b/benchmarks/memory/server/scenarios/error-paths/solid/memory.not-found.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() const workload = workloadGroup.workloads[1]! -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/memory.unmatched.bench.ts b/benchmarks/memory/server/scenarios/error-paths/solid/memory.unmatched.bench.ts index b2c3d24200..6179e469dd 100644 --- a/benchmarks/memory/server/scenarios/error-paths/solid/memory.unmatched.bench.ts +++ b/benchmarks/memory/server/scenarios/error-paths/solid/memory.unmatched.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() const workload = workloadGroup.workloads[3]! -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/vite.config.ts b/benchmarks/memory/server/scenarios/error-paths/solid/vite.config.ts index d7a0bb51b0..7e7c59b1d5 100644 --- a/benchmarks/memory/server/scenarios/error-paths/solid/vite.config.ts +++ b/benchmarks/memory/server/scenarios/error-paths/solid/vite.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import solid from 'vite-plugin-solid' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -24,7 +24,16 @@ export default defineConfig({ }, test: { isolate: true, - ...memoryConfig('server'), + // Keep lazily-compiled code alive for the whole run: the pinned + // collections age code fast enough for V8 to flush unused bytecode, + // and the mid-measurement recompile injects a multi-MB allocation + // burst at a run-dependent time. + execArgv: [ + ...memoryExecArgv(), + '--no-flush-bytecode', + '--min-semi-space-size=16', + '--max-semi-space-size=16', + ], name: '@benchmarks/memory-server error-paths (solid)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/memory.bench.ts b/benchmarks/memory/server/scenarios/error-paths/vue/memory.bench.ts index a6f07b97be..2780830cb2 100644 --- a/benchmarks/memory/server/scenarios/error-paths/vue/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/error-paths/vue/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() const workload = workloadGroup.workloads[0]! -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/memory.error.bench.ts b/benchmarks/memory/server/scenarios/error-paths/vue/memory.error.bench.ts index 89071137c3..d41877e6ce 100644 --- a/benchmarks/memory/server/scenarios/error-paths/vue/memory.error.bench.ts +++ b/benchmarks/memory/server/scenarios/error-paths/vue/memory.error.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() const workload = workloadGroup.workloads[2]! -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/memory.not-found.bench.ts b/benchmarks/memory/server/scenarios/error-paths/vue/memory.not-found.bench.ts index fa6a6693ed..42d67b1164 100644 --- a/benchmarks/memory/server/scenarios/error-paths/vue/memory.not-found.bench.ts +++ b/benchmarks/memory/server/scenarios/error-paths/vue/memory.not-found.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() const workload = workloadGroup.workloads[1]! -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/memory.unmatched.bench.ts b/benchmarks/memory/server/scenarios/error-paths/vue/memory.unmatched.bench.ts index b2c3d24200..6179e469dd 100644 --- a/benchmarks/memory/server/scenarios/error-paths/vue/memory.unmatched.bench.ts +++ b/benchmarks/memory/server/scenarios/error-paths/vue/memory.unmatched.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() const workload = workloadGroup.workloads[3]! -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/target.$id.tsx b/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/target.$id.tsx index 0bbf4a3dc6..17ade6bf5b 100644 --- a/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/target.$id.tsx +++ b/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/target.$id.tsx @@ -1,14 +1,11 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' -const TargetComponent = defineComponent({ - setup() { - const params = Route.useParams() - - return () =>
{`target-${params.value.id}`}
- }, -}) - export const Route = createFileRoute('/target/$id')({ component: TargetComponent, }) + +function TargetComponent() { + const params = Route.useParams() + + return
{`target-${params.value.id}`}
+} diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/vite.config.ts b/benchmarks/memory/server/scenarios/error-paths/vue/vite.config.ts index 3dc0762aa0..fc43376502 100644 --- a/benchmarks/memory/server/scenarios/error-paths/vue/vite.config.ts +++ b/benchmarks/memory/server/scenarios/error-paths/vue/vite.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -24,7 +24,16 @@ export default defineConfig({ }, test: { isolate: true, - ...memoryConfig('server'), + // Keep lazily-compiled code alive for the whole run: the pinned + // collections age code fast enough for V8 to flush unused bytecode, + // and the mid-measurement recompile injects a multi-MB allocation + // burst at a run-dependent time. + execArgv: [ + ...memoryExecArgv(), + '--no-flush-bytecode', + '--min-semi-space-size=16', + '--max-semi-space-size=16', + ], name: '@benchmarks/memory-server error-paths (vue)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/memory.bench.ts b/benchmarks/memory/server/scenarios/peak-large-page/react/memory.bench.ts index 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/peak-large-page/react/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/vite.config.ts b/benchmarks/memory/server/scenarios/peak-large-page/react/vite.config.ts index dcfcf1f92b..202b646c03 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/vite.config.ts +++ b/benchmarks/memory/server/scenarios/peak-large-page/react/vite.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -23,7 +23,16 @@ export default defineConfig({ minify: false, }, test: { - ...memoryConfig('server'), + // Keep lazily-compiled code alive for the whole run: the pinned + // collections age code fast enough for V8 to flush unused bytecode, + // and the mid-measurement recompile injects a multi-MB allocation + // burst at a run-dependent time. + execArgv: [ + ...memoryExecArgv(), + '--no-flush-bytecode', + '--min-semi-space-size=16', + '--max-semi-space-size=16', + ], name: '@benchmarks/memory-server peak-large-page (react)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/peak-large-page/shared.ts b/benchmarks/memory/server/scenarios/peak-large-page/shared.ts index 085e576244..486c025f5a 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/shared.ts +++ b/benchmarks/memory/server/scenarios/peak-large-page/shared.ts @@ -48,7 +48,7 @@ export function createWorkloadGroup( framework: Framework, handler: StartRequestHandler, ) { - const run = async () => + const run = () => runSequentialRequestLoop(handler, { seed: benchmarkSeed, iterations: peakLargePageIterations, diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/memory.bench.ts b/benchmarks/memory/server/scenarios/peak-large-page/solid/memory.bench.ts index 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/peak-large-page/solid/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/vite.config.ts b/benchmarks/memory/server/scenarios/peak-large-page/solid/vite.config.ts index 15b8c3a571..6cf1cfd56d 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/vite.config.ts +++ b/benchmarks/memory/server/scenarios/peak-large-page/solid/vite.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import solid from 'vite-plugin-solid' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -23,7 +23,16 @@ export default defineConfig({ minify: false, }, test: { - ...memoryConfig('server'), + // Keep lazily-compiled code alive for the whole run: the pinned + // collections age code fast enough for V8 to flush unused bytecode, + // and the mid-measurement recompile injects a multi-MB allocation + // burst at a run-dependent time. + execArgv: [ + ...memoryExecArgv(), + '--no-flush-bytecode', + '--min-semi-space-size=16', + '--max-semi-space-size=16', + ], name: '@benchmarks/memory-server peak-large-page (solid)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/memory.bench.ts b/benchmarks/memory/server/scenarios/peak-large-page/vue/memory.bench.ts index 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.l7.l8.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.l7.l8.tsx index 7f7a42d645..bd079aa1a0 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.l7.l8.tsx +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.l7.l8.tsx @@ -1,34 +1,28 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { makeLargePageHead, makeLargePageLevelData, } from '../../../large-page-data' -const LevelEightComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () => { - const first = data.value.records[0]! - - return ( -
-

{data.value.marker}

-

records: {data.value.records.length}

-
-

{first.name}

-

{first.id}

-

{first.description}

-
-
- ) - } - }, -}) - export const Route = createFileRoute('/l1/l2/l3/l4/l5/l6/l7/l8')({ loader: () => makeLargePageLevelData(8, 0x5eed_1008), head: ({ loaderData }) => makeLargePageHead(loaderData), component: LevelEightComponent, }) + +function LevelEightComponent() { + const data = Route.useLoaderData() + const first = data.value.records[0]! + + return ( +
+

{data.value.marker}

+

records: {data.value.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+
+ ) +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.l7.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.l7.tsx index a99c56e529..7f69f6f438 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.l7.tsx +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.l7.tsx @@ -1,35 +1,29 @@ -import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' import { makeLargePageHead, makeLargePageLevelData, } from '../../../large-page-data' -const LevelSevenComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () => { - const first = data.value.records[0]! - - return ( -
-

{data.value.marker}

-

records: {data.value.records.length}

-
-

{first.name}

-

{first.id}

-

{first.description}

-
- -
- ) - } - }, -}) - export const Route = createFileRoute('/l1/l2/l3/l4/l5/l6/l7')({ loader: () => makeLargePageLevelData(7, 0x5eed_1007), head: ({ loaderData }) => makeLargePageHead(loaderData), component: LevelSevenComponent, }) + +function LevelSevenComponent() { + const data = Route.useLoaderData() + const first = data.value.records[0]! + + return ( +
+

{data.value.marker}

+

records: {data.value.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+ +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.tsx index 3de3f03427..75a7c717e3 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.tsx +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.tsx @@ -1,35 +1,29 @@ -import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' import { makeLargePageHead, makeLargePageLevelData, } from '../../../large-page-data' -const LevelSixComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () => { - const first = data.value.records[0]! - - return ( -
-

{data.value.marker}

-

records: {data.value.records.length}

-
-

{first.name}

-

{first.id}

-

{first.description}

-
- -
- ) - } - }, -}) - export const Route = createFileRoute('/l1/l2/l3/l4/l5/l6')({ loader: () => makeLargePageLevelData(6, 0x5eed_1006), head: ({ loaderData }) => makeLargePageHead(loaderData), component: LevelSixComponent, }) + +function LevelSixComponent() { + const data = Route.useLoaderData() + const first = data.value.records[0]! + + return ( +
+

{data.value.marker}

+

records: {data.value.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+ +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.tsx index 5d936f83b5..f390ae3db3 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.tsx +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.tsx @@ -1,35 +1,29 @@ -import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' import { makeLargePageHead, makeLargePageLevelData, } from '../../../large-page-data' -const LevelFiveComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () => { - const first = data.value.records[0]! - - return ( -
-

{data.value.marker}

-

records: {data.value.records.length}

-
-

{first.name}

-

{first.id}

-

{first.description}

-
- -
- ) - } - }, -}) - export const Route = createFileRoute('/l1/l2/l3/l4/l5')({ loader: () => makeLargePageLevelData(5, 0x5eed_1005), head: ({ loaderData }) => makeLargePageHead(loaderData), component: LevelFiveComponent, }) + +function LevelFiveComponent() { + const data = Route.useLoaderData() + const first = data.value.records[0]! + + return ( +
+

{data.value.marker}

+

records: {data.value.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+ +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.tsx index 8e10331f2d..6b30bd50dc 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.tsx +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.tsx @@ -1,35 +1,29 @@ -import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' import { makeLargePageHead, makeLargePageLevelData, } from '../../../large-page-data' -const LevelFourComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () => { - const first = data.value.records[0]! - - return ( -
-

{data.value.marker}

-

records: {data.value.records.length}

-
-

{first.name}

-

{first.id}

-

{first.description}

-
- -
- ) - } - }, -}) - export const Route = createFileRoute('/l1/l2/l3/l4')({ loader: () => makeLargePageLevelData(4, 0x5eed_1004), head: ({ loaderData }) => makeLargePageHead(loaderData), component: LevelFourComponent, }) + +function LevelFourComponent() { + const data = Route.useLoaderData() + const first = data.value.records[0]! + + return ( +
+

{data.value.marker}

+

records: {data.value.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+ +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.tsx index d69529c50c..6ec6f32fea 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.tsx +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.tsx @@ -1,35 +1,29 @@ -import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' import { makeLargePageHead, makeLargePageLevelData, } from '../../../large-page-data' -const LevelThreeComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () => { - const first = data.value.records[0]! - - return ( -
-

{data.value.marker}

-

records: {data.value.records.length}

-
-

{first.name}

-

{first.id}

-

{first.description}

-
- -
- ) - } - }, -}) - export const Route = createFileRoute('/l1/l2/l3')({ loader: () => makeLargePageLevelData(3, 0x5eed_1003), head: ({ loaderData }) => makeLargePageHead(loaderData), component: LevelThreeComponent, }) + +function LevelThreeComponent() { + const data = Route.useLoaderData() + const first = data.value.records[0]! + + return ( +
+

{data.value.marker}

+

records: {data.value.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+ +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.tsx index d04bc7f827..e5b4cf0de1 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.tsx +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.tsx @@ -1,35 +1,29 @@ -import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' import { makeLargePageHead, makeLargePageLevelData, } from '../../../large-page-data' -const LevelTwoComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () => { - const first = data.value.records[0]! - - return ( -
-

{data.value.marker}

-

records: {data.value.records.length}

-
-

{first.name}

-

{first.id}

-

{first.description}

-
- -
- ) - } - }, -}) - export const Route = createFileRoute('/l1/l2')({ loader: () => makeLargePageLevelData(2, 0x5eed_1002), head: ({ loaderData }) => makeLargePageHead(loaderData), component: LevelTwoComponent, }) + +function LevelTwoComponent() { + const data = Route.useLoaderData() + const first = data.value.records[0]! + + return ( +
+

{data.value.marker}

+

records: {data.value.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+ +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.tsx index a95ae7f9b0..a29e465cd4 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.tsx +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.tsx @@ -1,35 +1,29 @@ -import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' import { makeLargePageHead, makeLargePageLevelData, } from '../../../large-page-data' -const LevelOneComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () => { - const first = data.value.records[0]! - - return ( -
-

{data.value.marker}

-

records: {data.value.records.length}

-
-

{first.name}

-

{first.id}

-

{first.description}

-
- -
- ) - } - }, -}) - export const Route = createFileRoute('/l1')({ loader: () => makeLargePageLevelData(1, 0x5eed_1001), head: ({ loaderData }) => makeLargePageHead(loaderData), component: LevelOneComponent, }) + +function LevelOneComponent() { + const data = Route.useLoaderData() + const first = data.value.records[0]! + + return ( +
+

{data.value.marker}

+

records: {data.value.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+ +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/vite.config.ts b/benchmarks/memory/server/scenarios/peak-large-page/vue/vite.config.ts index 3fab2aff9e..8e18d805ed 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/vite.config.ts +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/vite.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -23,7 +23,16 @@ export default defineConfig({ minify: false, }, test: { - ...memoryConfig('server'), + // Keep lazily-compiled code alive for the whole run: the pinned + // collections age code fast enough for V8 to flush unused bytecode, + // and the mid-measurement recompile injects a multi-MB allocation + // burst at a run-dependent time. + execArgv: [ + ...memoryExecArgv(), + '--no-flush-bytecode', + '--min-semi-space-size=16', + '--max-semi-space-size=16', + ], name: '@benchmarks/memory-server peak-large-page (vue)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/request-churn/react/memory.bench.ts b/benchmarks/memory/server/scenarios/request-churn/react/memory.bench.ts index 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/request-churn/react/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/request-churn/react/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) diff --git a/benchmarks/memory/server/scenarios/request-churn/react/vite.config.ts b/benchmarks/memory/server/scenarios/request-churn/react/vite.config.ts index 35adf6a249..e29fac4fe9 100644 --- a/benchmarks/memory/server/scenarios/request-churn/react/vite.config.ts +++ b/benchmarks/memory/server/scenarios/request-churn/react/vite.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -23,7 +23,16 @@ export default defineConfig({ minify: false, }, test: { - ...memoryConfig('server'), + // Keep lazily-compiled code alive for the whole run: the pinned + // collections age code fast enough for V8 to flush unused bytecode, + // and the mid-measurement recompile injects a multi-MB allocation + // burst at a run-dependent time. + execArgv: [ + ...memoryExecArgv(), + '--no-flush-bytecode', + '--min-semi-space-size=16', + '--max-semi-space-size=16', + ], name: '@benchmarks/memory-server request-churn (react)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/request-churn/shared.ts b/benchmarks/memory/server/scenarios/request-churn/shared.ts index b200c96ed6..32125148cd 100644 --- a/benchmarks/memory/server/scenarios/request-churn/shared.ts +++ b/benchmarks/memory/server/scenarios/request-churn/shared.ts @@ -62,7 +62,7 @@ export function createWorkloadGroup( return new Request(`http://localhost/items/${id}?q=${q}`, requestInit) } - const run = async () => + const run = () => runSequentialRequestLoop(handler, { random: benchmarkRandom, iterations: requestChurnIterations, diff --git a/benchmarks/memory/server/scenarios/request-churn/solid/memory.bench.ts b/benchmarks/memory/server/scenarios/request-churn/solid/memory.bench.ts index 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/request-churn/solid/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/request-churn/solid/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) diff --git a/benchmarks/memory/server/scenarios/request-churn/solid/vite.config.ts b/benchmarks/memory/server/scenarios/request-churn/solid/vite.config.ts index 6601309a74..6f66d036d1 100644 --- a/benchmarks/memory/server/scenarios/request-churn/solid/vite.config.ts +++ b/benchmarks/memory/server/scenarios/request-churn/solid/vite.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import solid from 'vite-plugin-solid' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -23,7 +23,16 @@ export default defineConfig({ minify: false, }, test: { - ...memoryConfig('server'), + // Keep lazily-compiled code alive for the whole run: the pinned + // collections age code fast enough for V8 to flush unused bytecode, + // and the mid-measurement recompile injects a multi-MB allocation + // burst at a run-dependent time. + execArgv: [ + ...memoryExecArgv(), + '--no-flush-bytecode', + '--min-semi-space-size=16', + '--max-semi-space-size=16', + ], name: '@benchmarks/memory-server request-churn (solid)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/request-churn/vue/memory.bench.ts b/benchmarks/memory/server/scenarios/request-churn/vue/memory.bench.ts index 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/request-churn/vue/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/request-churn/vue/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) diff --git a/benchmarks/memory/server/scenarios/request-churn/vue/src/routes/items.$id.tsx b/benchmarks/memory/server/scenarios/request-churn/vue/src/routes/items.$id.tsx index 570561f2a8..a98d036565 100644 --- a/benchmarks/memory/server/scenarios/request-churn/vue/src/routes/items.$id.tsx +++ b/benchmarks/memory/server/scenarios/request-churn/vue/src/routes/items.$id.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' const itemIndexes = Array.from({ length: 5 }, (_, index) => index) @@ -7,24 +6,6 @@ type ItemSearch = { q: string } -const ItemComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () => ( -
-

{data.value.title}

-

{data.value.q}

-
    - {data.value.items.map((item) => ( -
  • {item.label}
  • - ))} -
-
- ) - }, -}) - export const Route = createFileRoute('/items/$id')({ validateSearch: (search: Record): ItemSearch => ({ q: typeof search.q === 'string' ? search.q : '', @@ -41,3 +22,19 @@ export const Route = createFileRoute('/items/$id')({ }), component: ItemComponent, }) + +function ItemComponent() { + const data = Route.useLoaderData() + + return ( +
+

{data.value.title}

+

{data.value.q}

+
    + {data.value.items.map((item) => ( +
  • {item.label}
  • + ))} +
+
+ ) +} diff --git a/benchmarks/memory/server/scenarios/request-churn/vue/vite.config.ts b/benchmarks/memory/server/scenarios/request-churn/vue/vite.config.ts index 7f15c5c7af..7bb96efffa 100644 --- a/benchmarks/memory/server/scenarios/request-churn/vue/vite.config.ts +++ b/benchmarks/memory/server/scenarios/request-churn/vue/vite.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -23,7 +23,16 @@ export default defineConfig({ minify: false, }, test: { - ...memoryConfig('server'), + // Keep lazily-compiled code alive for the whole run: the pinned + // collections age code fast enough for V8 to flush unused bytecode, + // and the mid-measurement recompile injects a multi-MB allocation + // burst at a run-dependent time. + execArgv: [ + ...memoryExecArgv(), + '--no-flush-bytecode', + '--min-semi-space-size=16', + '--max-semi-space-size=16', + ], name: '@benchmarks/memory-server request-churn (vue)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/serialization-payload/react/memory.bench.ts b/benchmarks/memory/server/scenarios/serialization-payload/react/memory.bench.ts index 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/serialization-payload/react/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/serialization-payload/react/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/react/vite.config.ts b/benchmarks/memory/server/scenarios/serialization-payload/react/vite.config.ts index 1ed3bcc335..ea8783aa79 100644 --- a/benchmarks/memory/server/scenarios/serialization-payload/react/vite.config.ts +++ b/benchmarks/memory/server/scenarios/serialization-payload/react/vite.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -23,7 +23,16 @@ export default defineConfig({ minify: false, }, test: { - ...memoryConfig('server'), + // Keep lazily-compiled code alive for the whole run: the pinned + // collections age code fast enough for V8 to flush unused bytecode, + // and the mid-measurement recompile injects a multi-MB allocation + // burst at a run-dependent time. + execArgv: [ + ...memoryExecArgv(), + '--no-flush-bytecode', + '--min-semi-space-size=16', + '--max-semi-space-size=16', + ], name: '@benchmarks/memory-server serialization-payload (react)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/serialization-payload/shared.ts b/benchmarks/memory/server/scenarios/serialization-payload/shared.ts index 14ec8f7e0a..7f40aeb9d2 100644 --- a/benchmarks/memory/server/scenarios/serialization-payload/shared.ts +++ b/benchmarks/memory/server/scenarios/serialization-payload/shared.ts @@ -55,7 +55,7 @@ export function createWorkloadGroup( framework: Framework, handler: StartRequestHandler, ) { - const run = async () => + const run = () => runSequentialRequestLoop(handler, { seed: benchmarkSeed, iterations: serializationPayloadIterations, diff --git a/benchmarks/memory/server/scenarios/serialization-payload/solid/memory.bench.ts b/benchmarks/memory/server/scenarios/serialization-payload/solid/memory.bench.ts index 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/serialization-payload/solid/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/serialization-payload/solid/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/solid/vite.config.ts b/benchmarks/memory/server/scenarios/serialization-payload/solid/vite.config.ts index a2d04b986c..2d26f8c74a 100644 --- a/benchmarks/memory/server/scenarios/serialization-payload/solid/vite.config.ts +++ b/benchmarks/memory/server/scenarios/serialization-payload/solid/vite.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import solid from 'vite-plugin-solid' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -23,7 +23,16 @@ export default defineConfig({ minify: false, }, test: { - ...memoryConfig('server'), + // Keep lazily-compiled code alive for the whole run: the pinned + // collections age code fast enough for V8 to flush unused bytecode, + // and the mid-measurement recompile injects a multi-MB allocation + // burst at a run-dependent time. + execArgv: [ + ...memoryExecArgv(), + '--no-flush-bytecode', + '--min-semi-space-size=16', + '--max-semi-space-size=16', + ], name: '@benchmarks/memory-server serialization-payload (solid)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/serialization-payload/vue/memory.bench.ts b/benchmarks/memory/server/scenarios/serialization-payload/vue/memory.bench.ts index 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/serialization-payload/vue/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/serialization-payload/vue/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/vue/src/routes/data.$id.tsx b/benchmarks/memory/server/scenarios/serialization-payload/vue/src/routes/data.$id.tsx index 37b1a590e4..e6b4cfadfb 100644 --- a/benchmarks/memory/server/scenarios/serialization-payload/vue/src/routes/data.$id.tsx +++ b/benchmarks/memory/server/scenarios/serialization-payload/vue/src/routes/data.$id.tsx @@ -1,20 +1,17 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { makeSerializationPayload } from '../../../serialization-payload' -const DataComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () => ( -
- Map size: {data.value.lookup.size} -
- ) - }, -}) - export const Route = createFileRoute('/data/$id')({ loader: ({ params }) => makeSerializationPayload(params.id), component: DataComponent, }) + +function DataComponent() { + const data = Route.useLoaderData() + + return ( +
+ Map size: {data.value.lookup.size} +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/vue/vite.config.ts b/benchmarks/memory/server/scenarios/serialization-payload/vue/vite.config.ts index b63a561228..f7884525ad 100644 --- a/benchmarks/memory/server/scenarios/serialization-payload/vue/vite.config.ts +++ b/benchmarks/memory/server/scenarios/serialization-payload/vue/vite.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -23,7 +23,16 @@ export default defineConfig({ minify: false, }, test: { - ...memoryConfig('server'), + // Keep lazily-compiled code alive for the whole run: the pinned + // collections age code fast enough for V8 to flush unused bytecode, + // and the mid-measurement recompile injects a multi-MB allocation + // burst at a run-dependent time. + execArgv: [ + ...memoryExecArgv(), + '--no-flush-bytecode', + '--min-semi-space-size=16', + '--max-semi-space-size=16', + ], name: '@benchmarks/memory-server serialization-payload (vue)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/react/memory.bench.ts b/benchmarks/memory/server/scenarios/server-fn-churn/react/memory.bench.ts index 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/server-fn-churn/react/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/server-fn-churn/react/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/react/vite.config.ts b/benchmarks/memory/server/scenarios/server-fn-churn/react/vite.config.ts index f72cc53d6f..5fa9cfbb82 100644 --- a/benchmarks/memory/server/scenarios/server-fn-churn/react/vite.config.ts +++ b/benchmarks/memory/server/scenarios/server-fn-churn/react/vite.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -23,7 +23,16 @@ export default defineConfig({ minify: false, }, test: { - ...memoryConfig('server'), + // Keep lazily-compiled code alive for the whole run: the pinned + // collections age code fast enough for V8 to flush unused bytecode, + // and the mid-measurement recompile injects a multi-MB allocation + // burst at a run-dependent time. + execArgv: [ + ...memoryExecArgv(), + '--no-flush-bytecode', + '--min-semi-space-size=16', + '--max-semi-space-size=16', + ], name: '@benchmarks/memory-server server-fn-churn (react)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/shared.ts b/benchmarks/memory/server/scenarios/server-fn-churn/shared.ts index 167b24d3b6..2bc224c979 100644 --- a/benchmarks/memory/server/scenarios/server-fn-churn/shared.ts +++ b/benchmarks/memory/server/scenarios/server-fn-churn/shared.ts @@ -38,6 +38,8 @@ type SerovalNode = const benchmarkSeed = 0xdecafbad const payloadSeed = 0x51f0cafe const fixtureCount = 16 +// Sized to sit just above the 2s measured-run floor on CI (per-iteration +// cost with the pinned collection is ~0.08-0.11s across frameworks). const serverFnChurnIterations = 30 const origin = 'http://localhost' const tssContentTypeFramed = 'application/x-tss-framed' @@ -202,7 +204,7 @@ export async function createWorkloadGroup( handler: StartRequestHandler, ) { const urls = await discoverUrls(handler) - const run = async () => + const run = () => runSequentialRequestLoop(handler, { seed: benchmarkSeed, iterations: serverFnChurnIterations, diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/solid/memory.bench.ts b/benchmarks/memory/server/scenarios/server-fn-churn/solid/memory.bench.ts index 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/server-fn-churn/solid/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/server-fn-churn/solid/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/solid/vite.config.ts b/benchmarks/memory/server/scenarios/server-fn-churn/solid/vite.config.ts index 4fba196bd2..233d3ef5a3 100644 --- a/benchmarks/memory/server/scenarios/server-fn-churn/solid/vite.config.ts +++ b/benchmarks/memory/server/scenarios/server-fn-churn/solid/vite.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import solid from 'vite-plugin-solid' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -23,7 +23,16 @@ export default defineConfig({ minify: false, }, test: { - ...memoryConfig('server'), + // Keep lazily-compiled code alive for the whole run: the pinned + // collections age code fast enough for V8 to flush unused bytecode, + // and the mid-measurement recompile injects a multi-MB allocation + // burst at a run-dependent time. + execArgv: [ + ...memoryExecArgv(), + '--no-flush-bytecode', + '--min-semi-space-size=16', + '--max-semi-space-size=16', + ], name: '@benchmarks/memory-server server-fn-churn (solid)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/vue/memory.bench.ts b/benchmarks/memory/server/scenarios/server-fn-churn/vue/memory.bench.ts index 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/server-fn-churn/vue/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/server-fn-churn/vue/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/vue/vite.config.ts b/benchmarks/memory/server/scenarios/server-fn-churn/vue/vite.config.ts index 5ab5ec37e3..c264768167 100644 --- a/benchmarks/memory/server/scenarios/server-fn-churn/vue/vite.config.ts +++ b/benchmarks/memory/server/scenarios/server-fn-churn/vue/vite.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -23,7 +23,16 @@ export default defineConfig({ minify: false, }, test: { - ...memoryConfig('server'), + // Keep lazily-compiled code alive for the whole run: the pinned + // collections age code fast enough for V8 to flush unused bytecode, + // and the mid-measurement recompile injects a multi-MB allocation + // burst at a run-dependent time. + execArgv: [ + ...memoryExecArgv(), + '--no-flush-bytecode', + '--min-semi-space-size=16', + '--max-semi-space-size=16', + ], name: '@benchmarks/memory-server server-fn-churn (vue)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/streaming-peak/react/memory.bench.ts b/benchmarks/memory/server/scenarios/streaming-peak/react/memory.bench.ts index 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/streaming-peak/react/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/react/vite.config.ts b/benchmarks/memory/server/scenarios/streaming-peak/react/vite.config.ts index 5d555441b6..11639a2665 100644 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/vite.config.ts +++ b/benchmarks/memory/server/scenarios/streaming-peak/react/vite.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -23,7 +23,16 @@ export default defineConfig({ minify: false, }, test: { - ...memoryConfig('server'), + // Keep lazily-compiled code alive for the whole run: the pinned + // collections age code fast enough for V8 to flush unused bytecode, + // and the mid-measurement recompile injects a multi-MB allocation + // burst at a run-dependent time. + execArgv: [ + ...memoryExecArgv(), + '--no-flush-bytecode', + '--min-semi-space-size=16', + '--max-semi-space-size=16', + ], name: '@benchmarks/memory-server streaming-peak (react)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/streaming-peak/shared.ts b/benchmarks/memory/server/scenarios/streaming-peak/shared.ts index c027047408..148649a854 100644 --- a/benchmarks/memory/server/scenarios/streaming-peak/shared.ts +++ b/benchmarks/memory/server/scenarios/streaming-peak/shared.ts @@ -92,7 +92,7 @@ export function createWorkloadGroup( framework: Framework, handler: StartRequestHandler, ) { - const run = async () => + const run = () => runSequentialRequestLoop(handler, { seed: benchmarkSeed, iterations: streamingPeakIterations, @@ -101,12 +101,7 @@ export function createWorkloadGroup( }) return { - sanity: async () => { - // Import the route chunks before checking streaming. Cold disk I/O can - // otherwise outlast the deferred payload and collapse the first response. - await run() - await assertStreamingPeakSanity(handler) - }, + sanity: () => assertStreamingPeakSanity(handler), workloads: [ { name: `mem server streaming-peak chunked (${framework})`, diff --git a/benchmarks/memory/server/scenarios/streaming-peak/solid/memory.bench.ts b/benchmarks/memory/server/scenarios/streaming-peak/solid/memory.bench.ts index 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/streaming-peak/solid/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/solid/vite.config.ts b/benchmarks/memory/server/scenarios/streaming-peak/solid/vite.config.ts index 5fbdb48c23..8a47faf33a 100644 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/vite.config.ts +++ b/benchmarks/memory/server/scenarios/streaming-peak/solid/vite.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import solid from 'vite-plugin-solid' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -23,7 +23,16 @@ export default defineConfig({ minify: false, }, test: { - ...memoryConfig('server'), + // Keep lazily-compiled code alive for the whole run: the pinned + // collections age code fast enough for V8 to flush unused bytecode, + // and the mid-measurement recompile injects a multi-MB allocation + // burst at a run-dependent time. + execArgv: [ + ...memoryExecArgv(), + '--no-flush-bytecode', + '--min-semi-space-size=16', + '--max-semi-space-size=16', + ], name: '@benchmarks/memory-server streaming-peak (solid)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/streaming-peak/vue/memory.bench.ts b/benchmarks/memory/server/scenarios/streaming-peak/vue/memory.bench.ts index 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/streaming-peak/vue/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routes/stream.$id.tsx b/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routes/stream.$id.tsx index 750d1cb47d..0c71a8d3a0 100644 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routes/stream.$id.tsx +++ b/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routes/stream.$id.tsx @@ -1,5 +1,5 @@ import { Await, createFileRoute } from '@tanstack/vue-router' -import { Suspense, defineComponent } from 'vue' +import { Suspense } from 'vue' import { makeDeferredSectionPayload, type DeferredSectionPayload, @@ -7,47 +7,6 @@ import { const fallbackFlushTicks = 20 -const StreamComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () => { - const deferredSections = [ - { index: 0, promise: data.value.deferred0 }, - { index: 1, promise: data.value.deferred1 }, - { index: 2, promise: data.value.deferred2 }, - { index: 3, promise: data.value.deferred3 }, - ] as const - - return ( -
-

{data.value.eager}

- {deferredSections.map(({ index, promise }) => ( - <> -

- streaming-peak-fallback-{index} -

- - {{ - default: () => ( - ( - - )} - /> - ), - fallback: () => null, - }} - - - ))} -
- ) - } - }, -}) - export const Route = createFileRoute('/stream/$id')({ loader: ({ params }) => ({ eager: `streaming-peak-eager-${params.id}`, @@ -89,6 +48,42 @@ function makeDeferredSection(id: string, sectionIndex: number) { ) } +function StreamComponent() { + const data = Route.useLoaderData() + const deferredSections = [ + { index: 0, promise: data.value.deferred0 }, + { index: 1, promise: data.value.deferred1 }, + { index: 2, promise: data.value.deferred2 }, + { index: 3, promise: data.value.deferred3 }, + ] as const + + return ( +
+

{data.value.eager}

+ {deferredSections.map(({ index, promise }) => ( + <> +

+ streaming-peak-fallback-{index} +

+ + {{ + default: () => ( + ( + + )} + /> + ), + fallback: () => null, + }} + + + ))} +
+ ) +} + function DeferredSection({ section }: { section: DeferredSectionPayload }) { const marker = `streaming-peak-deferred-${section.index}` diff --git a/benchmarks/memory/server/scenarios/streaming-peak/vue/vite.config.ts b/benchmarks/memory/server/scenarios/streaming-peak/vue/vite.config.ts index cd848584a5..3dbe508d1c 100644 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/vite.config.ts +++ b/benchmarks/memory/server/scenarios/streaming-peak/vue/vite.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' -import { memoryConfig } from '../../../../runtime' +import { memoryExecArgv } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -23,7 +23,16 @@ export default defineConfig({ minify: false, }, test: { - ...memoryConfig('server'), + // Keep lazily-compiled code alive for the whole run: the pinned + // collections age code fast enough for V8 to flush unused bytecode, + // and the mid-measurement recompile injects a multi-MB allocation + // burst at a run-dependent time. + execArgv: [ + ...memoryExecArgv(), + '--no-flush-bytecode', + '--min-semi-space-size=16', + '--max-semi-space-size=16', + ], name: '@benchmarks/memory-server streaming-peak (vue)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/tsconfig.json b/benchmarks/memory/server/tsconfig.json index 86d36f047a..499ec37192 100644 --- a/benchmarks/memory/server/tsconfig.json +++ b/benchmarks/memory/server/tsconfig.json @@ -7,6 +7,7 @@ "bench-utils.ts", "scenarios/*/shared.ts", "../runtime.ts", - "vitest.setup.ts" + "*.test.ts", + "vitest.unit.config.ts" ] } diff --git a/benchmarks/client-nav/link-performance/vitest.config.ts b/benchmarks/memory/server/vitest.unit.config.ts similarity index 63% rename from benchmarks/client-nav/link-performance/vitest.config.ts rename to benchmarks/memory/server/vitest.unit.config.ts index f8454c819d..19405a6f92 100644 --- a/benchmarks/client-nav/link-performance/vitest.config.ts +++ b/benchmarks/memory/server/vitest.unit.config.ts @@ -1,8 +1,6 @@ -import { fileURLToPath } from 'node:url' import { defineConfig } from 'vitest/config' export default defineConfig({ - root: fileURLToPath(new URL('.', import.meta.url)), test: { watch: false, environment: 'node', diff --git a/benchmarks/memory/turn.ts b/benchmarks/memory/turn.ts deleted file mode 100644 index 08729685fe..0000000000 --- a/benchmarks/memory/turn.ts +++ /dev/null @@ -1,34 +0,0 @@ -export function isMemoryInstrumented() { - return ( - process.env.CODSPEED_ENV !== undefined && - process.env.CODSPEED_RUNNER_MODE === 'memory' - ) -} - -// CodSpeed calls beforeEach before its forced GC and measurement marker. End -// the previous warmup's job so WeakRef targets can be released by that GC. -export function endMemoryTurn() { - return new Promise((resolve) => setImmediate(resolve)) -} - -/** - * Per-invocation bench hooks. CodSpeed runs them around every warmup - * invocation and the measured one, outside the measurement marker: the turn - * ends first, then the workload prepares fresh state before the forced GC. - */ -export function memoryBenchHooks( - workload: { - before?: () => Promise | void - after?: () => Promise | void - } = {}, -) { - return { - async beforeEach() { - if (isMemoryInstrumented()) { - await endMemoryTurn() - } - await workload.before?.() - }, - afterEach: workload.after, - } -} diff --git a/benchmarks/ssr/README.md b/benchmarks/ssr/README.md index 3d90af1598..625e1006c5 100644 --- a/benchmarks/ssr/README.md +++ b/benchmarks/ssr/README.md @@ -98,18 +98,3 @@ Use `react`, `solid`, or `vue` for ``. The baseline projects use `@be - Server-function loops must include `sec-fetch-site: same-origin` so the default CSRF middleware accepts the request. - Loops that expect non-200 responses pass a custom `validateResponse` to `runRequestLoop`. - Bench loops must build deterministic requests from the seeded random helper and consume response bodies through `runRequestLoop` or `runSsrRequestLoop`. - -## Optional React Link workloads - -The [opt-in Link suite](../client-nav/README.md#opt-in-react-link-performance-suite) -adds focused standalone React Router SSR coverage for params/updaters, -inheritance, search middlewares, optional/splat segments, encoding, masks, -rewrites, and active props. Each timed batch creates four fresh routers and -renders their Links to HTML; it does not measure Start HTTP/streaming overhead. - -```bash -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/react-link-performance:test:perf:ssr --outputStyle=stream --skipRemoteCache -- --run -``` - -These cases are excluded from this directory's aggregate projects and normal -CodSpeed dependency graph; they only run through the dedicated target above. diff --git a/benchmarks/ssr/package.json b/benchmarks/ssr/package.json index 20c1837468..07fbd92849 100644 --- a/benchmarks/ssr/package.json +++ b/benchmarks/ssr/package.json @@ -15,11 +15,11 @@ "vue": "^3.5.16" }, "devDependencies": { - "@codspeed/vitest-plugin": "^6.0.1", + "@codspeed/vitest-plugin": "^5.5.0", "@vitejs/plugin-react": "^6.0.1", "@vitejs/plugin-vue-jsx": "^5.1.5", "@types/react": "catalog:", - "seroval": "^1.6.7", + "seroval": "^1.6.2", "@typescript/native": "npm:typescript@^7.0.2", "jsdom": "29.1.1", "typescript": "npm:@typescript/typescript6@^6.0.2", @@ -116,7 +116,7 @@ "build:vue" ], "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark", + "command": "NODE_ENV=production vitest bench", "cwd": "benchmarks/ssr" } }, @@ -134,7 +134,7 @@ "build:react" ], "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.react.config.ts", + "command": "NODE_ENV=production vitest bench --config ./vitest.react.config.ts", "cwd": "benchmarks/ssr" } }, @@ -145,7 +145,7 @@ "build:solid" ], "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.solid.config.ts", + "command": "NODE_ENV=production vitest bench --config ./vitest.solid.config.ts", "cwd": "benchmarks/ssr" } }, @@ -156,7 +156,7 @@ "build:vue" ], "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.vue.config.ts", + "command": "NODE_ENV=production vitest bench --config ./vitest.vue.config.ts", "cwd": "benchmarks/ssr" } }, diff --git a/benchmarks/ssr/react/speed.bench.ts b/benchmarks/ssr/react/speed.bench.ts index 6825a7ddfb..419b1ccb36 100644 --- a/benchmarks/ssr/react/speed.bench.ts +++ b/benchmarks/ssr/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { runSsrRequestLoop } from '../bench-utils' import type { StartRequestHandler } from '../bench-utils' @@ -11,12 +11,14 @@ const { default: handler } = (await import( default: StartRequestHandler } -test('ssr', async ({ bench }) => { - await bench('ssr request loop (react)', async () => - runSsrRequestLoop(handler, { seed: benchmarkSeed }), - ).run({ - warmupIterations: 100, - time: 10_000, - throws: true, - }) +describe('ssr', () => { + bench( + 'ssr request loop (react)', + () => runSsrRequestLoop(handler, { seed: benchmarkSeed }), + { + warmupIterations: 100, + time: 10_000, + throws: true, + }, + ) }) diff --git a/benchmarks/ssr/scenarios/assets/react/speed.assets-linked-css-control.bench.ts b/benchmarks/ssr/scenarios/assets/react/speed.assets-linked-css-control.bench.ts index 0496613afb..6413559b92 100644 --- a/benchmarks/ssr/scenarios/assets/react/speed.assets-linked-css-control.bench.ts +++ b/benchmarks/ssr/scenarios/assets/react/speed.assets-linked-css-control.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertAssetsScenario, assetsBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertAssetsScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr assets linked-css control (react)', async () => - runAssetsLinkedControlLoop(handler), - ).run(assetsBenchOptions) +describe('ssr', () => { + bench( + 'ssr assets linked-css control (react)', + () => runAssetsLinkedControlLoop(handler), + assetsBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/assets/react/speed.bench.ts b/benchmarks/ssr/scenarios/assets/react/speed.bench.ts index 7dc57d89f1..5970b88f0b 100644 --- a/benchmarks/ssr/scenarios/assets/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/assets/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertAssetsScenario, assetsBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertAssetsScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr assets inline-css cdn (react)', async () => - runAssetsInlineLoop(handler), - ).run(assetsBenchOptions) +describe('ssr', () => { + bench( + 'ssr assets inline-css cdn (react)', + () => runAssetsInlineLoop(handler), + assetsBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/assets/solid/speed.assets-linked-css-control.bench.ts b/benchmarks/ssr/scenarios/assets/solid/speed.assets-linked-css-control.bench.ts index d159124a04..63fa209ac3 100644 --- a/benchmarks/ssr/scenarios/assets/solid/speed.assets-linked-css-control.bench.ts +++ b/benchmarks/ssr/scenarios/assets/solid/speed.assets-linked-css-control.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertAssetsScenario, assetsBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertAssetsScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr assets linked-css control (solid)', async () => - runAssetsLinkedControlLoop(handler), - ).run(assetsBenchOptions) +describe('ssr', () => { + bench( + 'ssr assets linked-css control (solid)', + () => runAssetsLinkedControlLoop(handler), + assetsBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/assets/solid/speed.bench.ts b/benchmarks/ssr/scenarios/assets/solid/speed.bench.ts index 47f483df11..fb5631a50e 100644 --- a/benchmarks/ssr/scenarios/assets/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/assets/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertAssetsScenario, assetsBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertAssetsScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr assets inline-css cdn (solid)', async () => - runAssetsInlineLoop(handler), - ).run(assetsBenchOptions) +describe('ssr', () => { + bench( + 'ssr assets inline-css cdn (solid)', + () => runAssetsInlineLoop(handler), + assetsBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/assets/vue/speed.assets-linked-css-control.bench.ts b/benchmarks/ssr/scenarios/assets/vue/speed.assets-linked-css-control.bench.ts index e56d41df6b..ae8712da75 100644 --- a/benchmarks/ssr/scenarios/assets/vue/speed.assets-linked-css-control.bench.ts +++ b/benchmarks/ssr/scenarios/assets/vue/speed.assets-linked-css-control.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertAssetsScenario, assetsBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertAssetsScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr assets linked-css control (vue)', async () => - runAssetsLinkedControlLoop(handler), - ).run(assetsBenchOptions) +describe('ssr', () => { + bench( + 'ssr assets linked-css control (vue)', + () => runAssetsLinkedControlLoop(handler), + assetsBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/assets/vue/speed.bench.ts b/benchmarks/ssr/scenarios/assets/vue/speed.bench.ts index 3f77a0dcc1..5225e3dc66 100644 --- a/benchmarks/ssr/scenarios/assets/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/assets/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertAssetsScenario, assetsBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertAssetsScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr assets inline-css cdn (vue)', async () => - runAssetsInlineLoop(handler), - ).run(assetsBenchOptions) +describe('ssr', () => { + bench( + 'ssr assets inline-css cdn (vue)', + () => runAssetsInlineLoop(handler), + assetsBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.$y.tsx b/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.$y.tsx index a29fe59f22..a20e292938 100644 --- a/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.$y.tsx +++ b/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.$y.tsx @@ -1,21 +1,6 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import '../styles/assets-leaf.css' -const LeafComponent = defineComponent({ - setup() { - const params = Route.useParams() - - return () => ( -
-

- assets-leaf-{params.value.x}-{params.value.y} -

-
- ) - }, -}) - export const Route = createFileRoute('/a/$x/$y')({ head: ({ params }) => ({ meta: [{ title: `SSR Assets ${params.x} ${params.y}` }], @@ -27,3 +12,15 @@ export const Route = createFileRoute('/a/$x/$y')({ }), component: LeafComponent, }) + +function LeafComponent() { + const params = Route.useParams() + + return ( +
+

+ assets-leaf-{params.value.x}-{params.value.y} +

+
+ ) +} diff --git a/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.tsx b/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.tsx index e1fe0418e4..f8038f6f28 100644 --- a/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.tsx +++ b/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.tsx @@ -1,20 +1,6 @@ -import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' import '../styles/assets-a.css' -const LevelAComponent = defineComponent({ - setup() { - const params = Route.useParams() - - return () => ( -
-

assets-level-a-{params.value.x}

- -
- ) - }, -}) - export const Route = createFileRoute('/a/$x')({ head: ({ params }) => ({ meta: [{ title: `SSR Assets ${params.x}` }], @@ -26,3 +12,14 @@ export const Route = createFileRoute('/a/$x')({ }), component: LevelAComponent, }) + +function LevelAComponent() { + const params = Route.useParams() + + return ( +
+

assets-level-a-{params.value.x}

+ +
+ ) +} diff --git a/benchmarks/ssr/scenarios/before-load/react/speed.bench.ts b/benchmarks/ssr/scenarios/before-load/react/speed.bench.ts index 8a4355a168..09073687c0 100644 --- a/benchmarks/ssr/scenarios/before-load/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/before-load/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertBeforeLoadScenario, beforeLoadBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertBeforeLoadScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr before-load chain (react)', async () => - runBeforeLoadLoop(handler), - ).run(beforeLoadBenchOptions) +describe('ssr', () => { + bench( + 'ssr before-load chain (react)', + () => runBeforeLoadLoop(handler), + beforeLoadBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/before-load/solid/speed.bench.ts b/benchmarks/ssr/scenarios/before-load/solid/speed.bench.ts index 27e0d3a64c..5f6e8baf8a 100644 --- a/benchmarks/ssr/scenarios/before-load/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/before-load/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertBeforeLoadScenario, beforeLoadBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertBeforeLoadScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr before-load chain (solid)', async () => - runBeforeLoadLoop(handler), - ).run(beforeLoadBenchOptions) +describe('ssr', () => { + bench( + 'ssr before-load chain (solid)', + () => runBeforeLoadLoop(handler), + beforeLoadBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/before-load/vue/speed.bench.ts b/benchmarks/ssr/scenarios/before-load/vue/speed.bench.ts index 8684c159eb..d2cfd6814b 100644 --- a/benchmarks/ssr/scenarios/before-load/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/before-load/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertBeforeLoadScenario, beforeLoadBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertBeforeLoadScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr before-load chain (vue)', async () => - runBeforeLoadLoop(handler), - ).run(beforeLoadBenchOptions) +describe('ssr', () => { + bench( + 'ssr before-load chain (vue)', + () => runBeforeLoadLoop(handler), + beforeLoadBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/before-load/vue/src/routes/$a.$b.$c.tsx b/benchmarks/ssr/scenarios/before-load/vue/src/routes/$a.$b.$c.tsx index 178d4071eb..118e16553b 100644 --- a/benchmarks/ssr/scenarios/before-load/vue/src/routes/$a.$b.$c.tsx +++ b/benchmarks/ssr/scenarios/before-load/vue/src/routes/$a.$b.$c.tsx @@ -1,15 +1,6 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { makeBeforeLoadMarker, type BeforeLoadContext } from '../../../shared' -const LevelCComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () =>
{data.value.marker}
- }, -}) - export const Route = createFileRoute('/$a/$b/$c')({ beforeLoad: ({ params, context }) => { const parent = context as BeforeLoadContext @@ -24,3 +15,9 @@ export const Route = createFileRoute('/$a/$b/$c')({ }), component: LevelCComponent, }) + +function LevelCComponent() { + const data = Route.useLoaderData() + + return
{data.value.marker}
+} diff --git a/benchmarks/ssr/scenarios/control-flow/react/speed.bench.ts b/benchmarks/ssr/scenarios/control-flow/react/speed.bench.ts index 899f400799..3c0a3f502e 100644 --- a/benchmarks/ssr/scenarios/control-flow/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/control-flow/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr redirect (react)', async () => runRedirectLoop(handler)).run( +describe('ssr', () => { + bench( + 'ssr redirect (react)', + () => runRedirectLoop(handler), controlFlowBenchOptions, ) }) diff --git a/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-error-500.bench.ts b/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-error-500.bench.ts index 0a93c5eac3..3e117895d8 100644 --- a/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-error-500.bench.ts +++ b/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-error-500.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr control-flow error 500 (react)', async () => - runErrorLoop(handler), - ).run(controlFlowBenchOptions) +describe('ssr', () => { + bench( + 'ssr control-flow error 500 (react)', + () => runErrorLoop(handler), + controlFlowBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-route-headers.bench.ts b/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-route-headers.bench.ts index 53e09fd34e..566748735e 100644 --- a/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-route-headers.bench.ts +++ b/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-route-headers.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr control-flow route headers (react)', async () => - runRouteHeadersLoop(handler), - ).run(controlFlowBenchOptions) +describe('ssr', () => { + bench( + 'ssr control-flow route headers (react)', + () => runRouteHeadersLoop(handler), + controlFlowBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-unmatched-404.bench.ts b/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-unmatched-404.bench.ts index 1cd7c1044c..b7c25a0bb2 100644 --- a/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-unmatched-404.bench.ts +++ b/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-unmatched-404.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr control-flow unmatched 404 (react)', async () => - runUnmatchedLoop(handler), - ).run(controlFlowBenchOptions) +describe('ssr', () => { + bench( + 'ssr control-flow unmatched 404 (react)', + () => runUnmatchedLoop(handler), + controlFlowBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/control-flow/react/speed.not-found.bench.ts b/benchmarks/ssr/scenarios/control-flow/react/speed.not-found.bench.ts index 1e8abfd318..e56335c602 100644 --- a/benchmarks/ssr/scenarios/control-flow/react/speed.not-found.bench.ts +++ b/benchmarks/ssr/scenarios/control-flow/react/speed.not-found.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr not-found (react)', async () => - runNotFoundLoop(handler), - ).run(controlFlowBenchOptions) +describe('ssr', () => { + bench( + 'ssr not-found (react)', + () => runNotFoundLoop(handler), + controlFlowBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/control-flow/solid/speed.bench.ts b/benchmarks/ssr/scenarios/control-flow/solid/speed.bench.ts index 904b693e25..b76cd741df 100644 --- a/benchmarks/ssr/scenarios/control-flow/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/control-flow/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr redirect (solid)', async () => runRedirectLoop(handler)).run( +describe('ssr', () => { + bench( + 'ssr redirect (solid)', + () => runRedirectLoop(handler), controlFlowBenchOptions, ) }) diff --git a/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-error-500.bench.ts b/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-error-500.bench.ts index 57a2f0fbe9..119f65c9ee 100644 --- a/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-error-500.bench.ts +++ b/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-error-500.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr control-flow error 500 (solid)', async () => - runErrorLoop(handler), - ).run(controlFlowBenchOptions) +describe('ssr', () => { + bench( + 'ssr control-flow error 500 (solid)', + () => runErrorLoop(handler), + controlFlowBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-route-headers.bench.ts b/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-route-headers.bench.ts index 6581e92b39..8954e67986 100644 --- a/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-route-headers.bench.ts +++ b/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-route-headers.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr control-flow route headers (solid)', async () => - runRouteHeadersLoop(handler), - ).run(controlFlowBenchOptions) +describe('ssr', () => { + bench( + 'ssr control-flow route headers (solid)', + () => runRouteHeadersLoop(handler), + controlFlowBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-unmatched-404.bench.ts b/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-unmatched-404.bench.ts index 40f1679320..d59282def9 100644 --- a/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-unmatched-404.bench.ts +++ b/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-unmatched-404.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr control-flow unmatched 404 (solid)', async () => - runUnmatchedLoop(handler), - ).run(controlFlowBenchOptions) +describe('ssr', () => { + bench( + 'ssr control-flow unmatched 404 (solid)', + () => runUnmatchedLoop(handler), + controlFlowBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/control-flow/solid/speed.not-found.bench.ts b/benchmarks/ssr/scenarios/control-flow/solid/speed.not-found.bench.ts index efcb7cc229..66cf63fe79 100644 --- a/benchmarks/ssr/scenarios/control-flow/solid/speed.not-found.bench.ts +++ b/benchmarks/ssr/scenarios/control-flow/solid/speed.not-found.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr not-found (solid)', async () => - runNotFoundLoop(handler), - ).run(controlFlowBenchOptions) +describe('ssr', () => { + bench( + 'ssr not-found (solid)', + () => runNotFoundLoop(handler), + controlFlowBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/control-flow/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/control-flow/solid/src/routeTree.gen.ts index 3cec17d9c8..5e7342c172 100644 --- a/benchmarks/ssr/scenarios/control-flow/solid/src/routeTree.gen.ts +++ b/benchmarks/ssr/scenarios/control-flow/solid/src/routeTree.gen.ts @@ -10,30 +10,20 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as BoomIdRouteImport } from './routes/boom.$id' -import { Route as FromIdRouteImport } from './routes/from.$id' -import { Route as HeadersIdRouteImport } from './routes/headers.$id' -import { Route as MissingIdRouteImport } from './routes/missing.$id' import { Route as TargetIdRouteImport } from './routes/target.$id' +import { Route as MissingIdRouteImport } from './routes/missing.$id' +import { Route as HeadersIdRouteImport } from './routes/headers.$id' +import { Route as FromIdRouteImport } from './routes/from.$id' +import { Route as BoomIdRouteImport } from './routes/boom.$id' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const BoomIdRoute = BoomIdRouteImport.update({ - id: '/boom/$id', - path: '/boom/$id', - getParentRoute: () => rootRouteImport, -} as any) -const FromIdRoute = FromIdRouteImport.update({ - id: '/from/$id', - path: '/from/$id', - getParentRoute: () => rootRouteImport, -} as any) -const HeadersIdRoute = HeadersIdRouteImport.update({ - id: '/headers/$id', - path: '/headers/$id', +const TargetIdRoute = TargetIdRouteImport.update({ + id: '/target/$id', + path: '/target/$id', getParentRoute: () => rootRouteImport, } as any) const MissingIdRoute = MissingIdRouteImport.update({ @@ -41,9 +31,19 @@ const MissingIdRoute = MissingIdRouteImport.update({ path: '/missing/$id', getParentRoute: () => rootRouteImport, } as any) -const TargetIdRoute = TargetIdRouteImport.update({ - id: '/target/$id', - path: '/target/$id', +const HeadersIdRoute = HeadersIdRouteImport.update({ + id: '/headers/$id', + path: '/headers/$id', + getParentRoute: () => rootRouteImport, +} as any) +const FromIdRoute = FromIdRouteImport.update({ + id: '/from/$id', + path: '/from/$id', + getParentRoute: () => rootRouteImport, +} as any) +const BoomIdRoute = BoomIdRouteImport.update({ + id: '/boom/$id', + path: '/boom/$id', getParentRoute: () => rootRouteImport, } as any) @@ -117,25 +117,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/boom/$id': { - id: '/boom/$id' - path: '/boom/$id' - fullPath: '/boom/$id' - preLoaderRoute: typeof BoomIdRouteImport - parentRoute: typeof rootRouteImport - } - '/from/$id': { - id: '/from/$id' - path: '/from/$id' - fullPath: '/from/$id' - preLoaderRoute: typeof FromIdRouteImport - parentRoute: typeof rootRouteImport - } - '/headers/$id': { - id: '/headers/$id' - path: '/headers/$id' - fullPath: '/headers/$id' - preLoaderRoute: typeof HeadersIdRouteImport + '/target/$id': { + id: '/target/$id' + path: '/target/$id' + fullPath: '/target/$id' + preLoaderRoute: typeof TargetIdRouteImport parentRoute: typeof rootRouteImport } '/missing/$id': { @@ -145,11 +131,25 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof MissingIdRouteImport parentRoute: typeof rootRouteImport } - '/target/$id': { - id: '/target/$id' - path: '/target/$id' - fullPath: '/target/$id' - preLoaderRoute: typeof TargetIdRouteImport + '/headers/$id': { + id: '/headers/$id' + path: '/headers/$id' + fullPath: '/headers/$id' + preLoaderRoute: typeof HeadersIdRouteImport + parentRoute: typeof rootRouteImport + } + '/from/$id': { + id: '/from/$id' + path: '/from/$id' + fullPath: '/from/$id' + preLoaderRoute: typeof FromIdRouteImport + parentRoute: typeof rootRouteImport + } + '/boom/$id': { + id: '/boom/$id' + path: '/boom/$id' + fullPath: '/boom/$id' + preLoaderRoute: typeof BoomIdRouteImport parentRoute: typeof rootRouteImport } } diff --git a/benchmarks/ssr/scenarios/control-flow/vue/speed.bench.ts b/benchmarks/ssr/scenarios/control-flow/vue/speed.bench.ts index 0b95f426f2..e57ec26b52 100644 --- a/benchmarks/ssr/scenarios/control-flow/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/control-flow/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr redirect (vue)', async () => runRedirectLoop(handler)).run( +describe('ssr', () => { + bench( + 'ssr redirect (vue)', + () => runRedirectLoop(handler), controlFlowBenchOptions, ) }) diff --git a/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-error-500.bench.ts b/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-error-500.bench.ts index 262ca951af..e118e1dd28 100644 --- a/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-error-500.bench.ts +++ b/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-error-500.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr control-flow error 500 (vue)', async () => - runErrorLoop(handler), - ).run(controlFlowBenchOptions) +describe('ssr', () => { + bench( + 'ssr control-flow error 500 (vue)', + () => runErrorLoop(handler), + controlFlowBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-route-headers.bench.ts b/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-route-headers.bench.ts index bf8c90a8a1..0bef524eaf 100644 --- a/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-route-headers.bench.ts +++ b/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-route-headers.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr control-flow route headers (vue)', async () => - runRouteHeadersLoop(handler), - ).run(controlFlowBenchOptions) +describe('ssr', () => { + bench( + 'ssr control-flow route headers (vue)', + () => runRouteHeadersLoop(handler), + controlFlowBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-unmatched-404.bench.ts b/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-unmatched-404.bench.ts index d7f8ebeb9e..e29919dc56 100644 --- a/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-unmatched-404.bench.ts +++ b/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-unmatched-404.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr control-flow unmatched 404 (vue)', async () => - runUnmatchedLoop(handler), - ).run(controlFlowBenchOptions) +describe('ssr', () => { + bench( + 'ssr control-flow unmatched 404 (vue)', + () => runUnmatchedLoop(handler), + controlFlowBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/control-flow/vue/speed.not-found.bench.ts b/benchmarks/ssr/scenarios/control-flow/vue/speed.not-found.bench.ts index 4b84fb594c..b2ab3af3c7 100644 --- a/benchmarks/ssr/scenarios/control-flow/vue/speed.not-found.bench.ts +++ b/benchmarks/ssr/scenarios/control-flow/vue/speed.not-found.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr not-found (vue)', async () => runNotFoundLoop(handler)).run( +describe('ssr', () => { + bench( + 'ssr not-found (vue)', + () => runNotFoundLoop(handler), controlFlowBenchOptions, ) }) diff --git a/benchmarks/ssr/scenarios/control-flow/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/control-flow/vue/src/routeTree.gen.ts index 6dcf0d095e..f5063d1c09 100644 --- a/benchmarks/ssr/scenarios/control-flow/vue/src/routeTree.gen.ts +++ b/benchmarks/ssr/scenarios/control-flow/vue/src/routeTree.gen.ts @@ -10,30 +10,20 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as BoomIdRouteImport } from './routes/boom.$id' -import { Route as FromIdRouteImport } from './routes/from.$id' -import { Route as HeadersIdRouteImport } from './routes/headers.$id' -import { Route as MissingIdRouteImport } from './routes/missing.$id' import { Route as TargetIdRouteImport } from './routes/target.$id' +import { Route as MissingIdRouteImport } from './routes/missing.$id' +import { Route as HeadersIdRouteImport } from './routes/headers.$id' +import { Route as FromIdRouteImport } from './routes/from.$id' +import { Route as BoomIdRouteImport } from './routes/boom.$id' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const BoomIdRoute = BoomIdRouteImport.update({ - id: '/boom/$id', - path: '/boom/$id', - getParentRoute: () => rootRouteImport, -} as any) -const FromIdRoute = FromIdRouteImport.update({ - id: '/from/$id', - path: '/from/$id', - getParentRoute: () => rootRouteImport, -} as any) -const HeadersIdRoute = HeadersIdRouteImport.update({ - id: '/headers/$id', - path: '/headers/$id', +const TargetIdRoute = TargetIdRouteImport.update({ + id: '/target/$id', + path: '/target/$id', getParentRoute: () => rootRouteImport, } as any) const MissingIdRoute = MissingIdRouteImport.update({ @@ -41,9 +31,19 @@ const MissingIdRoute = MissingIdRouteImport.update({ path: '/missing/$id', getParentRoute: () => rootRouteImport, } as any) -const TargetIdRoute = TargetIdRouteImport.update({ - id: '/target/$id', - path: '/target/$id', +const HeadersIdRoute = HeadersIdRouteImport.update({ + id: '/headers/$id', + path: '/headers/$id', + getParentRoute: () => rootRouteImport, +} as any) +const FromIdRoute = FromIdRouteImport.update({ + id: '/from/$id', + path: '/from/$id', + getParentRoute: () => rootRouteImport, +} as any) +const BoomIdRoute = BoomIdRouteImport.update({ + id: '/boom/$id', + path: '/boom/$id', getParentRoute: () => rootRouteImport, } as any) @@ -117,25 +117,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/boom/$id': { - id: '/boom/$id' - path: '/boom/$id' - fullPath: '/boom/$id' - preLoaderRoute: typeof BoomIdRouteImport - parentRoute: typeof rootRouteImport - } - '/from/$id': { - id: '/from/$id' - path: '/from/$id' - fullPath: '/from/$id' - preLoaderRoute: typeof FromIdRouteImport - parentRoute: typeof rootRouteImport - } - '/headers/$id': { - id: '/headers/$id' - path: '/headers/$id' - fullPath: '/headers/$id' - preLoaderRoute: typeof HeadersIdRouteImport + '/target/$id': { + id: '/target/$id' + path: '/target/$id' + fullPath: '/target/$id' + preLoaderRoute: typeof TargetIdRouteImport parentRoute: typeof rootRouteImport } '/missing/$id': { @@ -145,11 +131,25 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof MissingIdRouteImport parentRoute: typeof rootRouteImport } - '/target/$id': { - id: '/target/$id' - path: '/target/$id' - fullPath: '/target/$id' - preLoaderRoute: typeof TargetIdRouteImport + '/headers/$id': { + id: '/headers/$id' + path: '/headers/$id' + fullPath: '/headers/$id' + preLoaderRoute: typeof HeadersIdRouteImport + parentRoute: typeof rootRouteImport + } + '/from/$id': { + id: '/from/$id' + path: '/from/$id' + fullPath: '/from/$id' + preLoaderRoute: typeof FromIdRouteImport + parentRoute: typeof rootRouteImport + } + '/boom/$id': { + id: '/boom/$id' + path: '/boom/$id' + fullPath: '/boom/$id' + preLoaderRoute: typeof BoomIdRouteImport parentRoute: typeof rootRouteImport } } diff --git a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/headers.$id.tsx b/benchmarks/ssr/scenarios/control-flow/vue/src/routes/headers.$id.tsx index 20c1bbe5ac..ac2ec01b52 100644 --- a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/headers.$id.tsx +++ b/benchmarks/ssr/scenarios/control-flow/vue/src/routes/headers.$id.tsx @@ -1,14 +1,5 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' -const HeadersComponent = defineComponent({ - setup() { - const params = Route.useParams() - - return () =>
{`headers-${params.value.id}`}
- }, -}) - export const Route = createFileRoute('/headers/$id')({ headers: ({ params }) => ({ 'x-bench-route-header': `route-header-${params.id}`, @@ -16,3 +7,9 @@ export const Route = createFileRoute('/headers/$id')({ }), component: HeadersComponent, }) + +function HeadersComponent() { + const params = Route.useParams() + + return
{`headers-${params.value.id}`}
+} diff --git a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/target.$id.tsx b/benchmarks/ssr/scenarios/control-flow/vue/src/routes/target.$id.tsx index 0bbf4a3dc6..17ade6bf5b 100644 --- a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/target.$id.tsx +++ b/benchmarks/ssr/scenarios/control-flow/vue/src/routes/target.$id.tsx @@ -1,14 +1,11 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' -const TargetComponent = defineComponent({ - setup() { - const params = Route.useParams() - - return () =>
{`target-${params.value.id}`}
- }, -}) - export const Route = createFileRoute('/target/$id')({ component: TargetComponent, }) + +function TargetComponent() { + const params = Route.useParams() + + return
{`target-${params.value.id}`}
+} diff --git a/benchmarks/ssr/scenarios/global-middleware/bench.ts b/benchmarks/ssr/scenarios/global-middleware/bench.ts index d2784aed38..a89d03cabb 100644 --- a/benchmarks/ssr/scenarios/global-middleware/bench.ts +++ b/benchmarks/ssr/scenarios/global-middleware/bench.ts @@ -7,13 +7,10 @@ import { import { expectedFunctionTotal, expectedRequestTotal, - getExpectedRequestContext, makeDocumentMarker, makeServerFnMarker, makeServerRouteMarker, - setRequestMiddlewareCount, } from './shared' -import type { RequestMiddlewareCount } from './shared' import type { StartRequestHandler } from '../../bench-utils' export type { StartRequestHandler } @@ -143,7 +140,6 @@ function buildPostRequest(urls: FnUrls, bodies: Array, index: number) { export async function setupGlobalMiddlewareBench( handler: StartRequestHandler, ): Promise { - setRequestMiddlewareCount(3) const urls = await discoverUrls(handler) const payloads = createPayloads() const bodies = await createBodies(payloads) @@ -158,7 +154,6 @@ export async function setupGlobalMiddlewareBench( } async function assertDocumentResponse(handler: StartRequestHandler) { - setRequestMiddlewareCount(3) const id = 'page-sanity' const response = await handler.fetch( new Request(`${origin}/page/${id}`, documentRequestInit), @@ -180,11 +175,7 @@ async function assertDocumentResponse(handler: StartRequestHandler) { } } -async function assertServerRouteResponseForCount( - handler: StartRequestHandler, - count: RequestMiddlewareCount, -) { - setRequestMiddlewareCount(count) +async function assertServerRouteResponse(handler: StartRequestHandler) { const id = 'route-sanity' const response = await handler.fetch( new Request(`${origin}/api/ping/${id}`, apiRequestInit), @@ -208,8 +199,10 @@ async function assertServerRouteResponseForCount( marker?: string requestTotal?: number } - const expectedContext = getExpectedRequestContext(count) - const expectedMarker = makeServerRouteMarker(id, expectedContext) + const expectedMarker = makeServerRouteMarker(id, { + requestTrace: 'req.r1.r2.r3', + requestTotal: expectedRequestTotal, + }) if (body.marker !== expectedMarker) { throw new Error( @@ -217,9 +210,9 @@ async function assertServerRouteResponseForCount( ) } - if (body.requestTotal !== expectedContext.requestTotal) { + if (body.requestTotal !== expectedRequestTotal) { throw new Error( - `Expected server route requestTotal ${expectedContext.requestTotal}, received ${body.requestTotal}`, + `Expected server route requestTotal ${expectedRequestTotal}, received ${body.requestTotal}`, ) } } @@ -228,7 +221,6 @@ async function assertServerFnResponse( handler: StartRequestHandler, context: GlobalMiddlewareBenchContext, ) { - setRequestMiddlewareCount(3) const response = await handler.fetch( buildPostRequest(context.urls, context.bodies, 0), ) @@ -265,14 +257,10 @@ export async function assertGlobalMiddlewareScenario( ) { await assertDocumentResponse(handler) await assertServerFnResponse(handler, context) - for (const count of [0, 1, 2, 3] as const) { - await assertServerRouteResponseForCount(handler, count) - } - setRequestMiddlewareCount(3) + await assertServerRouteResponse(handler) } export function runGlobalMiddlewareDocumentLoop(handler: StartRequestHandler) { - setRequestMiddlewareCount(3) return runRequestLoop(handler, { seed: benchmarkSeed, concurrency: 16, @@ -285,7 +273,6 @@ export function runGlobalMiddlewareServerFnLoop( handler: StartRequestHandler, context: GlobalMiddlewareBenchContext, ) { - setRequestMiddlewareCount(3) return runRequestLoop(handler, { seed: benchmarkSeed, concurrency: 16, @@ -297,9 +284,7 @@ export function runGlobalMiddlewareServerFnLoop( export function runGlobalMiddlewareServerRouteLoop( handler: StartRequestHandler, - count: RequestMiddlewareCount = 3, ) { - setRequestMiddlewareCount(count) return runRequestLoop(handler, { seed: benchmarkSeed, concurrency: 16, diff --git a/benchmarks/ssr/scenarios/global-middleware/react/speed.bench.ts b/benchmarks/ssr/scenarios/global-middleware/react/speed.bench.ts index cb3f9f427c..c68d718262 100644 --- a/benchmarks/ssr/scenarios/global-middleware/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/global-middleware/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertGlobalMiddlewareScenario, globalMiddlewareBenchOptions, @@ -18,8 +18,10 @@ const context = await setupGlobalMiddlewareBench(handler) await assertGlobalMiddlewareScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr global-mw document (react)', async () => - runGlobalMiddlewareDocumentLoop(handler), - ).run(globalMiddlewareBenchOptions) +describe('ssr', () => { + bench( + 'ssr global-mw document (react)', + () => runGlobalMiddlewareDocumentLoop(handler), + globalMiddlewareBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-fn.bench.ts b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-fn.bench.ts index 48c444de77..2655ef2f49 100644 --- a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-fn.bench.ts +++ b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-fn.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertGlobalMiddlewareScenario, globalMiddlewareBenchOptions, @@ -18,8 +18,10 @@ const context = await setupGlobalMiddlewareBench(handler) await assertGlobalMiddlewareScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-fn (react)', async () => - runGlobalMiddlewareServerFnLoop(handler, context), - ).run(globalMiddlewareBenchOptions) +describe('ssr', () => { + bench( + 'ssr global-mw server-fn (react)', + () => runGlobalMiddlewareServerFnLoop(handler, context), + globalMiddlewareBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-0-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-0-middleware.bench.ts deleted file mode 100644 index 22f53883ee..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-0-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 0 middleware (react)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 0), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-1-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-1-middleware.bench.ts deleted file mode 100644 index f01b48d66e..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-1-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 1 middleware (react)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 1), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-2-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-2-middleware.bench.ts deleted file mode 100644 index b01957f806..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-2-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 2 middlewares (react)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 2), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route.bench.ts b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route.bench.ts index 08d97fcaf6..9dc19cf943 100644 --- a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route.bench.ts +++ b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertGlobalMiddlewareScenario, globalMiddlewareBenchOptions, @@ -18,8 +18,10 @@ const context = await setupGlobalMiddlewareBench(handler) await assertGlobalMiddlewareScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 3 middlewares (react)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 3), - ).run(globalMiddlewareBenchOptions) +describe('ssr', () => { + bench( + 'ssr global-mw server-route (react)', + () => runGlobalMiddlewareServerRouteLoop(handler), + globalMiddlewareBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/src/start.ts b/benchmarks/ssr/scenarios/global-middleware/react/src/start.ts index 8dfb2dd3c4..6b59e8035b 100644 --- a/benchmarks/ssr/scenarios/global-middleware/react/src/start.ts +++ b/benchmarks/ssr/scenarios/global-middleware/react/src/start.ts @@ -1,5 +1,4 @@ import { createMiddleware, createStart } from '@tanstack/react-start' -import { getRequestMiddlewareCount } from '../../shared' import type { GlobalMiddlewareContext } from '../../shared' function appendTrace( @@ -49,13 +48,6 @@ const requestMiddlewareC = createMiddleware({ type: 'request' }).server( }, ) -const requestMiddlewareSets: Array> = [ - [], - [requestMiddlewareA], - [requestMiddlewareA, requestMiddlewareB], - [requestMiddlewareA, requestMiddlewareB, requestMiddlewareC], -] - const functionMiddlewareA = createMiddleware({ type: 'function' }).server( ({ next, context }) => { const ctx = (context ?? {}) as GlobalMiddlewareContext @@ -83,6 +75,10 @@ const functionMiddlewareB = createMiddleware({ type: 'function' }).server( ) export const startInstance = createStart(() => ({ - requestMiddleware: requestMiddlewareSets[getRequestMiddlewareCount()], + requestMiddleware: [ + requestMiddlewareA, + requestMiddlewareB, + requestMiddlewareC, + ], functionMiddleware: [functionMiddlewareA, functionMiddlewareB], })) diff --git a/benchmarks/ssr/scenarios/global-middleware/shared.ts b/benchmarks/ssr/scenarios/global-middleware/shared.ts index 8fbe788911..f90fa9b233 100644 --- a/benchmarks/ssr/scenarios/global-middleware/shared.ts +++ b/benchmarks/ssr/scenarios/global-middleware/shared.ts @@ -10,41 +10,11 @@ export interface GlobalMiddlewareRouteContext extends GlobalMiddlewareContext { globalMiddlewareContext?: GlobalMiddlewareContext } -export type RequestMiddlewareCount = 0 | 1 | 2 | 3 - -const requestMiddlewareCountKey = '__TSR_SSR_BENCH_REQUEST_MIDDLEWARE_COUNT__' - -type BenchmarkGlobal = typeof globalThis & { - [requestMiddlewareCountKey]?: RequestMiddlewareCount -} - -const expectedRequestContexts: ReadonlyArray = [ - {}, - { requestTrace: 'req.r1', requestTotal: 1 }, - { requestTrace: 'req.r1.r2', requestTotal: 3 }, - { requestTrace: 'req.r1.r2.r3', requestTotal: 6 }, -] - export const expectedRequestTrace = 'req.r1.r2.r3' export const expectedRequestTotal = 6 export const expectedFunctionTrace = 'fn.f1.f2' export const expectedFunctionTotal = 30 -export function setRequestMiddlewareCount(count: RequestMiddlewareCount) { - const benchmarkGlobal = globalThis as BenchmarkGlobal - benchmarkGlobal[requestMiddlewareCountKey] = count -} - -export function getRequestMiddlewareCount(): RequestMiddlewareCount { - return (globalThis as BenchmarkGlobal)[requestMiddlewareCountKey] ?? 3 -} - -export function getExpectedRequestContext( - count: RequestMiddlewareCount, -): GlobalMiddlewareContext { - return expectedRequestContexts[count]! -} - export function makeDocumentMarker( id: string, context: GlobalMiddlewareContext, diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/speed.bench.ts b/benchmarks/ssr/scenarios/global-middleware/solid/speed.bench.ts index 0e5f504090..5f27210e36 100644 --- a/benchmarks/ssr/scenarios/global-middleware/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/global-middleware/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertGlobalMiddlewareScenario, globalMiddlewareBenchOptions, @@ -18,8 +18,10 @@ const context = await setupGlobalMiddlewareBench(handler) await assertGlobalMiddlewareScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr global-mw document (solid)', async () => - runGlobalMiddlewareDocumentLoop(handler), - ).run(globalMiddlewareBenchOptions) +describe('ssr', () => { + bench( + 'ssr global-mw document (solid)', + () => runGlobalMiddlewareDocumentLoop(handler), + globalMiddlewareBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-fn.bench.ts b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-fn.bench.ts index 915507ef9f..eb19e10ec9 100644 --- a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-fn.bench.ts +++ b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-fn.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertGlobalMiddlewareScenario, globalMiddlewareBenchOptions, @@ -18,8 +18,10 @@ const context = await setupGlobalMiddlewareBench(handler) await assertGlobalMiddlewareScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-fn (solid)', async () => - runGlobalMiddlewareServerFnLoop(handler, context), - ).run(globalMiddlewareBenchOptions) +describe('ssr', () => { + bench( + 'ssr global-mw server-fn (solid)', + () => runGlobalMiddlewareServerFnLoop(handler, context), + globalMiddlewareBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-0-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-0-middleware.bench.ts deleted file mode 100644 index a791145935..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-0-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 0 middleware (solid)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 0), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-1-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-1-middleware.bench.ts deleted file mode 100644 index 1baab0f344..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-1-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 1 middleware (solid)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 1), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-2-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-2-middleware.bench.ts deleted file mode 100644 index d6fde20764..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-2-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 2 middlewares (solid)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 2), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route.bench.ts b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route.bench.ts index 558ebeb9a4..495c57112a 100644 --- a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route.bench.ts +++ b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertGlobalMiddlewareScenario, globalMiddlewareBenchOptions, @@ -18,8 +18,10 @@ const context = await setupGlobalMiddlewareBench(handler) await assertGlobalMiddlewareScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 3 middlewares (solid)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 3), - ).run(globalMiddlewareBenchOptions) +describe('ssr', () => { + bench( + 'ssr global-mw server-route (solid)', + () => runGlobalMiddlewareServerRouteLoop(handler), + globalMiddlewareBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/global-middleware/solid/src/routeTree.gen.ts index 65f7fa5848..28d816525e 100644 --- a/benchmarks/ssr/scenarios/global-middleware/solid/src/routeTree.gen.ts +++ b/benchmarks/ssr/scenarios/global-middleware/solid/src/routeTree.gen.ts @@ -10,8 +10,8 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as ApiFnUrlsRouteImport } from './routes/api.fn-urls' import { Route as PageIdRouteImport } from './routes/page.$id' +import { Route as ApiFnUrlsRouteImport } from './routes/api.fn-urls' import { Route as ApiPingIdRouteImport } from './routes/api.ping.$id' const IndexRoute = IndexRouteImport.update({ @@ -19,16 +19,16 @@ const IndexRoute = IndexRouteImport.update({ path: '/', getParentRoute: () => rootRouteImport, } as any) -const ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ - id: '/api/fn-urls', - path: '/api/fn-urls', - getParentRoute: () => rootRouteImport, -} as any) const PageIdRoute = PageIdRouteImport.update({ id: '/page/$id', path: '/page/$id', getParentRoute: () => rootRouteImport, } as any) +const ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ + id: '/api/fn-urls', + path: '/api/fn-urls', + getParentRoute: () => rootRouteImport, +} as any) const ApiPingIdRoute = ApiPingIdRouteImport.update({ id: '/api/ping/$id', path: '/api/ping/$id', @@ -78,13 +78,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/api/fn-urls': { - id: '/api/fn-urls' - path: '/api/fn-urls' - fullPath: '/api/fn-urls' - preLoaderRoute: typeof ApiFnUrlsRouteImport - parentRoute: typeof rootRouteImport - } '/page/$id': { id: '/page/$id' path: '/page/$id' @@ -92,6 +85,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PageIdRouteImport parentRoute: typeof rootRouteImport } + '/api/fn-urls': { + id: '/api/fn-urls' + path: '/api/fn-urls' + fullPath: '/api/fn-urls' + preLoaderRoute: typeof ApiFnUrlsRouteImport + parentRoute: typeof rootRouteImport + } '/api/ping/$id': { id: '/api/ping/$id' path: '/api/ping/$id' diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/src/start.ts b/benchmarks/ssr/scenarios/global-middleware/solid/src/start.ts index a6f6214b82..8c4168d574 100644 --- a/benchmarks/ssr/scenarios/global-middleware/solid/src/start.ts +++ b/benchmarks/ssr/scenarios/global-middleware/solid/src/start.ts @@ -1,5 +1,4 @@ import { createMiddleware, createStart } from '@tanstack/solid-start' -import { getRequestMiddlewareCount } from '../../shared' import type { GlobalMiddlewareContext } from '../../shared' function appendTrace( @@ -49,13 +48,6 @@ const requestMiddlewareC = createMiddleware({ type: 'request' }).server( }, ) -const requestMiddlewareSets: Array> = [ - [], - [requestMiddlewareA], - [requestMiddlewareA, requestMiddlewareB], - [requestMiddlewareA, requestMiddlewareB, requestMiddlewareC], -] - const functionMiddlewareA = createMiddleware({ type: 'function' }).server( ({ next, context }) => { const ctx = (context ?? {}) as GlobalMiddlewareContext @@ -83,6 +75,10 @@ const functionMiddlewareB = createMiddleware({ type: 'function' }).server( ) export const startInstance = createStart(() => ({ - requestMiddleware: requestMiddlewareSets[getRequestMiddlewareCount()], + requestMiddleware: [ + requestMiddlewareA, + requestMiddlewareB, + requestMiddlewareC, + ], functionMiddleware: [functionMiddlewareA, functionMiddlewareB], })) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/speed.bench.ts b/benchmarks/ssr/scenarios/global-middleware/vue/speed.bench.ts index 9660f29d07..5d92aab849 100644 --- a/benchmarks/ssr/scenarios/global-middleware/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/global-middleware/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertGlobalMiddlewareScenario, globalMiddlewareBenchOptions, @@ -18,8 +18,10 @@ const context = await setupGlobalMiddlewareBench(handler) await assertGlobalMiddlewareScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr global-mw document (vue)', async () => - runGlobalMiddlewareDocumentLoop(handler), - ).run(globalMiddlewareBenchOptions) +describe('ssr', () => { + bench( + 'ssr global-mw document (vue)', + () => runGlobalMiddlewareDocumentLoop(handler), + globalMiddlewareBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-fn.bench.ts b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-fn.bench.ts index 297e8cee7b..ab158504c8 100644 --- a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-fn.bench.ts +++ b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-fn.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertGlobalMiddlewareScenario, globalMiddlewareBenchOptions, @@ -18,8 +18,10 @@ const context = await setupGlobalMiddlewareBench(handler) await assertGlobalMiddlewareScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-fn (vue)', async () => - runGlobalMiddlewareServerFnLoop(handler, context), - ).run(globalMiddlewareBenchOptions) +describe('ssr', () => { + bench( + 'ssr global-mw server-fn (vue)', + () => runGlobalMiddlewareServerFnLoop(handler, context), + globalMiddlewareBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-0-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-0-middleware.bench.ts deleted file mode 100644 index d023dd458a..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-0-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 0 middleware (vue)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 0), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-1-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-1-middleware.bench.ts deleted file mode 100644 index 5018163631..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-1-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 1 middleware (vue)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 1), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-2-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-2-middleware.bench.ts deleted file mode 100644 index f9abd8eb60..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-2-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 2 middlewares (vue)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 2), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route.bench.ts b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route.bench.ts index adcec3019f..e7fd4cd205 100644 --- a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route.bench.ts +++ b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertGlobalMiddlewareScenario, globalMiddlewareBenchOptions, @@ -18,8 +18,10 @@ const context = await setupGlobalMiddlewareBench(handler) await assertGlobalMiddlewareScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 3 middlewares (vue)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 3), - ).run(globalMiddlewareBenchOptions) +describe('ssr', () => { + bench( + 'ssr global-mw server-route (vue)', + () => runGlobalMiddlewareServerRouteLoop(handler), + globalMiddlewareBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/global-middleware/vue/src/routeTree.gen.ts index 3118848e4d..aae3329420 100644 --- a/benchmarks/ssr/scenarios/global-middleware/vue/src/routeTree.gen.ts +++ b/benchmarks/ssr/scenarios/global-middleware/vue/src/routeTree.gen.ts @@ -10,8 +10,8 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as ApiFnUrlsRouteImport } from './routes/api.fn-urls' import { Route as PageIdRouteImport } from './routes/page.$id' +import { Route as ApiFnUrlsRouteImport } from './routes/api.fn-urls' import { Route as ApiPingIdRouteImport } from './routes/api.ping.$id' const IndexRoute = IndexRouteImport.update({ @@ -19,16 +19,16 @@ const IndexRoute = IndexRouteImport.update({ path: '/', getParentRoute: () => rootRouteImport, } as any) -const ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ - id: '/api/fn-urls', - path: '/api/fn-urls', - getParentRoute: () => rootRouteImport, -} as any) const PageIdRoute = PageIdRouteImport.update({ id: '/page/$id', path: '/page/$id', getParentRoute: () => rootRouteImport, } as any) +const ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ + id: '/api/fn-urls', + path: '/api/fn-urls', + getParentRoute: () => rootRouteImport, +} as any) const ApiPingIdRoute = ApiPingIdRouteImport.update({ id: '/api/ping/$id', path: '/api/ping/$id', @@ -78,13 +78,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/api/fn-urls': { - id: '/api/fn-urls' - path: '/api/fn-urls' - fullPath: '/api/fn-urls' - preLoaderRoute: typeof ApiFnUrlsRouteImport - parentRoute: typeof rootRouteImport - } '/page/$id': { id: '/page/$id' path: '/page/$id' @@ -92,6 +85,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PageIdRouteImport parentRoute: typeof rootRouteImport } + '/api/fn-urls': { + id: '/api/fn-urls' + path: '/api/fn-urls' + fullPath: '/api/fn-urls' + preLoaderRoute: typeof ApiFnUrlsRouteImport + parentRoute: typeof rootRouteImport + } '/api/ping/$id': { id: '/api/ping/$id' path: '/api/ping/$id' diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/page.$id.tsx b/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/page.$id.tsx index 6e837ef0a0..2010d0cd2a 100644 --- a/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/page.$id.tsx +++ b/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/page.$id.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { getGlobalMiddlewareContext, @@ -6,14 +5,6 @@ import { type GlobalMiddlewareContext, } from '../../../shared' -const PageComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () =>
{data.value.marker}
- }, -}) - export const Route = createFileRoute('/page/$id')({ beforeLoad: ({ serverContext }) => ({ globalMiddlewareContext: (serverContext ?? {}) as GlobalMiddlewareContext, @@ -23,3 +14,9 @@ export const Route = createFileRoute('/page/$id')({ }), component: PageComponent, }) + +function PageComponent() { + const data = Route.useLoaderData() + + return
{data.value.marker}
+} diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/src/start.ts b/benchmarks/ssr/scenarios/global-middleware/vue/src/start.ts index 6e4eb2c5ef..dc3f142e27 100644 --- a/benchmarks/ssr/scenarios/global-middleware/vue/src/start.ts +++ b/benchmarks/ssr/scenarios/global-middleware/vue/src/start.ts @@ -1,5 +1,4 @@ import { createMiddleware, createStart } from '@tanstack/vue-start' -import { getRequestMiddlewareCount } from '../../shared' import type { GlobalMiddlewareContext } from '../../shared' function appendTrace( @@ -49,13 +48,6 @@ const requestMiddlewareC = createMiddleware({ type: 'request' }).server( }, ) -const requestMiddlewareSets: Array> = [ - [], - [requestMiddlewareA], - [requestMiddlewareA, requestMiddlewareB], - [requestMiddlewareA, requestMiddlewareB, requestMiddlewareC], -] - const functionMiddlewareA = createMiddleware({ type: 'function' }).server( ({ next, context }) => { const ctx = (context ?? {}) as GlobalMiddlewareContext @@ -83,6 +75,10 @@ const functionMiddlewareB = createMiddleware({ type: 'function' }).server( ) export const startInstance = createStart(() => ({ - requestMiddleware: requestMiddlewareSets[getRequestMiddlewareCount()], + requestMiddleware: [ + requestMiddlewareA, + requestMiddlewareB, + requestMiddlewareC, + ], functionMiddleware: [functionMiddlewareA, functionMiddlewareB], })) diff --git a/benchmarks/ssr/scenarios/head/react/speed.bench.ts b/benchmarks/ssr/scenarios/head/react/speed.bench.ts index f75008506e..19158b32a9 100644 --- a/benchmarks/ssr/scenarios/head/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/head/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertHeadSanity, headBenchOptions, runHeadLoop } from '../shared' import type { StartRequestHandler } from '../shared' @@ -12,8 +12,6 @@ const { default: handler } = (await import( await assertHeadSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr head (react)', async () => runHeadLoop(handler)).run( - headBenchOptions, - ) +describe('ssr', () => { + bench('ssr head (react)', () => runHeadLoop(handler), headBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/head/solid/speed.bench.ts b/benchmarks/ssr/scenarios/head/solid/speed.bench.ts index 333e2f091b..ad5bf52809 100644 --- a/benchmarks/ssr/scenarios/head/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/head/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertHeadSanity, headBenchOptions, runHeadLoop } from '../shared' import type { StartRequestHandler } from '../shared' @@ -12,8 +12,6 @@ const { default: handler } = (await import( await assertHeadSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr head (solid)', async () => runHeadLoop(handler)).run( - headBenchOptions, - ) +describe('ssr', () => { + bench('ssr head (solid)', () => runHeadLoop(handler), headBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/head/vue/speed.bench.ts b/benchmarks/ssr/scenarios/head/vue/speed.bench.ts index 936735a909..5d8243b588 100644 --- a/benchmarks/ssr/scenarios/head/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/head/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertHeadSanity, headBenchOptions, runHeadLoop } from '../shared' import type { StartRequestHandler } from '../shared' @@ -12,8 +12,6 @@ const { default: handler } = (await import( await assertHeadSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr head (vue)', async () => runHeadLoop(handler)).run( - headBenchOptions, - ) +describe('ssr', () => { + bench('ssr head (vue)', () => runHeadLoop(handler), headBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/loaders/react/speed.bench.ts b/benchmarks/ssr/scenarios/loaders/react/speed.bench.ts index 7acd43c635..a5eecfc648 100644 --- a/benchmarks/ssr/scenarios/loaders/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/loaders/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertLoadersSanity, benchOptions, @@ -16,8 +16,6 @@ const { default: handler } = (await import( await assertLoadersSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr loaders (react)', async () => runLoadersLoop(handler)).run( - benchOptions, - ) +describe('ssr', () => { + bench('ssr loaders (react)', () => runLoadersLoop(handler), benchOptions) }) diff --git a/benchmarks/ssr/scenarios/loaders/solid/speed.bench.ts b/benchmarks/ssr/scenarios/loaders/solid/speed.bench.ts index 7fc8d88389..7b3f6247ea 100644 --- a/benchmarks/ssr/scenarios/loaders/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/loaders/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertLoadersSanity, benchOptions, @@ -16,8 +16,6 @@ const { default: handler } = (await import( await assertLoadersSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr loaders (solid)', async () => runLoadersLoop(handler)).run( - benchOptions, - ) +describe('ssr', () => { + bench('ssr loaders (solid)', () => runLoadersLoop(handler), benchOptions) }) diff --git a/benchmarks/ssr/scenarios/loaders/vue/speed.bench.ts b/benchmarks/ssr/scenarios/loaders/vue/speed.bench.ts index 321350d98c..fb39e0652c 100644 --- a/benchmarks/ssr/scenarios/loaders/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/loaders/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertLoadersSanity, benchOptions, @@ -16,8 +16,6 @@ const { default: handler } = (await import( await assertLoadersSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr loaders (vue)', async () => runLoadersLoop(handler)).run( - benchOptions, - ) +describe('ssr', () => { + bench('ssr loaders (vue)', () => runLoadersLoop(handler), benchOptions) }) diff --git a/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.$c.tsx b/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.$c.tsx index 0a52b9c542..de927a8092 100644 --- a/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.$c.tsx +++ b/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.$c.tsx @@ -1,24 +1,6 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { makeLevelData } from '../../../shared-data' -const LevelCComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () => ( -
-

{data.value.meta.label}

-
    - {data.value.items.slice(0, 10).map((item) => ( -
  • {item.name}
  • - ))} -
-
- ) - }, -}) - export const Route = createFileRoute('/$a/$b/$c')({ beforeLoad: ({ params, context }) => { void context @@ -33,3 +15,18 @@ export const Route = createFileRoute('/$a/$b/$c')({ }, component: LevelCComponent, }) + +function LevelCComponent() { + const data = Route.useLoaderData() + + return ( +
+

{data.value.meta.label}

+
    + {data.value.items.slice(0, 10).map((item) => ( +
  • {item.name}
  • + ))} +
+
+ ) +} diff --git a/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.tsx b/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.tsx index f3943d58e7..e1a5f52ae2 100644 --- a/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.tsx +++ b/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.tsx @@ -1,25 +1,6 @@ -import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' import { makeLevelData } from '../../../shared-data' -const LevelBComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () => ( -
-

{data.value.meta.label}

-
    - {data.value.items.slice(0, 10).map((item) => ( -
  • {item.name}
  • - ))} -
- -
- ) - }, -}) - export const Route = createFileRoute('/$a/$b')({ beforeLoad: ({ params, context }) => { void context @@ -34,3 +15,19 @@ export const Route = createFileRoute('/$a/$b')({ }, component: LevelBComponent, }) + +function LevelBComponent() { + const data = Route.useLoaderData() + + return ( +
+

{data.value.meta.label}

+
    + {data.value.items.slice(0, 10).map((item) => ( +
  • {item.name}
  • + ))} +
+ +
+ ) +} diff --git a/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.tsx b/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.tsx index 63bb36949f..b197a8edf1 100644 --- a/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.tsx +++ b/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.tsx @@ -1,25 +1,6 @@ -import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' import { makeLevelData } from '../../../shared-data' -const LevelAComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () => ( -
-

{data.value.meta.label}

-
    - {data.value.items.slice(0, 10).map((item) => ( -
  • {item.name}
  • - ))} -
- -
- ) - }, -}) - export const Route = createFileRoute('/$a')({ beforeLoad: ({ params, context }) => { void context @@ -34,3 +15,19 @@ export const Route = createFileRoute('/$a')({ }, component: LevelAComponent, }) + +function LevelAComponent() { + const data = Route.useLoaderData() + + return ( +
+

{data.value.meta.label}

+
    + {data.value.items.slice(0, 10).map((item) => ( +
  • {item.name}
  • + ))} +
+ +
+ ) +} diff --git a/benchmarks/ssr/scenarios/rewrites/react/speed.bench.ts b/benchmarks/ssr/scenarios/rewrites/react/speed.bench.ts index 920186c5db..a8af260279 100644 --- a/benchmarks/ssr/scenarios/rewrites/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/rewrites/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertRewriteScenario, rewriteBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertRewriteScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr rewrite localized (react)', async () => - runRewriteLocalizedLoop(handler), - ).run(rewriteBenchOptions) +describe('ssr', () => { + bench( + 'ssr rewrite localized (react)', + () => runRewriteLocalizedLoop(handler), + rewriteBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/rewrites/react/speed.rewrite-passthrough.bench.ts b/benchmarks/ssr/scenarios/rewrites/react/speed.rewrite-passthrough.bench.ts index f5d09089a6..cffabcafb5 100644 --- a/benchmarks/ssr/scenarios/rewrites/react/speed.rewrite-passthrough.bench.ts +++ b/benchmarks/ssr/scenarios/rewrites/react/speed.rewrite-passthrough.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertRewriteScenario, rewriteBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertRewriteScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr rewrite passthrough (react)', async () => - runRewritePassthroughLoop(handler), - ).run(rewriteBenchOptions) +describe('ssr', () => { + bench( + 'ssr rewrite passthrough (react)', + () => runRewritePassthroughLoop(handler), + rewriteBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/rewrites/solid/speed.bench.ts b/benchmarks/ssr/scenarios/rewrites/solid/speed.bench.ts index 488fb2ca52..5fdef077c9 100644 --- a/benchmarks/ssr/scenarios/rewrites/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/rewrites/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertRewriteScenario, rewriteBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertRewriteScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr rewrite localized (solid)', async () => - runRewriteLocalizedLoop(handler), - ).run(rewriteBenchOptions) +describe('ssr', () => { + bench( + 'ssr rewrite localized (solid)', + () => runRewriteLocalizedLoop(handler), + rewriteBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/rewrites/solid/speed.rewrite-passthrough.bench.ts b/benchmarks/ssr/scenarios/rewrites/solid/speed.rewrite-passthrough.bench.ts index 7b86e2ba11..2458a59b69 100644 --- a/benchmarks/ssr/scenarios/rewrites/solid/speed.rewrite-passthrough.bench.ts +++ b/benchmarks/ssr/scenarios/rewrites/solid/speed.rewrite-passthrough.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertRewriteScenario, rewriteBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertRewriteScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr rewrite passthrough (solid)', async () => - runRewritePassthroughLoop(handler), - ).run(rewriteBenchOptions) +describe('ssr', () => { + bench( + 'ssr rewrite passthrough (solid)', + () => runRewritePassthroughLoop(handler), + rewriteBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/rewrites/vue/speed.bench.ts b/benchmarks/ssr/scenarios/rewrites/vue/speed.bench.ts index 5fd4da9d3e..b8a98c3408 100644 --- a/benchmarks/ssr/scenarios/rewrites/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/rewrites/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertRewriteScenario, rewriteBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertRewriteScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr rewrite localized (vue)', async () => - runRewriteLocalizedLoop(handler), - ).run(rewriteBenchOptions) +describe('ssr', () => { + bench( + 'ssr rewrite localized (vue)', + () => runRewriteLocalizedLoop(handler), + rewriteBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/rewrites/vue/speed.rewrite-passthrough.bench.ts b/benchmarks/ssr/scenarios/rewrites/vue/speed.rewrite-passthrough.bench.ts index f3664b5f21..e011a9fc8d 100644 --- a/benchmarks/ssr/scenarios/rewrites/vue/speed.rewrite-passthrough.bench.ts +++ b/benchmarks/ssr/scenarios/rewrites/vue/speed.rewrite-passthrough.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertRewriteScenario, rewriteBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertRewriteScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr rewrite passthrough (vue)', async () => - runRewritePassthroughLoop(handler), - ).run(rewriteBenchOptions) +describe('ssr', () => { + bench( + 'ssr rewrite passthrough (vue)', + () => runRewritePassthroughLoop(handler), + rewriteBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.$b.tsx b/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.$b.tsx index 3c9de1806e..3fdb7014f4 100644 --- a/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.$b.tsx +++ b/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.$b.tsx @@ -1,41 +1,5 @@ -import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' -const LeafComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () => ( -
-

- rewrite-leaf {data.value.a} {data.value.b} -

- - leaf-self-link - - - leaf-next-link - - - leaf-parent-link - -
- ) - }, -}) - export const Route = createFileRoute('/p/$a/$b')({ loader: ({ params }) => ({ a: params.a, @@ -44,3 +8,32 @@ export const Route = createFileRoute('/p/$a/$b')({ }), component: LeafComponent, }) + +function LeafComponent() { + const data = Route.useLoaderData() + + return ( +
+

+ rewrite-leaf {data.value.a} {data.value.b} +

+ + leaf-self-link + + + leaf-next-link + + + leaf-parent-link + +
+ ) +} diff --git a/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.tsx b/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.tsx index 9702ebedd7..acb74aabbd 100644 --- a/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.tsx +++ b/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.tsx @@ -1,26 +1,5 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' -const ParentComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () => ( -
-

rewrite-parent {data.value.a}

- - parent-branch-link - - -
- ) - }, -}) - export const Route = createFileRoute('/p/$a')({ loader: ({ params }) => ({ a: params.a, @@ -28,3 +7,21 @@ export const Route = createFileRoute('/p/$a')({ }), component: ParentComponent, }) + +function ParentComponent() { + const data = Route.useLoaderData() + + return ( +
+

rewrite-parent {data.value.a}

+ + parent-branch-link + + +
+ ) +} diff --git a/benchmarks/ssr/scenarios/selective-ssr/react/speed.bench.ts b/benchmarks/ssr/scenarios/selective-ssr/react/speed.bench.ts index ba6bd4a61d..e0e8a0e3c4 100644 --- a/benchmarks/ssr/scenarios/selective-ssr/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/selective-ssr/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertSelectiveSanity, benchOptions, @@ -16,8 +16,6 @@ const { default: handler } = (await import( await assertSelectiveSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr selective (react)', async () => - runSelectiveLoop(handler), - ).run(benchOptions) +describe('ssr', () => { + bench('ssr selective (react)', () => runSelectiveLoop(handler), benchOptions) }) diff --git a/benchmarks/ssr/scenarios/selective-ssr/solid/speed.bench.ts b/benchmarks/ssr/scenarios/selective-ssr/solid/speed.bench.ts index 76265397ab..6a2803d45f 100644 --- a/benchmarks/ssr/scenarios/selective-ssr/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/selective-ssr/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertSelectiveSanity, benchOptions, @@ -16,8 +16,6 @@ const { default: handler } = (await import( await assertSelectiveSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr selective (solid)', async () => - runSelectiveLoop(handler), - ).run(benchOptions) +describe('ssr', () => { + bench('ssr selective (solid)', () => runSelectiveLoop(handler), benchOptions) }) diff --git a/benchmarks/ssr/scenarios/selective-ssr/vue/speed.bench.ts b/benchmarks/ssr/scenarios/selective-ssr/vue/speed.bench.ts index ff60341b27..f3082a102d 100644 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/selective-ssr/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertSelectiveSanity, benchOptions, @@ -16,8 +16,6 @@ const { default: handler } = (await import( await assertSelectiveSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr selective (vue)', async () => runSelectiveLoop(handler)).run( - benchOptions, - ) +describe('ssr', () => { + bench('ssr selective (vue)', () => runSelectiveLoop(handler), benchOptions) }) diff --git a/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.$b.$c.tsx b/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.$b.$c.tsx index 8ae7d468f1..46d7541c2b 100644 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.$b.$c.tsx +++ b/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.$b.$c.tsx @@ -1,21 +1,6 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { makeLevelData } from '../../../../loaders/shared-data' -const LevelCComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - const params = Route.useParams() - - return () => ( -
-

{`csr-rendered-${params.value.c}`}

-

{data.value.marker}

-
- ) - }, -}) - export const Route = createFileRoute('/mix/$a/$b/$c')({ ssr: false, loader: async ({ params }) => { @@ -26,3 +11,15 @@ export const Route = createFileRoute('/mix/$a/$b/$c')({ }, component: LevelCComponent, }) + +function LevelCComponent() { + const data = Route.useLoaderData() + const params = Route.useParams() + + return ( +
+

{`csr-rendered-${params.value.c}`}

+

{data.value.marker}

+
+ ) +} diff --git a/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.$b.tsx b/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.$b.tsx index c10751489e..bc685478cc 100644 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.$b.tsx +++ b/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.$b.tsx @@ -1,22 +1,6 @@ -import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' import { makeLevelData } from '../../../../loaders/shared-data' -const LevelBComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - const params = Route.useParams() - - return () => ( -
-

{`data-only-rendered-${params.value.b}`}

-

{data.value.marker}

- -
- ) - }, -}) - export const Route = createFileRoute('/mix/$a/$b')({ ssr: 'data-only', loader: async ({ params }) => { @@ -27,3 +11,16 @@ export const Route = createFileRoute('/mix/$a/$b')({ }, component: LevelBComponent, }) + +function LevelBComponent() { + const data = Route.useLoaderData() + const params = Route.useParams() + + return ( +
+

{`data-only-rendered-${params.value.b}`}

+

{data.value.marker}

+ +
+ ) +} diff --git a/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.tsx b/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.tsx index c96165c6d6..8ab4c7d54d 100644 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.tsx +++ b/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.tsx @@ -1,22 +1,6 @@ -import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' import { makeLevelData } from '../../../../loaders/shared-data' -const LevelAComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - const params = Route.useParams() - - return () => ( -
-

{`level-a-rendered-${params.value.a}`}

-

{data.value.items[0]?.name}

- -
- ) - }, -}) - export const Route = createFileRoute('/mix/$a')({ ssr: true, loader: async ({ params }) => { @@ -24,3 +8,16 @@ export const Route = createFileRoute('/mix/$a')({ }, component: LevelAComponent, }) + +function LevelAComponent() { + const data = Route.useLoaderData() + const params = Route.useParams() + + return ( +
+

{`level-a-rendered-${params.value.a}`}

+

{data.value.items[0]?.name}

+ +
+ ) +} diff --git a/benchmarks/ssr/scenarios/serialization/react/speed.bench.ts b/benchmarks/ssr/scenarios/serialization/react/speed.bench.ts index 8be07d2643..9032280e51 100644 --- a/benchmarks/ssr/scenarios/serialization/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/serialization/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertSerializationScenario, runRichSerializationLoop, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertSerializationScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr dehydrate rich types (react)', async () => - runRichSerializationLoop(handler), - ).run(serializationBenchOptions) +describe('ssr', () => { + bench( + 'ssr dehydrate rich types (react)', + () => runRichSerializationLoop(handler), + serializationBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/serialization/react/speed.dehydrate-plain-control.bench.ts b/benchmarks/ssr/scenarios/serialization/react/speed.dehydrate-plain-control.bench.ts index c70fddc6c4..a6c8d99fb6 100644 --- a/benchmarks/ssr/scenarios/serialization/react/speed.dehydrate-plain-control.bench.ts +++ b/benchmarks/ssr/scenarios/serialization/react/speed.dehydrate-plain-control.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertSerializationScenario, runPlainSerializationLoop, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertSerializationScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr dehydrate plain control (react)', async () => - runPlainSerializationLoop(handler), - ).run(serializationBenchOptions) +describe('ssr', () => { + bench( + 'ssr dehydrate plain control (react)', + () => runPlainSerializationLoop(handler), + serializationBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/serialization/solid/speed.bench.ts b/benchmarks/ssr/scenarios/serialization/solid/speed.bench.ts index 70bda8c7af..3fa22ccea9 100644 --- a/benchmarks/ssr/scenarios/serialization/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/serialization/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertSerializationScenario, runRichSerializationLoop, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertSerializationScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr dehydrate rich types (solid)', async () => - runRichSerializationLoop(handler), - ).run(serializationBenchOptions) +describe('ssr', () => { + bench( + 'ssr dehydrate rich types (solid)', + () => runRichSerializationLoop(handler), + serializationBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/serialization/solid/speed.dehydrate-plain-control.bench.ts b/benchmarks/ssr/scenarios/serialization/solid/speed.dehydrate-plain-control.bench.ts index d7ccb16f6f..354512e09d 100644 --- a/benchmarks/ssr/scenarios/serialization/solid/speed.dehydrate-plain-control.bench.ts +++ b/benchmarks/ssr/scenarios/serialization/solid/speed.dehydrate-plain-control.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertSerializationScenario, runPlainSerializationLoop, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertSerializationScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr dehydrate plain control (solid)', async () => - runPlainSerializationLoop(handler), - ).run(serializationBenchOptions) +describe('ssr', () => { + bench( + 'ssr dehydrate plain control (solid)', + () => runPlainSerializationLoop(handler), + serializationBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/serialization/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/serialization/solid/src/routeTree.gen.ts index b9e25f918e..69b63cffe9 100644 --- a/benchmarks/ssr/scenarios/serialization/solid/src/routeTree.gen.ts +++ b/benchmarks/ssr/scenarios/serialization/solid/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 PlainIdRouteImport } from './routes/plain.$id' import { Route as RichIdRouteImport } from './routes/rich.$id' +import { Route as PlainIdRouteImport } from './routes/plain.$id' -const PlainIdRoute = PlainIdRouteImport.update({ - id: '/plain/$id', - path: '/plain/$id', - getParentRoute: () => rootRouteImport, -} as any) const RichIdRoute = RichIdRouteImport.update({ id: '/rich/$id', path: '/rich/$id', getParentRoute: () => rootRouteImport, } as any) +const PlainIdRoute = PlainIdRouteImport.update({ + id: '/plain/$id', + path: '/plain/$id', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/plain/$id': typeof PlainIdRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/plain/$id': { - id: '/plain/$id' - path: '/plain/$id' - fullPath: '/plain/$id' - preLoaderRoute: typeof PlainIdRouteImport - parentRoute: typeof rootRouteImport - } '/rich/$id': { id: '/rich/$id' path: '/rich/$id' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof RichIdRouteImport parentRoute: typeof rootRouteImport } + '/plain/$id': { + id: '/plain/$id' + path: '/plain/$id' + fullPath: '/plain/$id' + preLoaderRoute: typeof PlainIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/ssr/scenarios/serialization/vue/speed.bench.ts b/benchmarks/ssr/scenarios/serialization/vue/speed.bench.ts index 7f733dd601..d68c615fdc 100644 --- a/benchmarks/ssr/scenarios/serialization/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/serialization/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertSerializationScenario, runRichSerializationLoop, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertSerializationScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr dehydrate rich types (vue)', async () => - runRichSerializationLoop(handler), - ).run(serializationBenchOptions) +describe('ssr', () => { + bench( + 'ssr dehydrate rich types (vue)', + () => runRichSerializationLoop(handler), + serializationBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/serialization/vue/speed.dehydrate-plain-control.bench.ts b/benchmarks/ssr/scenarios/serialization/vue/speed.dehydrate-plain-control.bench.ts index 8efdeb6c79..875a858226 100644 --- a/benchmarks/ssr/scenarios/serialization/vue/speed.dehydrate-plain-control.bench.ts +++ b/benchmarks/ssr/scenarios/serialization/vue/speed.dehydrate-plain-control.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertSerializationScenario, runPlainSerializationLoop, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertSerializationScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr dehydrate plain control (vue)', async () => - runPlainSerializationLoop(handler), - ).run(serializationBenchOptions) +describe('ssr', () => { + bench( + 'ssr dehydrate plain control (vue)', + () => runPlainSerializationLoop(handler), + serializationBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/serialization/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/serialization/vue/src/routeTree.gen.ts index cd7b0b449b..02268c2c3c 100644 --- a/benchmarks/ssr/scenarios/serialization/vue/src/routeTree.gen.ts +++ b/benchmarks/ssr/scenarios/serialization/vue/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 PlainIdRouteImport } from './routes/plain.$id' import { Route as RichIdRouteImport } from './routes/rich.$id' +import { Route as PlainIdRouteImport } from './routes/plain.$id' -const PlainIdRoute = PlainIdRouteImport.update({ - id: '/plain/$id', - path: '/plain/$id', - getParentRoute: () => rootRouteImport, -} as any) const RichIdRoute = RichIdRouteImport.update({ id: '/rich/$id', path: '/rich/$id', getParentRoute: () => rootRouteImport, } as any) +const PlainIdRoute = PlainIdRouteImport.update({ + id: '/plain/$id', + path: '/plain/$id', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/plain/$id': typeof PlainIdRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/plain/$id': { - id: '/plain/$id' - path: '/plain/$id' - fullPath: '/plain/$id' - preLoaderRoute: typeof PlainIdRouteImport - parentRoute: typeof rootRouteImport - } '/rich/$id': { id: '/rich/$id' path: '/rich/$id' @@ -65,6 +58,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof RichIdRouteImport parentRoute: typeof rootRouteImport } + '/plain/$id': { + id: '/plain/$id' + path: '/plain/$id' + fullPath: '/plain/$id' + preLoaderRoute: typeof PlainIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/ssr/scenarios/serialization/vue/src/routes/plain.$id.tsx b/benchmarks/ssr/scenarios/serialization/vue/src/routes/plain.$id.tsx index 47fdeb971f..d41d123f1f 100644 --- a/benchmarks/ssr/scenarios/serialization/vue/src/routes/plain.$id.tsx +++ b/benchmarks/ssr/scenarios/serialization/vue/src/routes/plain.$id.tsx @@ -1,27 +1,24 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { makePlainSerializationData } from '../../../shared-data' -const PlainComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () => ( -
-

{data.value.label}

-

{data.value.createdAt}

-

{data.value.lookup[0]?.[1].label}

-

{data.value.tags[0]}

-

{data.value.count}

-

{data.value.nested[0]?.id}

-

{data.value.points[0]?.label}

-

{data.value.problem.message}

-
- ) - }, -}) - export const Route = createFileRoute('/plain/$id')({ loader: ({ params }) => makePlainSerializationData(params.id), component: PlainComponent, }) + +function PlainComponent() { + const data = Route.useLoaderData() + + return ( +
+

{data.value.label}

+

{data.value.createdAt}

+

{data.value.lookup[0]?.[1].label}

+

{data.value.tags[0]}

+

{data.value.count}

+

{data.value.nested[0]?.id}

+

{data.value.points[0]?.label}

+

{data.value.problem.message}

+
+ ) +} diff --git a/benchmarks/ssr/scenarios/serialization/vue/src/routes/rich.$id.tsx b/benchmarks/ssr/scenarios/serialization/vue/src/routes/rich.$id.tsx index 1ee86cefd3..d50a3f292d 100644 --- a/benchmarks/ssr/scenarios/serialization/vue/src/routes/rich.$id.tsx +++ b/benchmarks/ssr/scenarios/serialization/vue/src/routes/rich.$id.tsx @@ -1,27 +1,24 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { makeRichSerializationData } from '../../../shared-data' -const RichComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () => ( -
-

{data.value.label}

-

{data.value.createdAt.toISOString()}

-

{data.value.lookup.get('k0')?.label}

-

{Array.from(data.value.tags)[0]}

-

{data.value.count.toString()}

-

{data.value.nested[0]?.id}

-

{data.value.points[0]?.label}

-

{data.value.problem.message}

-
- ) - }, -}) - export const Route = createFileRoute('/rich/$id')({ loader: ({ params }) => makeRichSerializationData(params.id), component: RichComponent, }) + +function RichComponent() { + const data = Route.useLoaderData() + + return ( +
+

{data.value.label}

+

{data.value.createdAt.toISOString()}

+

{data.value.lookup.get('k0')?.label}

+

{Array.from(data.value.tags)[0]}

+

{data.value.count.toString()}

+

{data.value.nested[0]?.id}

+

{data.value.points[0]?.label}

+

{data.value.problem.message}

+
+ ) +} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/react/speed.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/react/speed.bench.ts index fa80cdb690..149ff591ed 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-fn-transport/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnTransportScenario, runServerFnMultipartRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnTransportBench(handler) await assertServerFnTransportScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn multipart (react)', async () => - runServerFnMultipartRequestLoop(handler, context), - ).run(serverFnTransportBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn multipart (react)', + () => runServerFnMultipartRequestLoop(handler, context), + serverFnTransportBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/react/speed.server-fn-raw-response.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/react/speed.server-fn-raw-response.bench.ts index fd535ee313..43b31c609d 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/speed.server-fn-raw-response.bench.ts +++ b/benchmarks/ssr/scenarios/server-fn-transport/react/speed.server-fn-raw-response.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnTransportScenario, runServerFnRawResponseRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnTransportBench(handler) await assertServerFnTransportScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn raw-response (react)', async () => - runServerFnRawResponseRequestLoop(handler, context), - ).run(serverFnTransportBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn raw-response (react)', + () => runServerFnRawResponseRequestLoop(handler, context), + serverFnTransportBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/react/speed.server-fn-raw-stream.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/react/speed.server-fn-raw-stream.bench.ts index 8fbce405dd..4c90ffb847 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/speed.server-fn-raw-stream.bench.ts +++ b/benchmarks/ssr/scenarios/server-fn-transport/react/speed.server-fn-raw-stream.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnTransportScenario, runServerFnRawStreamRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnTransportBench(handler) await assertServerFnTransportScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn raw-stream (react)', async () => - runServerFnRawStreamRequestLoop(handler, context), - ).run(serverFnTransportBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn raw-stream (react)', + () => runServerFnRawStreamRequestLoop(handler, context), + serverFnTransportBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.bench.ts index adac07cb22..aaa2028902 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnTransportScenario, runServerFnMultipartRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnTransportBench(handler) await assertServerFnTransportScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn multipart (solid)', async () => - runServerFnMultipartRequestLoop(handler, context), - ).run(serverFnTransportBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn multipart (solid)', + () => runServerFnMultipartRequestLoop(handler, context), + serverFnTransportBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.server-fn-raw-response.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.server-fn-raw-response.bench.ts index 843a4c97ce..661430c3ae 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.server-fn-raw-response.bench.ts +++ b/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.server-fn-raw-response.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnTransportScenario, runServerFnRawResponseRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnTransportBench(handler) await assertServerFnTransportScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn raw-response (solid)', async () => - runServerFnRawResponseRequestLoop(handler, context), - ).run(serverFnTransportBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn raw-response (solid)', + () => runServerFnRawResponseRequestLoop(handler, context), + serverFnTransportBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.server-fn-raw-stream.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.server-fn-raw-stream.bench.ts index aa24d55e79..37d9b86e12 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.server-fn-raw-stream.bench.ts +++ b/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.server-fn-raw-stream.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnTransportScenario, runServerFnRawStreamRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnTransportBench(handler) await assertServerFnTransportScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn raw-stream (solid)', async () => - runServerFnRawStreamRequestLoop(handler, context), - ).run(serverFnTransportBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn raw-stream (solid)', + () => runServerFnRawStreamRequestLoop(handler, context), + serverFnTransportBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.bench.ts index 24305cf1bc..99d266298d 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnTransportScenario, runServerFnMultipartRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnTransportBench(handler) await assertServerFnTransportScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn multipart (vue)', async () => - runServerFnMultipartRequestLoop(handler, context), - ).run(serverFnTransportBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn multipart (vue)', + () => runServerFnMultipartRequestLoop(handler, context), + serverFnTransportBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.server-fn-raw-response.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.server-fn-raw-response.bench.ts index 2eeb9a4f6b..36e1b9ed22 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.server-fn-raw-response.bench.ts +++ b/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.server-fn-raw-response.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnTransportScenario, runServerFnRawResponseRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnTransportBench(handler) await assertServerFnTransportScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn raw-response (vue)', async () => - runServerFnRawResponseRequestLoop(handler, context), - ).run(serverFnTransportBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn raw-response (vue)', + () => runServerFnRawResponseRequestLoop(handler, context), + serverFnTransportBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.server-fn-raw-stream.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.server-fn-raw-stream.bench.ts index a73905004d..4c9e5dc752 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.server-fn-raw-stream.bench.ts +++ b/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.server-fn-raw-stream.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnTransportScenario, runServerFnRawStreamRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnTransportBench(handler) await assertServerFnTransportScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn raw-stream (vue)', async () => - runServerFnRawStreamRequestLoop(handler, context), - ).run(serverFnTransportBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn raw-stream (vue)', + () => runServerFnRawStreamRequestLoop(handler, context), + serverFnTransportBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-fns/react/speed.bench.ts b/benchmarks/ssr/scenarios/server-fns/react/speed.bench.ts index c876772ad1..697bfe967a 100644 --- a/benchmarks/ssr/scenarios/server-fns/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-fns/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnGetRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnBench(handler) await assertServerFnScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn GET (react)', async () => - runServerFnGetRequestLoop(handler, context), - ).run(serverFnBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn GET (react)', + () => runServerFnGetRequestLoop(handler, context), + serverFnBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-during-document-ssr.bench.ts b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-during-document-ssr.bench.ts index 6a0cb55f78..4b1c7c7d1e 100644 --- a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-during-document-ssr.bench.ts +++ b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-during-document-ssr.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnDocumentSsrRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnBench(handler) await assertServerFnScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn during document ssr (react)', async () => - runServerFnDocumentSsrRequestLoop(handler), - ).run(serverFnBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn during document ssr (react)', + () => runServerFnDocumentSsrRequestLoop(handler), + serverFnBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-not-found.bench.ts b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-not-found.bench.ts index 96f1160078..1f600dd8cf 100644 --- a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-not-found.bench.ts +++ b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-not-found.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnNotFoundRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnBench(handler) await assertServerFnScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn not-found (react)', async () => - runServerFnNotFoundRequestLoop(handler, context), - ).run(serverFnBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn not-found (react)', + () => runServerFnNotFoundRequestLoop(handler, context), + serverFnBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-post.bench.ts b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-post.bench.ts index e85d5debd3..0b4b3e5d6c 100644 --- a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-post.bench.ts +++ b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-post.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnPostRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnBench(handler) await assertServerFnScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn POST (react)', async () => - runServerFnPostRequestLoop(handler, context), - ).run(serverFnBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn POST (react)', + () => runServerFnPostRequestLoop(handler, context), + serverFnBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-redirect.bench.ts b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-redirect.bench.ts index 5dae598549..d07b4ab583 100644 --- a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-redirect.bench.ts +++ b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-redirect.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnRedirectRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnBench(handler) await assertServerFnScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn redirect (react)', async () => - runServerFnRedirectRequestLoop(handler, context), - ).run(serverFnBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn redirect (react)', + () => runServerFnRedirectRequestLoop(handler, context), + serverFnBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-send-context.bench.ts b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-send-context.bench.ts index 40d6961206..589e2ccaf3 100644 --- a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-send-context.bench.ts +++ b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-send-context.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnSendContextRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnBench(handler) await assertServerFnScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn send-context (react)', async () => - runServerFnSendContextRequestLoop(handler, context), - ).run(serverFnBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn send-context (react)', + () => runServerFnSendContextRequestLoop(handler, context), + serverFnBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-fns/solid/speed.bench.ts b/benchmarks/ssr/scenarios/server-fns/solid/speed.bench.ts index f6bbdc9e73..42e57c4ce2 100644 --- a/benchmarks/ssr/scenarios/server-fns/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-fns/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnGetRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnBench(handler) await assertServerFnScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn GET (solid)', async () => - runServerFnGetRequestLoop(handler, context), - ).run(serverFnBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn GET (solid)', + () => runServerFnGetRequestLoop(handler, context), + serverFnBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-during-document-ssr.bench.ts b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-during-document-ssr.bench.ts index 933f61b59c..1cbe7ef20b 100644 --- a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-during-document-ssr.bench.ts +++ b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-during-document-ssr.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnDocumentSsrRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnBench(handler) await assertServerFnScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn during document ssr (solid)', async () => - runServerFnDocumentSsrRequestLoop(handler), - ).run(serverFnBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn during document ssr (solid)', + () => runServerFnDocumentSsrRequestLoop(handler), + serverFnBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-not-found.bench.ts b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-not-found.bench.ts index 513b69f4ba..bd5cc10457 100644 --- a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-not-found.bench.ts +++ b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-not-found.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnNotFoundRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnBench(handler) await assertServerFnScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn not-found (solid)', async () => - runServerFnNotFoundRequestLoop(handler, context), - ).run(serverFnBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn not-found (solid)', + () => runServerFnNotFoundRequestLoop(handler, context), + serverFnBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-post.bench.ts b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-post.bench.ts index e2ce8ad9ee..d2cf977cfa 100644 --- a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-post.bench.ts +++ b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-post.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnPostRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnBench(handler) await assertServerFnScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn POST (solid)', async () => - runServerFnPostRequestLoop(handler, context), - ).run(serverFnBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn POST (solid)', + () => runServerFnPostRequestLoop(handler, context), + serverFnBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-redirect.bench.ts b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-redirect.bench.ts index 14353f1290..017ac79af0 100644 --- a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-redirect.bench.ts +++ b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-redirect.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnRedirectRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnBench(handler) await assertServerFnScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn redirect (solid)', async () => - runServerFnRedirectRequestLoop(handler, context), - ).run(serverFnBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn redirect (solid)', + () => runServerFnRedirectRequestLoop(handler, context), + serverFnBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-send-context.bench.ts b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-send-context.bench.ts index 76d3a554bd..a3d0a991d1 100644 --- a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-send-context.bench.ts +++ b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-send-context.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnSendContextRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnBench(handler) await assertServerFnScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn send-context (solid)', async () => - runServerFnSendContextRequestLoop(handler, context), - ).run(serverFnBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn send-context (solid)', + () => runServerFnSendContextRequestLoop(handler, context), + serverFnBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-fns/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/server-fns/solid/src/routeTree.gen.ts index 3d0bd34eaa..3db5e487b3 100644 --- a/benchmarks/ssr/scenarios/server-fns/solid/src/routeTree.gen.ts +++ b/benchmarks/ssr/scenarios/server-fns/solid/src/routeTree.gen.ts @@ -10,24 +10,24 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as ApiFnUrlsRouteImport } from './routes/api.fn-urls' import { Route as SsrCallIdRouteImport } from './routes/ssr-call.$id' +import { Route as ApiFnUrlsRouteImport } from './routes/api.fn-urls' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ - id: '/api/fn-urls', - path: '/api/fn-urls', - getParentRoute: () => rootRouteImport, -} as any) const SsrCallIdRoute = SsrCallIdRouteImport.update({ id: '/ssr-call/$id', path: '/ssr-call/$id', getParentRoute: () => rootRouteImport, } as any) +const ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ + id: '/api/fn-urls', + path: '/api/fn-urls', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -68,13 +68,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/api/fn-urls': { - id: '/api/fn-urls' - path: '/api/fn-urls' - fullPath: '/api/fn-urls' - preLoaderRoute: typeof ApiFnUrlsRouteImport - parentRoute: typeof rootRouteImport - } '/ssr-call/$id': { id: '/ssr-call/$id' path: '/ssr-call/$id' @@ -82,6 +75,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof SsrCallIdRouteImport parentRoute: typeof rootRouteImport } + '/api/fn-urls': { + id: '/api/fn-urls' + path: '/api/fn-urls' + fullPath: '/api/fn-urls' + preLoaderRoute: typeof ApiFnUrlsRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/ssr/scenarios/server-fns/vue/speed.bench.ts b/benchmarks/ssr/scenarios/server-fns/vue/speed.bench.ts index 3f67c1a500..c4d94659d9 100644 --- a/benchmarks/ssr/scenarios/server-fns/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-fns/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnGetRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnBench(handler) await assertServerFnScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn GET (vue)', async () => - runServerFnGetRequestLoop(handler, context), - ).run(serverFnBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn GET (vue)', + () => runServerFnGetRequestLoop(handler, context), + serverFnBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-during-document-ssr.bench.ts b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-during-document-ssr.bench.ts index 56c9addca5..c6155bcead 100644 --- a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-during-document-ssr.bench.ts +++ b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-during-document-ssr.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnDocumentSsrRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnBench(handler) await assertServerFnScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn during document ssr (vue)', async () => - runServerFnDocumentSsrRequestLoop(handler), - ).run(serverFnBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn during document ssr (vue)', + () => runServerFnDocumentSsrRequestLoop(handler), + serverFnBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-not-found.bench.ts b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-not-found.bench.ts index e9a6e31617..dca17511b8 100644 --- a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-not-found.bench.ts +++ b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-not-found.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnNotFoundRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnBench(handler) await assertServerFnScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn not-found (vue)', async () => - runServerFnNotFoundRequestLoop(handler, context), - ).run(serverFnBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn not-found (vue)', + () => runServerFnNotFoundRequestLoop(handler, context), + serverFnBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-post.bench.ts b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-post.bench.ts index df9312ccd1..4c2166056a 100644 --- a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-post.bench.ts +++ b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-post.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnPostRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnBench(handler) await assertServerFnScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn POST (vue)', async () => - runServerFnPostRequestLoop(handler, context), - ).run(serverFnBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn POST (vue)', + () => runServerFnPostRequestLoop(handler, context), + serverFnBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-redirect.bench.ts b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-redirect.bench.ts index 67c4611644..25741baa62 100644 --- a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-redirect.bench.ts +++ b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-redirect.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnRedirectRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnBench(handler) await assertServerFnScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn redirect (vue)', async () => - runServerFnRedirectRequestLoop(handler, context), - ).run(serverFnBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn redirect (vue)', + () => runServerFnRedirectRequestLoop(handler, context), + serverFnBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-send-context.bench.ts b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-send-context.bench.ts index 6f51ef4bab..c1c2d581ba 100644 --- a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-send-context.bench.ts +++ b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-send-context.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnSendContextRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnBench(handler) await assertServerFnScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn send-context (vue)', async () => - runServerFnSendContextRequestLoop(handler, context), - ).run(serverFnBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn send-context (vue)', + () => runServerFnSendContextRequestLoop(handler, context), + serverFnBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-fns/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/server-fns/vue/src/routeTree.gen.ts index 0e24cd9c15..fa27fb1a5d 100644 --- a/benchmarks/ssr/scenarios/server-fns/vue/src/routeTree.gen.ts +++ b/benchmarks/ssr/scenarios/server-fns/vue/src/routeTree.gen.ts @@ -10,24 +10,24 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as ApiFnUrlsRouteImport } from './routes/api.fn-urls' import { Route as SsrCallIdRouteImport } from './routes/ssr-call.$id' +import { Route as ApiFnUrlsRouteImport } from './routes/api.fn-urls' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ - id: '/api/fn-urls', - path: '/api/fn-urls', - getParentRoute: () => rootRouteImport, -} as any) const SsrCallIdRoute = SsrCallIdRouteImport.update({ id: '/ssr-call/$id', path: '/ssr-call/$id', getParentRoute: () => rootRouteImport, } as any) +const ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ + id: '/api/fn-urls', + path: '/api/fn-urls', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -68,13 +68,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/api/fn-urls': { - id: '/api/fn-urls' - path: '/api/fn-urls' - fullPath: '/api/fn-urls' - preLoaderRoute: typeof ApiFnUrlsRouteImport - parentRoute: typeof rootRouteImport - } '/ssr-call/$id': { id: '/ssr-call/$id' path: '/ssr-call/$id' @@ -82,6 +75,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof SsrCallIdRouteImport parentRoute: typeof rootRouteImport } + '/api/fn-urls': { + id: '/api/fn-urls' + path: '/api/fn-urls' + fullPath: '/api/fn-urls' + preLoaderRoute: typeof ApiFnUrlsRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/ssr/scenarios/server-fns/vue/src/routes/ssr-call.$id.tsx b/benchmarks/ssr/scenarios/server-fns/vue/src/routes/ssr-call.$id.tsx index 45fad23dc0..8abe77c2af 100644 --- a/benchmarks/ssr/scenarios/server-fns/vue/src/routes/ssr-call.$id.tsx +++ b/benchmarks/ssr/scenarios/server-fns/vue/src/routes/ssr-call.$id.tsx @@ -1,17 +1,6 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { echoGet } from '../fns' -const SsrCallComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () => ( -
{data.value.marker}
- ) - }, -}) - export const Route = createFileRoute('/ssr-call/$id')({ loader: async ({ params }) => { const result = await echoGet({ @@ -26,3 +15,9 @@ export const Route = createFileRoute('/ssr-call/$id')({ }, component: SsrCallComponent, }) + +function SsrCallComponent() { + const data = Route.useLoaderData() + + return
{data.value.marker}
+} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/react/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes-middleware/react/speed.bench.ts index 6331216522..8e96bc8e04 100644 --- a/benchmarks/ssr/scenarios/server-routes-middleware/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-routes-middleware/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerRouteMiddlewareResponse, runServerRouteMiddlewareLoop, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertServerRouteMiddlewareResponse(handler) -test('ssr', async ({ bench }) => { - await bench('ssr server-route middleware (react)', async () => - runServerRouteMiddlewareLoop(handler), - ).run(serverRouteMiddlewareBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-route middleware (react)', + () => runServerRouteMiddlewareLoop(handler), + serverRouteMiddlewareBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/solid/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes-middleware/solid/speed.bench.ts index 77d58e7b19..7e6fac4bbe 100644 --- a/benchmarks/ssr/scenarios/server-routes-middleware/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-routes-middleware/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerRouteMiddlewareResponse, runServerRouteMiddlewareLoop, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertServerRouteMiddlewareResponse(handler) -test('ssr', async ({ bench }) => { - await bench('ssr server-route middleware (solid)', async () => - runServerRouteMiddlewareLoop(handler), - ).run(serverRouteMiddlewareBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-route middleware (solid)', + () => runServerRouteMiddlewareLoop(handler), + serverRouteMiddlewareBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/vue/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes-middleware/vue/speed.bench.ts index 3d03b9c1fa..e67ca0a420 100644 --- a/benchmarks/ssr/scenarios/server-routes-middleware/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-routes-middleware/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerRouteMiddlewareResponse, runServerRouteMiddlewareLoop, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertServerRouteMiddlewareResponse(handler) -test('ssr', async ({ bench }) => { - await bench('ssr server-route middleware (vue)', async () => - runServerRouteMiddlewareLoop(handler), - ).run(serverRouteMiddlewareBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-route middleware (vue)', + () => runServerRouteMiddlewareLoop(handler), + serverRouteMiddlewareBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-routes/react/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes/react/speed.bench.ts index 631314148a..1bdb7946b2 100644 --- a/benchmarks/ssr/scenarios/server-routes/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-routes/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerRouteResponse, runServerRouteLoop, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertServerRouteResponse(handler) -test('ssr', async ({ bench }) => { - await bench('ssr server-route (react)', async () => - runServerRouteLoop(handler), - ).run(serverRouteBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-route (react)', + () => runServerRouteLoop(handler), + serverRouteBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-routes/solid/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes/solid/speed.bench.ts index 4788d31854..ce3e1f8a21 100644 --- a/benchmarks/ssr/scenarios/server-routes/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-routes/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerRouteResponse, runServerRouteLoop, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertServerRouteResponse(handler) -test('ssr', async ({ bench }) => { - await bench('ssr server-route (solid)', async () => - runServerRouteLoop(handler), - ).run(serverRouteBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-route (solid)', + () => runServerRouteLoop(handler), + serverRouteBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-routes/vue/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes/vue/speed.bench.ts index 09c0bbe90b..f2b9e27acb 100644 --- a/benchmarks/ssr/scenarios/server-routes/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-routes/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerRouteResponse, runServerRouteLoop, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertServerRouteResponse(handler) -test('ssr', async ({ bench }) => { - await bench('ssr server-route (vue)', async () => - runServerRouteLoop(handler), - ).run(serverRouteBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-route (vue)', + () => runServerRouteLoop(handler), + serverRouteBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/streaming/react/speed.bench.ts b/benchmarks/ssr/scenarios/streaming/react/speed.bench.ts index eb4c9dc1d6..c1dbf38ae5 100644 --- a/benchmarks/ssr/scenarios/streaming/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/streaming/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertStreamingSanity, benchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertStreamingSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr streaming deferred (react)', async () => - runStreamingLoop(handler), - ).run(benchOptions) +describe('ssr', () => { + bench( + 'ssr streaming deferred (react)', + () => runStreamingLoop(handler), + benchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/streaming/solid/speed.bench.ts b/benchmarks/ssr/scenarios/streaming/solid/speed.bench.ts index 19d5817d32..0828715220 100644 --- a/benchmarks/ssr/scenarios/streaming/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/streaming/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertStreamingSanity, benchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertStreamingSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr streaming deferred (solid)', async () => - runStreamingLoop(handler), - ).run(benchOptions) +describe('ssr', () => { + bench( + 'ssr streaming deferred (solid)', + () => runStreamingLoop(handler), + benchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/streaming/vue/speed.bench.ts b/benchmarks/ssr/scenarios/streaming/vue/speed.bench.ts index 42473fc694..a484f95d6a 100644 --- a/benchmarks/ssr/scenarios/streaming/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/streaming/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertStreamingSanity, benchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertStreamingSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr streaming deferred (vue)', async () => - runStreamingLoop(handler), - ).run(benchOptions) +describe('ssr', () => { + bench( + 'ssr streaming deferred (vue)', + () => runStreamingLoop(handler), + benchOptions, + ) }) diff --git a/benchmarks/ssr/solid/speed.bench.ts b/benchmarks/ssr/solid/speed.bench.ts index 2f72977612..0c4317415d 100644 --- a/benchmarks/ssr/solid/speed.bench.ts +++ b/benchmarks/ssr/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { runSsrRequestLoop } from '../bench-utils' import type { StartRequestHandler } from '../bench-utils' @@ -11,12 +11,14 @@ const { default: handler } = (await import( default: StartRequestHandler } -test('ssr', async ({ bench }) => { - await bench('ssr request loop (solid)', async () => - runSsrRequestLoop(handler, { seed: benchmarkSeed }), - ).run({ - warmupIterations: 100, - time: 10_000, - throws: true, - }) +describe('ssr', () => { + bench( + 'ssr request loop (solid)', + () => runSsrRequestLoop(handler, { seed: benchmarkSeed }), + { + warmupIterations: 100, + time: 10_000, + throws: true, + }, + ) }) diff --git a/benchmarks/ssr/vue/speed.bench.ts b/benchmarks/ssr/vue/speed.bench.ts index 57b59e0504..849f042e3c 100644 --- a/benchmarks/ssr/vue/speed.bench.ts +++ b/benchmarks/ssr/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { runSsrRequestLoop } from '../bench-utils' import type { StartRequestHandler } from '../bench-utils' @@ -11,12 +11,14 @@ const { default: handler } = (await import( default: StartRequestHandler } -test('ssr', async ({ bench }) => { - await bench('ssr request loop (vue)', async () => - runSsrRequestLoop(handler, { seed: benchmarkSeed }), - ).run({ - warmupIterations: 100, - time: 10_000, - throws: true, - }) +describe('ssr', () => { + bench( + 'ssr request loop (vue)', + () => runSsrRequestLoop(handler, { seed: benchmarkSeed }), + { + warmupIterations: 100, + time: 10_000, + throws: true, + }, + ) }) diff --git a/docs/AGENTS.md b/docs/AGENTS.md deleted file mode 100644 index ab2d4117e2..0000000000 --- a/docs/AGENTS.md +++ /dev/null @@ -1,4 +0,0 @@ -# Documentation - -- Register new published pages in `router/config.json` or `start/config.json`; drafts need not be registered. -- Run `pnpm test:docs` from the repository root for Markdown link validation. It checks `docs/**/*.md`, not Markdown elsewhere. Relative links resolve from the containing file. diff --git a/docs/router/api/file-based-routing.md b/docs/router/api/file-based-routing.md index 7c94d484d1..ad3e07fad7 100644 --- a/docs/router/api/file-based-routing.md +++ b/docs/router/api/file-based-routing.md @@ -188,7 +188,7 @@ By default, this value is set to `false`. ### `autoCodeSplitting` -This feature is only available if you are using the TanStack Router Bundler Plugin with Vite, Rspack/Rsbuild or Webpack. With Esbuild, setting it to `true` is an error. +This feature is only available if you are using the TanStack Router Bundler Plugin. This option is used to enable automatic code-splitting for non-critical route configuration items. See the "Automatic Code-Splitting" guide for more information. diff --git a/docs/router/api/router/RouteOptionsType.md b/docs/router/api/router/RouteOptionsType.md index 2adfc6e5c6..41d9e575c9 100644 --- a/docs/router/api/router/RouteOptionsType.md +++ b/docs/router/api/router/RouteOptionsType.md @@ -280,22 +280,18 @@ type loaderDeps = (opts: { search: TFullSearchSchema }) => Record - Type: `(match: RouteMatch) => void` - Optional - A function that will be called when a route is matched and loaded after not being matched in the previous location. -- Routes below an error or not-found boundary do not enter the active route lifecycle. The boundary itself remains active. A previously hidden route receives `onEnter` when a navigation makes it active again. ### `onStay` property - Type: `(match: RouteMatch) => void` - Optional - A function that will be called when a route is matched and loaded after being matched in the previous location. -- Both navigations must include the route in the active branch, through the first error or not-found boundary. ### `onLeave` property - Type: `(match: RouteMatch) => void` - Optional - A function that will be called when a route is no longer matched after being matched in the previous location. -- This also runs when a navigation hides a previously active route below an error or not-found boundary, even if the route remains structurally matched. -- Background reloads update route data without dispatching these lifecycle callbacks. ### `onCatch` property diff --git a/docs/router/api/router/RouterEventsType.md b/docs/router/api/router/RouterEventsType.md index c27887fba1..c79bb47f81 100644 --- a/docs/router/api/router/RouterEventsType.md +++ b/docs/router/api/router/RouterEventsType.md @@ -47,6 +47,9 @@ type RouterEvents = { hrefChanged: boolean hashChanged: boolean } + onInjectedHtml: { + type: 'onInjectedHtml' + } onRendered: { type: 'onRendered' fromLocation?: ParsedLocation @@ -64,7 +67,7 @@ Once an event is emitted, the following properties will be present on the event ### `type` property -- Type: `onBeforeNavigate | onBeforeLoad | onLoad | onBeforeRouteMount | onResolved | onRendered` +- Type: `onBeforeNavigate | onBeforeLoad | onLoad | onBeforeRouteMount | onResolved | onRendered | onInjectedHtml` - The type of the event - This is useful for discriminating between events in a listener function. diff --git a/docs/router/api/router/RouterOptionsType.md b/docs/router/api/router/RouterOptionsType.md index 31f410b208..7a52e62241 100644 --- a/docs/router/api/router/RouterOptionsType.md +++ b/docs/router/api/router/RouterOptionsType.md @@ -223,13 +223,6 @@ const router = createRouter({ - Defaults to `/` - The basepath for the entire router. This is useful for mounting a router instance at a subpath. -### `origin` property - -- Type: `string` -- Optional -- The origin used to resolve URLs. Defaults to the browser origin, or `http://localhost` on the server and in browsers with an opaque origin. -- Pass a normalized origin, such as `https://example.com` or `http://localhost:3000`, without a path or trailing slash. The router uses this value as provided; if you have a full URL, normalize it with `new URL(url).origin` before passing it to the router. - ### `rewrite` property - Type: `LocationRewrite` @@ -375,10 +368,9 @@ const router = createRouter({ ### `pathParamsAllowedCharacters` property -- Type: `ReadonlyArray<';' | ':' | '@' | '&' | '=' | '+' | '$' | ','>` +- Type: `Array<';' | ':' | '@' | '&' | '=' | '+' | '$' | ','>` - Optional - Configures which URI characters are allowed in path params that would ordinarily be escaped by encodeURIComponent. -- Read only when the router is created. To change these characters, create a new router instance. Router option updates and provider props do not change this setting. ### `defaultStructuralSharing` property diff --git a/docs/router/api/router/RouterType.md b/docs/router/api/router/RouterType.md index 3fde90e32e..cf8fdebeae 100644 --- a/docs/router/api/router/RouterType.md +++ b/docs/router/api/router/RouterType.md @@ -11,9 +11,8 @@ An instance of the `Router` has the following properties and methods: ### `.update` method -- Type: `(newOptions: Omit) => void` +- Type: `(newOptions: RouterOptions) => void` - Updates the router instance with new options. -- Initialization-only options such as `pathParamsAllowedCharacters` cannot be updated. Create a new router instance to change them. ### `state` property diff --git a/docs/router/api/router/linkComponent.md b/docs/router/api/router/linkComponent.md index 478271a208..a8227913b5 100644 --- a/docs/router/api/router/linkComponent.md +++ b/docs/router/api/router/linkComponent.md @@ -43,7 +43,7 @@ By default, param values with characters such as `@` will be encoded in the URL: ``` -To opt out, set [pathParamsAllowedCharacters](../router/RouterOptionsType#pathparamsallowedcharacters-property) when creating the router. This setting cannot be changed on an existing router instance. +To opt-out, update the [pathParamsAllowedCharacters](../router/RouterOptionsType#pathparamsallowedcharacters-property) config on the router ```tsx import { createRouter } from '@tanstack/react-router' diff --git a/docs/router/eslint/create-route-property-order.md b/docs/router/eslint/create-route-property-order.md index 453fd64acc..c22aa7c52d 100644 --- a/docs/router/eslint/create-route-property-order.md +++ b/docs/router/eslint/create-route-property-order.md @@ -37,10 +37,7 @@ import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/path')({ loader: async ({ context }) => { - await context.queryClient.query({ - ...getQueryOptions(context.hello), - staleTime: 'static', - }) + await context.queryClient.ensureQueryData(getQueryOptions(context.hello)) }, beforeLoad: () => ({ hello: 'world' }), }) @@ -58,10 +55,7 @@ import { createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/path')({ loader: async ({ context }) => { - await context.queryClient.query({ - ...getQueryOptions(context.hello), - staleTime: 'static', - }) + await context.queryClient.ensureQueryData(getQueryOptions(context.hello)) }, beforeLoad: () => ({ hello: 'world' }), }) @@ -86,10 +80,7 @@ import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/path')({ beforeLoad: () => ({ hello: 'world' }), loader: async ({ context }) => { - await context.queryClient.query({ - ...getQueryOptions(context.hello), - staleTime: 'static', - }) + await context.queryClient.ensureQueryData(getQueryOptions(context.hello)) }, }) ``` @@ -107,10 +98,7 @@ import { createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/path')({ beforeLoad: () => ({ hello: 'world' }), loader: async ({ context }) => { - await context.queryClient.query({ - ...getQueryOptions(context.hello), - staleTime: 'static', - }) + await context.queryClient.ensureQueryData(getQueryOptions(context.hello)) }, }) ``` diff --git a/docs/router/guide/automatic-code-splitting.md b/docs/router/guide/automatic-code-splitting.md index 859a19ff09..be599845bc 100644 --- a/docs/router/guide/automatic-code-splitting.md +++ b/docs/router/guide/automatic-code-splitting.md @@ -4,7 +4,7 @@ title: Automatic Code Splitting The automatic code splitting feature in TanStack Router allows you to optimize your application's bundle size by lazily loading route components and their associated data. This is particularly useful for large applications where you want to minimize the initial load time by only loading the necessary code for the current route. -To turn this feature on, simply set the `autoCodeSplitting` option to `true` in your bundler plugin configuration. This enables the router to automatically handle code splitting for your routes without requiring any additional setup. It is available with Vite, Rspack/Rsbuild and Webpack, not with Esbuild. +To turn this feature on, simply set the `autoCodeSplitting` option to `true` in your bundler plugin configuration. This enables the router to automatically handle code splitting for your routes without requiring any additional setup. ```ts // vite.config.ts diff --git a/docs/router/guide/deferred-data-loading.md b/docs/router/guide/deferred-data-loading.md index f378d7adbf..9956542ebd 100644 --- a/docs/router/guide/deferred-data-loading.md +++ b/docs/router/guide/deferred-data-loading.md @@ -90,16 +90,15 @@ So, instead of using `defer` and `Await`, you'll instead want to use the Route's ```tsx // src/routes/posts.$postId.tsx import { createFileRoute } from '@tanstack/react-router' -import { noop } from '@tanstack/react-query' import { slowDataOptions, fastDataOptions } from '~/api/query-options' export const Route = createFileRoute('/posts/$postId')({ loader: async ({ context: { queryClient } }) => { // Kick off the fetching of some slower data, but do not await it - void queryClient.query(slowDataOptions()).catch(noop) + queryClient.prefetchQuery(slowDataOptions()) // Fetch and await some data that resolves quickly - await queryClient.query({ ...fastDataOptions(), staleTime: 'static' }) + await queryClient.ensureQueryData(fastDataOptions()) }, }) ``` @@ -109,16 +108,15 @@ export const Route = createFileRoute('/posts/$postId')({ ```tsx // src/routes/posts.$postId.tsx import { createFileRoute } from '@tanstack/solid-router' -import { noop } from '@tanstack/solid-query' import { slowDataOptions, fastDataOptions } from '~/api/query-options' export const Route = createFileRoute('/posts/$postId')({ loader: async ({ context: { queryClient } }) => { // Kick off the fetching of some slower data, but do not await it - void queryClient.query(slowDataOptions()).catch(noop) + queryClient.prefetchQuery(slowDataOptions()) // Fetch and await some data that resolves quickly - await queryClient.query({ ...fastDataOptions(), staleTime: 'static' }) + await queryClient.ensureQueryData(fastDataOptions()) }, }) ``` diff --git a/docs/router/guide/external-data-loading.md b/docs/router/guide/external-data-loading.md index 4ffb318686..b9265facec 100644 --- a/docs/router/guide/external-data-loading.md +++ b/docs/router/guide/external-data-loading.md @@ -6,8 +6,6 @@ title: External Data Loading > [!IMPORTANT] > This guide is geared towards external state management libraries and their integration with TanStack Router for data fetching, ssr, hydration/dehydration and streaming. If you haven't read the standard [Data Loading](./data-loading.md) guide, please do so first. -Router can coordinate loaders and an existing API without Start. If you also want an integrated server runtime and typed server functions for your React application, follow [TanStack Query with Start](/start/latest/docs/framework/react/guide/tanstack-query) for request-scoped SSR, hydration, and mutation invalidation with a tested example. - ## To **Store** or to **Coordinate**? While Router is very capable of storing and managing most data needs out of the box, sometimes you just might want something more robust! @@ -84,8 +82,7 @@ const postsQueryOptions = queryOptions({ export const Route = createFileRoute('/posts')({ // Use the `loader` option to ensure that the data is loaded - loader: () => - queryClient.query({ ...postsQueryOptions, staleTime: 'static' }), + loader: () => queryClient.ensureQueryData(postsQueryOptions), component: () => { // Read the data from the cache and subscribe to updates const { @@ -109,8 +106,7 @@ When an error occurs while using `suspense` with `TanStack Query`, you need to l ```tsx export const Route = createFileRoute('/')({ - loader: () => - queryClient.query({ ...postsQueryOptions, staleTime: 'static' }), + loader: () => queryClient.ensureQueryData(postsQueryOptions), errorComponent: ({ error, reset }) => { const router = useRouter() const queryErrorResetBoundary = useQueryErrorResetBoundary() diff --git a/docs/router/guide/history-types.md b/docs/router/guide/history-types.md index 0c6a914fb6..9e20736854 100644 --- a/docs/router/guide/history-types.md +++ b/docs/router/guide/history-types.md @@ -9,7 +9,6 @@ If you don't create a history instance, a browser-oriented instance of this API - `createBrowserHistory`: The default history type. - `createHashHistory`: A history type that uses a hash to track history. - `createMemoryHistory`: A history type that keeps the history in memory. -- `createServerHistory`: A history type with a fixed request URL and no-op navigation, used by the SSR request handlers. Once you have a history instance, you can pass it to the `Router` constructor: diff --git a/docs/router/guide/path-params.md b/docs/router/guide/path-params.md index d326eabb4b..7ebaaad19e 100644 --- a/docs/router/guide/path-params.md +++ b/docs/router/guide/path-params.md @@ -1395,8 +1395,6 @@ const router = createRouter({ }) ``` -This setting is fixed when the router is created. To use different allowed characters, create a new router instance. - The following is the list of accepted allowed characters: - `;` diff --git a/docs/router/guide/router-context.md b/docs/router/guide/router-context.md index 347082106f..5fc4001010 100644 --- a/docs/router/guide/router-context.md +++ b/docs/router/guide/router-context.md @@ -278,10 +278,9 @@ Then, in your route: export const Route = createFileRoute('/todos')({ component: Todos, loader: async ({ context }) => { - await context.queryClient.query({ + await context.queryClient.ensureQueryData({ queryKey: ['todos', { userId: user.id }], queryFn: fetchTodos, - staleTime: 'static', }) }, }) diff --git a/docs/router/guide/ssr.md b/docs/router/guide/ssr.md index 46a0941e7c..f87849f8a1 100644 --- a/docs/router/guide/ssr.md +++ b/docs/router/guide/ssr.md @@ -60,9 +60,7 @@ To implement non-streaming SSR with TanStack Router, you will need the following ### Automatic Server History -On the client, Router defaults to using an instance of `createBrowserHistory`. On the server, the Router SSR request handler and TanStack Start automatically create a lightweight history containing only the request URL. This history does not keep a navigation stack or respond to `push`, `replace`, `go`, `back`, or `forward` calls. - -Server-side calls to `router.navigate()` and `router.commitLocation()` are also no-ops: their promises resolve without changing the request location or running another load. To redirect a request, use the dedicated [redirect API](../api/router/redirectFunction.md), such as `throw redirect({ to: '/login' })` in `beforeLoad` or a loader. +On the client, Router defaults to using an instance of `createBrowserHistory`, which is the preferred type of history to use on the client. On the server, however, you will want to use an instance of `createMemoryHistory` instead. This is because `createBrowserHistory` uses the `window` object, which does not exist on the server. This is handled automatically for you in the RouterServer component. ### Automatic Loader Dehydration/Hydration @@ -158,8 +156,6 @@ export async function render({ request }: { request: Request }) { using `renderRouterToString` -React and Solid use their native synchronous string renderers. Suspended components render their Suspense fallback without waiting for the component to resolve. The router still finishes serializing hydration data before returning the response. Use `renderRouterToStream` when you need the server to render suspended content after it resolves. - # React @@ -262,9 +258,6 @@ This pattern can be useful for pages that have slow or high-latency data fetchin > [!NOTE] > This streaming pattern is all automatic as long as you are using either `defaultStreamHandler` or `renderRouterToStream`. -> [!IMPORTANT] -> Render [``](./document-head-management.md#scripts) inside `` of your root route. It emits the route scripts and marks where the router inserts streamed hydration data. Without it the response still completes, but the page cannot hydrate. - using `defaultStreamHandler` diff --git a/docs/router/guide/type-safety.md b/docs/router/guide/type-safety.md index 3faaed79e7..2adffc58c5 100644 --- a/docs/router/guide/type-safety.md +++ b/docs/router/guide/type-safety.md @@ -137,13 +137,12 @@ As your application scales, TypeScript check times will naturally increase. Ther ### Only infer types you need -A great pattern with client side data caches (TanStack Query, etc.) is to prefetch data. For example with TanStack Query you might have a route which calls `queryClient.query` in a `loader`. +A great pattern with client side data caches (TanStack Query, etc.) is to prefetch data. For example with TanStack Query you might have a route which calls `queryClient.ensureQueryData` in a `loader`. ```tsx export const Route = createFileRoute('/posts/$postId/deep')({ - // (ctx: LoaderFnContext) => Promise loader: ({ context: { queryClient }, params: { postId } }) => - queryClient.query({ ...postQueryOptions(postId), staleTime: 'static' }), + queryClient.ensureQueryData(postQueryOptions(postId)), component: PostDeepComponent, }) @@ -155,16 +154,12 @@ function PostDeepComponent() { } ``` -This may look fine and for small route trees and you may not notice any TS performance issues. However in this case TS has to infer the loader's return type, despite it never being used in your route. If the loader data is a complex type with many routes that prefetch in this manner, it can slow down editor performance. In this case, the change is quite simple and let typescript infer `Promise`. +This may look fine and for small route trees and you may not notice any TS performance issues. However in this case TS has to infer the loader's return type, despite it never being used in your route. If the loader data is a complex type with many routes that prefetch in this manner, it can slow down editor performance. In this case, the change is quite simple and let typescript infer Promise. ```tsx export const Route = createFileRoute('/posts/$postId/deep')({ - // (ctx: LoaderFnContext) => Promise loader: async ({ context: { queryClient }, params: { postId } }) => { - await queryClient.query({ - ...postQueryOptions(postId), - staleTime: 'static', - }) + await queryClient.ensureQueryData(postQueryOptions(postId)) }, component: PostDeepComponent, }) diff --git a/docs/router/guide/url-rewrites.md b/docs/router/guide/url-rewrites.md index e780e01781..7bc3df8545 100644 --- a/docs/router/guide/url-rewrites.md +++ b/docs/router/guide/url-rewrites.md @@ -343,8 +343,6 @@ const navigate = useNavigate() navigate({ to: '/about' }) ``` -When the final output URL has a different origin, programmatic navigation performs a full page load automatically. You do not need to set `reloadDocument: true` for cross-origin rewrites. If a route mask is applied, its output URL determines whether navigation stays on the current origin. - ### Hard Links for Cross-Origin Rewrites When an output rewrite changes the origin (hostname), the `` component automatically renders a standard anchor tag instead of using client-side navigation: diff --git a/docs/router/how-to/setup-testing.md b/docs/router/how-to/setup-testing.md index 104cbedc0d..48afa122f4 100644 --- a/docs/router/how-to/setup-testing.md +++ b/docs/router/how-to/setup-testing.md @@ -659,10 +659,9 @@ describe('React Query Integration', () => { path: '/posts', component: PostsList, loader: ({ context: { queryClient } }) => - queryClient.query({ + queryClient.ensureQueryData({ queryKey: ['posts'], queryFn: mockFetchPosts, - staleTime: 'static', }), }) diff --git a/docs/router/how-to/share-search-params-across-routes.md b/docs/router/how-to/share-search-params-across-routes.md index 23a202b176..e1e24c1e0d 100644 --- a/docs/router/how-to/share-search-params-across-routes.md +++ b/docs/router/how-to/share-search-params-across-routes.md @@ -2,6 +2,8 @@ title: Share Search Parameters Across Routes --- +# How to Share Search Parameters Across Routes + Search parameters automatically inherit from parent routes in TanStack Router. When a parent route validates search parameters, child routes can access them via `Route.useSearch()` alongside their own parameters. ## How Parameter Inheritance Works diff --git a/docs/router/installation/with-esbuild.md b/docs/router/installation/with-esbuild.md index 8ecd9b8d0a..b5cad0622c 100644 --- a/docs/router/installation/with-esbuild.md +++ b/docs/router/installation/with-esbuild.md @@ -25,6 +25,7 @@ export default { plugins: [ tanstackRouter({ target: 'react', + autoCodeSplitting: true, }), ], } @@ -49,7 +50,10 @@ const ctx = await esbuild.context({ format: 'esm', target: ['esnext'], sourcemap: true, - plugins: [solidPlugin(), tanstackRouter({ target: 'solid' })], + plugins: [ + solidPlugin(), + tanstackRouter({ target: 'solid', autoCodeSplitting: true }), + ], }) if (isDev) { @@ -68,9 +72,6 @@ Or, you can clone our [Quickstart Esbuild example](https://github.com/TanStack/r Now that you've added the plugin to your Esbuild configuration, you're all set to start using file-based routing with TanStack Router. -> [!NOTE] -> Automatic code splitting is not available with Esbuild: the plugin throws an error when `autoCodeSplitting` is `true`. Route generation works as usual. To split routes, use [manual code splitting](../guide/code-splitting.md) or another bundler. - ## Ignoring the generated route tree file If your project is configured to use a linter and/or formatter, you may want to ignore the generated route tree file. This file is managed by TanStack Router and therefore shouldn't be changed by your linter or formatter. diff --git a/docs/router/integrations/query.md b/docs/router/integrations/query.md index 707f90900c..fd174187b5 100644 --- a/docs/router/integrations/query.md +++ b/docs/router/integrations/query.md @@ -152,7 +152,7 @@ Preload critical data in the route `loader` to avoid waterfalls and loading flas -# Blocking `query` in loader +# React ```tsx title="src/routes/posts.tsx" import { queryOptions, useSuspenseQuery, useQuery } from '@tanstack/react-query' @@ -165,12 +165,7 @@ const postsQuery = queryOptions({ export const Route = createFileRoute('/posts')({ // Ensure the data is in the cache before render - loader: ({ context }) => - context.queryClient.query({ - ...postsQuery, - // returns data from cache immediately, otherwise executes a fetch - staleTime: 'static', - }), + loader: ({ context }) => context.queryClient.ensureQueryData(postsQuery), component: PostsPage, }) @@ -185,15 +180,15 @@ function PostsPage() { ### Prefetching and streaming -You can also prefetch with `query` in a loader without consuming the data in a component. If you return the promise directly from the loader, it will be awaited and thus block the SSR request until the query finishes. If you don't await the promise nor return it, the query will be started on the server and will be streamed to the client without blocking the SSR request. +You can also prefetch with `fetchQuery` or `ensureQueryData` in a loader without consuming the data in a component. If you return the promise directly from the loader, it will be awaited and thus block the SSR request until the query finishes. If you don't await the promise nor return it, the query will be started on the server and will be streamed to the client without blocking the SSR request. -# Non-blocking `query` in loader +# React ```tsx title="src/routes/users.$id.tsx" import { createFileRoute } from '@tanstack/react-router' -import { noop, queryOptions, useQuery } from '@tanstack/react-query' +import { queryOptions, useQuery } from '@tanstack/react-query' const userQuery = (id: string) => queryOptions({ @@ -202,18 +197,15 @@ const userQuery = (id: string) => }) export const Route = createFileRoute('/user/$id')({ - loader: ({ context, params }) => { - // Do not await this nor return the promise, just kick off the query to stream it to the client - void context.queryClient.query(userQuery(params.id)).catch(noop) + loader: ({ params }) => { + // do not await this nor return the promise, just kick off the query to stream it to the client + context.queryClient.fetchQuery(userQuery(params.id)) }, }) ``` -> [!NOTE] -> Previous versions of this guide used `queryClient.ensureQueryData` and `queryClient.prefetchQuery`. These methods are now deprecated in TanStack Query in favor of `queryClient.query`. See the TanStack Query [v5 migration guide](https://tanstack.com/query/latest/docs/framework/react/guides/migrating-to-v5#imperative-queryclient-methods) for more details. - ## Redirect handling If a query or mutation throws a `redirect(...)`, the integration intercepts it on the client and performs a router navigation. diff --git a/docs/start/config.json b/docs/start/config.json index 36af0e6e0d..57703aad89 100644 --- a/docs/start/config.json +++ b/docs/start/config.json @@ -36,10 +36,6 @@ { "label": "Migrate from Next.js", "to": "framework/react/migrate-from-next-js" - }, - { - "label": "Migrate from the Release Candidate", - "to": "framework/react/migrate-from-release-candidate" } ] }, @@ -57,10 +53,6 @@ { "label": "Build from Scratch", "to": "framework/solid/build-from-scratch" - }, - { - "label": "Migrate from the Release Candidate", - "to": "framework/solid/migrate-from-release-candidate" } ] } @@ -284,10 +276,6 @@ { "label": "react", "children": [ - { - "label": "Production Checklist", - "to": "framework/react/guide/production-checklist" - }, { "label": "Hosting", "to": "framework/react/guide/hosting" @@ -322,7 +310,7 @@ "label": "react", "children": [ { - "label": "Choose Authentication", + "label": "Authentication Overview", "to": "framework/react/guide/authentication-overview" }, { @@ -330,16 +318,12 @@ "to": "framework/react/guide/authentication-server-primitives" }, { - "label": "Implement Authentication", + "label": "Authentication", "to": "framework/react/guide/authentication" }, { "label": "Databases", "to": "framework/react/guide/databases" - }, - { - "label": "TanStack Query", - "to": "framework/react/guide/tanstack-query" } ] }, @@ -347,7 +331,7 @@ "label": "solid", "children": [ { - "label": "Choose Authentication", + "label": "Authentication Overview", "to": "framework/solid/guide/authentication-overview" }, { @@ -355,7 +339,7 @@ "to": "framework/solid/guide/authentication-server-primitives" }, { - "label": "Implement Authentication", + "label": "Authentication", "to": "framework/solid/guide/authentication" }, { diff --git a/docs/start/framework/react/comparison.md b/docs/start/framework/react/comparison.md index b72e286a76..5c39e0f602 100644 --- a/docs/start/framework/react/comparison.md +++ b/docs/start/framework/react/comparison.md @@ -1,61 +1,338 @@ --- title: Comparison | TanStack Start vs Next.js vs React Router -description: Compare rendering, server APIs, caching, forms, and deployment in TanStack Start, Next.js App Router, and React Router Framework Mode. toc: false --- -This matrix compares full-stack framework capabilities. For the choice between Start and Next.js, read [TanStack Start vs Next.js](./start-vs-nextjs). For navigation and URL-state APIs, see the [TanStack Router comparison](/router/latest/docs/comparison). +Choosing a full-stack React framework? This comparison focuses on the **full-stack framework features** that distinguish TanStack Start from Next.js and React Router (v7 Framework Mode). -Checked September 11, 2026 against the linked documentation: TanStack Start's current guides, Next.js 16.3 App Router, and React Router 8.3 Framework Mode. +> **🚨 IMPORTANT: Looking for routing features?** +> +> TanStack Start is built on **TanStack Router**, which provides industry-leading type-safe routing capabilities. For a comprehensive comparison of routing features (nested routes, search params, type safety, loaders, etc.), please see: +> +> ### [📖 TanStack Router Comparison vs React Router / Next.js →](/router/latest/docs/framework/react/comparison) +> +> That comparison covers all the routing features in detail. This page focuses specifically on **full-stack framework capabilities** like SSR, server functions, middleware, deployment, and more. -## Rendering and data +While we aim to provide an accurate and fair comparison, please note that this table may not capture every nuance or recent update of each framework. We recommend reviewing the official documentation and trying out each solution to make the most informed decision for your specific use case. -| Capability | TanStack Start | Next.js App Router | React Router Framework Mode | -| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | -| Server rendering | [SSR with hydration by default](./overview) | [Server and Client Components contribute to initial HTML](https://nextjs.org/docs/app/getting-started/server-and-client-components) | [Server rendering is configurable](https://reactrouter.com/start/framework/rendering) | -| Rendering control | [Per-route full, data-only, or disabled SSR](./guide/selective-ssr) | [Server/Client Component boundaries](https://nextjs.org/docs/app/getting-started/server-and-client-components); `use client` does not disable initial SSR | [Global SSR setting and route-level client loaders](https://reactrouter.com/start/framework/rendering) | -| SPA applications | [Dedicated SPA mode](./guide/spa-mode) | [Documented SPA patterns](https://nextjs.org/docs/app/guides/single-page-applications) | [`ssr: false`](https://reactrouter.com/start/framework/rendering) | -| Static output | [Prerendering configuration](./guide/static-prerendering) | [Static export](https://nextjs.org/docs/app/guides/static-exports), with server-feature limitations | [Prerender selected URLs](https://reactrouter.com/start/framework/rendering) | -| React Server Components | [Experimental, opt-in](./guide/server-components) | [Core App Router component model](https://nextjs.org/docs/app/getting-started/server-and-client-components) | [Unstable RSC integration](https://reactrouter.com/how-to/react-server-components) | -| Client data reuse | [Router loader caching](/router/latest/docs/guide/data-loading), plus [Query integration](/router/latest/docs/integrations/query) | [Navigation caching and server cache APIs](https://nextjs.org/docs/app/getting-started/caching); a query library can manage additional client data | [Loader/action revalidation](https://reactrouter.com/start/framework/actions); separate client-data tools can be added | -| Revalidation after deployment | [HTTP caching and provider-specific ISR configuration](./guide/isr) | [ISR and cache coordination](https://nextjs.org/docs/app/guides/self-hosting) | [HTTP response headers](https://reactrouter.com/how-to/headers) and deployment infrastructure | +If you find any discrepancies or have suggestions for improvement, please don't hesitate to contribute via the "Edit this page on GitHub" link at the bottom of this page or open an issue in the [TanStack Router GitHub repository](https://github.com/TanStack/router). -A client loader cache, a cached server result, and a cached HTML response are different things. Compare invalidation behavior, persistence, and multi-instance coordination for the layer your application needs. A CDN honoring `stale-while-revalidate` is not proof of identical ISR behavior across providers. +Feature/Capability Key: -## Server APIs and forms +- ✅ 1st-class, built-in, and ready to use with no added configuration or code +- 🟡 Partial Support (rated 1-5 where noted) +- 🟠 Supported via addon/community package +- 🔶 Possible, but requires custom code/implementation/casting +- 🛑 Not officially supported -| Capability | TanStack Start | Next.js App Router | React Router Framework Mode | -| -------------------------- | -------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | -| Server calls and mutations | [Typed server functions with GET or POST](./guide/server-functions) | [Server Actions](https://nextjs.org/docs/app/guides/forms) | [Route actions and fetchers](https://reactrouter.com/start/framework/actions) | -| Input validation | [Validator API with inferred types](./guide/server-functions) | [Validate action input with application code or a schema](https://nextjs.org/docs/app/guides/forms) | [Validate action input with application code](https://reactrouter.com/how-to/form-validation) | -| Middleware | [Request middleware and client/server function middleware](./guide/middleware) | [Request interception with Proxy](https://nextjs.org/docs/app/getting-started/proxy); action authorization belongs in server code | [Server and client route middleware](https://reactrouter.com/how-to/middleware) | -| Form handling | [Server functions](./guide/server-functions) can be called from event handlers; use a form library when needed | [Built-in `next/form`](https://nextjs.org/docs/app/api-reference/components/form), plus [Server Action forms](https://nextjs.org/docs/app/guides/forms) | [`Form`, actions, and fetchers](https://reactrouter.com/start/framework/actions) | -| Server endpoints | [Server routes](./guide/server-routes) | [Route Handlers](https://nextjs.org/docs/app/getting-started/route-handlers) | [Resource routes](https://reactrouter.com/how-to/resource-routes) | +| | TanStack Start | Next.js [_(Website)_][nextjs] | React Router [_(Website)_][react-router] | +| ----------------------------------------------------------------- | ------------------------------------------------ | --------------------------------------------- | ------------------------------------------ | +| Github Repo / Stars | [![][stars-tanstack-router]][gh-tanstack-router] | [![][stars-nextjs]][gh-nextjs] | [![][stars-react-router]][gh-react-router] | +| Bundle Size | [![][bp-tanstack-router]][bpl-tanstack-router] | ❓ | ❓ | +| -- | -- | -- | -- | +| **Routing Features** [_(See Full Comparison)_][router-comparison] | ✅ Built on TanStack Router | ✅ File-based App Router | ✅ File-based Nested Routes | +| -- | -- | -- | -- | +| **Full-Stack Features** | -- | -- | -- | +| SSR | ✅ | ✅ | ✅ | +| Streaming SSR | ✅ | ✅ | ✅ | +| Selective SSR (per-route) | ✅ | 🔶 | 🔶 | +| SPA Mode | ✅ | 🔶 (via "use client") | ✅ | +| Built-in Client-Side SWR Caching | ✅ (via TanStack Router) | 🔶 (fetch cache only) | 🛑 | +| Data Fetching Library Integration | ✅ (Official TanStack Query, Apollo, etc.) | 🔶 (manual integration) | 🔶 (manual integration) | +| Static Prerendering (SSG) | ✅ | ✅ | ✅ | +| Incremental Static Regeneration (ISR) | ✅ (via Cache-Control headers) | ✅ (Proprietary) | ✅ (via Cache-Control headers) | +| React Server Components | 🟡 (Experimental) | ✅ | 🟡 (Experimental) | +| Server Functions | ✅ (RPC-based) | ✅ (Server Actions) | ✅ (Actions) | +| Server Function Client Middleware | ✅ | 🛑 | 🛑 | +| Server Function Server Middleware | ✅ | 🛑 | ✅ | +| Request Middleware (All Routes) | ✅ | ✅ | ✅ | +| Server Function Input Validation | ✅ | 🔶 (manual) | 🔶 (manual) | +| API Routes / Server Routes / Resource Routes | ✅ | ✅ | ✅ | +| `
` API | 🛑 | 🟠 (via React 19 useActionState) | ✅ | +| -- | -- | -- | -- | +| **Developer Experience** | -- | -- | -- | +| Devtools | ✅ | 🛑 | 🟠 (3rd party) | +| CLI Tooling | ✅ | ✅ | ✅ | +| Dev Server Startup Speed | ✅ (Fast) | 🛑 (Slow) | ✅ (Fast) | +| HMR Speed | ✅ (Fast, Vite or Rsbuild) | 🛑 (Slow, Webpack/Turbopack) | ✅ (Fast, Vite) | +| Dev Navigation Speed | ✅ | 🟡 | ✅ | +| Dev Resource Usage (CPU/RAM) | ✅ (Lightweight) | 🛑 (Heavy) | ✅ (Lightweight) | +| TypeScript Support | ✅ | ✅ | ✅ | +| Type-First Architecture | ✅ | 🛑 | 🛑 | +| -- | -- | -- | -- | +| **Deployment & Hosting** | -- | -- | -- | +| Deployment Flexibility | ✅ (Vite and Rsbuild builds) | 🟡 (Optimized for Vercel, possible elsewhere) | ✅ (Multiple adapters) | +| Edge Runtime Support | ✅ | ✅ | ✅ | +| Serverless Support | ✅ | ✅ | ✅ | +| Node.js Support | ✅ | ✅ | ✅ | +| Docker Support | ✅ | ✅ | ✅ | +| Static Export | ✅ | ✅ | ✅ | +| Official Cloudflare Support | ✅ | 🟡 | ✅ | +| Official Netlify Support | ✅ | 🟡 | ✅ | +| Official Vercel Support | ✅ (via Nitro) | ✅ | ✅ | -Type inference helps callers write valid code. It does not validate an incoming HTTP request or authorize access to a record. All three frameworks need runtime validation and server-side authorization for private operations. For Start, see [Authentication Server Primitives](./guide/authentication-server-primitives). +--- -## Tooling and deployment +> **⚠️ Remember:** For detailed comparisons of **routing features** (type safety, search params, loaders, navigation, etc.), see the [**TanStack Router Comparison**][router-comparison]. This page focuses on full-stack framework capabilities. -| Capability | TanStack Start | Next.js App Router | React Router Framework Mode | -| ----------------------- | ------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | -| Build integration | [Vite or Rsbuild](./build-from-scratch) | [Turbopack](https://nextjs.org/docs/app/api-reference/turbopack) | [Framework tooling](https://reactrouter.com/start/framework/installation) | -| Type support | [Router inference](/router/latest/docs/guide/type-safety) and [server function inference](./guide/server-functions) | [Stable opt-in typed links](https://nextjs.org/docs/app/api-reference/config/next-config-js/typedRoutes) and TypeScript APIs | [Generated route-module types](https://reactrouter.com/how-to/route-module-type-safety) | -| Metadata | [Route head management and SEO guide](./guide/seo) | [Metadata API and file conventions](https://nextjs.org/docs/app/getting-started/metadata-and-og-images) | [Route-module metadata](https://reactrouter.com/start/framework/route-module) | -| Image and font handling | Choose CSS, an image service, or an integration for your deployment | Built-in [`next/image`](https://nextjs.org/docs/app/api-reference/components/image) and [`next/font`](https://nextjs.org/docs/app/api-reference/components/font) | Choose CSS, an image service, or an integration for your deployment | -| Hosting | [Provider and runtime guides](./guide/hosting) | [Self-hosting](https://nextjs.org/docs/app/guides/self-hosting) or a deployment provider | [Deployment templates and hosting options](https://reactrouter.com/start/framework/deploying) | +--- -Deployment support depends on the adapter, runtime, and features you use. Check streaming, image processing, filesystem access, background work, and shared-cache behavior on your chosen target. Next.js self-hosting includes image optimization and ISR configuration; those features should not be labeled Vercel-only. +## Key Philosophical Differences -## Performance Considerations +### TanStack Start -This page does not establish a performance winner. Startup time, HMR, memory use, JavaScript shipped, and response latency require separate measurements. Comparing a router package's bundle size with an entire framework is not a valid application benchmark. +**Philosophy**: Maximum developer freedom with best-in-class type safety. -For a useful comparison, build the same representative application with recommended patterns in each framework. Record package versions, hardware, dependencies, route count, rendering and caching settings, deployment target, warm and cold runs, and the raw results. +- **Router-First**: Built on TanStack Router (see [full routing comparison][router-comparison]) +- **Deployment Agnostic**: Built on Vite and Rsbuild integrations, deploy without vendor lock-in +- **Composable Middleware**: Middleware system works at both the request level AND individual server function level (both client & server) +- **Selective SSR**: Fine-grained control over SSR behavior per route (full SSR, data-only, or client-only) +- **Developer Control**: Explicit, composable patterns over convention-based magic +- **Type Safety First**: End-to-end compile-time safety for server functions, loaders, and routing + +### Next.js + +**Philosophy**: Production-ready with optimal defaults, best with Vercel. + +- **RSC-First**: Deep integration with React Server Components as the primary paradigm +- **Vercel-Optimized**: Best performance and DX on Vercel's infrastructure +- **Convention over Configuration**: Opinionated structure with file-system routing conventions +- **Automatic Optimizations**: Many performance optimizations happen automatically +- **Production Grade**: Battle-tested at massive scale + +### React Router (v7 Framework Mode) + +**Philosophy**: Web fundamentals with progressive enhancement. + +- **Web Standards**: Embraces web platform primitives (fetch, FormData, Headers) +- **Progressive Enhancement**: Works without JavaScript by default +- **Nested Routes**: First-class support for nested routing and data loading +- **Action-Based**: Form submissions via actions follow web standards +- **Framework Evolution**: Successor to Remix, with Vite-based architecture ## When to Choose Each Framework -- **TanStack Start:** you want typed route context and URL state, explicit loaders and server functions, and control over per-route rendering. -- **Next.js:** you want its Server Component model and integrated image, font, metadata, and form facilities. Existing team experience and integrations can also make staying with Next.js the better choice. -- **React Router Framework Mode:** you want route loaders and actions, fetchers, and form-driven workflows. Read its [progressive enhancement guide](https://reactrouter.com/explanation/progressive-enhancement) if operation before JavaScript loads matters to your application. +### Choose TanStack Start if you: -Check Start's [overview](./overview) and [Server Components guide](./guide/server-components) for current release and experimental-feature status before adopting those features. To try Start, use [Getting Started](./getting-started) or [Migrate from Next.js](./migrate-from-next-js). +- Want the absolute best type safety for routing (see [Router Comparison][router-comparison]) +- Need deployment flexibility without vendor lock-in (works with Vite and Rsbuild builds) +- Prefer composable, explicit patterns over convention +- Want fine-grained control over SSR behavior (selective SSR per route) +- Need composable middleware that works at both request and server function levels +- Are building a complex application that benefits from TanStack Router's advanced features +- Already use TanStack Query or other TanStack libraries + +### Choose Next.js if you: + +- Want to use React Server Components today with full ecosystem support +- Are deploying to Vercel or want a Vercel-optimized experience +- Prefer convention over configuration for faster initial development +- Want automatic image optimization and font loading + +### Choose React Router if you: + +- Prioritize progressive enhancement +- Want your app to work without JavaScript +- Prefer action-based mutations following web conventions + +## Feature Deep Dives + +### Built-in Client-Side Caching + +**TanStack Start** includes powerful built-in SWR (stale-while-revalidate) caching through TanStack Router: + +- **Out-of-the-box performance** - Loader data is automatically cached and revalidated +- **Fine-grained control** - Configure `staleTime`, `gcTime`, and revalidation per route +- **Structural sharing** - Efficient updates that only re-render what changed +- **Official integrations** - Turn-key support for TanStack Query, Apollo, and other data fetching libraries +- **More performant** - Optimized for the user experience with instant navigation and background updates + +```tsx +export const Route = createFileRoute('/posts/$postId')({ + loader: async ({ params }) => fetchPost(params.postId), + staleTime: 10_000, // Consider fresh for 10 seconds + gcTime: 5 * 60_000, // Keep in memory for 5 minutes +}) +``` + +For advanced scenarios, TanStack Start integrates seamlessly with TanStack Query: + +```tsx +import { queryOptions } from '@tanstack/react-query' + +const postQueryOptions = (postId: string) => + queryOptions({ + queryKey: ['post', postId], + queryFn: () => fetchPost(postId), + }) + +export const Route = createFileRoute('/posts/$postId')({ + loader: ({ context, params }) => + context.queryClient.ensureQueryData(postQueryOptions(params.postId)), +}) + +function Post() { + const { postId } = Route.useParams() + const { data } = useQuery(postQueryOptions(postId)) + // Automatically uses cached data from loader +} +``` + +**Next.js** has basic fetch caching but lacks fine-grained control and requires manual integration with libraries like React Query. + +**React Router** doesn't have built-in client-side caching - you need to manually integrate a caching solution. + +### Server Functions vs Server Actions + +**TanStack Start Server Functions**: + +```tsx +export const getTodos = createServerFn({ method: 'GET' }) + .validator(zodValidator(z.object({ userId: z.string() }))) + .middleware([authMiddleware]) + .handler(async ({ data, context }) => { + // Fully typed data and context + return db.todos.findMany({ where: { userId: data.userId } }) + }) + +// Call from anywhere with full type safety +const todos = await getTodos({ data: { userId: '123' } }) +``` + +**Next.js Server Actions**: + +```tsx +'use server' +export async function getTodos(userId: string) { + // Runs on server, called from client + return db.todos.findMany({ where: { userId } }) +} + +// Call from client component +const todos = await getTodos('123') +``` + +Key differences: + +- Start's server functions support both client and server middleware +- Start has built-in input validation +- Start's approach is more explicit about the client/server boundary +- Start's server functions support both GET and POST methods (configurable via the `method` option, defaults to GET), while Next.js Server Actions only support POST. +- Next.js Server Actions integrate more seamlessly with forms + +### Middleware Architecture + +**TanStack Start** has two types of middleware: + +1. **Request Middleware**: Runs for all requests (SSR, API routes, server functions) +2. **Server Function Middleware**: Runs specifically for server functions, supports both client-side and server-side execution + +This composability allows for: + +```tsx +const authMiddleware = createMiddleware({ type: 'function' }) + .client(async ({ next }) => { + // Run auth checks on client + return next({ + headers: { Authorization: `Bearer ${getToken()}` }, + }) + }) + .server(async ({ next }) => { + // Validate auth on server + return next({ context: { user: await getUser() } }) + }) +``` + +**Next.js** has a single proxy.ts file that runs on the Node.js runtime. Unlike the deprecated middleware.ts (which ran on Edge Runtime), proxy.ts has full access to server-side resources like databases. + +### Deployment Flexibility + +**TanStack Start** leverages modern build tool ecosystems: + +- Deploy to Cloudflare Workers, Netlify, Vercel, Railway, Fly.io, AWS, etc. +- Use Nitro for universal deployment support +- No vendor-specific features or lock-in +- Same codebase works everywhere + +**Next.js** is optimized for Vercel: + +- Many features work best or only on Vercel (ISR, Image Optimization, Middleware) +- Self-hosting requires more configuration +- Deployment to other platforms may have limitations + +## React Server Components (RSC) + +**Current Status**: + +- **Next.js**: Full production support with extensive ecosystem +- **TanStack Start**: Experimental support available +- **React Router**: Experimental support available + +TanStack Start's RSC implementation takes a client-led composition approach: server components are treated as data that the client can fetch, cache, and compose. See the [Server Components guide](/start/latest/docs/framework/react/guide/server-components) for details. + +## Performance Considerations + +### Production Performance + +All three frameworks are capable of achieving excellent production performance and top Lighthouse scores. The differences come down to optimization strategies: + +- **TanStack Start**: Optimized bundler builds, SWR caching reduces server load, lightweight runtime +- **Next.js**: Automatic code splitting, image optimization, and built-in performance features +- **React Router**: Web standards-based caching and optimization + +### Development Performance + +This is where the frameworks differ significantly: + +**TanStack Start & React Router:** + +- ⚡ **Instant dev server startup** - Vite and Rsbuild start quickly +- ⚡ **Lightning-fast HMR** - Changes reflect instantly without page refresh +- ⚡ **Fast dev navigation** - Full-speed routing during development +- ⚡ **Lightweight resource usage** - Minimal CPU and RAM consumption +- ⚡ **High dev throughput** - Handle many concurrent requests efficiently + +**Next.js:** + +- 🐌 **Slow dev server startup** - Can take many seconds to start, especially on larger projects +- 🐌 **Slow HMR** - Hot reloading is noticeably sluggish even with Turbopack +- 🐌 **Throttled dev navigation** - Navigation is artificially slowed during development +- 🐌 **Heavy resource usage** - Significant CPU and RAM consumption during development + +**Why This Matters:** + +Development performance directly impacts developer productivity. Faster feedback loops mean: + +- More iterations per hour +- Better flow state and focus +- Lower machine requirements +- Reduced frustration during development +- Faster CI/CD pipelines for development builds + +While Next.js's production performance is excellent, the development experience can be notably slower, especially on larger codebases or less powerful machines. + +## Community and Ecosystem + +- **Next.js**: Largest community, most third-party integrations, extensive learning resources +- **React Router**: One of the oldest and most widely used React libraries, strong community, excellent documentation +- **TanStack Start**: Growing community, part of TanStack ecosystem, excellent Discord support + +## Maturity + +- **Next.js**: Production-ready, used by thousands of companies, proven at scale +- **React Router**: Production-ready, powers millions of apps, v7 Framework Mode is the evolution of Remix +- **TanStack Start**: Release Candidate stage, feature-complete, rapidly stabilizing toward v1 + +[bp-tanstack-router]: https://badgen.net/bundlephobia/minzip/@tanstack/react-router +[bpl-tanstack-router]: https://bundlephobia.com/result?p=@tanstack/react-router +[gh-tanstack-router]: https://github.com/tanstack/router +[stars-tanstack-router]: https://img.shields.io/github/stars/tanstack/router?label=%F0%9F%8C%9F +[router-comparison]: /router/latest/docs/framework/react/comparison +[_]: _ +[nextjs]: https://nextjs.org/ +[gh-nextjs]: https://github.com/vercel/next.js +[stars-nextjs]: https://img.shields.io/github/stars/vercel/next.js?label=%F0%9F%8C%9F +[_]: _ +[react-router]: https://reactrouter.com/ +[gh-react-router]: https://github.com/remix-run/react-router +[stars-react-router]: https://img.shields.io/github/stars/remix-run/react-router?label=%F0%9F%8C%9F diff --git a/docs/start/framework/react/getting-started.md b/docs/start/framework/react/getting-started.md index 6e5bcd8841..0320fdab4e 100644 --- a/docs/start/framework/react/getting-started.md +++ b/docs/start/framework/react/getting-started.md @@ -3,7 +3,6 @@ id: getting-started title: Getting Started redirect_from: - /framework/react/quick-start -description: Create a TanStack Start application with TanStack Builder, the CLI, or a working example, then run it locally and start adding routes. --- ## Start a new project diff --git a/docs/start/framework/react/guide/authentication-overview.md b/docs/start/framework/react/guide/authentication-overview.md index e80ba97f8c..8b5838a9f9 100644 --- a/docs/start/framework/react/guide/authentication-overview.md +++ b/docs/start/framework/react/guide/authentication-overview.md @@ -1,11 +1,8 @@ --- id: authentication-overview -title: Choose Authentication for React Apps -description: Compare hosted services, auth libraries, and custom authentication for React apps built with TanStack Start. Choose an approach before implementing sessions and authorization. +title: Authentication --- -Choose how your React app will handle identity, sessions, and permissions. This page compares approaches and providers. Once you have chosen an approach, use [Implement Authentication in React](./authentication.md) for the application workflow. - ## Authentication vs Authorization - **Authentication**: Who is this user? (Login/logout, identity verification) @@ -116,7 +113,7 @@ Build your own authentication system using TanStack Start's server functions and - **Full Control**: Complete customization over authentication flow - **Server Primitives**: Sessions, OAuth, CSRF, rate limiting — see [Authentication Server Primitives](./authentication-server-primitives.md) -- **Session Management**: HTTP-only cookies written with `setCookie`, read with `getCookie` +- **Session Management**: HTTP-only cookies via `setResponseHeader`, read with `getRequestHeader` - **Type Safety**: End-to-end type safety for authentication state ### 🌐 Other Excellent Options diff --git a/docs/start/framework/react/guide/authentication-server-primitives.md b/docs/start/framework/react/guide/authentication-server-primitives.md index 103e9c4455..20cc143d2f 100644 --- a/docs/start/framework/react/guide/authentication-server-primitives.md +++ b/docs/start/framework/react/guide/authentication-server-primitives.md @@ -3,7 +3,7 @@ id: authentication-server-primitives title: Authentication Server Primitives --- -This guide covers the **server-side primitives** for building authentication in TanStack Start: session cookies, session lookup, OAuth, password-reset hardening, CSRF, and rate limiting. It pairs with the [routing-side guide](/router/latest/docs/framework/react/guide/authenticated-routes) (`_authenticated` layout, `beforeLoad`, redirects, RBAC). +This guide covers the **server-side primitives** for building authentication in TanStack Start: session cookies, session lookup, OAuth, password-reset hardening, CSRF, and rate limiting. It pairs with the [routing-side guide](../../../../router/guide/authenticated-routes.md) (`_authenticated` layout, `beforeLoad`, redirects, RBAC). If you can use a managed solution like [Clerk](https://go.clerk.com/wOwHtuJ) or [WorkOS](https://workos.com/), prefer that — they handle most of what this guide describes. Read on if you're rolling your own. @@ -28,39 +28,47 @@ Whichever you choose, the cookie flags matter: ```ts // src/server/session.ts import { - deleteCookie, - getCookie, - setCookie, + getRequestHeader, + setResponseHeader, } from '@tanstack/react-start/server' const SESSION_COOKIE = '__Host-session' const ONE_DAY = 60 * 60 * 24 -const sessionCookieOptions = { - httpOnly: true, - secure: true, - sameSite: 'lax', - path: '/', -} as const - export function setSessionCookie(token: string) { - setCookie(SESSION_COOKIE, token, { - ...sessionCookieOptions, - maxAge: ONE_DAY, - }) + setResponseHeader( + 'Set-Cookie', + [ + `${SESSION_COOKIE}=${token}`, + `HttpOnly`, + `Secure`, + `SameSite=Lax`, + `Path=/`, + `Max-Age=${ONE_DAY}`, + ].join('; '), + ) } export function clearSessionCookie() { - deleteCookie(SESSION_COOKIE, sessionCookieOptions) + setResponseHeader( + 'Set-Cookie', + `${SESSION_COOKIE}=; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=0`, + ) } export function readSessionToken(): string | null { - return getCookie(SESSION_COOKIE) ?? null + const header = getRequestHeader('cookie') + if (!header) return null + for (const part of header.split(/;\s*/)) { + // Split only on the FIRST '=' — signed/base64 values often contain '='. + const eq = part.indexOf('=') + if (eq === -1) continue + if (part.slice(0, eq) === SESSION_COOKIE) return part.slice(eq + 1) + } + return null } ``` -Write cookies with `setCookie` (or `appendResponseHeader('set-cookie', serialized)` for a cookie that a library already serialized). Do not use `setResponseHeader('Set-Cookie', ...)` for this: it replaces every cookie on the outgoing response, including cookies set by other middleware or returned by a handler. - | Flag | Why | | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `HttpOnly` | JavaScript can't read the cookie. An XSS bug can't exfiltrate the session. | @@ -161,7 +169,7 @@ For OAuth authorization-code flow: // src/server/oauth.functions.ts import { createServerFn } from '@tanstack/react-start' import { redirect } from '@tanstack/react-router' -import { setCookie } from '@tanstack/react-start/server' +import { setResponseHeader } from '@tanstack/react-start/server' import crypto from 'node:crypto' const OAUTH_STATE_COOKIE = '__Host-oauth' @@ -182,13 +190,10 @@ export const startOAuth = createServerFn({ method: 'GET' }).handler( crypto.createHash('sha256').update(verifier).digest(), ) - setCookie(OAUTH_STATE_COOKIE, signed({ state, verifier }), { - httpOnly: true, - secure: true, - sameSite: 'lax', - path: '/', - maxAge: 600, - }) + setResponseHeader( + 'Set-Cookie', + `${OAUTH_STATE_COOKIE}=${signed({ state, verifier })}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=600`, + ) throw redirect({ href: @@ -344,7 +349,7 @@ See [Execution Model: Module-Level `process.env` Reads](./execution-model.md#mod ## See Also - [Authentication Overview](./authentication-overview.md) — choosing between partner solutions, OSS libraries, and DIY. -- [Authenticated Routes (Router)](/router/latest/docs/framework/react/guide/authenticated-routes) — the routing-side guide. +- [Authenticated Routes (Router)](../../../../router/guide/authenticated-routes.md) — the routing-side guide. - [Server Functions](./server-functions.md) — the RPC primitive that auth lives inside. - [Middleware](./middleware.md) — composing `authMiddleware`. - [OWASP Cheat Sheets — Authentication](https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html), [Session Management](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html), [CSRF](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html). diff --git a/docs/start/framework/react/guide/authentication.md b/docs/start/framework/react/guide/authentication.md index c77c681ee0..da839e1fbe 100644 --- a/docs/start/framework/react/guide/authentication.md +++ b/docs/start/framework/react/guide/authentication.md @@ -1,12 +1,11 @@ --- id: authentication -title: Implement Authentication in React -description: Implement sessions, sign-in, sign-out, protected routes, and server-side authorization in a TanStack Start React app. +title: Authentication --- -Implement the authentication workflow in your React app, from sessions and sign-in to protected routes and authorization. +This guide covers authentication patterns and shows how to implement your own authentication system with TanStack Start. -To compare libraries and hosted services, read [Choose Authentication for React Apps](./authentication-overview.md). +> **📋 Before You Start:** Check our [Authentication Overview](./authentication-overview.md) for all available options including partner solutions and hosted services. ## Authentication Approaches @@ -35,7 +34,7 @@ Authentication involves many considerations including password security, session - **Authentication**: Who is this user? (Login/logout) - **Authorization**: What can this user do? (Permissions/roles) -TanStack Start provides server functions, request and cookie utilities, and route protection. Session storage and authentication come from your application or a library you choose. +TanStack Start provides the tools for both through server functions, sessions, and route protection. > Protect the data/API boundary first. Any server function, server route, or other API endpoint that returns or mutates private data must authorize the request itself. `beforeLoad` is useful for route UX: it keeps users out of screens they cannot use and avoids triggering work that would fail anyway. It is not the security boundary for the data. See [Authentication Server Primitives](./authentication-server-primitives.md) for the server-side pattern. @@ -48,7 +47,6 @@ Server functions handle sensitive authentication logic securely on the server: ```tsx import { createServerFn } from '@tanstack/react-start' import { redirect } from '@tanstack/react-router' -import { getAppSession } from '~/utils/session' // Login server function export const loginFn = createServerFn({ method: 'POST' }) @@ -62,9 +60,11 @@ export const loginFn = createServerFn({ method: 'POST' }) } // Create session - const session = await getAppSession() - session.userId = user.id - await session.save() + const session = await useAppSession() + await session.update({ + userId: user.id, + email: user.email, + }) // Redirect to protected area throw redirect({ to: '/dashboard' }) @@ -72,131 +72,98 @@ export const loginFn = createServerFn({ method: 'POST' }) // Logout server function export const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await getAppSession() - session.destroy() + const session = await useAppSession() + await session.clear() throw redirect({ to: '/' }) }) // Get current user export const getCurrentUserFn = createServerFn({ method: 'GET' }).handler( async () => { - const session = await getAppSession() - const userId = session.userId + const session = await useAppSession() + const userId = session.data.userId if (!userId) { return null } - const user = await getUserById(userId) - return user ? { id: user.id, email: user.email, role: user.role } : null + return await getUserById(userId) }, ) ``` ### 2. Session Management -Start does not provide a session API. This guide uses iron-session for encrypted cookie sessions. Start's cookie helpers connect it to server functions, server routes, and request middleware. - -For encrypted cookie sessions, install [iron-session](https://github.com/vvo/iron-session): - -```sh -pnpm add iron-session -``` - -This example uses iron-session 9's cookie adapter. Its Node runtime requires Node 22.13 or newer; check the library's runtime requirements for other deployment targets. +TanStack Start provides secure HTTP-only cookie sessions: ```tsx -// utils/session.ts — import only from server code -import { getIronSession } from 'iron-session' -import { getCookie, setCookie } from '@tanstack/react-start/server' +// utils/session.ts +import { useSession } from '@tanstack/react-start/server' type SessionData = { - userId: string - oauthState: string + userId?: string + email?: string + role?: string } -export function getAppSession(ttl = 7 * 24 * 60 * 60) { - const password = process.env.SESSION_SECRET - if (!password || password.length < 32) { - throw new Error('SESSION_SECRET must be at least 32 characters') - } - - return getIronSession( - { read: getCookie, write: setCookie }, - { - cookieName: 'app-session', - password, - ttl, - cookieOptions: { - secure: process.env.NODE_ENV === 'production', - sameSite: 'lax', - httpOnly: true, - path: '/', - }, +export function useAppSession() { + return useSession({ + // Session configuration + name: 'app-session', + password: process.env.SESSION_SECRET!, // At least 32 characters + // Optional: customize cookie settings + cookie: { + secure: process.env.NODE_ENV === 'production', + sameSite: 'lax', + httpOnly: true, }, - ) + }) } ``` -Read fields directly from the returned session, change them, then `await session.save()` before returning or redirecting. Missing or expired sessions have no user ID. `session.destroy()` removes the browser cookie. Keep one session object for the operation; another call to `getAppSession()` reads the incoming request again. For middleware, pass that object through request context when downstream code needs the same mutations. - -The `getAppSession` helper belongs to your application. Start does not cache sessions, choose expiration rules, or synchronize concurrent writes. Keep secrets and session objects in server code, and read request-specific configuration inside the active request. - ### 3. Authentication Context -Load the current user in your root route's `beforeLoad` so the initial server render and child routes receive the same authentication state. `useServerFn` returns a callable function, not an object with `data`, `isLoading`, or `refetch`. You can call a server function directly from `beforeLoad`. - -Merge this pattern into your existing root route, keeping its metadata and document shell: +Share authentication state across your application: ```tsx -// routes/__root.tsx -import { - createRootRoute, - HeadContent, - Outlet, - Scripts, -} from '@tanstack/react-router' -import type { ReactNode } from 'react' +// contexts/auth.tsx +import { createContext, useContext, ReactNode } from 'react' +import { useServerFn } from '@tanstack/react-start' import { getCurrentUserFn } from '../server/auth' -export const Route = createRootRoute({ - headers: () => ({ 'Cache-Control': 'private, no-store' }), - beforeLoad: async () => ({ user: await getCurrentUserFn() }), - component: Outlet, - shellComponent: RootDocument, -}) +type User = { + id: string + email: string + role: string +} + +type AuthContextType = { + user: User | null + isLoading: boolean + refetch: () => void +} + +const AuthContext = createContext(undefined) + +export function AuthProvider({ children }: { children: ReactNode }) { + const { data: user, isLoading, refetch } = useServerFn(getCurrentUserFn) -function RootDocument({ children }: { children: ReactNode }) { return ( - - - - - - {children} - - - + + {children} + ) } -``` -The root includes session-specific data, so its responses use `Cache-Control: private, no-store`. Keep that policy on child routes that render this data, and do not override it with public caching at your CDN. - -Read that state from a descendant component: - -```tsx -// components/AuthStatus.tsx -import { Route } from '../routes/__root' - -export function AuthStatus() { - const { user } = Route.useRouteContext() - return {user ? user.email : 'Signed out'} +export function useAuth() { + const context = useContext(AuthContext) + if (!context) { + throw new Error('useAuth must be used within AuthProvider') + } + return context } ``` -After login or logout changes the session, call `await router.invalidate()` to reload the current user and rerun route guards. Keep private-data authorization in the server function itself, even when a route already checks the user. - ### 4. Route Protection Protect routes using `beforeLoad`: @@ -273,9 +240,8 @@ export const registerFn = createServerFn({ method: 'POST' }) }) // Create session - const session = await getAppSession() - session.userId = user.id - await session.save() + const session = await useAppSession() + await session.update({ userId: user.id }) return { success: true, user: { id: user.id, email: user.email } } }) @@ -343,9 +309,8 @@ export const initiateOAuthFn = createServerFn({ method: 'POST' }) const state = generateRandomState() // Store state in session for CSRF protection - const session = await getAppSession() - session.oauthState = state - await session.save() + const session = await useAppSession() + await session.update({ oauthState: state }) // Generate OAuth URL const authUrl = generateOAuthUrl(provider, state) @@ -408,9 +373,21 @@ const hashedPassword = await bcrypt.hash(password, saltRounds) ### 2. Session Security -Set the library's server-validated expiration as well as appropriate cookie attributes. In the iron-session example, `ttl` limits a sealed credential's lifetime from its latest save; saving again renews it. A numeric `cookieOptions.maxAge` controls browser retention. In iron-session 9, explicitly setting `maxAge: undefined` also disables seal expiry; omit the property to use the configured `ttl`. Use an application-validated timestamp or a server-side record if you also need an absolute lifetime that writes cannot extend. - -Use `httpOnly`, `sameSite`, and `path` deliberately, and require `secure: true` on HTTPS deployments. These cookie attributes complement server-side authorization and CSRF protections. Keep only the minimum session data and load current account permissions from their authoritative store. Logout removes a stateless cookie from the current browser; it cannot revoke a copy without server-side state. +```tsx +// Use secure session configuration +export function useAppSession() { + return useSession({ + name: 'app-session', + password: process.env.SESSION_SECRET!, // 32+ characters + cookie: { + secure: process.env.NODE_ENV === 'production', // HTTPS only in production + sameSite: 'lax', // CSRF protection + httpOnly: true, // XSS protection + maxAge: 7 * 24 * 60 * 60, // 7 days + }, + }) +} +``` ### 3. Rate Limiting @@ -512,69 +489,28 @@ describe('Authentication Flow', () => { ### Loading States -Call the function returned by `useServerFn` with `{ data }`. Track pending state in the component, handle invalid credentials, and refresh route context after a successful login. This form uses the `loginFn` from the server-functions example above. It requires JavaScript, so the fields stay disabled until hydration; `method="post"` also prevents credentials appearing in a native GET submission. - ```tsx -// components/LoginForm.tsx -import { useState } from 'react' -import type { FormEvent } from 'react' -import { useHydrated, useRouter } from '@tanstack/react-router' -import { useServerFn } from '@tanstack/react-start' -import { loginFn } from '../server/auth' - -export function LoginForm() { - const hydrated = useHydrated() +function LoginForm() { const [isLoading, setIsLoading] = useState(false) - const [error, setError] = useState('') - const login = useServerFn(loginFn) - const router = useRouter() - - const handleSubmit = async (event: FormEvent) => { - event.preventDefault() - const formData = new FormData(event.currentTarget) - const email = formData.get('email') - const password = formData.get('password') - if (typeof email !== 'string' || typeof password !== 'string') { - return - } + const loginMutation = useServerFn(loginFn) + const handleSubmit = async (data: LoginData) => { setIsLoading(true) - setError('') try { - const result = await login({ data: { email, password } }) - if (result?.error) { - setError(result.error) - return - } - await router.invalidate() - } catch { - setError('Login failed. Please try again.') + await loginMutation.mutate(data) + } catch (error) { + // Handle error } finally { setIsLoading(false) } } return ( - -
- - - -
-

{error}

+ + {/* Form fields */} + ) } @@ -589,14 +525,16 @@ export const loginFn = createServerFn({ method: 'POST' }) ) .handler(async ({ data }) => { const user = await authenticateUser(data.email, data.password) - if (!user) { - return { error: 'Invalid credentials' } - } + if (!user) return { error: 'Invalid credentials' } - const ttl = data.rememberMe ? 30 * 24 * 60 * 60 : 8 * 60 * 60 - const session = await getAppSession(ttl) - session.userId = user.id - await session.save() + const session = await useAppSession() + await session.update( + { userId: user.id }, + { + // Extend session if remember me is checked + maxAge: data.rememberMe ? 30 * 24 * 60 * 60 : undefined, // 30 days vs session + }, + ) return { success: true } }) @@ -624,6 +562,7 @@ If you're migrating from client-side authentication (localStorage, context only) ### From Other Frameworks - **Next.js**: Replace API routes with server functions, migrate NextAuth sessions +- **Remix**: Convert loaders/actions to server functions, adapt session patterns - **SvelteKit**: Move form actions to server functions, update route protection ## Production Considerations diff --git a/docs/start/framework/react/guide/cdn-asset-urls.md b/docs/start/framework/react/guide/cdn-asset-urls.md index ac5f3e7b57..28c9c8c030 100644 --- a/docs/start/framework/react/guide/cdn-asset-urls.md +++ b/docs/start/framework/react/guide/cdn-asset-urls.md @@ -3,6 +3,8 @@ id: cdn-asset-urls title: CDN Asset URLs --- +# CDN Asset URLs + > **Experimental:** `transformAssets` is experimental and subject to change. Use this guide when you need TanStack Start to rewrite manifest-managed asset URLs at runtime. The most common use case is serving JavaScript and CSS from a CDN whose origin is known only when the server starts, or varies per request. diff --git a/docs/start/framework/react/guide/client-entry-point.md b/docs/start/framework/react/guide/client-entry-point.md index 3d81a13ac2..02d0ecd426 100644 --- a/docs/start/framework/react/guide/client-entry-point.md +++ b/docs/start/framework/react/guide/client-entry-point.md @@ -3,6 +3,8 @@ id: client-entry-point title: Client Entry Point --- +# Client Entry Point + > [!NOTE] > The client entry point is **optional** out of the box. If not provided, TanStack Start will automatically handle the client entry point for you using the below as a default. diff --git a/docs/start/framework/react/guide/databases.md b/docs/start/framework/react/guide/databases.md index 774a9df61b..cbafa13f51 100644 --- a/docs/start/framework/react/guide/databases.md +++ b/docs/start/framework/react/guide/databases.md @@ -1,7 +1,6 @@ --- id: databases title: Databases -description: Connect a database to TanStack Start through server functions and server routes, and compare supported database providers. --- Databases are at the core of any dynamic application, providing the necessary infrastructure to store, retrieve, and manage data. TanStack Start makes it easy to integrate with a variety of databases, offering a flexible approach to managing your application's data layer. diff --git a/docs/start/framework/react/guide/deferred-hydration.md b/docs/start/framework/react/guide/deferred-hydration.md index ba07d65b24..1dc4760fa7 100644 --- a/docs/start/framework/react/guide/deferred-hydration.md +++ b/docs/start/framework/react/guide/deferred-hydration.md @@ -244,7 +244,7 @@ chunks only exist when `split` is enabled, so TypeScript rejects strategy-form Use procedural prefetch when you need custom work: ```tsx -import { noop, useQueryClient } from '@tanstack/react-query' +import { useQueryClient } from '@tanstack/react-query' import { Hydrate } from '@tanstack/react-start' import { visible } from '@tanstack/react-start/hydration' @@ -255,10 +255,8 @@ function DeferredReviews() { { - await Promise.all([ - preload(), - queryClient.query(reviewsQueryOptions).catch(noop), - ]) + await preload() + await queryClient.prefetchQuery(reviewsQueryOptions) }} > diff --git a/docs/start/framework/react/guide/early-hints.md b/docs/start/framework/react/guide/early-hints.md index 2341215022..da633a84d7 100644 --- a/docs/start/framework/react/guide/early-hints.md +++ b/docs/start/framework/react/guide/early-hints.md @@ -3,6 +3,8 @@ id: early-hints title: Early Hints --- +# Early Hints + > **Experimental:** Early Hints are experimental and subject to change. HTTP `103 Early Hints` lets your server tell the browser about important resources before the final HTML response is ready. TanStack Start can collect route assets and route `head().links`, then call your server entry so your runtime can send `103` responses. @@ -164,7 +166,6 @@ Static Early Hints are collected from the final Start manifest resolved for the - CDN URL rewrites are reflected in Early Hints. - `crossOrigin` returned from `transformAssets` is reflected in Early Hints. - JavaScript hints follow the client output format: `modulepreload` for module output, or `preload; as=script` for IIFE output. -- JavaScript hints carry `fetchpriority=low`, matching the generated HTML preload links, so they don't compete with render-blocking stylesheets. - Per-request transforms with `cache: false` are reflected in Early Hints for that request. - Inlined CSS assets are skipped when Start's [CSS inlining](./css-styling#inline-route-css-in-production) build option inlines them into the HTML. diff --git a/docs/start/framework/react/guide/environment-functions.md b/docs/start/framework/react/guide/environment-functions.md index 94fbb52501..f472a3a26a 100644 --- a/docs/start/framework/react/guide/environment-functions.md +++ b/docs/start/framework/react/guide/environment-functions.md @@ -121,37 +121,3 @@ Environment functions are tree-shaken based on the environment for each bundle p Functions created using `createIsomorphicFn()` are tree-shaken. All codes inside `.client()` are not included in server bundle, and vice-versa. On the server, functions created using `createClientOnlyFn()` are replaced with a function that throws an `Error` on the server. The reverse is true for `createServerOnlyFn` functions on the client. - -## Troubleshooting - -### A loader works on refresh but throws during navigation - -If a loader throws `createServerOnlyFn() functions can only be called on the server!` after clicking a link, check whether it calls a server-only helper directly. Route loaders also run in the browser during client navigation. `createServerOnlyFn` guards a local function, it does not send a request to the server. - -Wrap the server work in `createServerFn` and call that function from the loader: - -```tsx -import { createFileRoute } from '@tanstack/react-router' -import { createServerFn, createServerOnlyFn } from '@tanstack/react-start' - -const readOnlyOnServer = createServerOnlyFn(() => 'Read on the server') -const readThroughRpc = createServerFn().handler(() => readOnlyOnServer()) - -export const Route = createFileRoute('/example')({ - loader: () => readThroughRpc(), -}) -``` - -The server function runs directly during SSR and makes a request to the server when called in the browser. Test both a direct page request and navigation from another route. A successful refresh alone does not exercise the browser loader. - -The [execution-boundary tests](https://github.com/TanStack/router/blob/main/e2e/react-start/basic/tests/environment-functions.spec.ts) include the failing direct call and the working server-function version. See [Server Functions](./server-functions.md) for validation and middleware when the function accepts user input. - -### Browser code throws `window is not defined` on the server - -This means browser-only code ran during server execution. Use the stack trace to find the first application or dependency module that reads `window`, `document`, or another browser API. - -For a browser-only component, render it inside `ClientOnly` from `@tanstack/react-router` with a useful fallback. The Start compiler removes its children from the server bundle, which lets the bundler remove imports used only by those children. The [ClientOnly example](https://github.com/TanStack/router/blob/main/e2e/react-start/basic/src/routes/client-only.tsx) covers a component that reads `window` at module scope, and its [tests](https://github.com/TanStack/router/blob/main/e2e/react-start/basic/tests/client-only.spec.ts) check the server fallback and hydrated content. - -A browser API used elsewhere, such as a route loader or server function, still needs the correct execution boundary. Move component side effects into an effect or event handler. For logic that needs different server and browser implementations, use `createIsomorphicFn` with both implementations. Wrapping a function in `createClientOnlyFn` does not defer its call until the browser, calling that wrapper on the server throws the client-only guard error instead. - -If the stack points into build tooling or the error persists in a minimal app with the correct boundary, include that app and the installed Start and bundler versions in a [bug report](https://github.com/TanStack/router/issues/new/choose). A compiler or dependency bug needs a reproducible fix, not a blanket change to rendering mode. diff --git a/docs/start/framework/react/guide/hosting.md b/docs/start/framework/react/guide/hosting.md index 2d02f881b3..aa1806c6bf 100644 --- a/docs/start/framework/react/guide/hosting.md +++ b/docs/start/framework/react/guide/hosting.md @@ -1,7 +1,6 @@ --- id: hosting title: Hosting -description: Deploy TanStack Start with Vite or Rsbuild using hosting guides for Cloudflare, Netlify, Railway, Vercel, Node.js, and other runtimes. --- Hosting is the process of deploying your application to the internet so that users can access it. This is a critical part of any web development project, ensuring your application is available to the world. TanStack Start supports Vite and Rsbuild, giving you flexible build outputs for different hosting providers and runtimes. @@ -116,32 +115,6 @@ Deploy your application to Cloudflare Workers using their one-click deployment p A full TanStack Start example for Cloudflare Workers is available [here](https://github.com/TanStack/router/tree/main/examples/react/start-basic-cloudflare). -#### Deployment fails even though the Vite build succeeds - -If Wrangler reports a missing server entry or unresolved Start virtual modules, check whether your deployment command passes `--config wrangler.jsonc`. With the Cloudflare Vite plugin, that file is the build input. The plugin generates a deployment config with the built server entry and client assets, then writes `.wrangler/deploy/config.json` so Wrangler can find it. Forcing Wrangler to read the source config bypasses that redirect. - -Run these commands from the application directory to validate the generated deployment without publishing: - -```sh -pnpm run build -pnpm exec wrangler deploy --dry-run -``` - -Check that Wrangler reports the generated config under `dist`, rather than just the source `wrangler.jsonc`. Keep the source `main` set to `@tanstack/react-start/server-entry` or your custom server entry, and let the Vite plugin generate the deployment entry. Marking unresolved Start modules as external does not fix the missing build transformation. - -If your build and deployment run in separate jobs, preserve the build output and `.wrangler/deploy/config.json` with their relative paths, or explicitly pass the generated deployment config. Do not edit generated files to repair the source configuration. See Cloudflare's [generated configuration documentation](https://developers.cloudflare.com/workers/wrangler/configuration/#generated-configuration) for how Wrangler finds that output. - -For a named Cloudflare environment, select it when building. For example, if `env.staging` is defined in your source config: - -```sh -CLOUDFLARE_ENV=staging pnpm run build -pnpm exec wrangler deploy --dry-run -``` - -The plugin resolves the environment into the generated config. A later `wrangler deploy --env staging` does not select a different built environment. See [Cloudflare environments](https://developers.cloudflare.com/workers/vite-plugin/reference/cloudflare-environments/). - -The [Cloudflare fixture tests](https://github.com/TanStack/router/blob/main/e2e/react-start/basic-cloudflare/tests/app.spec.ts) exercise a generated-config dry run and preview the built app locally. A dry run validates packaging, it does not verify account permissions, a live domain, or deployed bindings. - ### Netlify ⭐ _Official Partner_ @@ -501,7 +474,7 @@ In your Appwrite project, navigate to the **Sites** page from the sidebar. Click 3. Confirm the build settings: - **Install command:** `npm install` - **Build command:** `npm run build` - - **Output directory:** `./dist` (if you're using Nitro, this should be `./.output`) + - **Output directory:** `./dist` (if you're using Nitro v2 or v3, this should be `./.output`) 4. Add any required **environment variables** 5. Click **Deploy** diff --git a/docs/start/framework/react/guide/import-protection.md b/docs/start/framework/react/guide/import-protection.md index 451d405f81..8bf47c729a 100644 --- a/docs/start/framework/react/guide/import-protection.md +++ b/docs/start/framework/react/guide/import-protection.md @@ -3,6 +3,8 @@ id: import-protection title: Import Protection --- +> **Experimental:** Import protection is experimental and subject to change. + Import protection prevents server-only code from leaking into client bundles and client-only code from leaking into server bundles. It runs inside TanStack Start and is enabled by default. ## How It Works diff --git a/docs/start/framework/react/guide/isr.md b/docs/start/framework/react/guide/isr.md index 98007d3f15..5704af1a11 100644 --- a/docs/start/framework/react/guide/isr.md +++ b/docs/start/framework/react/guide/isr.md @@ -492,5 +492,5 @@ Track key metrics: - [Static Prerendering](./static-prerendering.md) - Build-time page generation - [Hosting](./hosting.md) - CDN deployment configurations - [Server Functions](./server-functions.md) - Creating dynamic data endpoints -- [Data Loading](/router/latest/docs/guide/data-loading) - Client-side cache control +- [Data Loading](../../../../router/guide/data-loading.md) - Client-side cache control - [Middleware](./middleware.md) - Request/response customization diff --git a/docs/start/framework/react/guide/path-aliases.md b/docs/start/framework/react/guide/path-aliases.md index bd75dc01ed..ff9735df83 100644 --- a/docs/start/framework/react/guide/path-aliases.md +++ b/docs/start/framework/react/guide/path-aliases.md @@ -26,7 +26,9 @@ After updating your `tsconfig.json` file, configure your build tool so it resolv # Vite -Vite has [built-in support for path aliases](https://vite.dev/config/shared-options#resolve-tsconfigpaths), which is disabled by default. To enable it, add the following configuration to your `vite.config.ts` file: +## Vite 8 + +Vite 8+ has [built-in support for path aliases](https://vite.dev/config/shared-options#resolve-tsconfigpaths), which is disabled by default. To enable it, simply add the following configuration to your `vite.config.ts` file: ```ts // vite.config.ts @@ -40,6 +42,31 @@ export default defineConfig({ }) ``` +## Vite 7 and earlier + +For Vite 7 and earlier, install the `vite-tsconfig-paths` plugin to enable path aliases in your TanStack Start project. You can do this by running the following command: + +```sh +npm install -D vite-tsconfig-paths +``` + +Now, you'll need to update your `vite.config.ts` file to include the following: + +```ts +// vite.config.ts +import { defineConfig } from 'vite' +import viteTsConfigPaths from 'vite-tsconfig-paths' + +export default defineConfig({ + plugins: [ + // this is the plugin that enables path aliases + viteTsConfigPaths({ + projects: ['./tsconfig.json'], + }), + ], +}) +``` + # Rsbuild Rsbuild reads the `paths` field from `tsconfig.json` by default. No extra config is needed when your aliases live in the root `tsconfig.json`. diff --git a/docs/start/framework/react/guide/production-checklist.md b/docs/start/framework/react/guide/production-checklist.md deleted file mode 100644 index b46cd70f2e..0000000000 --- a/docs/start/framework/react/guide/production-checklist.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -id: production-checklist -title: Production Checklist -description: Check a TanStack Start production build for secret exposure, authorization, cache isolation, HTTP status codes, SEO, assets, logging, and deployment failures. ---- - -Run these checks against the production build and again through your public hostname. A passing development server does not verify your deployment adapter, runtime environment, or CDN. - -## Secrets and server boundaries - -- [ ] **Check required environment variables at runtime.** Start the production server with the same variable names and runtime bindings as your host. Missing configuration should fail clearly before it serves dependent requests. Look for undefined credentials, connections to a development database, or values that only existed during the build. See [Environment Variables](./environment-variables). -- [ ] **Keep secrets out of browser output.** Build with a harmless, unique test secret and search the emitted client files, source maps you publish, and response bodies for that value. Do not use a real secret for this check. A match means a value crossed the server boundary, even if its variable name lacks `VITE_`. Check server-function return values as well as imports. See [Environment Variables](./environment-variables#security-best-practices) and [Import Protection](./import-protection). - -## Authorization and mutations - -- [ ] **Test endpoints directly.** Record a private read and write, then repeat them while signed out and as a different account. Both must reject unauthorized access without changing data. A redirect in `beforeLoad` does not protect a separately callable endpoint. See [Authentication Server Primitives](./authentication-server-primitives#protect-data-first). -- [ ] **Exercise session expiry and sign-out.** Reload a private page, expire its session, sign out, and revisit it. Confirm the cookie's HTTPS flags and that old account data disappears from browser caches. Look for sessions that survive beyond your intended policy or another account's data appearing after switching accounts. See [Session Cookies](./authentication-server-primitives#session-cookies). -- [ ] **Reject invalid and cross-site writes.** Send malformed input and browser-like requests from an untrusted origin to each mutation entry point, including ordinary server-route forms. Use an authenticated test session for protected writes so an authentication failure cannot be mistaken for CSRF protection. Verify validation and your intended CSRF policy before any write occurs. Also test rapid or repeated submissions. A disabled button helps the interface, but the endpoint still needs its own checks. See [Authentication Server Primitives](./authentication-server-primitives) and [Server Functions](./server-functions). - -## Cache isolation and rendering - -- [ ] **Request the same private URL as two accounts concurrently.** Inspect each HTML response and any serialized loader or query data. Each response must contain only its own account's values. Repeat through the CDN and after a browser account switch. Shared personalized HTML or process-wide user caches are failures. See [Middleware](./middleware) and [Authentication Server Primitives](./authentication-server-primitives). -- [ ] **Check final cache headers and update behavior.** Use `Cache-Control: no-store` for personalized responses unless you have an explicit identity-partitioned cache key and lifecycle that prevents reuse across accounts. `private` alone does not prevent a browser cache from retaining one account's response after sign-out. For public cached content, perform a write and confirm it becomes visible within the freshness policy you chose. Inspect the final headers from your host, not just the values assigned in route code. Query invalidation, Router invalidation, and CDN invalidation affect different caches. See [Server Routes](./server-routes) and [Static Prerendering](./static-prerendering). -- [ ] **Compare a direct visit with client navigation.** Test initial HTML, hydration, back/forward navigation, and a reload for a parameterized route and a route with search values. Missing content, mismatched metadata, hydration warnings, or repeated immediate reads need investigation. See [Hydration Errors](./hydration-errors) and [Routing](./routing). - -## HTTP responses and search visibility - -- [ ] **Probe success, missing, redirect, and error responses.** A real missing public resource should return HTTP 404, a moved URL should use its intended redirect, and a failed request should not masquerade as a successful page. Check status codes before following redirects. Test a controlled failure in staging and confirm the error interface offers recovery without leaking sensitive details. See [Server Routes](./server-routes), [Error Boundaries](./error-boundaries), and [Router Not Found Errors](/router/latest/docs/guide/not-found-errors). -- [ ] **Inspect public HTML before JavaScript runs.** Verify useful content, a specific title and description, the public canonical URL, and relevant social metadata. Repeat after client navigation. Look for preview hostnames in canonicals, duplicate titles, or metadata that depends on a browser effect. See [SEO](./seo). -- [ ] **Check indexing rules and discovery files.** Fetch `robots.txt` and the sitemap from the deployed hostname. Sitemap URLs should resolve to intended public canonical pages. Remove accidental production `noindex` rules, but keep private and preview content out of search. Robots rules are not access control. See [SEO](./seo#sitemaps). - -## Assets, logging, and deployment - -- [ ] **Inspect the production network waterfall.** Test a representative page on a narrow viewport with slower network and CPU settings. Check large images, missing dimensions, font loading, third-party scripts, and failed asset requests. Record a baseline so later releases have something to compare against. Local lab results do not establish real-user performance. See [SEO performance guidance](./seo#performance-matters), [CDN Asset URLs](./cdn-asset-urls), and [Observability](./observability). -- [ ] **Trigger and find a controlled error.** Confirm your chosen logs or error service receive it with enough route and release context to investigate. Check that credentials, cookies, and sensitive payloads are absent. An error boundary that only changes the screen is not evidence of a working alert. See [Observability](./observability). -- [ ] **Run the deployed entry point and rehearse rollback.** Use your adapter's production output and start command, then test a direct deep link, a static asset, a server function, and a server route. Check that requests still work after a restart. Rehearse restoring a previous release and account for any database migration separately. Local success cannot prove host bindings, asset retention, or database rollback safety. See [Hosting](./hosting). - -## Keep a release record - -Record the tested commit, runtime, hostname, commands, and results. Turn repeatable HTTP and browser checks into CI tests; repeat host-specific checks after deployment changes. - -The [Next.js migration reference](../examples/start-next-migration) provides production browser checks for public HTML and metadata, search, redirects, missing pages, session reloads, and protected mutations. Its demo credentials and cookie session are for local comparison, not a production authentication system. Use its tests as a starting point, then add your own authorization rules, external services, CDN behavior, and operational checks. diff --git a/docs/start/framework/react/guide/rendering-markdown.md b/docs/start/framework/react/guide/rendering-markdown.md index bf644124d9..4258d6f4f1 100644 --- a/docs/start/framework/react/guide/rendering-markdown.md +++ b/docs/start/framework/react/guide/rendering-markdown.md @@ -3,85 +3,191 @@ id: rendering-markdown title: Rendering Markdown --- -Use [TanStack Markdown](https://tanstack.com/markdown/latest/docs/overview) to render Markdown in your TanStack Start application. Its React renderer works synchronously during server rendering and client navigation, so content does not need to wait for a client effect. +This guide covers two methods for importing and rendering markdown content in your TanStack Start application: -This guide covers static posts loaded with Content Collections and remote content fetched through a server function. Both use the same Markdown component. +1. **Static markdown** with `content-collections` for build-time loading (e.g., blog posts) +2. **Dynamic markdown** fetched at runtime from GitHub or any remote source -## Rendering Markdown +Both methods share a common rendering pipeline using the `unified` ecosystem. -Install TanStack Markdown: +## Setting Up the Markdown Processor + +Both approaches use the same markdown-to-HTML processing pipeline. First, install the required dependencies: ```bash -npm install @tanstack/markdown +npm install unified remark-parse remark-gfm remark-rehype rehype-raw rehype-slug rehype-autolink-headings rehype-stringify shiki html-react-parser gray-matter ``` -Create a shared component that accepts either Markdown source or a parsed document: +Create a markdown processor utility: + +```tsx +// src/utils/markdown.ts +import { unified } from 'unified' +import remarkParse from 'remark-parse' +import remarkGfm from 'remark-gfm' +import remarkRehype from 'remark-rehype' +import rehypeRaw from 'rehype-raw' +import rehypeSlug from 'rehype-slug' +import rehypeAutolinkHeadings from 'rehype-autolink-headings' +import rehypeStringify from 'rehype-stringify' + +export type MarkdownHeading = { + id: string + text: string + level: number +} + +export type MarkdownResult = { + markup: string + headings: Array +} + +export async function renderMarkdown(content: string): Promise { + const headings: Array = [] + + const result = await unified() + .use(remarkParse) // Parse markdown + .use(remarkGfm) // Support GitHub Flavored Markdown + .use(remarkRehype, { allowDangerousHtml: true }) // Convert to HTML AST + .use(rehypeRaw) // Process raw HTML in markdown + .use(rehypeSlug) // Add IDs to headings + .use(rehypeAutolinkHeadings, { + behavior: 'wrap', + properties: { className: ['anchor'] }, + }) + .use(() => (tree) => { + // Extract headings for table of contents + const { visit } = require('unist-util-visit') + const { toString } = require('hast-util-to-string') + + visit(tree, 'element', (node: any) => { + if (['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(node.tagName)) { + headings.push({ + id: node.properties?.id || '', + text: toString(node), + level: parseInt(node.tagName.charAt(1), 10), + }) + } + }) + }) + .use(rehypeStringify) // Serialize to HTML string + .process(content) + + return { + markup: String(result), + headings, + } +} +``` + +## Creating a Markdown Component + +Create a React component that renders the processed HTML with custom element handling: ```tsx // src/components/Markdown.tsx -import { Markdown as ReactMarkdown } from '@tanstack/markdown/react' -import type { MarkdownDocument } from '@tanstack/markdown' +import parse, { type HTMLReactParserOptions, Element } from 'html-react-parser' +import { renderMarkdown, type MarkdownResult } from '~/utils/markdown' type MarkdownProps = { - content: string | MarkdownDocument + content: string className?: string } export function Markdown({ content, className }: MarkdownProps) { - return ( -
- {content} -
- ) + const [result, setResult] = useState(null) + + useEffect(() => { + renderMarkdown(content).then(setResult) + }, [content]) + + if (!result) { + return
Loading...
+ } + + const options: HTMLReactParserOptions = { + replace: (domNode) => { + if (domNode instanceof Element) { + // Customize rendering of specific elements + if (domNode.name === 'a') { + // Handle links + const href = domNode.attribs.href + if (href?.startsWith('/')) { + // Internal link - use your router's Link component + return ( + {domToReact(domNode.children, options)} + ) + } + } + + if (domNode.name === 'img') { + // Add lazy loading to images + return ( + + ) + } + } + }, + } + + return
{parse(result.markup, options)}
} ``` -Headings receive stable IDs, and `headingAnchors` adds links to them. Raw HTML is escaped and unsafe URL protocols are removed by default. Keep these defaults for remote or user-written content. TanStack Markdown does not execute MDX or implement every CommonMark or GFM feature, so check the [supported syntax](https://tanstack.com/markdown/latest/docs/core-concepts/syntax-profile) when migrating existing content. +## Method 1: Static Markdown with content-collections -Use the `components` prop to customize elements, for example to lazy-load images: +The `content-collections` package is ideal for static content like blog posts that are included in your repository. It processes markdown files at build time and provides type-safe access to the content. -```tsx - , - }} -> - {content} - -``` - -The examples below use `~/*` for the `src/*` import alias. The `prose` class is optional and requires your own typography styles, such as Tailwind Typography. - -## Static Markdown with Content Collections - -[Content Collections](https://www.content-collections.dev/docs/quickstart/tanstack-start) loads local Markdown files and validates their frontmatter. Pass the Markdown body from the generated collection to the shared renderer. - -### Installation and Configuration +### Installation ```bash -npm install -D @content-collections/core @content-collections/vite zod +npm install @content-collections/core @content-collections/vite ``` -```ts +### Configuration + +Create a `content-collections.ts` file in your project root: + +```tsx // content-collections.ts import { defineCollection, defineConfig } from '@content-collections/core' -import { z } from 'zod' +import matter from 'gray-matter' + +function extractFrontMatter(content: string) { + const { data, content: body, excerpt } = matter(content, { excerpt: true }) + return { data, body, excerpt: excerpt || '' } +} const posts = defineCollection({ name: 'posts', - directory: './src/blog', + directory: './src/blog', // Directory containing your .md files include: '*.md', - schema: z.object({ + schema: (z) => ({ title: z.string(), - published: z.string().regex(/^\d{4}-\d{2}-\d{2}$/), - description: z.string(), - authors: z.array(z.string()), - content: z.string(), - }), - transform: (post) => ({ - ...post, - slug: post._meta.path, + published: z.string().date(), + description: z.string().optional(), + authors: z.string().array(), }), + transform: ({ content, ...post }) => { + const frontMatter = extractFrontMatter(content) + + // Extract header image (first image in the document) + const headerImageMatch = content.match(/!\[([^\]]*)\]\(([^)]+)\)/) + const headerImage = headerImageMatch ? headerImageMatch[2] : undefined + + return { + ...post, + slug: post._meta.path, + excerpt: frontMatter.excerpt, + description: frontMatter.data.description, + headerImage, + content: frontMatter.body, + } + }, }) export default defineConfig({ @@ -89,56 +195,40 @@ export default defineConfig({ }) ``` -Content Collections already separates frontmatter from `content`, so this transform does not need a second frontmatter parser. +### Vite Integration -Add the plugin to your existing Vite configuration, keeping any deployment plugins your app needs: +Add the content-collections plugin to your Vite config: -```ts -// vite.config.ts +```tsx +// app.config.ts +import { defineConfig } from '@tanstack/react-start/config' import contentCollections from '@content-collections/vite' -import { tanstackStart } from '@tanstack/react-start/plugin/vite' -import viteReact from '@vitejs/plugin-react' -import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' export default defineConfig({ - plugins: [ - contentCollections(), - tsConfigPaths({ projects: ['./tsconfig.json'] }), - tanstackStart(), - viteReact(), - ], + vite: { + plugins: [contentCollections()], + }, }) ``` -Add the generated collection alias to your existing `tsconfig.json`: +### Creating Blog Posts -```json -{ - "compilerOptions": { - "paths": { - "~/*": ["./src/*"], - "content-collections": ["./.content-collections/generated"] - } - } -} -``` - -Add `.content-collections` to `.gitignore`. Starting the Vite dev server or running a build generates the collection. - -### Creating a Post - -Create `src/blog/hello-world.md`: +Create markdown files in your designated directory: ````markdown ---- +## + title: Hello World -published: '2026-01-15' -description: My first blog post +published: 2024-01-15 authors: - - Jane Doe + +- Jane Doe + description: My first blog post + --- +![Hero Image](/images/hero.jpg) + Welcome to my blog! This is my first post. ## Getting Started @@ -150,11 +240,13 @@ console.log('Hello, world!') ``` ```` -### Listing Posts +### Using the Collection + +Access your posts through the generated collection: ```tsx // src/routes/blog.index.tsx -import { createFileRoute, Link } from '@tanstack/react-router' +import { createFileRoute } from '@tanstack/react-router' import { allPosts } from 'content-collections' export const Route = createFileRoute('/blog/')({ @@ -162,30 +254,31 @@ export const Route = createFileRoute('/blog/')({ }) function BlogIndex() { - const sortedPosts = [...allPosts].sort((a, b) => - b.published.localeCompare(a.published), + // Posts are sorted by published date + const sortedPosts = allPosts.sort( + (a, b) => new Date(b.published).getTime() - new Date(a.published).getTime(), ) return ( -
+

Blog

    {sortedPosts.map((post) => (
  • - {post.title} +

    {post.title}

    +

    {post.excerpt}

    + {post.published} -

    {post.description}

    -
  • ))}
-
+ ) } ``` -### Rendering a Post +### Rendering a Single Post ```tsx // src/routes/blog.$slug.tsx @@ -195,7 +288,7 @@ import { Markdown } from '~/components/Markdown' export const Route = createFileRoute('/blog/$slug')({ loader: ({ params }) => { - const post = allPosts.find((post) => post.slug === params.slug) + const post = allPosts.find((p) => p.slug === params.slug) if (!post) { throw notFound() } @@ -209,169 +302,202 @@ function BlogPost() { return (
-

{post.title}

-

- By {post.authors.join(', ')} on {post.published} -

+
+

{post.title}

+

+ By {post.authors.join(', ')} on {post.published} +

+
) } ``` -The renderer parses the Markdown synchronously and renders React elements on both the server and client. +## Method 2: Dynamic Markdown from Remote Sources -## Remote Markdown with a Server Function +For content stored externally (like GitHub repositories), you can fetch and render markdown dynamically using server functions. -Fetch remote content in a server function and parse it before returning it to the route. Install `gray-matter` if the remote files contain frontmatter: - -```bash -npm install gray-matter -``` - -Keep the repository, branch, and content directory in server code. Validate the requested filename before building the URL: - -```ts -// src/utils/docs.ts -import { createServerFn } from '@tanstack/react-start' -import { notFound } from '@tanstack/react-router' -import { parseMarkdown } from '@tanstack/markdown/parser' -import matter from 'gray-matter' - -export const fetchDocs = createServerFn({ method: 'GET' }) - .validator((slug: unknown) => { - if (typeof slug !== 'string' || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug)) { - throw new Error('Invalid document slug') - } - return slug - }) - .handler(async ({ data: slug }) => { - // Replace this with your public repository's content directory. - const baseUrl = - 'https://raw.githubusercontent.com/your-org/your-repo/main/docs' - const response = await fetch(`${baseUrl}/${slug}.md`) - - if (response.status === 404) { - throw notFound() - } - if (!response.ok) { - throw new Error(`Failed to fetch document: ${response.status}`) - } - - const { data, content } = matter(await response.text()) - - return { - title: typeof data.title === 'string' ? data.title : slug, - document: parseMarkdown(content), - } - }) -``` +### Creating a Fetch Utility ```tsx -// src/routes/docs.$slug.tsx -import { createFileRoute } from '@tanstack/react-router' -import { Markdown } from '~/components/Markdown' -import { fetchDocs } from '~/utils/docs' +// src/utils/docs.server.ts +import { createServerFn } from '@tanstack/react-start' +import matter from 'gray-matter' -export const Route = createFileRoute('/docs/$slug')({ - loader: ({ params }) => fetchDocs({ data: params.slug }), +type FetchDocsParams = { + repo: string // e.g., 'tanstack/router' + branch: string // e.g., 'main' + filePath: string // e.g., 'docs/guide/getting-started.md' +} + +export const fetchDocs = createServerFn({ method: 'GET' }) + .validator((params: FetchDocsParams) => params) + .handler(async ({ data: { repo, branch, filePath } }) => { + const url = `https://raw.githubusercontent.com/${repo}/${branch}/${filePath}` + + const response = await fetch(url, { + headers: { + // Add GitHub token for private repos or higher rate limits + // Authorization: `token ${process.env.GITHUB_TOKEN}`, + }, + }) + + if (!response.ok) { + throw new Error(`Failed to fetch: ${response.status}`) + } + + const rawContent = await response.text() + const { data: frontmatter, content } = matter(rawContent) + + return { + frontmatter, + content, + filePath, + } + }) +``` + +### Adding Cache Headers + +For production, add appropriate cache headers: + +```tsx +export const fetchDocs = createServerFn({ method: 'GET' }) + .validator((params: FetchDocsParams) => params) + .handler(async ({ data: { repo, branch, filePath }, context }) => { + // Set cache headers for CDN caching + context.response.headers.set( + 'Cache-Control', + 'public, max-age=0, must-revalidate', + ) + context.response.headers.set( + 'CDN-Cache-Control', + 'max-age=300, stale-while-revalidate=300', + ) + + // ... fetch logic + }) +``` + +### Using Dynamic Markdown in Routes + +```tsx +// src/routes/docs.$path.tsx +import { createFileRoute } from '@tanstack/react-router' +import { fetchDocs } from '~/utils/docs.server' +import { Markdown } from '~/components/Markdown' + +export const Route = createFileRoute('/docs/$path')({ + loader: async ({ params }) => { + return fetchDocs({ + data: { + repo: 'your-org/your-repo', + branch: 'main', + filePath: `docs/${params.path}.md`, + }, + }) + }, component: DocsPage, }) function DocsPage() { - const { title, document } = Route.useLoaderData() + const { frontmatter, content } = Route.useLoaderData() return (
-

{title}

- +

{frontmatter.title}

+
) } ``` -Relative Markdown links and image URLs resolve against your app's URL, not the source repository. Use app-relative or absolute URLs in the content, or transform them for your site's route and asset layout. +### Fetching Directory Contents -## Syntax Highlighting with TanStack Highlight - -Install [TanStack Highlight](https://tanstack.com/highlight/latest/docs/overview). The Markdown adapter requires version `0.0.6` or newer: - -```bash -npm install @tanstack/highlight -``` - -Register the languages your content uses and create the Markdown adapter: - -```ts -// src/utils/markdown-highlighter.ts -import { createHighlighter } from '@tanstack/highlight/core' -import { js } from '@tanstack/highlight/languages/js' -import { plaintext } from '@tanstack/highlight/languages/plaintext' -import { ts } from '@tanstack/highlight/languages/ts' -import { tsx } from '@tanstack/highlight/languages/tsx' -import { createTanStackMarkdownHighlighter } from '@tanstack/highlight/markdown' - -const highlighter = createHighlighter({ - languages: [plaintext, js, ts, tsx], -}) - -export const highlightMarkdownCode = - createTanStackMarkdownHighlighter(highlighter) -``` - -Update the shared component to pass the highlighter and include its theme styles: +To build navigation from a GitHub directory: ```tsx -// src/components/Markdown.tsx -import { createThemeCss } from '@tanstack/highlight/theme' -import { githubDarkTheme } from '@tanstack/highlight/themes/github-dark' -import { githubLightTheme } from '@tanstack/highlight/themes/github-light' -import { Markdown as ReactMarkdown } from '@tanstack/markdown/react' -import type { MarkdownDocument } from '@tanstack/markdown' -import { highlightMarkdownCode } from '~/utils/markdown-highlighter' - -const themeCss = createThemeCss({ - light: githubLightTheme, - dark: githubDarkTheme, - lightSelector: '.markdown-renderer', - darkSelector: '.dark .markdown-renderer', - codeBlockSelector: '.markdown-renderer pre.tm-code', - lineNumbersSelector: '.markdown-renderer .tm-code--line-numbers', -}) - -type MarkdownProps = { - content: string | MarkdownDocument - className?: string +// src/utils/docs.server.ts +type GitHubContent = { + name: string + path: string + type: 'file' | 'dir' } -export function Markdown({ content, className }: MarkdownProps) { - return ( -
- - - {content} - -
+export const fetchRepoContents = createServerFn({ method: 'GET' }) + .validator((params: { repo: string; branch: string; path: string }) => params) + .handler(async ({ data: { repo, branch, path } }) => { + const url = `https://api.github.com/repos/${repo}/contents/${path}?ref=${branch}` + + const response = await fetch(url, { + headers: { + Accept: 'application/vnd.github.v3+json', + // Authorization: `token ${process.env.GITHUB_TOKEN}`, + }, + }) + + if (!response.ok) { + throw new Error(`Failed to fetch contents: ${response.status}`) + } + + const contents: Array = await response.json() + + return contents + .filter((item) => item.type === 'file' && item.name.endsWith('.md')) + .map((item) => ({ + name: item.name.replace('.md', ''), + path: item.path, + })) + }) +``` + +## Adding Syntax Highlighting with Shiki + +For code blocks with syntax highlighting, integrate Shiki into your markdown processor: + +```tsx +// src/utils/markdown.ts +import { codeToHtml } from 'shiki' + +// Process code blocks after parsing +export async function highlightCode( + code: string, + language: string, +): Promise { + return codeToHtml(code, { + lang: language, + themes: { + light: 'github-light', + dark: 'tokyo-night', + }, + }) +} +``` + +Then handle code blocks in your Markdown component: + +```tsx +// In your Markdown component's replace function +if (domNode.name === 'pre') { + const codeElement = domNode.children.find( + (child) => child instanceof Element && child.name === 'code', ) + if (codeElement) { + const className = codeElement.attribs.class || '' + const language = className.replace('language-', '') || 'text' + const code = getText(codeElement) + + return + } } ``` -The adapter returns escaped token markup inside the renderer's own `
` elements. Unknown languages fall back to plain text. Add a `dark` class to an ancestor to select the dark theme. See the [syntax highlighting guide](https://tanstack.com/markdown/latest/docs/guides/syntax-highlighting) for line numbers and highlighted lines.
+## Summary
 
-## Table of Contents
+| Approach            | Best For                                  | Pros                                           | Cons                                      |
+| ------------------- | ----------------------------------------- | ---------------------------------------------- | ----------------------------------------- |
+| content-collections | Blog posts, static docs bundled with app  | Type-safe, build-time processing, fast runtime | Requires rebuild for content updates      |
+| Dynamic fetching    | External docs, frequently updated content | Always fresh, no rebuild needed                | Runtime overhead, requires error handling |
 
-To collect headings, add the docs preset when parsing the document:
-
-```ts
-import { docsMarkdownExtensions } from '@tanstack/markdown/extensions/docs'
-import { parseMarkdown } from '@tanstack/markdown/parser'
-
-const document = parseMarkdown(content, {
-  extensions: docsMarkdownExtensions(),
-})
-
-const headings = document.headings ?? []
-// Each heading has an id, text, and level.
-```
-
-Use this in the server function, then render links to each heading's `id`. The [docs preset guide](https://tanstack.com/markdown/latest/docs/guides/docs-preset) also covers callouts and custom comment components. Those features need the same extensions passed to the renderer.
+Choose the approach that best fits your content update frequency and deployment workflow. For hybrid scenarios, you can use both methods in the same application.
diff --git a/docs/start/framework/react/guide/seo.md b/docs/start/framework/react/guide/seo.md
index 1a202503a8..2d3e98757d 100644
--- a/docs/start/framework/react/guide/seo.md
+++ b/docs/start/framework/react/guide/seo.md
@@ -1,7 +1,6 @@
 ---
 id: seo
 title: SEO
-description: Configure SEO in TanStack Start with page metadata, canonical URLs, structured data, server rendering, sitemaps, and robots.txt.
 ---
 
 > [!NOTE]
diff --git a/docs/start/framework/react/guide/server-components.md b/docs/start/framework/react/guide/server-components.md
index 581ae145bd..6bbc716754 100644
--- a/docs/start/framework/react/guide/server-components.md
+++ b/docs/start/framework/react/guide/server-components.md
@@ -86,7 +86,7 @@ export default defineConfig({
 
 
 
-**Requirements:** React 19+, Vite 8+ or Rsbuild 2+
+**Requirements:** React 19+, Vite 7+ or Rsbuild 2+
 
 ## Quick Start
 
@@ -401,10 +401,7 @@ const postQueryOptions = (postId: string) => ({
 export const Route = createFileRoute('/posts/$postId')({
   loader: async ({ context, params }) => {
     // Prefetch during SSR - data reused on client without refetch
-    await context.queryClient.query({
-      ...postQueryOptions(params.postId),
-      staleTime: 'static',
-    })
+    await context.queryClient.ensureQueryData(postQueryOptions(params.postId))
   },
   component: PostPage,
 })
diff --git a/docs/start/framework/react/guide/server-entry-point.md b/docs/start/framework/react/guide/server-entry-point.md
index 5f74eb7846..5acc8ee550 100644
--- a/docs/start/framework/react/guide/server-entry-point.md
+++ b/docs/start/framework/react/guide/server-entry-point.md
@@ -3,72 +3,38 @@ id: server-entry-point
 title: Server Entry Point
 ---
 
+# Server Entry Point
+
 > [!NOTE]
-> A custom server entry point is **optional**. Without one, TanStack Start uses its built-in entry, which renders requests and converts uncaught errors into HTTP responses automatically.
+> The server entry point is **optional** out of the box. If not provided, TanStack Start will automatically handle the server entry point for you using the below as a default.
 
 The Server Entry Point supports the universal fetch handler format, commonly used by [Cloudflare Workers](https://developers.cloudflare.com/workers/runtime-apis/handlers/fetch/) and other WinterCG-compatible runtimes.
 
-The default export must provide a `fetch` method that accepts a `Request` and Start's request options, then returns a `Response` or `Promise`. Use `createServerEntry` to infer these types and keep the complete callback inside the request's context, including custom error handling. For example, this custom `src/server.ts` delegates to the built-in entry:
+To ensure interoperability, the default export must conform to our `ServerEntry` interface:
+
+```ts
+export default {
+  fetch(req: Request, opts?: RequestOptions): Response | Promise {
+    // ...
+  },
+}
+```
+
+TanStack Start exposes a wrapper to make creation type-safe. This is done in the `src/server.ts` file.
 
 ```tsx
 // src/server.ts
 import handler, { createServerEntry } from '@tanstack/react-start/server-entry'
 
 export default createServerEntry({
-  fetch(request, opts) {
-    return handler.fetch(request, opts)
+  fetch(request) {
+    return handler.fetch(request)
   },
 })
 ```
 
 Whether we are statically generating our app or serving it dynamically, the `server.ts` file is the entry point for doing all SSR-related work as well as for handling server routes and server function requests.
 
-## Configuring a Custom Server Entry
-
-Start automatically detects `src/server.ts`. If that file is absent, it uses the built-in entry. For a custom entry at another path, configure `server.entry` in your bundler plugin. This path is resolved relative to `srcDirectory`, which defaults to `src`.
-
-
-
-# Vite
-
-```ts title="vite.config.ts"
-import { defineConfig } from 'vite'
-import { tanstackStart } from '@tanstack/react-start/plugin/vite'
-import viteReact from '@vitejs/plugin-react'
-
-export default defineConfig({
-  plugins: [
-    tanstackStart({
-      server: {
-        entry: './server-entry.ts',
-      },
-    }),
-    viteReact(),
-  ],
-})
-```
-
-# Rsbuild
-
-```ts title="rsbuild.config.ts"
-import { defineConfig } from '@rsbuild/core'
-import { pluginReact } from '@rsbuild/plugin-react'
-import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild'
-
-export default defineConfig({
-  plugins: [
-    pluginReact(),
-    tanstackStart({
-      server: {
-        entry: './server-entry.ts',
-      },
-    }),
-  ],
-})
-```
-
-
-
 ## Custom Server Handlers
 
 You can create custom server handlers to modify how your application is rendered:
@@ -87,155 +53,16 @@ const customHandler = defineHandlerCallback((ctx) => {
   return defaultStreamHandler(ctx)
 })
 
-const startHandler = createStartHandler(customHandler)
+const fetch = createStartHandler(customHandler)
 
 export default createServerEntry({
-  fetch(request, opts) {
-    return startHandler(request, opts)
-  },
+  fetch,
 })
 ```
 
-## Error Handling
-
-The built-in entry uses `createServerEntry` to catch errors that escape the Start handler and call `handleStartError(error)` inside the active request context. This works without a custom `src/server.ts`. Response helpers such as `setResponseStatus`, `setResponseHeader`, and `setCookie` are applied to the error response.
-
-For an uncaught error, Start returns a generic JSON error body with status `500` unless a response helper or HTTP-style error property supplies an error status. A thrown `Response` keeps its body and response metadata, with response helpers applied, and loses its body for `HEAD` requests and for statuses `204`, `205`, and `304`, including one selected by a helper. The generic error body Start generates always uses an error status, so only `HEAD` removes it.
-
-For example, a request to this server route returns `401` with a `WWW-Authenticate` header:
-
-```tsx
-// src/routes/api/protected.ts
-import { createFileRoute } from '@tanstack/react-router'
-import { createMiddleware } from '@tanstack/react-start'
-import {
-  setResponseHeader,
-  setResponseStatus,
-} from '@tanstack/react-start/server'
-
-const authMiddleware = createMiddleware().server(() => {
-  setResponseStatus(401, 'Unauthorized')
-  setResponseHeader('www-authenticate', 'Bearer')
-  throw new Error('Unauthorized')
-})
-
-export const Route = createFileRoute('/api/protected')({
-  server: {
-    middleware: [authMiddleware],
-    handlers: {
-      GET: () => new Response('Protected content'),
-    },
-  },
-})
-```
-
-Error conversion preserves:
-
-- Error statuses (`400`-`599`) and their status text from `setResponseStatus`
-- Header operations from the response helpers
-- Cookies from `setCookie` and `appendResponseHeader('set-cookie', ...)`, including multiple `Set-Cookie` headers
-- HTTP-style error metadata such as `error.status`, `error.statusText`, `error.headers`, and `error.cause.headers`
-
-Start builds a new JSON body for an error, so it never copies the framing and connection headers `Content-Length`, `Content-Encoding`, `Transfer-Encoding`, `Trailer`, `Connection`, `Keep-Alive`, `Proxy-Connection`, and `TE` from error metadata. When `error.cause` is a `Response`, such as a failed upstream `fetch` from any fetch implementation, Start uses its status and status text but none of its headers, because they were written for that upstream reply.
-
-Explicit helper error statuses, their status text, and header operations take precedence over error metadata. An error response only uses an error status (`400`-`599`). A status set with `setResponseStatus` before the error applies only when it is an error status. A success, redirect, or bodyless status such as `200`, `201`, `302`, or `204` describes the response that the failure replaced, so Start discards it together with its status text and uses the error's own status or `500`. Error metadata such as `error.status` or `error.statusCode` likewise applies only when it is `400` or higher.
-
-Start logs the error to the server console unless the error's own metadata marks it as an HTTP error with a status of `400` or higher, even when a helper selected the status. The generic JSON body does not expose the error's message or stack.
-
-Errors that Router handles through route error components do not reach this top-level catch. Server function calls and their request middleware use a separate error response path that preserves the RPC serialization protocol. Failures during initialization, before that path is established, fall back to the top-level error response. Errors in a streamed body after the entry has returned its `Response` cannot replace that response's status or headers.
-
-You can use `createServerEntry` with your own `try`/`catch`, including for error reporting with Sentry. Your catch runs first; the wrapper converts only errors that escape your callback. Call the handler returned by `createStartHandler(...)` inside that catch, because it rethrows the original uncaught value:
-
-```tsx
-// src/server.ts
-import {
-  createStartHandler,
-  defaultStreamHandler,
-  handleStartError,
-} from '@tanstack/react-start/server'
-import { createServerEntry } from '@tanstack/react-start/server-entry'
-
-const startHandler = createStartHandler(defaultStreamHandler)
-
-export default createServerEntry({
-  async fetch(request, opts) {
-    try {
-      return await startHandler(request, opts)
-    } catch (error) {
-      // Report the original error here, for example to Sentry.
-      return handleStartError(error)
-    }
-  },
-})
-```
-
-After reporting, choose how to finish the catch:
-
-- Return `handleStartError(error)` to obtain Start's error response explicitly.
-- Rethrow `error` to let `createServerEntry` produce that same error response.
-- Return your own `Response` to choose its body, status, and headers.
-
-All three options keep `createServerEntry` and its request context. The first two preserve Start's response-helper state.
-
-The wrapper creates the request context before calling your `fetch` callback. The entire callback, including its own catch and code after `await`, runs inside that context. Calling the Start handler with the same `Request` reuses it. `handleStartError` therefore uses the correct request's state even when the thrown value is a primitive, or several requests throw the same `Error` object. Start does not attach request state to errors or remember them for a later catch. A catch outside this wrapper cannot recover a completed request's helper state from the error.
-
-The default export from `@tanstack/react-start/server-entry` is already wrapped. Calling its `fetch` method converts uncaught errors before an outer catch can see them. Use the handler returned by `createStartHandler(...)` inside your callback when you need to catch the original error, as above.
-
-Delegating to the default entry or another wrapped entry with the same `Request` object shares the current request context. A cloned or rewritten `Request` starts a separate context. When passing a new request to a raw `createStartHandler` handler, wrap that invocation with `createServerEntry` too, so errors are converted before leaving the new context:
-
-```tsx
-import {
-  createStartHandler,
-  defaultStreamHandler,
-} from '@tanstack/react-start/server'
-import { createServerEntry } from '@tanstack/react-start/server-entry'
-
-const rewrittenEntry = createServerEntry({
-  fetch: createStartHandler(defaultStreamHandler),
-})
-
-export default createServerEntry({
-  fetch(request, opts) {
-    const url = new URL(request.url)
-    if (url.pathname === '/legacy-home') {
-      url.pathname = '/'
-    }
-    return rewrittenEntry.fetch(new Request(url, request), opts)
-  },
-})
-```
-
-The rewritten request owns its response helper state. Catching a raw rewritten handler's error only in the original request's scope would not recover the rewritten request's headers or cookies.
-
-To replace an uncaught error response completely, return your own response from the custom catch:
-
-```tsx
-// src/server.ts
-import {
-  createStartHandler,
-  defaultStreamHandler,
-} from '@tanstack/react-start/server'
-import { createServerEntry } from '@tanstack/react-start/server-entry'
-
-const startHandler = createStartHandler(defaultStreamHandler)
-
-export default createServerEntry({
-  async fetch(request, opts) {
-    try {
-      return await startHandler(request, opts)
-    } catch (error) {
-      console.error(error)
-      return new Response('Internal Server Error', { status: 500 })
-    }
-  },
-})
-```
-
-`createServerEntry` returns custom responses as-is, whether they come from a catch or a successful callback. Such responses do not automatically inherit helper state. Likewise, helper writes after `await handler.fetch(...)` are not automatically applied to its returned response; modify that response directly or put the helper writes in Start middleware. Call `handleStartError` in a catch when the error response should inherit helper state.
-
 ## Request context
 
-When your server needs to pass additional, typed data into request handlers (for example, authenticated user info, a database connection, or per-request flags), register a request context type via TypeScript module augmentation. Pass the runtime values through the `context` property of the second argument to `handler.fetch`. Type registration does not create these values. The context is available throughout the server-side middleware chain — including global middleware, request/function middleware, server routes, server functions, and the router itself.
+When your server needs to pass additional, typed data into request handlers (for example, authenticated user info, a database connection, or per-request flags), register a request context type via TypeScript module augmentation. The registered context is delivered as the second argument to the server `fetch` handler and is available throughout the server-side middleware chain — including global middleware, request/function middleware, server routes, server functions, and the router itself.
 
 To add types for your request context, augment the `Register` interface from `@tanstack/react-router` with a `server.requestContext` property. The runtime `context` you pass to `handler.fetch` will then match that type. Example:
 
@@ -256,11 +83,8 @@ declare module '@tanstack/react-router' {
 }
 
 export default createServerEntry({
-  fetch(request, opts) {
-    return handler.fetch(request, {
-      ...opts,
-      context: { hello: 'world', foo: 123 },
-    })
+  async fetch(request) {
+    return handler.fetch(request, { context: { hello: 'world', foo: 123 } })
   },
 })
 ```
diff --git a/docs/start/framework/react/guide/server-functions.md b/docs/start/framework/react/guide/server-functions.md
index 879aa9e867..903e5d7b86 100644
--- a/docs/start/framework/react/guide/server-functions.md
+++ b/docs/start/framework/react/guide/server-functions.md
@@ -390,7 +390,7 @@ Stream typed data from server functions to the client. See the [Streaming Data f
 
 ### Raw Responses
 
-Return a `Response` for binary data or custom content types, and the call resolves with it. Throw a `Response` instead to reject the call with it. Either way, the caller receives its body and headers, and its status unless a response helper set one. The browser follows a `Response` with a redirect status and a `Location` header before the caller sees it, so use `redirect()` to send the user elsewhere.
+Return `Response` objects binary data, or custom content types.
 
 ### Progressive Enhancement
 
@@ -425,9 +425,7 @@ Customization:
 
 You can customize function ID generation for the production build by providing a `generateFunctionId` function when configuring the TanStack Start build tool plugin.
 
-Return `undefined` (or an empty string) to use the default ID. Prefer deterministic inputs (filename + functionName) so IDs remain stable between builds.
-
-The ID becomes one segment of the server function's URL (`/_serverFn/`), unencoded, so use only ASCII letters, digits, `-`, `.`, `_`, `~` and `$`, and not `.` or `..`. An ID with whitespace, a control or non-ASCII character, or any of `"`, `#`, `/`, `<`, `>`, `?`, `\`, `^`, `` ` ``, `{` and `}`, an ID that is `.` or `..`, or one with a percent-encoding the server reads as another ID (`%41` for `A`, lowercase hex, `%2E`) or rejects, fails the build with an error naming the file, the function and the ID: the request would reach another function or none. Other characters (`%`, `+`, `:`, `;`, `@`, `'`, `|`, `[`, `]`, …) still work, with a deprecation warning: the next major version rejects them, since proxies and servers may encode or normalise them in the URL. `filename` contains `/`, so hash it (as in the example below) rather than embedding it as is.
+Prefer deterministic inputs (filename + functionName) so IDs remain stable between builds.
 
 Please note that this customization is **experimental** and subject to change.
 
diff --git a/docs/start/framework/react/guide/tanstack-query.md b/docs/start/framework/react/guide/tanstack-query.md
deleted file mode 100644
index dec42ca26c..0000000000
--- a/docs/start/framework/react/guide/tanstack-query.md
+++ /dev/null
@@ -1,158 +0,0 @@
----
-id: tanstack-query
-title: TanStack Query
-updated: '2026-09-11'
-testedWith:
-  '@tanstack/react-start': '1.168.52'
-  '@tanstack/react-query': '5.102.0'
-  react: '19.2.3'
-  vite: '8.0.14'
-description: Use TanStack Query with TanStack Start for request-isolated SSR, hydration, route preloading, streaming, and mutation invalidation.
----
-
-TanStack Start uses Router loaders to coordinate navigation. TanStack Query can own the fetched data, freshness, and mutation state. Use them together when your application needs a query cache across routes, background updates, or mutation-driven invalidation.
-
-The [React Query example](../examples/start-basic-react-query) includes a `/preferences` page that reads and updates a display name stored in a cookie. Its [tests](https://github.com/TanStack/router/blob/main/examples/react/start-basic-react-query/tests/preferences.spec.ts) check server-rendered data, isolation between requests, hydration without a duplicate read, and invalidation after a server function. The preference cookie is not an authentication mechanism.
-
-## Install and create a QueryClient per router
-
-Install `@tanstack/react-query` and `@tanstack/react-router-ssr-query`. The example uses Query 5.102 or newer, including `queryClient.query`. See the [integration reference](/router/latest/docs/integrations/query) for its options.
-
-```tsx title="src/router.tsx"
-import { QueryClient } from '@tanstack/react-query'
-import { createRouter } from '@tanstack/react-router'
-import { setupRouterSsrQueryIntegration } from '@tanstack/react-router-ssr-query'
-import { routeTree } from './routeTree.gen'
-
-export function getRouter() {
-  const queryClient = new QueryClient({
-    defaultOptions: { queries: { staleTime: 30_000 } },
-  })
-  const router = createRouter({
-    routeTree,
-    context: { queryClient },
-    defaultPreload: 'intent',
-    defaultPreloadStaleTime: 0,
-  })
-
-  setupRouterSsrQueryIntegration({ router, queryClient })
-  return router
-}
-```
-
-Create the client inside `getRouter`, not at module scope. Start creates a router for each SSR request. A process-wide QueryClient could reuse one reader's cached data in another reader's HTML. The browser then keeps the client attached to its router during navigation.
-
-Declare `queryClient: QueryClient` in the root route's `createRootRouteWithContext` type so child loaders can access it. The integration supplies the Query provider and handles SSR dehydration, hydration, and streaming. Do not add a second QueryClient or independently dehydrate the same cache. If you already own the provider wrapper, use the integration's `wrapQueryClient: false` option.
-
-`defaultPreloadStaleTime: 0` lets Query decide whether a preload needs data. The example's 30-second Query `staleTime` prevents an immediate repeat read when the browser receives fresh SSR data. Choose the freshness window for your application, rather than treating 30 seconds as a universal setting.
-
-## Share query options between the loader and component
-
-Keep a query's key and function together. Privileged reads belong in a server function, because a normal route loader can also run in the browser during navigation.
-
-```tsx title="src/utils/preferences.ts"
-import { queryOptions } from '@tanstack/react-query'
-import { createServerFn } from '@tanstack/react-start'
-import { getCookie, setResponseHeader } from '@tanstack/react-start/server'
-
-export const getReaderName = createServerFn({ method: 'GET' }).handler(() => {
-  setResponseHeader('Cache-Control', 'private, no-store')
-  return getCookie('reader-name') || 'Guest'
-})
-
-export const readerNameOptions = queryOptions({
-  queryKey: ['reader-name'],
-  queryFn: () => getReaderName(),
-})
-```
-
-The route awaits the query for content that must appear in the initial HTML:
-
-```tsx title="src/routes/preferences.tsx"
-import { useSuspenseQuery } from '@tanstack/react-query'
-import { createFileRoute } from '@tanstack/react-router'
-import { readerNameOptions } from '../utils/preferences'
-
-export const Route = createFileRoute('/preferences')({
-  loader: async ({ context }) => {
-    await context.queryClient.query(readerNameOptions)
-  },
-  headers: () => ({ 'Cache-Control': 'private, no-store' }),
-  component: Preferences,
-})
-
-function Preferences() {
-  const { data: name } = useSuspenseQuery(readerNameOptions)
-  return 

Hello, {name}

-} -``` - -Both calls use the same query key and options. The loader populates the request's cache; the component reads it; the integration transfers it to the browser. The component does not need to call the server function again in an effect. - -For a parameterized resource, include its identity in the key, such as `['post', postId]`. If search values affect the result, validate them and include them in both `loaderDeps` and the query key. Keep secrets out of keys and serialized query data. - -## Await critical data and stream secondary data - -Await queries that determine the page's main content, title, authorization, redirects, or whether it exists. Return title and description data from the loader when a route's `head` needs them, as the example's post route does. - -Secondary content can begin loading without blocking the loader, then render inside a Suspense boundary. Keep that query under the SSR integration so its result can stream to the browser. Handle the imperative query promise's rejection as well as the component's error boundary; a fire-and-forget promise should not become an unhandled server rejection. - -The example's existing `/deferred` route shows a separate Suspense boundary. See [streaming and prefetching](/router/latest/docs/integrations/query#prefetching-and-streaming) for the integration's behavior. A plain `useQuery` that has no loader prefetch is not a guarantee that its data will be in the server-rendered HTML. - -## Invalidate Query after a server mutation - -The preference example validates the display name and writes its cookie inside a POST server function. Its `src/start.ts` enables Start's CSRF middleware for server-function requests. The component calls that function through `useServerFn`, then invalidates the query that reads the cookie: - -```tsx -const queryClient = useQueryClient() -const save = useServerFn(saveReaderName) -const mutation = useMutation({ - mutationFn: (name: string) => save({ data: name }), - onSuccess: () => - queryClient.invalidateQueries({ queryKey: readerNameOptions.queryKey }), -}) -``` - -Returning the invalidation promise keeps the mutation pending until its active query's refetch finishes. The form can use `mutation.isPending` and `mutation.isError` for feedback. The example also disables its JavaScript-dependent form until hydration and uses a POST method so a native submission cannot put form values in the URL. - -Invalidate the data's actual owner. `queryClient.invalidateQueries` refreshes Query data; `router.invalidate()` reloads Router-owned loader data and route context. Use both only when the mutation changes both, such as a login that changes root authentication context and private queries. Neither call purges your CDN or invalidates a database cache. - -If a mutation returns the complete updated resource, `setQueryData` can update that cache entry directly instead. Optimistic updates need cancellation, rollback on failure, and reconciliation with the server result. This example uses a confirmed write followed by invalidation, not an optimistic update. - -## Keep account data isolated beyond SSR - -Request-scoped QueryClients prevent cross-request cache sharing on the server. They do not authorize reads or automatically clear a browser cache when its account changes. - -For authenticated applications, authorize every private read and mutation on the server, including resource-level permissions. On sign-out or account switching, cancel and remove the previous account's private queries, then reload the relevant route context. Include account or tenant identity in keys when that is part of the resource's identity, but do not treat a key as an access-control check. - -The `/preferences` route and its server functions return `Cache-Control: private, no-store` because their output varies by cookie. Verify the final response through your hosting provider and CDN. Do not publicly cache personalized HTML merely because the QueryClient itself is isolated. - -## Diagnose extra requests - -Check when and where each request occurs. A background refresh after the freshness window, a reconnect, or a deliberate invalidation can be expected. - -| Symptom | Check | -| --------------------------------------------------- | --------------------------------------------------------------------------------------------- | -| A read repeats immediately after hydration | Query `staleTime`, hydration configuration, matching keys, and accidental extra QueryClients | -| Navigation loads different data than a direct visit | Search validation, `loaderDeps`, query keys, and server-only boundaries | -| A mutation succeeds but old data stays visible | Which cache owns the displayed value and which keys were invalidated | -| A second account sees the first account's data | Module-scoped server clients, browser cache cleanup, account keys, and shared HTTP caches | -| SSR contains only a loading state | Whether the loader awaited critical data and whether the component reads the prefetched query | - -Start with the same options object in the loader and component. Avoid adding manual hydration code or disabling all refetching to hide a duplicate request. - -## Run the example's checks - -From the repository root, install dependencies and build the framework packages as described in [Contributing](https://github.com/TanStack/router/blob/main/CONTRIBUTING.md). Then: - -```sh -cd examples/react/start-basic-react-query -pnpm exec playwright install chromium -pnpm test:e2e -pnpm build -QUERY_EXAMPLE_PRODUCTION=1 pnpm test:e2e -``` - -The tests send concurrent SSR requests with different preference cookies while using the same query key. Each HTML response must contain only its own reader's value. The browser test then requires zero additional reads during hydration, exactly one read after mutation invalidation, and no extra read after a reload hydrates fresh data. - -The post and user demos use JSONPlaceholder. The preference tests run without that external API. diff --git a/docs/start/framework/react/migrate-from-next-js.md b/docs/start/framework/react/migrate-from-next-js.md index dc5377df08..2f4d988449 100644 --- a/docs/start/framework/react/migrate-from-next-js.md +++ b/docs/start/framework/react/migrate-from-next-js.md @@ -1,187 +1,510 @@ --- id: migrate-from-next-js title: Migrate from Next.js -description: Move a Next.js App Router application to TanStack Start while preserving routes, metadata, authentication, mutations, and deployment behavior. --- -This guide migrates a Next.js App Router application to TanStack Start. The [runnable before-and-after example](https://github.com/TanStack/router/tree/main/examples/react/start-next-migration) implements the same article site in both frameworks, including public articles, URL search, sign-in, a private saved-article page, and a mutation. +This guide provides a step-by-step process to migrate a project from the Next.js App Router to **TanStack Start**. We respect the powerful features of Next.js and aim to make this transition as smooth as possible. -Start does not interpret Next.js route conventions or configuration. Keep your application behavior, then translate each framework boundary. If your application relies heavily on React Server Components, read the [comparison](./start-vs-nextjs) and [RSC guide](./guide/server-components) first. Start's RSC support is experimental and opt-in; the example uses ordinary route components and server functions. +## Step-by-Step (Basics) -## Run the reference application +This step-by-step guide provides an overview of how to migrate your Next.js App Router project to TanStack Start. The goal is to help you understand the basic steps involved in the migration process so you can adapt them to your specific project needs. -Use Node 24 or newer and pnpm 12: +### Prerequisites + +Before we begin, this guide assumes your project structure looks like this: + +```txt +├── next.config.ts +├── package.json +├── postcss.config.mjs +├── public +│ ├── file.svg +│ ├── globe.svg +│ ├── next.svg +│ ├── vercel.svg +│ └── window.svg +├── README.md +├── src +│ └── app +│ ├── favicon.ico +│ ├── globals.css +│ ├── layout.tsx +│ └── page.tsx +└── tsconfig.json +``` + +Alternatively, you can follow along by cloning the following [starter template](https://github.com/nrjdalal/awesome-templates/tree/main/next.js-apps/next.js-start): ```sh -git clone --depth 1 https://github.com/TanStack/router.git -cd router -pnpm install -pnpm nx run @tanstack/react-start:build -cd examples/react/start-next-migration +npx gitpick nrjdalal/awesome-templates/tree/main/next.js-apps/next.js-start next.js-start-er ``` -Follow the example's [README](https://github.com/TanStack/router/blob/main/examples/react/start-next-migration/README.md) to set `SESSION_PASSWORD` and `DEMO_PASSWORD`. Run `pnpm dev:next` at `http://localhost:3100` and `pnpm dev` in another terminal at `http://localhost:3101`. +This structure is a basic Next.js application using the App Router, which we will migrate to TanStack Start. -The example's single account is `reader@example.com`. It stores one saved-article flag in a session cookie so you can exercise a protected mutation without connecting a database. It is not a production authentication implementation. Both apps use iron-session with different cookie names, so sign in separately to each. +### 1. Remove Next.js -With those ports free, run: +First, uninstall Next.js and remove related configuration files: ```sh -pnpm exec playwright install chromium -pnpm test:e2e -pnpm build:next -pnpm build -MIGRATION_PRODUCTION=1 pnpm test:e2e +npm uninstall @tailwindcss/postcss next +rm postcss.config.* next.config.* ``` -The same browser tests run against both apps. They check public URLs, server-rendered metadata, query filtering, redirects, missing pages, sitemap entries, sign-in errors, session persistence, private response caching, mutations, and server rejection after sign-out. +### 2. Install Required Dependencies -## Inventory the application before changing it +TanStack Start leverages TanStack Router and supports [Vite](https://vite.dev) or [Rsbuild](https://rsbuild.dev/) as the build tool. The Vite setup below includes [Nitro](https://nitro.build/) as a deployment plugin. -Record your current paths and observable behavior. Include dynamic paths, query parameters, redirects, trailing slashes, locale prefixes, response status, title, description, canonical, robots directives, and sitemap membership. Keep representative HTML responses and run your existing application tests against the replacement. + -Inventory Next.js-specific code separately: `next/*` imports, `'use server'`, server-only modules, metadata exports, `generateStaticParams`, `revalidatePath`, `revalidateTag`, cache directives, route configuration, Proxy or middleware, and image/font configuration. A route that renders successfully can still have lost authentication, cache invalidation, or an important search URL. +# Vite -| Request | Required behavior | -| -------------------------- | -------------------------------------------------------------------- | -| `/` | Article list, title, description, self-referencing canonical | -| `/?q=metadata` | Filtered article list; canonical remains `/` | -| `/posts/keeping-your-urls` | Same article, title, description, canonical, and Open Graph title | -| `/posts/missing` | HTTP 404 | -| `/old-notes` | HTTP 308 to `/posts/keeping-your-urls` | -| `/saved` | Signed-out users reach sign-in; private HTML is not shared-cacheable | -| `/sitemap.xml` | Public pages only | - -For your application, decide which query variants deserve indexing. Do not copy the example's canonical policy onto meaningful product filters or paginated results without checking their content. - -## Set up Start alongside the existing app - -Create a Start application using [Getting Started](./getting-started) and [Build from Scratch](./build-from-scratch). Keep the Next.js app runnable until the migrated routes pass their checks. You do not need to remove Next.js, its configuration, or its CSS tooling before you can test Start. - -```text -next-app/ # Before: Next.js App Router - app/ - layout.tsx - page.tsx - posts/[slug]/page.tsx - actions.ts -src/ # After: TanStack Start - router.tsx - routes/ - __root.tsx - index.tsx - posts.$slug.tsx - server/account.ts -vite.config.ts +```sh +npm i @tanstack/react-router @tanstack/react-start nitro vite @vitejs/plugin-react ``` -The Start Vite plugin generates `src/routeTree.gen.ts`. `src/router.tsx` returns a new router using that tree. The root route renders `HeadContent` in the document head and `Scripts` in the body. Merge your existing CSS, document attributes, and providers into that root. +# Rsbuild -The reference uses Vite and Nitro's Node output. If you use another host or build tool, follow its [hosting instructions](./guide/hosting) and test its actual build output. A Next.js deployment adapter does not become a Start adapter by changing dependencies. - -## Preserve paths while changing route files - -| Next.js App Router | Default Start route directory | -| ------------------------------ | ---------------------------------------------- | -| `app/layout.tsx` | `src/routes/__root.tsx` | -| `app/page.tsx` | `src/routes/index.tsx` | -| `app/posts/page.tsx` | `src/routes/posts.index.tsx` | -| `app/posts/[slug]/page.tsx` | `src/routes/posts.$slug.tsx` | -| `app/docs/[...parts]/page.tsx` | `src/routes/docs.$.tsx` | -| `app/api/hello/route.ts` | `src/routes/api.hello.ts` with server handlers | - -`src/routes` is a source directory, not a URL prefix. A route for `/posts/example` uses `createFileRoute('/posts/$slug')`, not `/app/posts/$slug`. - -Nested layouts, pathless layouts, route groups, optional parameters, catch-alls, parallel routes, and intercepting routes need individual mapping. Read [routing concepts](/router/latest/docs/routing/routing-concepts) instead of mechanically renaming every file. The reference does not reproduce Next.js parallel or intercepting route behavior. - -Replace `next/link` with Router's `Link`. Dynamic paths use typed `params`: - -```tsx - - {article.title} - +```sh +npm i @tanstack/react-router @tanstack/react-start @rsbuild/core @rsbuild/plugin-react ``` -Check direct requests, client navigation, back/forward, and reload for each representative path. Update your redirects and sitemap from the same route inventory. + -## Validate URL search state +For Tailwind CSS, install the build tool integration you want to use: -Next.js passes `searchParams` to an App Router page. Start validates URL state in the route: + -```tsx -export const Route = createFileRoute('/')({ - validateSearch: (search) => ({ - q: typeof search.q === 'string' ? search.q : '', - }), - component: Articles, -}) +# Vite -function Articles() { - const { q } = Route.useSearch() - return

Searching for: {q}

+```sh +npm i -D @tailwindcss/vite tailwindcss +``` + +# Rsbuild + +```sh +npm i -D @tailwindcss/postcss tailwindcss +``` + + + +### 3. Update Project Configuration + +Now that you've installed the necessary dependencies, update your project configuration files to work with TanStack Start. + + + +# Vite + +```json +{ + "type": "module", + "scripts": { + "dev": "vite dev", + "build": "vite build", + "start": "node .output/server/index.mjs" + } } ``` -If a loader depends on search state, declare the relevant values in `loaderDeps`. That makes those values part of the loader's dependency and cache behavior. Validate page numbers, sorting, and filters at runtime; TypeScript types alone do not validate an incoming URL. See [search parameters](/router/latest/docs/guide/search-params) and [data loading](/router/latest/docs/guide/data-loading). +# Rsbuild -## Move server reads into server functions +```json +{ + "type": "module", + "scripts": { + "dev": "rsbuild dev", + "build": "rsbuild build" + } +} +``` -An ordinary Start route loader can execute on the server for the initial request and in the browser during navigation. Do not move a database query, credential, or privileged SDK directly from an async Next.js Server Component into an ordinary loader. + -Put the privileged read inside a [server function](./guide/server-functions), then call it from the loader. The reference's `/saved` route calls `getAccount`, checks the result, and redirects signed-out readers. Its public article loader only reads bundled public content. + -Return the data the browser is allowed to see, not an entire database record. Keep connection setup and secrets on the server. For a database-backed application, preserve your schema and access layer where possible, and change the framework-facing handler around them. +# Vite -## Translate mutations and their invalidation +```ts title="vite.config.ts" +import { defineConfig } from 'vite' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import viteReact from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' +import { nitro } from 'nitro/vite' -The reference's Next.js form calls a Server Action. That Action authorizes the session, changes the saved flag, and calls `revalidatePath('/saved')`. The Start version calls a POST server function through `useServerFn`, then awaits `router.invalidate()` to reload the active route data. +export default defineConfig({ + server: { + port: 3000, + }, + resolve: { + // Enables Vite to resolve imports using path aliases. + tsconfigPaths: true, + }, + plugins: [ + tailwindcss(), + tanstackStart({ + srcDirectory: 'src', // This is the default + router: { + // Specifies the directory TanStack Router uses for your routes. + routesDirectory: 'app', // Defaults to "routes", relative to srcDirectory + }, + }), + viteReact(), + nitro(), + ], +}) +``` -These invalidation APIs operate on different caches. `router.invalidate()` does not purge a CDN, clear a database cache, or revalidate all statically generated pages. If the app uses TanStack Query, invalidate the relevant query keys as well. Map each existing `revalidatePath`, tag, and cache directive to the layer that owns the replacement data. +# Rsbuild -The Start function checks authorization even though the route already checks it. A caller can invoke the mutation without visiting the page. Validate every untrusted input inside the server boundary and preserve resource-level permissions. +```ts title="rsbuild.config.ts" +import { defineConfig } from '@rsbuild/core' +import { pluginReact } from '@rsbuild/plugin-react' +import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' -`useServerFn` returns a callable function. The reference keeps pending and error state in the component and reloads route data after a successful mutation. It also tests replaying the mutation after sign-out. +export default defineConfig({ + server: { + port: 3000, + }, + plugins: [ + pluginReact(), + tanstackStart({ + srcDirectory: 'src', // This is the default + router: { + // Specifies the directory TanStack Router uses for your routes. + routesDirectory: 'app', // Defaults to "routes", relative to srcDirectory + }, + }), + ], +}) +``` -Next.js Action forms and these Start event-handler forms have different no-JavaScript behavior. The latter require JavaScript and keep their fields disabled until hydration. If progressive enhancement is a requirement, use a FormData-compatible [server function URL](./guide/server-functions#progressive-enhancement) or an ordinary form POST to a [server route](./guide/server-routes). Include validation, CSRF protection, and an appropriate response or redirect. Do not treat `createServerFn` as a drop-in replacement for the React form Action protocol. +```js title="postcss.config.mjs" +export default { + plugins: { + '@tailwindcss/postcss': {}, + }, +} +``` -## Preserve authentication and session boundaries + -Follow the [authentication guide](./guide/authentication) for the route-context pattern. Check sessions on the server for private reads and mutations. A hidden button or a client route guard is not authorization. +By default, `routesDirectory` is set to `routes`. To maintain consistency with Next.js App Router conventions, you can set it to `app` instead. -The example keeps `iron-session` and replaces Next.js `cookies()` with a small adapter using Start's `getCookie` and `setCookie`. Start does not provide a session API. The example uses different cookie names to keep its two local apps independent; sharing a library alone does not make every session configuration compatible. A real migration can keep its existing auth provider or session service and adapt the request boundary instead. If sessions must survive cutover or rollback, verify cookie names, domains, paths, signing/encryption formats, expiration, key rotation, and logout in both deployments. +### 4. Adapt the Root Layout -Private pages need a cache policy that prevents another user receiving personalized HTML. The Start reference returns `Cache-Control: private, no-store` for `/saved`. Check the final response through your deployment and CDN, including after sign-in and sign-out. Do not prerender or publicly cache pages that include private account data. +> TanStack Start uses a routing approach similar to Remix, with some changes to support nested structures and special features using tokens. Learn more about it at [Routing Concepts](/router/latest/docs/framework/react/routing/routing-concepts) guide. -## Preserve metadata and search responses +Instead of `layout.tsx`, create a file named `__root.tsx` in the `src/app` directory. This file will serve as the root layout for your application. -Next.js `metadata` and `generateMetadata` become a Start route's `head` configuration. The article route derives title, description, Open Graph title, and canonical from its loader result. Keep `HeadContent` in the root document so those values appear in the response. +- `src/app/layout.tsx` to `src/app/__root.tsx` -Compare HTML responses before JavaScript runs, then check the head after client navigation. Keep the public canonical origin independent of a local or preview host. Preserve locale alternates and social images where your app has them. See [SEO](./guide/seo) and [head management](/router/latest/docs/guide/document-head-management). +```tsx +- import type { Metadata } from "next" // [!code --] +import { + Outlet, + createRootRoute, + HeadContent, + Scripts, +} from "@tanstack/react-router" +import appCss from "./globals.css?url" -Next.js metadata file conventions also need replacements. The reference turns `app/sitemap.ts` into a Start server route at `/sitemap.xml`. Migrate `robots.txt`, icons, manifests, and generated social images explicitly. Return real 404s for missing content and maintain intentional permanent redirects. Avoid redirecting every missing URL to the homepage. +- export const metadata: Metadata = { // [!code --] +- title: "Create Next App", // [!code --] +- description: "Generated by create next app", // [!code --] +- } // [!code --] +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: "utf-8" }, + { + name: "viewport", + content: "width=device-width, initial-scale=1", + }, + { title: "TanStack Start Starter" } + ], + links: [ + { + rel: 'stylesheet', + href: appCss, + }, + ], + }), + component: RootLayout, +}) -## Replace image and font services deliberately +- export default function RootLayout({ // [!code --] +- children, // [!code --] +- }: Readonly<{ // [!code --] +- children: React.ReactNode // [!code --] +- }>) { // [!code --] +- return ( // [!code --] +- // [!code --] +- {children} // [!code --] +- // [!code --] +- ) // [!code --] +- } // [!code --] +function RootLayout() { + return ( + + + + + + + + + + ) +} +``` -Start does not automatically provide the Next.js image optimizer. Preserve image dimensions, responsive sources, loading behavior, alt text, and cache policy. Plain `` works for preprocessed assets; an image component such as Unpic needs a compatible image service or prepared sources to provide transformations. It does not create Next.js's image processing backend by itself. Next.js also supports its optimizer when [self-hosted](https://nextjs.org/docs/app/guides/self-hosting). +### 5. Adapt the Home Page -Replace `next/font` with self-hosted font files, a package such as Fontsource, or another chosen font delivery method. CSS `@font-face` does not require Tailwind. Preserve font weights and subsets, set an appropriate `font-display`, and check layout shift and network requests. Copy public assets and update imports only after confirming their resulting URLs. +Instead of `page.tsx`, create an `index.tsx` file for the `/` route. -The reference uses text and the browser's default font. It does not claim to verify your image transformations or font loading. +- `src/app/page.tsx` to `src/app/index.tsx` -## Rebuild caching and deployment behavior +```tsx ++ import { createFileRoute } from '@tanstack/react-router' // [!code ++] -List each cache separately: browser data, Router loaders, Query, server data, generated pages, and CDN responses. Define what populates it, its key, expiration, and the operation that invalidates it. Test after changing data, signing out, and deploying a new version. +- export default function Home() { // [!code --] ++ export const Route = createFileRoute('/')({ // [!code ++] ++ component: Home, // [!code ++] ++ }) // [!code ++] -Next.js cache directives, revalidation, and `generateStaticParams` do not carry across automatically. Use [static prerendering](./guide/static-prerendering) only for suitable public routes, and review [ISR](./guide/isr) with your hosting provider's actual behavior. A cache header alone is not proof of equivalent regeneration or invalidation. ++ function Home() { // [!code ++] + return ( +
+ ) +} +``` -Move server-only environment variables into the server runtime. Audit any public variable prefix changes rather than exposing the old environment wholesale. Verify API/webhook URLs, forwarded host/protocol, cookies behind a proxy, asset paths, streaming, and runtime limits in the deployment you will use. +### 6. Are we migrated yet? -## Cut over with a rollback path +Before you can run the development server, you need to create a file that will define the behavior of TanStack Router within TanStack Start. -1. Build both applications and run the contract checks against a staging deployment of Start. Include real representative data, authenticated sessions, and the CDN in that check. -2. Keep the current database schema compatible with both versions during the transition. Separate destructive schema changes from the framework cutover. -3. Preserve the public origin and paths where possible. If paths must change, deploy tested redirects and update internal links, canonicals, and sitemaps together. -4. Record the previous deployment and routing configuration. Know how to route traffic back, and what happens to sessions and writes if you do. -5. Monitor error rates, login and mutation failures, response status, indexing signals, and application conversion events after cutover. Compare against the baseline rather than assuming a framework change will improve search traffic. +- `src/router.tsx` -Remove Next.js and its unused configuration after the migrated behavior and rollback plan are verified. Retain historical redirects and any assets still referenced by public content. +```tsx +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + const router = createRouter({ + routeTree, + scrollRestoration: true, + }) + + return router +} +``` + +> 🧠 Here you can configure everything from the default [preloading functionality](/router/latest/docs/framework/react/guide/preloading) to [caching staleness](/router/latest/docs/framework/react/guide/data-loading). + +Don't worry if you see some TypeScript errors at this point; the next step will resolve them. + +### 7. Verify the Migration + +Run the development server: + +```sh +npm run dev +``` + +Then, visit `http://localhost:3000`. You should see the TanStack Start welcome page with its logo and a documentation link. + +> If you encounter issues, review the steps above and ensure that file names and paths match exactly. For a reference implementation, see the [post-migration repository](https://github.com/nrjdalal/next-to-start). + +## Next Steps (Advanced) + +Now that you have migrated the basic structure of your Next.js application to TanStack Start, you can explore more advanced features and concepts. + +### Routing Concepts + +| Route Example | Next.js | TanStack Start | +| ------------------------------ | ---------------------------------- | ------------------------- | +| Root Layout | `src/app/layout.tsx` | `src/app/__root.tsx` | +| `/` (Home Page) | `src/app/page.tsx` | `src/app/index.tsx` | +| `/posts` (Static Route) | `src/app/posts/page.tsx` | `src/app/posts.tsx` | +| `/posts/[slug]` (Dynamic) | `src/app/posts/[slug]/page.tsx` | `src/app/posts/$slug.tsx` | +| `/posts/[...slug]` (Catch-All) | `src/app/posts/[...slug]/page.tsx` | `src/app/posts/$.tsx` | +| `/api/endpoint` (API Route) | `src/app/api/endpoint/route.ts` | `src/app/api/endpoint.ts` | + +Learn more about the [Routing Concepts](/router/latest/docs/framework/react/routing/routing-concepts). + +### Dynamic and Catch-All Routes + +Retrieving dynamic route parameters in TanStack Start is straightforward. + +```tsx +- export default async function Page({ // [!code --] +- params, // [!code --] +- }: { // [!code --] +- params: Promise<{ slug: string }> // [!code --] +- }) { // [!code --] ++ export const Route = createFileRoute('/app/posts/$slug')({ // [!code ++] ++ component: Page, // [!code ++] ++ }) // [!code ++] + ++ function Page() { // [!code ++] +- const { slug } = await params // [!code --] ++ const { slug } = Route.useParams() // [!code ++] + return
My Post: {slug}
+} +``` + +> Note: If you've made a catch-all route (like `src/app/posts/$.tsx`), you can access the parameters via `const { _splat } = Route.useParams()`. + +Similarly, you can access `searchParams` using `const { page, filter, sort } = Route.useSearch()`. + +Learn more about the [Dynamic and Catch-All Routes](/router/latest/docs/framework/react/routing/routing-concepts#dynamic-route-segments). + +### Links + +```tsx +- import Link from "next/link" // [!code --] ++ import { Link } from "@tanstack/react-router" // [!code ++] + +function Component() { +- return Dashboard // [!code --] ++ return Dashboard // [!code ++] +} +``` + +Learn more about the [Links](/router/latest/docs/framework/react/guide/navigation#link-component). + +### Images + +Next.js uses the `next/image` component for optimized images. In TanStack Start, you can use the package called [Unpic](https://unpic.pics/) for similar functionality +and almost a drop-in replacement. + +```tsx +import Image from 'next/image' // [!code --] +import { Image } from '@unpic/react' // [!code ++] +function Component() { + return ( + Description + ) +} +``` + +### Server ~Actions~ Functions + +```tsx +- 'use server' // [!code --] ++ import { createServerFn } from "@tanstack/react-start" // [!code ++] + +- export const create = async () => { // [!code --] ++ export const create = createServerFn().handler(async () => { // [!code ++] + return true +- } // [!code --] ++ }) // [!code ++] +``` + +Learn more about the [Server Functions](./guide/server-functions). + +### Server Routes ~Handlers~ + +```ts +- export async function GET() { // [!code --] ++ export const Route = createFileRoute('/api/hello')({ // [!code ++] ++ server: { // [!code ++] ++ handlers: { // [!code ++] ++ GET: async () => { // [!code ++] ++ return Response.json("Hello, World!") ++ } // [!code ++] ++ } // [!code ++] ++ } // [!code ++] ++ }) // [!code ++] +``` + +Learn more about the [Server Routes](./guide/server-routes). + +### Fonts + +```tsx +- import { Inter } from "next/font/google" // [!code --] + +- const inter = Inter({ // [!code --] +- subsets: ["latin"], // [!code --] +- display: "swap", // [!code --] +- }) // [!code --] + +- export default function Page() { // [!code --] +- return

Font Sans

// [!code --] +- } // [!code --] +``` + +Instead of `next/font`, use Tailwind CSS’s CSS-first approach. Install fonts (for example, from [Fontsource](https://github.com/fontsource/fontsource)): + +```sh +npm i -D @fontsource-variable/dm-sans @fontsource-variable/jetbrains-mono +``` + +Add the following to `src/app/globals.css`: + +```css +@import 'tailwindcss' source('../'); + +@import '@fontsource-variable/dm-sans'; /* [!code ++] */ +@import '@fontsource-variable/jetbrains-mono'; /* [!code ++] */ + +@theme inline { + --font-sans: 'DM Sans Variable', sans-serif; /* [!code ++] */ + --font-mono: 'JetBrains Mono Variable', monospace; /* [!code ++] */ + /* ... */ +} + +/* ... */ +``` + +### Fetching Data + +```tsx +- export default async function Page() { // [!code --] ++ export const Route = createFileRoute('/')({ // [!code ++] ++ component: Page, // [!code ++] ++ loader: async () => { // [!code ++] ++ const res = await fetch('https://api.vercel.app/blog') // [!code ++] ++ return res.json() // [!code ++] ++ }, // [!code ++] ++ }) // [!code ++] + ++ function Page() { // [!code ++] +- const data = await fetch('https://api.vercel.app/blog') // [!code --] +- const posts = await data.json() // [!code --] ++ const posts = Route.useLoaderData() // [!code ++] + + return ( +
    + {posts.map((post) => ( +
  • {post.title}
  • + ))} +
+ ) +} +``` diff --git a/docs/start/framework/react/migrate-from-release-candidate.md b/docs/start/framework/react/migrate-from-release-candidate.md deleted file mode 100644 index 5cfa614cda..0000000000 --- a/docs/start/framework/react/migrate-from-release-candidate.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -id: migrate-from-release-candidate -title: Migrate from the Release Candidate -description: Upgrade a TanStack Start release-candidate app to the first stable release, 1.169. ---- - -`@tanstack/react-start` 1.169 is the first stable release of TanStack Start. Upgrading from a release candidate means replacing the removed APIs below and checking the behavior changes that apply to your app. - -## Vite 8 - -Start requires Vite 8 when you build with Vite. Upgrade with Vite's [migration guide](https://vite.dev/guide/migration). - -## Removed APIs - -| Removed | Use instead | -| ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `@tanstack/nitro-v2-vite-plugin` | `nitro()` from `nitro/vite`. See [Nitro hosting](./guide/hosting#nitro). | -| `useSession` | A session library such as iron-session. See [Session Management](./guide/authentication#2-session-management). The new library cannot read existing Start session cookies: use a new cookie name and sign users in again, or test a migration that reads the old cookies first. | -| `.inputValidator()` on server functions and middleware | `.validator()`, which takes the same validator. | - -## Errors - -- A handler returned by `createStartHandler(...)` now rethrows the original error. `createServerEntry` converts errors to responses, and the built-in entry already uses it. In a custom entry, catch inside the `createServerEntry` callback and `return handleStartError(error)` or rethrow. See [Error Handling](./guide/server-entry-point#error-handling). -- Uncaught errors produce a generic JSON body with a status from `400` to `599` (`500` by default), even if a success status was set before the error. Return a `Response` when an endpoint needs a specific error payload. -- A server-function call rejects with whatever was thrown, including a `Response` and falsy values such as `undefined`. Return a `Response` to resolve the call with it. See [Raw Responses](./guide/server-functions#raw-responses). -- Errors thrown by request middleware during a server-function call are sent to the client with their message, and their status is no longer always `500`. - -## Responses - -- Response helpers override the response you return or throw. `setResponseStatus(401)` followed by returning a `200` response sends `401`. -- `setResponseHeader('set-cookie', cookie)` replaces all outgoing cookies. Use `setCookie` or `appendResponseHeader('set-cookie', cookie)` to add one. -- `setResponseStatus` ignores codes outside `200`-`599` and warns outside production. -- Serialized server-function replies never carry `Location`, `Content-Encoding`, or `Content-Length` from helpers, and ignore a helper `204`, `205`, or `304`. Use `redirect()` to redirect. - -## Requests and middleware - -- `getRequestHeader(name)` returns `''` for a header that is present but empty, and `undefined` only when it is missing. -- A path with invalid percent-encoding, such as `/%E0%A4%A`, gets `400 Bad Request` before your server entry or middleware runs. -- When no function middleware sends context, `sendContext` is `undefined` instead of `{}`. diff --git a/docs/start/framework/react/overview.md b/docs/start/framework/react/overview.md index ced7b65458..3494b7a187 100644 --- a/docs/start/framework/react/overview.md +++ b/docs/start/framework/react/overview.md @@ -1,11 +1,12 @@ --- id: overview title: TanStack Start Overview -description: Build full-stack React applications with TanStack Start, including server rendering, streaming, server functions, and type-safe routing. --- > [!NOTE] -> TanStack Start is stable. If you're upgrading from a release candidate, follow [Migrate from the Release Candidate](./migrate-from-release-candidate). +> TanStack Start is currently in the **Release Candidate** stage! This means it is considered feature-complete and its API is considered stable. +> **This does not mean it is bug-free or without issues, which is why we invite you to try it out and provide feedback!** +> The road to v1 will likely be a quick one, so don't wait too long to try it out! TanStack Start is a full-stack React framework powered by TanStack Router. It provides a full-document SSR, streaming, server functions, client/server builds, and more. With [Vite](https://vite.dev/) and [Rsbuild](https://rsbuild.dev/) support, it's ready to develop and deploy to the hosting provider or runtime you want. diff --git a/docs/start/framework/react/start-vs-nextjs.md b/docs/start/framework/react/start-vs-nextjs.md index f1dd175a41..27b814725f 100644 --- a/docs/start/framework/react/start-vs-nextjs.md +++ b/docs/start/framework/react/start-vs-nextjs.md @@ -1,67 +1,286 @@ --- id: start-vs-nextjs title: TanStack Start vs Next.js -description: Compare TanStack Start and Next.js for routing, rendering, server functions, caching, deployment, and the work each framework handles for you. --- -TanStack Start is a good fit when you want TanStack Router's typed navigation, search parameters, and loaders in a full-stack application. Next.js is a good fit when you want the App Router's Server Component model and integrated image, font, and metadata tools. Both can build interactive applications and server-rendered websites. +Choosing between TanStack Start and Next.js isn't just about features - it's about understanding what each framework optimizes for and how those decisions cascade through your entire development experience. -This comparison was checked on September 11, 2026 against the linked documentation, including Next.js 16.3. For a broader feature matrix, see [Start, Next.js, and React Router](./comparison). For a practical migration, see [Migrate from Next.js](./migrate-from-next-js). +This page explains the fundamental differences, addresses common misconceptions, and helps you make an informed decision. For a feature-by-feature matrix, see the [full comparison table](./comparison). Ready to switch? See the [migration guide](./migrate-from-next-js). -## Rendering and interactivity +**A note on benchmarks:** If someone quotes performance numbers comparing Start and Next without methodology, app complexity, hosting details, and configuration specifics - those numbers are meaningless. Comparisons must assume best practices on both sides. You can't give Next the benefit of optimized usage while assuming Start users misconfigure things. -Start's React components are server-rendered and hydrated by default. You can change rendering behavior per route with [selective SSR](./guide/selective-ssr), including data-only and client-only rendering. You do not need React Server Components to use Start's server functions or SSR. +## Two Different Visions of React -Next.js App Router layouts and pages are Server Components by default. A `use client` boundary enables client-side state, effects, and event handlers. It applies to the imported module tree, so you do not add the directive to every interactive component. Client Components can still contribute server-rendered HTML on the initial request. [Next.js component model](https://nextjs.org/docs/app/getting-started/server-and-client-components). +Both frameworks want to help you build great React applications. But they start from different assumptions about what "great" means. -Start's [Server Components support](./guide/server-components) is **experimental and opt-in**. It uses client-led composition of server-produced UI. That is a different integration model from Next.js, and experimental support should not be presented as production feature parity. +### Next.js: The Platform Play + +Next.js optimizes for **Vercel's vision of the web**: server-first rendering, tight platform integration, and automatic optimizations that work best on their infrastructure. + +The core bet: most web content is static or near-static. Server Components should be the default. Interactivity is the exception you opt into. The framework should make decisions for you, and those decisions should be optimized for their infrastructure. + +This works well if: + +- You're deploying to Vercel and want tight platform integration +- Your app is content-heavy with islands of interactivity +- You want the framework to make architectural decisions for you + +### TanStack Start: The Developer-First Play + +TanStack Start optimizes for **developer control and correctness**: type safety everywhere, explicit over implicit, composable primitives, and deployment freedom. + +The core bet: developers know their apps better than frameworks do. Server rendering is an optimization you opt into where it makes sense. The framework should give you powerful primitives and get out of your way. + +This works well if: + +- You want your deployment target to be a decision you make, not one the framework makes for you +- Your app is highly interactive +- You value type safety and explicit control +- You want to understand exactly what your code is doing + +## The Mental Model Gap + +This is the most important difference to understand. Everything else flows from it. + +### Both SSR - Different Defaults for Interactivity + +Let's be clear: both frameworks SSR by default, and both support static generation and React Server Components. The difference isn't capability - it's how you access those capabilities and how much control you have. + +**Next.js** defaults to Server Components. Every component is a Server Component unless you add `"use client"`. Server Components can't use state, effects, or event handlers - so the path to interactivity requires understanding the framework's implicit boundaries, caching layers, and serialization rules. + +**TanStack Start** defaults to interactive components (traditional React). Your components SSR and hydrate, ready for state and event handlers out of the box. You opt into Server Components where they provide value - for heavy static content, keeping secrets server-side, or reducing bundle size. + +Both approaches get you to the same destination. The question is: which direction feels like swimming upstream for _your_ app? + +Consider: + +- If most of your components need state, effects, or event handlers, Next's defaults mean constant `"use client"` annotations and thinking about serialization boundaries +- If most of your content is static, Start lets you explicitly opt those components into server-only rendering - with clearer control over caching and hydration +- Either way, Start gives you more granular control over _how_ things render, not just _where_ + +### Implicit vs Explicit + +Both frameworks handle the fundamentals - code splitting, caching, SSR, static optimization. The difference is visibility and predictability. **Next.js** layers implicit behaviors: multi-layer server-side caching with a history of breaking changes and community frustration, data fetching conventions tied to file structure, optimizations that require understanding the framework's internals to override. + +**TanStack Start** is explicit without being verbose. Loader functions, cache configuration, middleware chains - they're visible in your code, not hidden behind conventions. This doesn't mean more code; it means the code you write maps directly to what happens at runtime. + +## Architecture Deep Dive + +### The Build Pipeline + +**Next.js** uses a custom build system (historically Webpack, now Turbopack). It's tightly integrated with their architecture, which enables optimizations but limits flexibility. Turbopack has improved dev speed, but it's still no match for Vite or Rsbuild. + +**TanStack Start** supports Vite and Rsbuild. This means: + +- Faster dev server startup +- Faster HMR +- Access to modern plugin ecosystems +- Standard tooling that transfers to other projects + +### The Runtime + +**Next.js** ships a substantial runtime to support Server Components, server-side caching, automatic optimizations, and the App Router's conventions. This runtime has real weight. + +**TanStack Start** ships a minimal runtime. The router is powerful but lean. Server functions are thin RPC wrappers. There's no framework magic layer between you and React. + +Bundle size isn't everything, but it's the baseline everything else builds on. Start's architecture is designed to minimize runtime overhead - even with RSC support, the runtime stays lean. Much of Next's bundle weight is architectural tax, not feature weight. + +### The Type System + +**Next.js** has TypeScript support. **TanStack Start** is built around TypeScript. + +The difference matters: + +- In Next.js, the boundary between client and server creates type gaps. Server Actions can receive data that doesn't match what TypeScript expects. You need runtime validation to be safe. +- In Start, server functions have end-to-end type safety. Input validation, return types, middleware context, route parameters - all checked at compile time. + +In the age of AI-assisted development, end-to-end type safety should be non-negotiable. Types aren't just "nice for DX" - they're correctness guarantees that prevent production errors. ## Routing -Start inherits [TanStack Router's routing model](/router/latest/docs/guide/type-safety). Route definitions connect the types for links, path parameters, validated search parameters, loaders, and route context. This is useful when application state lives in the URL or when many screens share typed data dependencies. +This is where TanStack shines brightest. TanStack Router (which powers Start) is the most powerful, type-safe router in any framework. -Next.js also provides compile-time checking for links through its stable, opt-in [`typedRoutes`](https://nextjs.org/docs/app/api-reference/config/next-config-js/typedRoutes) option. Describing it as only IDE hints is inaccurate. The distinction is the scope of inference and validation across your application, not whether Next.js supports TypeScript. +**Features Next.js doesn't have:** -In either framework, a valid route type does not prove that a database record exists or that a user may access it. Handle missing data and authorization at runtime. +- **Typesafe search params** - Define, validate, and parse search params with full type inference. Next gives you `?foo=bar` as strings; Start gives you validated, typed objects +- **Search param validation & middleware** - Transform and validate search params at the route level +- **Typesafe path params** - Path params are inferred and validated, not just `string | string[]` +- **Typesafe route context** - Pass typed context down through nested routes +- **Path param validation & custom parsing** - Parse `/users/123` as a number, validate it exists +- **Route mount/transition/unmount events** - Hook into the route lifecycle +- **Code-based routes** - Define routes in code when file-based doesn't fit +- **Built-in devtools** - Inspect router state, cache, and pending navigations +- **Element scroll restoration** - Restore scroll position for specific elements, not just the page +- **Navigation blocking** - `useBlocker` for unsaved changes warnings -For detailed navigation features, see the [Router comparison](/router/latest/docs/comparison). +**Type safety that actually works:** + +- Route paths are fully typed - typos are compile errors +- Links validate their destinations - no broken links in production +- Loaders know their route context - no guessing what data is available +- Search params are typed end-to-end - from URL to component + +Next.js has file-based routing that works, but the type safety is superficial (an IDE plugin for link hints) compared to TanStack Router's compile-time guarantees. + +**First-class integrations:** + +TanStack Router was designed from the ground up for isomorphism and hydration. This makes it the foundation for first-class integrations with TanStack Query and other data-fetching libraries. In Next, you wire up Query manually; in Start, it's a supported pattern with official integrations. + +See the [full router comparison](/router/latest/docs/framework/react/comparison) for the complete feature matrix. + +## The Caching Question + +Caching is where the philosophical differences become most visible. + +### Next.js: Implicit and Server-Side + +Next.js caches aggressively by default (or did - they've changed this multiple times). The caching happens in layers: + +- Request memoization +- Data cache +- Full route cache +- Router cache + +Each layer has its own invalidation semantics. The system has been rewritten multiple times with community criticism for being unpredictable. Next 15 simplified the defaults, but the fundamental complexity of server-side RSC stream caching remains. + +When people talk about "component caching," they're referring to caching serialized RSC streams on the server. This is more complicated than most realize: + +- You're caching text streams with complex invalidation semantics +- This happens in lambda-style environments with their own constraints +- Granular invalidation requires explicit tagging setup +- Cache misses cascade through the component tree in ways that aren't always predictable + +**Ask anyone claiming server-side component caching is special:** "How do you invalidate a cached RSC stream when a data dependency changes?" Most can't answer clearly. + +### TanStack Start: RSCs Are Just Data + +Start treats Server Component output the same as any other data flowing through your app. There's no special "component cache" with its own semantics - RSC payloads are data, and you cache data however you want: + +- **TanStack Router** - Built-in SWR-style caching with `staleTime` and `gcTime` +- **TanStack Query** - Full-featured async state management +- **CDN caching** - Standard HTTP cache headers at the edge +- **Redis, database, whatever** - It's just data; use your existing infrastructure + +```tsx +export const Route = createFileRoute('/posts/$postId')({ + loader: async ({ params }) => fetchPost(params.postId), + staleTime: 10_000, // Fresh for 10 seconds + gcTime: 5 * 60_000, // Keep in memory for 5 minutes +}) +``` + +This is the same SWR pattern TanStack Query has battle-tested across millions of applications. No new mental model. No framework-specific caching semantics to learn. No chasing ghosts. + +The caching layers are well-understood and compose naturally: + +- Client-side SWR caching (built into the router) +- CDN caching at the edge (standard HTTP semantics) +- Server-side caching where you want it (explicit, opt-in) + +You already know how to cache data. Start doesn't make you learn a new way. + +### The Bottom Line on RSCs + +Start has full RSC support with feature parity to Next.js. The difference is mental model and cognitive overhead. + +In Next, RSCs are the paradigm - you build around them, think about them constantly, manage their boundaries everywhere. In Start, RSCs are just another data primitive. Fetch them, cache them, compose them - using patterns you already know from TanStack Query and Router. + +We call our approach **Composite Components** - server-produced React components that the client can fetch, cache, stream, and assemble. The client owns composition; the server ships UI pieces. No new mental model. No framework-specific caching semantics. Just data flowing through tools you already understand. + +For the full deep-dive, see [Composite Components: Server Components with Client-Led Composition](https://tanstack.com/blog/composite-components). ## Server Functions vs Server Actions -Start's [server functions](./guide/server-functions) provide callable server endpoints with inferred inputs and outputs. You can choose GET or POST, supply an input validator, and compose [function middleware](./guide/middleware). Use runtime validation for untrusted inputs and server-side authorization for private data. +Both frameworks let you call server code from the client. The approaches differ significantly. -Next.js Server Actions integrate with forms and React's pending and error-state APIs. They can validate input with a schema too. Receiving `FormData` does not prevent validation, and a TypeScript annotation does not perform validation in either framework. [Next.js forms and validation](https://nextjs.org/docs/app/guides/forms). +### Next.js Server Actions -Choose the API that fits your application's data flow. A typed RPC call and a form action solve overlapping problems, but they are not interchangeable in every workflow. +```tsx +'use server' -## Caching +export async function createPost(formData: FormData) { + const title = formData.get('title') + // No compile-time type safety on inputs + return db.posts.create({ title }) +} +``` -Start uses [TanStack Router's loader cache](/router/latest/docs/guide/data-loading) for navigation data, with options such as `staleTime` and `gcTime`. You can also use the [official Query integration](/router/latest/docs/integrations/query) when you need a separate query cache. Browser data caching, server data caching, and CDN response caching serve different purposes. +Server Actions integrate with forms and transitions. They're convenient for simple cases but provide limited type safety at the boundary. -Next.js documents explicit caching through Cache Components, enabled with `cacheComponents: true`. Its `use cache`, `cacheLife`, and tag-based revalidation APIs control reuse and invalidation. Applications without that option use a different documented caching model. Compare the configuration you intend to run, rather than treating every Next.js version and configuration as having the same defaults. [Next.js caching](https://nextjs.org/docs/app/getting-started/caching). +### TanStack Server Functions -Start's [ISR guide](./guide/isr) describes HTTP caching and provider-specific options. A `Cache-Control` header alone does not guarantee the same regeneration, invalidation, or shared-cache behavior on every host. Verify those behaviors on your deployment target. +```tsx +export const createPost = createServerFn({ method: 'POST' }) + .validator(z.object({ title: z.string().min(1) })) + .middleware([authMiddleware]) + .handler(async ({ data, context }) => { + // data is typed and validated + // context comes from middleware, also typed + return db.posts.create({ title: data.title }) + }) +``` -## Build tools +Server functions give you: -Start supports [Vite and Rsbuild](./build-from-scratch). Next.js integrates [Turbopack](https://nextjs.org/docs/app/api-reference/turbopack), with its own supported configuration and plugin surface. Your existing build tooling can make one choice easier to adopt. +- **Input validation** - Define schemas, get runtime validation and compile-time types +- **Middleware** - Composable, works on both client and server +- **Full type inference** - From input to output to error handling +- **Explicit RPC** - Clear mental model of what's happening -There is no benchmark in this comparison establishing a startup, HMR, build-time, memory, or runtime-size winner. A router package's bundle size is not the bundle size of a complete Start application. Measure the same application, dependencies, rendering behavior, hardware, and production deployment before drawing performance conclusions. - -## Deployment - -Start has [deployment guides](./guide/hosting) for several providers and runtimes. Check the guide for your chosen bundler and target, especially when you need streaming, image processing, background work, or cache invalidation. - -Next.js supports self-hosting. Its image optimizer works with `next start`, and its documentation covers ISR, shared caches, streaming, and multi-instance deployments. These features are not inherently Vercel-only. Operating them yourself still requires infrastructure configuration. [Next.js self-hosting](https://nextjs.org/docs/app/guides/self-hosting). +**Security note:** Start's architecture doesn't parse Flight data on the server - payloads flow one direction (server to client). Recent React security advisories around RSC serialization vulnerabilities don't apply to Start's model. ## Where Next.js Has the Advantage -Next.js is worth choosing when your application depends on its established Server Component integration, or when you want the built-in [`next/image`](https://nextjs.org/docs/app/api-reference/components/image), [`next/font`](https://nextjs.org/docs/app/api-reference/components/font), and [metadata conventions](https://nextjs.org/docs/app/getting-started/metadata-and-og-images). Replacing those facilities is migration work, even when alternatives exist. +Next.js has been around longer. That's not a technical advantage, but it creates real ecosystem effects: -If your team already maintains a working Next.js application, keep that experience and migration cost in the decision. A different routing model is not, by itself, a reason to rewrite a healthy application. +**More content** - More tutorials, more Stack Overflow answers, more blog posts, more example repos. When you Google a problem, you're more likely to find a Next-specific answer. -## When to Choose TanStack Start +**Mindshare** - Next is the default recommendation in many circles. That means more developers have used it, which means more content, which reinforces the cycle. -Start is worth choosing when typed URL state, route context, explicit loaders, and callable server functions fit how you build applications. Its [Router integration](./guide/routing), [selective SSR](./guide/selective-ssr), and [middleware](./guide/middleware) are concrete reasons to try it. +**Vercel integration** - Next.js is built by Vercel, so new Vercel platform features often ship with Next.js support first. That said, Start works great on Vercel too - you're not giving up preview deployments or edge functions by choosing Start. You're just not locked into Vercel as the only first-class option. -Build one representative route before committing to a migration: load real data, validate search parameters, submit a mutation, handle unauthorized access, and deploy it. If those tasks become easier to maintain, you have evidence that Start fits your application. Continue with [Getting Started](./getting-started) or the [Next.js migration guide](./migrate-from-next-js). +**Built-in image/font optimization** - Start supports image optimization via pluggable solutions (like [Unpic](https://unpic.pics/)), but it's not built-in. Whether "built-in" is better than "pluggable" depends on whether you want the framework making that choice for you. + +None of these are technical superiority - they're ecosystem and business model advantages. On the technical merits, we're confident in Start's approach. + +## What Start Does Better + +With RSC support, the question isn't "what does Start lack?" - it's: **"Why give up Start's router, type safety, caching design, and simpler mental model for Next's API design?"** + +**Type safety** - End-to-end, not bolted on. This prevents bugs and enables confident refactoring. + +**Routing** - The most powerful, type-safe router in any framework. Search params, path params, loaders, middleware - all fully typed. + +**Caching model** - Explicit SWR primitives you already understand if you've used TanStack Query. No implicit layers to debug. + +**Dev experience** - Vite and Rsbuild are fast. Instant startup, fast HMR, lower resource usage. This compounds over a workday - and even more so when AI agents are iterating on your code in tight loops. + +**Deployment as a feature** - Start treats deployment flexibility as a first-class feature. Cloudflare, Netlify, AWS, Fly, Railway, your own servers - they're all equally supported. Your app works the same everywhere because it's built on standards, not platform-specific optimizations. This means you can: + +- Choose hosting based on price, performance, or proximity to your users +- Switch providers without rewriting deployment logic +- Run the same code in development, staging, and production across different platforms +- Avoid accumulating platform-specific patterns that create friction later + +**Middleware** - Composable middleware that works at both the request level AND the server function level, on both client and server. + +**Debugging** - Predictable execution. When something breaks, you can trace it. No abstraction layers hiding behavior. + +## Summary + +| Aspect | TanStack Start | Next.js | +| -------------------- | ------------------------------------ | ------------------------------------- | +| **Philosophy** | Developer control, explicit patterns | Platform integration, conventions | +| **Components** | Interactive by default, opt into RSC | Server Components by default | +| **Type safety** | End-to-end, compile-time | TypeScript support with boundary gaps | +| **Server functions** | Typed, validated, middleware support | Untyped boundary, no middleware | +| **Caching** | Explicit SWR primitives | Multi-layer implicit caching | +| **Build tool** | Vite or Rsbuild | Turbopack/Webpack | +| **Deployment** | Equal support everywhere | Optimized for Vercel | +| **Routing** | Best-in-class type safety | File-based, basic types | +| **RSC** | Supported | Supported | +| **Maturity** | 2+ years, approaching 1.0 | 8+ years, historically unstable APIs | + +--- + +> **Ready to try Start?** See the [Getting Started guide](./getting-started) or [migrate from Next.js](./migrate-from-next-js). diff --git a/docs/start/framework/react/tutorial/reading-writing-file.md b/docs/start/framework/react/tutorial/reading-writing-file.md index f4af4480f1..11b1be0794 100644 --- a/docs/start/framework/react/tutorial/reading-writing-file.md +++ b/docs/start/framework/react/tutorial/reading-writing-file.md @@ -152,7 +152,7 @@ export type JokesData = Joke[] ### Step 1.3: Create Server Functions to Read the File -Let's create a new file `src/serverActions/jokesActions.ts` to create a server function to perform a read-write operation. We will be creating a server function using [`createServerFn`](https://tanstack.com/start/latest/docs/framework/react/guide/server-functions). +Let's create a new file `src/serverActions/jokesActions.ts` to create a server function to perform a read-write operation. We will be creating a server function using [`createServerFn`](https://tanstack.com/start/latest/docs/framework/react/server-functions). ```tsx // src/serverActions/jokesActions.ts diff --git a/docs/start/framework/solid/guide/authentication.md b/docs/start/framework/solid/guide/authentication.md index 460a58747c..8ae205ef21 100644 --- a/docs/start/framework/solid/guide/authentication.md +++ b/docs/start/framework/solid/guide/authentication.md @@ -1,12 +1,11 @@ --- id: authentication -title: Implement Authentication in SolidJS -description: Implement sessions, sign-in, sign-out, protected routes, and server-side authorization in a TanStack Start SolidJS app. +title: Authentication --- -Implement the authentication workflow in your SolidJS app, from sessions and sign-in to protected routes and authorization. +This guide covers authentication patterns and shows how to implement your own authentication system with TanStack Start. -To compare libraries and hosted services, read [Choose Authentication for SolidJS Apps](./authentication-overview.md). +> **📋 Before You Start:** Check our [Authentication Overview](./authentication-overview.md) for all available options including partner solutions and hosted services. ## Authentication Approaches @@ -35,7 +34,7 @@ Authentication involves many considerations including password security, session - **Authentication**: Who is this user? (Login/logout) - **Authorization**: What can this user do? (Permissions/roles) -TanStack Start provides server functions, request and cookie utilities, and route protection. Session storage and authentication come from your application or a library you choose. +TanStack Start provides the tools for both through server functions, sessions, and route protection. > Protect the data/API boundary first. Any server function, server route, or other API endpoint that returns or mutates private data must authorize the request itself. `beforeLoad` is useful for route UX: it keeps users out of screens they cannot use and avoids triggering work that would fail anyway. It is not the security boundary for the data. See [Authentication Server Primitives](./authentication-server-primitives.md) for the server-side pattern. @@ -48,7 +47,6 @@ Server functions handle sensitive authentication logic securely on the server: ```tsx import { createServerFn } from '@tanstack/solid-start' import { redirect } from '@tanstack/solid-router' -import { getAppSession } from '~/utils/session' // Login server function export const loginFn = createServerFn({ method: 'POST' }) @@ -62,9 +60,11 @@ export const loginFn = createServerFn({ method: 'POST' }) } // Create session - const session = await getAppSession() - session.userId = user.id - await session.save() + const session = await useAppSession() + await session.update({ + userId: user.id, + email: user.email, + }) // Redirect to protected area throw redirect({ to: '/dashboard' }) @@ -72,131 +72,98 @@ export const loginFn = createServerFn({ method: 'POST' }) // Logout server function export const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await getAppSession() - session.destroy() + const session = await useAppSession() + await session.clear() throw redirect({ to: '/' }) }) // Get current user export const getCurrentUserFn = createServerFn({ method: 'GET' }).handler( async () => { - const session = await getAppSession() - const userId = session.userId + const session = await useAppSession() + const userId = session.get('userId') if (!userId) { return null } - const user = await getUserById(userId) - return user ? { id: user.id, email: user.email, role: user.role } : null + return await getUserById(userId) }, ) ``` ### 2. Session Management -Start does not provide a session API. This guide uses iron-session for encrypted cookie sessions. Start's cookie helpers connect it to server functions, server routes, and request middleware. - -For encrypted cookie sessions, install [iron-session](https://github.com/vvo/iron-session): - -```sh -pnpm add iron-session -``` - -This example uses iron-session 9's cookie adapter. Its Node runtime requires Node 22.13 or newer; check the library's runtime requirements for other deployment targets. +TanStack Start provides secure HTTP-only cookie sessions: ```tsx -// utils/session.ts — import only from server code -import { getIronSession } from 'iron-session' -import { getCookie, setCookie } from '@tanstack/solid-start/server' +// utils/session.ts +import { useSession } from '@tanstack/solid-start/server' type SessionData = { - userId: string - oauthState: string + userId?: string + email?: string + role?: string } -export function getAppSession(ttl = 7 * 24 * 60 * 60) { - const password = process.env.SESSION_SECRET - if (!password || password.length < 32) { - throw new Error('SESSION_SECRET must be at least 32 characters') - } - - return getIronSession( - { read: getCookie, write: setCookie }, - { - cookieName: 'app-session', - password, - ttl, - cookieOptions: { - secure: process.env.NODE_ENV === 'production', - sameSite: 'lax', - httpOnly: true, - path: '/', - }, +export function useAppSession() { + return useSession({ + // Session configuration + name: 'app-session', + password: process.env.SESSION_SECRET!, // At least 32 characters + // Optional: customize cookie settings + cookie: { + secure: process.env.NODE_ENV === 'production', + sameSite: 'lax', + httpOnly: true, }, - ) + }) } ``` -Read fields directly from the returned session, change them, then `await session.save()` before returning or redirecting. Missing or expired sessions have no user ID. `session.destroy()` removes the browser cookie. Keep one session object for the operation; another call to `getAppSession()` reads the incoming request again. For middleware, pass that object through request context when downstream code needs the same mutations. - -The `getAppSession` helper belongs to your application. Start does not cache sessions, choose expiration rules, or synchronize concurrent writes. Keep secrets and session objects in server code, and read request-specific configuration inside the active request. - ### 3. Authentication Context -Load the current user in your root route's `beforeLoad` so the initial server render and child routes receive the same authentication state. `useServerFn` returns a callable function, not an object with `data`, `isLoading`, or `refetch`. You can call a server function directly from `beforeLoad`. - -Merge this pattern into your existing root route, keeping its metadata and document shell: +Share authentication state across your application: ```tsx -// routes/__root.tsx -import { - createRootRoute, - HeadContent, - Outlet, - Scripts, -} from '@tanstack/solid-router' -import type { JSX } from 'solid-js' +// contexts/auth.tsx +import { createContext, useContext } from 'solid-js' +import { useServerFn } from '@tanstack/solid-start' import { getCurrentUserFn } from '../server/auth' -export const Route = createRootRoute({ - headers: () => ({ 'Cache-Control': 'private, no-store' }), - beforeLoad: async () => ({ user: await getCurrentUserFn() }), - component: Outlet, - shellComponent: RootDocument, -}) +type User = { + id: string + email: string + role: string +} + +type AuthContextType = { + user: User | null + isLoading: boolean + refetch: () => void +} + +const AuthContext = createContext(undefined) + +export function AuthProvider(props) { + const { data: user, isLoading, refetch } = useServerFn(getCurrentUserFn) -function RootDocument({ children }: { children: JSX.Element }) { return ( - - - - - - {children} - - - + + {props.children} + ) } -``` -The root includes session-specific data, so its responses use `Cache-Control: private, no-store`. Keep that policy on child routes that render this data, and do not override it with public caching at your CDN. - -Read that state from a descendant component: - -```tsx -// components/AuthStatus.tsx -import { Route } from '../routes/__root' - -export function AuthStatus() { - const context = Route.useRouteContext() - return {context().user?.email ?? 'Signed out'} +export function useAuth() { + const context = useContext(AuthContext) + if (!context) { + throw new Error('useAuth must be used within AuthProvider') + } + return context } ``` -After login or logout changes the session, call `await router.invalidate()` to reload the current user and rerun route guards. Keep private-data authorization in the server function itself, even when a route already checks the user. - ### 4. Route Protection Protect routes using `beforeLoad`: @@ -273,9 +240,8 @@ export const registerFn = createServerFn({ method: 'POST' }) }) // Create session - const session = await getAppSession() - session.userId = user.id - await session.save() + const session = await useAppSession() + await session.update({ userId: user.id }) return { success: true, user: { id: user.id, email: user.email } } }) @@ -343,9 +309,8 @@ export const initiateOAuthFn = createServerFn({ method: 'POST' }) const state = generateRandomState() // Store state in session for CSRF protection - const session = await getAppSession() - session.oauthState = state - await session.save() + const session = await useAppSession() + await session.update({ oauthState: state }) // Generate OAuth URL const authUrl = generateOAuthUrl(provider, state) @@ -408,9 +373,21 @@ const hashedPassword = await bcrypt.hash(password, saltRounds) ### 2. Session Security -Set the library's server-validated expiration as well as appropriate cookie attributes. In the iron-session example, `ttl` limits a sealed credential's lifetime from its latest save; saving again renews it. A numeric `cookieOptions.maxAge` controls browser retention. In iron-session 9, explicitly setting `maxAge: undefined` also disables seal expiry; omit the property to use the configured `ttl`. Use an application-validated timestamp or a server-side record if you also need an absolute lifetime that writes cannot extend. - -Use `httpOnly`, `sameSite`, and `path` deliberately, and require `secure: true` on HTTPS deployments. These cookie attributes complement server-side authorization and CSRF protections. Keep only the minimum session data and load current account permissions from their authoritative store. Logout removes a stateless cookie from the current browser; it cannot revoke a copy without server-side state. +```tsx +// Use secure session configuration +export function useAppSession() { + return useSession({ + name: 'app-session', + password: process.env.SESSION_SECRET!, // 32+ characters + cookie: { + secure: process.env.NODE_ENV === 'production', // HTTPS only in production + sameSite: 'lax', // CSRF protection + httpOnly: true, // XSS protection + maxAge: 7 * 24 * 60 * 60, // 7 days + }, + }) +} +``` ### 3. Rate Limiting @@ -512,70 +489,28 @@ describe('Authentication Flow', () => { ### Loading States -Call the function returned by `useServerFn` with `{ data }`. Track pending state in the component, handle invalid credentials, and refresh route context after a successful login. This form uses the `loginFn` from the server-functions example above. It requires JavaScript, so the fields stay disabled until hydration; `method="post"` also prevents credentials appearing in a native GET submission. - ```tsx -// components/LoginForm.tsx -import { createSignal } from 'solid-js' -import { useHydrated, useRouter } from '@tanstack/solid-router' -import { useServerFn } from '@tanstack/solid-start' -import { loginFn } from '../server/auth' - -export function LoginForm() { - const hydrated = useHydrated() +function LoginForm() { const [isLoading, setIsLoading] = createSignal(false) - const [error, setError] = createSignal('') - const login = useServerFn(loginFn) - const router = useRouter() - - const handleSubmit = async ( - event: SubmitEvent & { currentTarget: HTMLFormElement }, - ) => { - event.preventDefault() - const formData = new FormData(event.currentTarget) - const email = formData.get('email') - const password = formData.get('password') - if (typeof email !== 'string' || typeof password !== 'string') { - return - } + const loginMutation = useServerFn(loginFn) + const handleSubmit = async (data: LoginData) => { setIsLoading(true) - setError('') try { - const result = await login({ data: { email, password } }) - if (result?.error) { - setError(result.error) - return - } - await router.invalidate() - } catch { - setError('Login failed. Please try again.') + await loginMutation.mutate(data) + } catch (error) { + // Handle error } finally { setIsLoading(false) } } return ( -
-
- - - -
-

{error()}

+ + {/* Form fields */} +
) } @@ -590,14 +525,16 @@ export const loginFn = createServerFn({ method: 'POST' }) ) .handler(async ({ data }) => { const user = await authenticateUser(data.email, data.password) - if (!user) { - return { error: 'Invalid credentials' } - } + if (!user) return { error: 'Invalid credentials' } - const ttl = data.rememberMe ? 30 * 24 * 60 * 60 : 8 * 60 * 60 - const session = await getAppSession(ttl) - session.userId = user.id - await session.save() + const session = await useAppSession() + await session.update( + { userId: user.id }, + { + // Extend session if remember me is checked + maxAge: data.rememberMe ? 30 * 24 * 60 * 60 : undefined, // 30 days vs session + }, + ) return { success: true } }) @@ -617,6 +554,7 @@ If you're migrating from client-side authentication (localStorage, context only) ### From Other Frameworks - **Next.js**: Replace API routes with server functions, migrate NextAuth sessions +- **Remix**: Convert loaders/actions to server functions, adapt session patterns - **SvelteKit**: Move form actions to server functions, update route protection ## Production Considerations diff --git a/docs/start/framework/solid/guide/client-entry-point.md b/docs/start/framework/solid/guide/client-entry-point.md index 929efc7a2d..b73408e8e4 100644 --- a/docs/start/framework/solid/guide/client-entry-point.md +++ b/docs/start/framework/solid/guide/client-entry-point.md @@ -3,6 +3,8 @@ id: client-entry-point title: Client Entry Point --- +# Client Entry Point + > [!NOTE] > The client entry point is **optional** out of the box. If not provided, TanStack Start will automatically handle the client entry point for you using the below as a default. diff --git a/docs/start/framework/solid/guide/reading-writing-file.md b/docs/start/framework/solid/guide/reading-writing-file.md new file mode 100644 index 0000000000..5aa48d8188 --- /dev/null +++ b/docs/start/framework/solid/guide/reading-writing-file.md @@ -0,0 +1,5 @@ +--- +ref: docs/start/framework/react/guide/reading-writing-file.md +replace: + { '@tanstack/react-start': '@tanstack/solid-start', 'React': 'SolidJS' } +--- diff --git a/docs/start/framework/solid/migrate-from-release-candidate.md b/docs/start/framework/solid/migrate-from-release-candidate.md deleted file mode 100644 index 9f988a14fc..0000000000 --- a/docs/start/framework/solid/migrate-from-release-candidate.md +++ /dev/null @@ -1,8 +0,0 @@ ---- -ref: docs/start/framework/react/migrate-from-release-candidate.md -replace: - { - '@tanstack/react-start': '@tanstack/solid-start', - '@tanstack/react-router': '@tanstack/solid-router', - } ---- diff --git a/docs/start/framework/solid/tutorial/reading-writing-file.md b/docs/start/framework/solid/tutorial/reading-writing-file.md index 09b58c38f5..de3d4d472e 100644 --- a/docs/start/framework/solid/tutorial/reading-writing-file.md +++ b/docs/start/framework/solid/tutorial/reading-writing-file.md @@ -1,8 +1,6 @@ --- id: reading-and-writing-file title: Building a Full Stack DevJokes App with TanStack Start -redirect_from: - - /framework/solid/guide/reading-writing-file --- This tutorial will guide you through building a complete full-stack application using TanStack Start. You'll create a DevJokes app where users can view and add developer-themed jokes, demonstrating key concepts of TanStack Start including server functions, file-based data storage, and Solid components. @@ -154,7 +152,7 @@ export type JokesData = Joke[] ### Step 1.3: Create Server Functions to Read the File -Let's create a new file `src/serverActions/jokesActions.ts` to create a server function to perform a read-write operation. We will be creating a server function using [`createServerFn`](https://tanstack.com/start/latest/docs/framework/solid/guide/server-functions). +Let's create a new file `src/serverActions/jokesActions.ts` to create a server function to perform a read-write operation. We will be creating a server function using [`createServerFn`](https://tanstack.com/start/latest/docs/framework/solid/server-functions). ```tsx // src/serverActions/jokesActions.ts diff --git a/e2e/AGENTS.md b/e2e/AGENTS.md deleted file mode 100644 index f373ecba4f..0000000000 --- a/e2e/AGENTS.md +++ /dev/null @@ -1,9 +0,0 @@ -# E2E tests - -- Read the project's `package.json` and test config. Inspect resolved targets with `CI=1 NX_DAEMON=false pnpm nx show project --json`: `nx.metadata.playwrightModes` generates modes, variants, and shards. The aggregate `test:e2e` can also run extra package-script suites. For focused Playwright runs, select an executable test target (a mode/shard target when inferred) and append filters after `--` (e.g. `-- tests/navigation.spec.ts --grep "redirect"`). -- Check Playwright's `webServer.command` to select dev or production coverage. A mode named `ssr` can still start a dev server. `e2e/eslint-plugin-start` uses Vitest instead of Playwright. -- For inferred Playwright modes, Nx builds first and supplies `MODE`, `E2E_TOOLCHAIN`, `E2E_DIST_DIR`, and `E2E_PORT_KEY`. Preserve these in server/config changes; let Nx own the build while `webServer.command` only starts the selected server. Target generation lives in [`scripts/nx/playwright-plugin.ts`](../scripts/nx/playwright-plugin.ts). -- Use the same `E2E_PORT_KEY`-aware key throughout config, app, and dummy-server setup/teardown. Clean only that key's port files, before allocation, when `TEST_WORKER_INDEX === undefined`; worker config reloads must not remap a running server's port. -- 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. diff --git a/e2e/e2e-utils/mock-api.mjs b/e2e/e2e-utils/mock-api.mjs deleted file mode 100644 index f92ec840e5..0000000000 --- a/e2e/e2e-utils/mock-api.mjs +++ /dev/null @@ -1,4 +0,0 @@ -import { setupServer } from 'msw/node' -import { apiHandlers } from './src/api-handlers.ts' - -setupServer(...apiHandlers).listen({ onUnhandledRequest: 'bypass' }) diff --git a/e2e/e2e-utils/package.json b/e2e/e2e-utils/package.json index fcfa5f8dc0..127f9a01f2 100644 --- a/e2e/e2e-utils/package.json +++ b/e2e/e2e-utils/package.json @@ -5,7 +5,7 @@ "clean": "rimraf ./dist && rimraf ./coverage", "build": "vite build", "test:eslint": "eslint ./src", - "test:unit": "vitest run" + "test:unit": "exit 0; vitest --typecheck" }, "type": "module", "types": "dist/types/index.d.ts", @@ -22,8 +22,7 @@ "default": "./dist/cjs/index.cjs" } }, - "./package.json": "./package.json", - "./mock-api": "./mock-api.mjs" + "./package.json": "./package.json" }, "sideEffects": false, "files": [ @@ -31,14 +30,13 @@ "src" ], "engines": { - "node": "^22.18.0 || >=24.0.0" + "node": ">=20.19" }, + "dependencies": {}, "devDependencies": { - "@msw/playwright": "0.6.7", - "msw": "2.15.0", - "rimraf": "catalog:", + "get-port-please": "^3.2.0", "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4", - "vitest": "catalog:" + "rimraf": "catalog:" } } diff --git a/e2e/e2e-utils/src/api-fixture.ts b/e2e/e2e-utils/src/api-fixture.ts deleted file mode 100644 index 90ca1912a3..0000000000 --- a/e2e/e2e-utils/src/api-fixture.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { test as base } from '@playwright/test' -import { defineNetworkFixture } from '@msw/playwright' -import { apiHandlers } from './api-handlers' - -// Opt in only for suites that consume the canned API. Playwright routing -// disables HTTP caching; other suites keep their normal browser behavior. -export const apiTest = base.extend<{ mockApi: void }>({ - mockApi: [ - async ({ context }, use) => { - const network = defineNetworkFixture({ context, handlers: apiHandlers }) - await network.enable() - await use() - await network.disable() - }, - { auto: true }, - ], -}) diff --git a/e2e/e2e-utils/src/api-handlers.ts b/e2e/e2e-utils/src/api-handlers.ts deleted file mode 100644 index 4e2c0498f4..0000000000 --- a/e2e/e2e-utils/src/api-handlers.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { HttpResponse, http } from 'msw' -import { posts } from './posts.ts' -import { users } from './users.ts' - -export const apiHandlers = [ - ...Object.entries({ posts, users }).flatMap(([resource, data]) => [ - http.get(`https://jsonplaceholder.typicode.com/${resource}`, () => - HttpResponse.json(data), - ), - http.get( - `https://jsonplaceholder.typicode.com/${resource}/:id`, - ({ params }) => { - const id = parseInt(String(params.id)) - if (Number.isNaN(id)) { - return HttpResponse.json( - { error: `invalid ${resource.slice(0, -1)} id` }, - { status: 404 }, - ) - } - const item = data.find((entry) => entry.id === id) - return item - ? HttpResponse.json(item) - : new HttpResponse(null, { - headers: { 'content-type': 'application/json' }, - }) - }, - ), - ]), - http.all('https://jsonplaceholder.typicode.com/*', () => - HttpResponse.error(), - ), -] diff --git a/e2e/e2e-utils/src/derivePort.ts b/e2e/e2e-utils/src/derivePort.ts new file mode 100644 index 0000000000..3ecb86cb53 --- /dev/null +++ b/e2e/e2e-utils/src/derivePort.ts @@ -0,0 +1,27 @@ +import fs from 'node:fs' +import { getRandomPort } from 'get-port-please' + +/** + * Check if a port has been allocated, if it hasn't generate a random port and save it. + * @param {string} input - port test allocation + * @returns {number} A random port. + */ +export async function derivePort(input: string): Promise { + const portFile = `port-${input}.txt` + + if (!fs.existsSync(portFile)) { + fs.writeFileSync(portFile, (await getRandomPort()).toString()) + } + + const portNumber = parseInt(await fs.promises.readFile(portFile, 'utf-8')) + console.info(`Mapped "${input}" to port ${portNumber}`) + return portNumber +} + +export async function getDummyServerPort(input: string): Promise { + return await derivePort(`${input}-external`) +} + +export async function getTestServerPort(input: string): Promise { + return await derivePort(input) +} diff --git a/e2e/e2e-utils/src/e2eSetupTeardown.ts b/e2e/e2e-utils/src/e2eSetupTeardown.ts new file mode 100644 index 0000000000..d1acf4740e --- /dev/null +++ b/e2e/e2e-utils/src/e2eSetupTeardown.ts @@ -0,0 +1,16 @@ +import { localDummyServer } from './localDummyServer' +import { getDummyServerPort } from './derivePort' + +export async function e2eStartDummyServer(input: string) { + const port = await getDummyServerPort(input) + + return await localDummyServer(port) +} + +export async function e2eStopDummyServer(input: string) { + const port = await getDummyServerPort(input) + + await fetch(`http://localhost:${port}/stop`, { + method: 'POST', + }) +} diff --git a/e2e/e2e-utils/src/index.ts b/e2e/e2e-utils/src/index.ts index 960a01a9be..17e58f82e5 100644 --- a/e2e/e2e-utils/src/index.ts +++ b/e2e/e2e-utils/src/index.ts @@ -1,9 +1,10 @@ -export { apiTest } from './api-fixture' +export { derivePort, getDummyServerPort, getTestServerPort } from './derivePort' +export { localDummyServer } from './localDummyServer' +export { toRuntimePath } from './to-runtime-path' +export { resolveRuntimeSuffix } from './resolve-runtime-suffix' +export { e2eStartDummyServer, e2eStopDummyServer } from './e2eSetupTeardown' export { preOptimizeDevServer, waitForServer } from './devServerWarmup' -export { collectBrowserErrors, test } from './fixture' export { createHmrFileEditor, replaceAll } from './hmrFileEditor' export type { HmrFileEditorOptions } from './hmrFileEditor' export type { Post } from './posts' -export { resolveRuntimeSuffix } from './resolve-runtime-suffix' -export { toRuntimePath } from './to-runtime-path' -export { appServerReady, appServerReadyPattern } from './webServer' +export { collectBrowserErrors, test } from './fixture' diff --git a/e2e/e2e-utils/src/localDummyServer.ts b/e2e/e2e-utils/src/localDummyServer.ts new file mode 100644 index 0000000000..d452f54c59 --- /dev/null +++ b/e2e/e2e-utils/src/localDummyServer.ts @@ -0,0 +1,128 @@ +import http from 'node:http' +import { posts } from './posts' +import { users } from './users' + +// some tests redirect to an external host +// however, in CI this is unstable due to network conditions +// so here we spawn a local server to simulate the external host + +export async function localDummyServer(port: number) { + const server = http.createServer((req, res) => { + // Set CORS headers + res.setHeader('Access-Control-Allow-Origin', '*') + res.setHeader('Access-Control-Request-Method', '*') + res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET, POST') + res.setHeader('Access-Control-Allow-Headers', '*') + + if (req.method === 'OPTIONS') { + res.writeHead(200) + res.end() + return + } + }) + + server.on('request', (req, res) => { + const url = new URL(req.url!, 'http://localhost') + + if (res.req.method === 'GET' && url.pathname === '/') { + res.writeHead(200, { 'Content-Type': 'text/html' }) + res.end('Hello World') + } + }) + + server.on('request', (req, res) => { + const url = new URL(req.url!, `http://localhost`) + + if (res.req.method === 'POST' && url.pathname === '/stop') { + server.close() + console.info( + `stopped local dummy server running at http://localhost:${port}`, + ) + + res.writeHead(200) + res.end() + } + }) + + server.on('request', (req, res) => { + const url = new URL(req.url ?? '/', `http://localhost`) + + if (req.method === 'GET' && url.pathname.startsWith('/posts')) { + const parts = url.pathname.split('/') + + if (parts.length === 2) { + res.writeHead(200, { 'content-type': 'application/json' }) + res.end(JSON.stringify(posts)) + return + } + + if (parts[2]) { + const postId = parseInt(parts[2]) + + if (isNaN(postId)) { + res.writeHead(404) + res.end(JSON.stringify({ error: 'invalid post id' })) + return + } + + const post = posts.find((post) => post.id === postId) + + res.writeHead(200, { 'content-type': 'application/json' }) + res.end(JSON.stringify(post)) + return + } + + res.writeHead(404) + res.end(JSON.stringify({ error: 'invalid posts path' })) + return + } + }) + + server.on('request', (req, res) => { + const url = new URL(req.url ?? '/', `http://localhost`) + + if (req.method === 'GET' && url.pathname.startsWith('/users')) { + const parts = url.pathname.split('/') + + if (parts.length === 2) { + res.writeHead(200, { 'content-type': 'application/json' }) + res.end(JSON.stringify(users)) + return + } + + if (parts[2]) { + const userId = parseInt(parts[2]) + + if (isNaN(userId)) { + res.writeHead(404) + res.end(JSON.stringify({ error: 'invalid user id' })) + return + } + + const user = users.find((user) => user.id === userId) + + res.writeHead(200, { 'content-type': 'application/json' }) + res.end(JSON.stringify(user)) + return + } + + res.writeHead(404) + res.end(JSON.stringify({ error: 'invalid users path' })) + return + } + }) + + const startServer = new Promise((resolve) => { + server.listen(port, 'localhost', () => { + console.info( + `started local dummy server running at http://localhost:${port}`, + ) + resolve() + }) + }) + + await startServer + + await new Promise((r) => setTimeout(r, 500)) + return server +} diff --git a/e2e/e2e-utils/src/webServer.ts b/e2e/e2e-utils/src/webServer.ts deleted file mode 100644 index 77536e4c69..0000000000 --- a/e2e/e2e-utils/src/webServer.ts +++ /dev/null @@ -1,9 +0,0 @@ -// Vite, Rsbuild, srvx, serve, and the custom E2E servers print their bound -// address only after listening. Playwright exports named captures to workers. -export const appServerReadyPattern = - /(?:Local:|Listening on|Accepting connections at|E2E app:)[^\n]*?https?:\/\/(?:localhost|127\.0\.0\.1|\[::\]):(?\d+)/ - -export const appServerReady = { - stdout: appServerReadyPattern, - stderr: appServerReadyPattern, -} diff --git a/e2e/e2e-utils/tests/mock-api.test.ts b/e2e/e2e-utils/tests/mock-api.test.ts deleted file mode 100644 index ba25c1254d..0000000000 --- a/e2e/e2e-utils/tests/mock-api.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { execFile } from 'node:child_process' -import { promisify } from 'node:util' -import { fileURLToPath } from 'node:url' -import { expect, test } from 'vitest' - -const execFileAsync = promisify(execFile) -const preload = fileURLToPath(new URL('../mock-api.mjs', import.meta.url)) - -test('independent Node processes mock the API with networking disabled', async () => { - const script = ` - const { Socket } = await import('node:net') - Socket.prototype.connect = () => { throw new Error('Network disabled') } - const posts = await fetch('https://jsonplaceholder.typicode.com/posts').then(r => r.json()) - const user = await fetch('https://jsonplaceholder.typicode.com/users/1').then(r => r.json()) - const invalid = await fetch('https://jsonplaceholder.typicode.com/posts/invalid') - const missing = await fetch('https://jsonplaceholder.typicode.com/posts/999') - console.log(JSON.stringify({ post: posts[0].id, user: user.id, invalid: invalid.status, missing: await missing.text() })) - ` - const results = await Promise.all( - [0, 1].map(() => - execFileAsync(process.execPath, ['--import', preload, '--eval', script]), - ), - ) - for (const result of results) { - expect(JSON.parse(result.stdout)).toEqual({ - post: 1, - user: 1, - invalid: 404, - missing: '', - }) - } -}) - -test('unhandled API requests fail without reaching the network', async () => { - const script = ` - const { Socket } = await import('node:net') - let connections = 0 - Socket.prototype.connect = () => { connections++; throw new Error('Network disabled') } - try { - await fetch('https://jsonplaceholder.typicode.com/unhandled') - process.exitCode = 1 - } catch { - console.log(JSON.stringify({ connections })) - } - ` - const result = await execFileAsync(process.execPath, [ - '--import', - preload, - '--eval', - script, - ]) - expect(JSON.parse(result.stdout)).toEqual({ connections: 0 }) -}) diff --git a/e2e/e2e-utils/tests/webServer.test.ts b/e2e/e2e-utils/tests/webServer.test.ts deleted file mode 100644 index fd3a8b239c..0000000000 --- a/e2e/e2e-utils/tests/webServer.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { stripVTControlCharacters } from 'node:util' -import { expect, test } from 'vitest' -import { appServerReadyPattern } from '../src/webServer' - -test.each([ - '➜ Local: http://localhost:49152/', - '\u001b[32m➜\u001b[39m \u001b[1mLocal\u001b[22m: \u001b[36mhttp://localhost:\u001b[1m49152\u001b[22m/\u001b[39m', - 'Listening on http://[::]:49152', - 'E2E app: http://localhost:49152', - 'Accepting connections at http://localhost:49152', - 'Local: https://localhost:49152/', -])('captures a bound application port from %s', (line) => { - expect( - appServerReadyPattern.exec(stripVTControlCharacters(line))?.groups - ?.E2E_APP_PORT, - ).toBe('49152') -}) - -test('does not confuse an arbitrary URL with app readiness', () => { - expect(appServerReadyPattern.test('fetching http://localhost:49152')).toBe( - false, - ) -}) diff --git a/e2e/e2e-utils/tsconfig.json b/e2e/e2e-utils/tsconfig.json index 5561f5d28f..9b21ee123b 100644 --- a/e2e/e2e-utils/tsconfig.json +++ b/e2e/e2e-utils/tsconfig.json @@ -1,7 +1,4 @@ { "extends": "../../tsconfig.json", - "include": ["src", "vite.config.ts", "tests"], - "compilerOptions": { - "rewriteRelativeImportExtensions": true - } + "include": ["src", "vite.config.ts", "tests"] } diff --git a/e2e/react-router/basepath-file-based/package.json b/e2e/react-router/basepath-file-based/package.json index 3dfbb58180..a155cc2173 100644 --- a/e2e/react-router/basepath-file-based/package.json +++ b/e2e/react-router/basepath-file-based/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", diff --git a/e2e/react-router/basepath-file-based/playwright.config.ts b/e2e/react-router/basepath-file-based/playwright.config.ts index 4eead86444..6069bbe59f 100644 --- a/e2e/react-router/basepath-file-based/playwright.config.ts +++ b/e2e/react-router/basepath-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/basepath-file-based/tests/scroll-restoration-session-storage-error.test.ts b/e2e/react-router/basepath-file-based/tests/scroll-restoration-session-storage-error.test.ts index d6a50de840..06b90f6528 100644 --- a/e2e/react-router/basepath-file-based/tests/scroll-restoration-session-storage-error.test.ts +++ b/e2e/react-router/basepath-file-based/tests/scroll-restoration-session-storage-error.test.ts @@ -1,41 +1,5 @@ -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' -import type { Page } from '@playwright/test' - -async function reloadAfterStorageFailure(page: Page) { - const errors: Array = [] - page.on('pageerror', (error) => errors.push(error.message)) - const snapshot = await page.evaluate(async () => { - let failures = 0 - const setItem = Storage.prototype.setItem - Storage.prototype.setItem = function (...args) { - try { - return setItem.apply(this, args) - } catch (error) { - failures++ - throw error - } - } - const scrolled = new Promise((resolve) => - addEventListener('scroll', () => resolve(), { once: true }), - ) - scrollTo(0, 200) - await scrolled - // Handler integration; genuine reload handoff is covered by the Start suite. - dispatchEvent(new PageTransitionEvent('pagehide', { persisted: false })) - return { mode: history.scrollRestoration, failures } - }) - expect(snapshot.failures).toBeGreaterThan(0) - // Storage failure must still allow native fallback; failure to restore is not a requirement. - expect(snapshot.mode).toBe('auto') - await page.reload() - await page.waitForLoadState('networkidle') - await expect( - page.getByRole('heading', { name: 'Scroll Error Test' }), - ).toBeVisible() - expect(await page.evaluate(() => history.scrollRestoration)).toBe('manual') - expect(errors).toEqual([]) -} +/* eslint-disable */ +import { expect, test } from '@playwright/test' test.describe('Scroll Restoration with Session Storage Error', () => { test('should not crash when sessionStorage.setItem throws an error', async ({ @@ -45,12 +9,22 @@ test.describe('Scroll Restoration with Session Storage Error', () => { await page.waitForLoadState('networkidle') await page.evaluate(() => { - Storage.prototype.setItem = () => { + sessionStorage.setItem = () => { throw new Error('Test Error') } }) - await reloadAfterStorageFailure(page) + await page.evaluate(() => window.scrollTo(0, 200)) + await page.waitForTimeout(150) + + await page.reload() + await page.waitForLoadState('networkidle') + + const heading = page.locator('h1:has-text("Scroll Error Test")') + await expect(heading).toBeVisible() + + const scrollPosition = await page.evaluate(() => window.scrollY) + expect(scrollPosition).not.toBe(200) }) test('should not crash when sessionStorage quota is exceeded', async ({ @@ -73,6 +47,16 @@ test.describe('Scroll Restoration with Session Storage Error', () => { } }) - await reloadAfterStorageFailure(page) + await page.evaluate(() => window.scrollTo(0, 200)) + await page.waitForTimeout(150) + + await page.reload() + await page.waitForLoadState('networkidle') + + const heading = page.locator('h1:has-text("Scroll Error Test")') + await expect(heading).toBeVisible() + + const scrollPosition = await page.evaluate(() => window.scrollY) + expect(scrollPosition).not.toBe(200) }) }) diff --git a/e2e/react-router/basepath-file-based/tests/setup/global.setup.ts b/e2e/react-router/basepath-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/basepath-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-router/basepath-file-based/tests/setup/global.teardown.ts b/e2e/react-router/basepath-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/basepath-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-router/basic-esbuild-file-based/package.json b/e2e/react-router/basic-esbuild-file-based/package.json index 59210c24d7..9421e4666c 100644 --- a/e2e/react-router/basic-esbuild-file-based/package.json +++ b/e2e/react-router/basic-esbuild-file-based/package.json @@ -7,7 +7,7 @@ "build": "esbuild src/main.tsx --bundle --outfile=dist/main.js && tsc --noEmit", "serve": "esbuild src/main.tsx --bundle --outfile=dist/main.js --servedir=.", "start": "dev", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", diff --git a/e2e/react-router/basic-esbuild-file-based/playwright.config.ts b/e2e/react-router/basic-esbuild-file-based/playwright.config.ts index a38252921f..ca0fb7a1da 100644 --- a/e2e/react-router/basic-esbuild-file-based/playwright.config.ts +++ b/e2e/react-router/basic-esbuild-file-based/playwright.config.ts @@ -1,8 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' - -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -13,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm run build && pnpm run serve --serve=${PORT} --define:process.env.NODE_ENV=\\"test\\"`, - wait: appServerReady, - reuseExistingServer: false, + command: `pnpm run build && pnpm run serve --serve=${PORT} --define:process.env.NODE_ENV=\\"test\\" --define:process.env.EXTERNAL_PORT="${EXTERNAL_PORT}"`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/basic-esbuild-file-based/src/esbuild.config.js b/e2e/react-router/basic-esbuild-file-based/src/esbuild.config.js index 954ddc026f..5f0f4fce03 100644 --- a/e2e/react-router/basic-esbuild-file-based/src/esbuild.config.js +++ b/e2e/react-router/basic-esbuild-file-based/src/esbuild.config.js @@ -2,5 +2,9 @@ import { tanstackRouter } from '@tanstack/router-plugin/esbuild' export default { // ... - plugins: [tanstackRouter()], + plugins: [ + tanstackRouter({ + autoCodeSplitting: true, + }), + ], } diff --git a/e2e/react-router/basic-esbuild-file-based/src/posts.tsx b/e2e/react-router/basic-esbuild-file-based/src/posts.tsx index 97c96d77eb..8f74b8c9aa 100644 --- a/e2e/react-router/basic-esbuild-file-based/src/posts.tsx +++ b/e2e/react-router/basic-esbuild-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (process.env.NODE_ENV === 'test') { + queryURL = `http://localhost:${process.env.EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/react-router/basic-esbuild-file-based/tests/app.spec.ts b/e2e/react-router/basic-esbuild-file-based/tests/app.spec.ts index c52191a7d4..7b322a8b1d 100644 --- a/e2e/react-router/basic-esbuild-file-based/tests/app.spec.ts +++ b/e2e/react-router/basic-esbuild-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/basic-esbuild-file-based/tests/setup/global.setup.ts b/e2e/react-router/basic-esbuild-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/basic-esbuild-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-router/basic-esbuild-file-based/tests/setup/global.teardown.ts b/e2e/react-router/basic-esbuild-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/basic-esbuild-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-router/basic-file-based-code-splitting/package.json b/e2e/react-router/basic-file-based-code-splitting/package.json index 82ebb90e93..8355ed79ab 100644 --- a/e2e/react-router/basic-file-based-code-splitting/package.json +++ b/e2e/react-router/basic-file-based-code-splitting/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/react-router/basic-file-based-code-splitting/playwright.config.ts b/e2e/react-router/basic-file-based-code-splitting/playwright.config.ts index 4eead86444..22c9bdcd7e 100644 --- a/e2e/react-router/basic-file-based-code-splitting/playwright.config.ts +++ b/e2e/react-router/basic-file-based-code-splitting/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/basic-file-based-code-splitting/src/posts.tsx b/e2e/react-router/basic-file-based-code-splitting/src/posts.tsx index 97c96d77eb..ae7142c5b6 100644 --- a/e2e/react-router/basic-file-based-code-splitting/src/posts.tsx +++ b/e2e/react-router/basic-file-based-code-splitting/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/react-router/basic-file-based-code-splitting/tests/app.spec.ts b/e2e/react-router/basic-file-based-code-splitting/tests/app.spec.ts index fbf093cd51..3e5a69ccaa 100644 --- a/e2e/react-router/basic-file-based-code-splitting/tests/app.spec.ts +++ b/e2e/react-router/basic-file-based-code-splitting/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/basic-file-based-code-splitting/tests/preload.spec.ts b/e2e/react-router/basic-file-based-code-splitting/tests/preload.spec.ts index fd17fcc47b..0bc3265760 100644 --- a/e2e/react-router/basic-file-based-code-splitting/tests/preload.spec.ts +++ b/e2e/react-router/basic-file-based-code-splitting/tests/preload.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/basic-file-based-code-splitting/tests/setup/global.setup.ts b/e2e/react-router/basic-file-based-code-splitting/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/basic-file-based-code-splitting/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-router/basic-file-based-code-splitting/tests/setup/global.teardown.ts b/e2e/react-router/basic-file-based-code-splitting/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/basic-file-based-code-splitting/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-router/basic-file-based-code-splitting/tests/shared-bindings.spec.ts b/e2e/react-router/basic-file-based-code-splitting/tests/shared-bindings.spec.ts index 2ad4ec3e78..512943c10d 100644 --- a/e2e/react-router/basic-file-based-code-splitting/tests/shared-bindings.spec.ts +++ b/e2e/react-router/basic-file-based-code-splitting/tests/shared-bindings.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/basic-file-based/package.json b/e2e/react-router/basic-file-based/package.json index 0f3d243432..9868755b87 100644 --- a/e2e/react-router/basic-file-based/package.json +++ b/e2e/react-router/basic-file-based/package.json @@ -9,7 +9,7 @@ "preview": "vite preview", "start": "vite", "test:e2e": "pnpm run test:e2e:default", - "test:e2e:default": "playwright test --project=chromium" + "test:e2e:default": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/react-router/basic-file-based/playwright.config.ts b/e2e/react-router/basic-file-based/playwright.config.ts index ea3ef9ffec..6e4e1d7703 100644 --- a/e2e/react-router/basic-file-based/playwright.config.ts +++ b/e2e/react-router/basic-file-based/playwright.config.ts @@ -1,9 +1,14 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` -const command = `pnpm build && pnpm preview --host 0.0.0.0 --port ${PORT}` +const command = `pnpm build && pnpm preview --port ${PORT}` console.info('Running with mode: ', process.env.MODE || 'default') @@ -16,6 +21,9 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, @@ -23,12 +31,15 @@ export default defineConfig({ webServer: { command, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { MODE: process.env.MODE || '', VITE_MODE: process.env.MODE || '', + VITE_NODE_ENV: 'test', + VITE_EXTERNAL_PORT: String(EXTERNAL_PORT), + VITE_SERVER_PORT: String(PORT), PORT: String(PORT), }, }, diff --git a/e2e/react-router/basic-file-based/public/external.html b/e2e/react-router/basic-file-based/public/external.html deleted file mode 100644 index 3b4062b778..0000000000 --- a/e2e/react-router/basic-file-based/public/external.html +++ /dev/null @@ -1,9 +0,0 @@ - - - - External destination - - - Hello World - - diff --git a/e2e/react-router/basic-file-based/src/main.tsx b/e2e/react-router/basic-file-based/src/main.tsx index d6a5aef382..12e202dae4 100644 --- a/e2e/react-router/basic-file-based/src/main.tsx +++ b/e2e/react-router/basic-file-based/src/main.tsx @@ -24,14 +24,6 @@ const router = createRouter({ defaultStaleTime: 5000, scrollRestoration: true, routeMasks: [mask], - rewrite: { - output: ({ url }) => { - if (url.pathname === '/document-navigation-target') { - return new URL(`http://127.0.0.1:${window.location.port}/external.html`) - } - return url - }, - }, }) // Register things for typesafety diff --git a/e2e/react-router/basic-file-based/src/posts.tsx b/e2e/react-router/basic-file-based/src/posts.tsx index 97c96d77eb..ae7142c5b6 100644 --- a/e2e/react-router/basic-file-based/src/posts.tsx +++ b/e2e/react-router/basic-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/react-router/basic-file-based/src/routeTree.gen.ts b/e2e/react-router/basic-file-based/src/routeTree.gen.ts index 83b504992f..2493a8c675 100644 --- a/e2e/react-router/basic-file-based/src/routeTree.gen.ts +++ b/e2e/react-router/basic-file-based/src/routeTree.gen.ts @@ -13,12 +13,9 @@ import { Route as IndexRouteImport } from './routes/index' import { Route as LayoutRouteImport } from './routes/_layout' import { Route as AnchorRouteImport } from './routes/anchor' import { Route as ComponentTypesTestRouteImport } from './routes/component-types-test' -import { Route as DocumentNavigationRouteImport } from './routes/document-navigation' -import { Route as DocumentNavigationTargetRouteImport } from './routes/document-navigation-target' import { Route as EditingARouteImport } from './routes/editing-a' import { Route as EditingBRouteImport } from './routes/editing-b' import { Route as FullpathTestRouteRouteImport } from './routes/fullpath-test/route' -import { Route as HistoryBlockingRouteImport } from './routes/history-blocking' import { Route as HoverPreloadHashRouteImport } from './routes/hover-preload-hash' import { Route as LazyErrorRouteImport } from './routes/lazy-error' import { Route as MasksRouteImport } from './routes/masks' @@ -152,17 +149,6 @@ const ComponentTypesTestRoute = ComponentTypesTestRouteImport.update({ path: '/component-types-test', getParentRoute: () => rootRouteImport, } as any) -const DocumentNavigationRoute = DocumentNavigationRouteImport.update({ - id: '/document-navigation', - path: '/document-navigation', - getParentRoute: () => rootRouteImport, -} as any) -const DocumentNavigationTargetRoute = - DocumentNavigationTargetRouteImport.update({ - id: '/document-navigation-target', - path: '/document-navigation-target', - getParentRoute: () => rootRouteImport, - } as any) const EditingARoute = EditingARouteImport.update({ id: '/editing-a', path: '/editing-a', @@ -178,11 +164,6 @@ const FullpathTestRouteRoute = FullpathTestRouteRouteImport.update({ path: '/fullpath-test', getParentRoute: () => rootRouteImport, } as any) -const HistoryBlockingRoute = HistoryBlockingRouteImport.update({ - id: '/history-blocking', - path: '/history-blocking', - getParentRoute: () => rootRouteImport, -} as any) const HoverPreloadHashRoute = HoverPreloadHashRouteImport.update({ id: '/hover-preload-hash', path: '/hover-preload-hash', @@ -806,11 +787,8 @@ export interface FileRoutesByFullPath { '/대한민국': typeof Char45824Char54620Char48124Char44397RouteRouteWithChildren '/anchor': typeof AnchorRoute '/component-types-test': typeof ComponentTypesTestRoute - '/document-navigation': typeof DocumentNavigationRoute - '/document-navigation-target': typeof DocumentNavigationTargetRoute '/editing-a': typeof EditingARoute '/editing-b': typeof EditingBRoute - '/history-blocking': typeof HistoryBlockingRoute '/hover-preload-hash': typeof HoverPreloadHashRoute '/lazy-error': typeof LazyErrorRoute '/masks': typeof MasksRouteWithChildren @@ -925,11 +903,8 @@ export interface FileRoutesByTo { '/대한민국': typeof Char45824Char54620Char48124Char44397RouteRouteWithChildren '/anchor': typeof AnchorRoute '/component-types-test': typeof ComponentTypesTestRoute - '/document-navigation': typeof DocumentNavigationRoute - '/document-navigation-target': typeof DocumentNavigationTargetRoute '/editing-a': typeof EditingARoute '/editing-b': typeof EditingBRoute - '/history-blocking': typeof HistoryBlockingRoute '/hover-preload-hash': typeof HoverPreloadHashRoute '/lazy-error': typeof LazyErrorRoute '/masks': typeof MasksRouteWithChildren @@ -1036,11 +1011,8 @@ export interface FileRoutesById { '/_layout': typeof LayoutRouteWithChildren '/anchor': typeof AnchorRoute '/component-types-test': typeof ComponentTypesTestRoute - '/document-navigation': typeof DocumentNavigationRoute - '/document-navigation-target': typeof DocumentNavigationTargetRoute '/editing-a': typeof EditingARoute '/editing-b': typeof EditingBRoute - '/history-blocking': typeof HistoryBlockingRoute '/hover-preload-hash': typeof HoverPreloadHashRoute '/lazy-error': typeof LazyErrorRoute '/masks': typeof MasksRouteWithChildren @@ -1162,11 +1134,8 @@ export interface FileRouteTypes { | '/대한민국' | '/anchor' | '/component-types-test' - | '/document-navigation' - | '/document-navigation-target' | '/editing-a' | '/editing-b' - | '/history-blocking' | '/hover-preload-hash' | '/lazy-error' | '/masks' @@ -1281,11 +1250,8 @@ export interface FileRouteTypes { | '/대한민국' | '/anchor' | '/component-types-test' - | '/document-navigation' - | '/document-navigation-target' | '/editing-a' | '/editing-b' - | '/history-blocking' | '/hover-preload-hash' | '/lazy-error' | '/masks' @@ -1391,11 +1357,8 @@ export interface FileRouteTypes { | '/_layout' | '/anchor' | '/component-types-test' - | '/document-navigation' - | '/document-navigation-target' | '/editing-a' | '/editing-b' - | '/history-blocking' | '/hover-preload-hash' | '/lazy-error' | '/masks' @@ -1517,11 +1480,8 @@ export interface RootRouteChildren { LayoutRoute: typeof LayoutRouteWithChildren AnchorRoute: typeof AnchorRoute ComponentTypesTestRoute: typeof ComponentTypesTestRoute - DocumentNavigationRoute: typeof DocumentNavigationRoute - DocumentNavigationTargetRoute: typeof DocumentNavigationTargetRoute EditingARoute: typeof EditingARoute EditingBRoute: typeof EditingBRoute - HistoryBlockingRoute: typeof HistoryBlockingRoute HoverPreloadHashRoute: typeof HoverPreloadHashRoute LazyErrorRoute: typeof LazyErrorRoute MasksRoute: typeof MasksRouteWithChildren @@ -1589,20 +1549,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ComponentTypesTestRouteImport parentRoute: typeof rootRouteImport } - '/document-navigation': { - id: '/document-navigation' - path: '/document-navigation' - fullPath: '/document-navigation' - preLoaderRoute: typeof DocumentNavigationRouteImport - parentRoute: typeof rootRouteImport - } - '/document-navigation-target': { - id: '/document-navigation-target' - path: '/document-navigation-target' - fullPath: '/document-navigation-target' - preLoaderRoute: typeof DocumentNavigationTargetRouteImport - parentRoute: typeof rootRouteImport - } '/editing-a': { id: '/editing-a' path: '/editing-a' @@ -1624,13 +1570,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof FullpathTestRouteRouteImport parentRoute: typeof rootRouteImport } - '/history-blocking': { - id: '/history-blocking' - path: '/history-blocking' - fullPath: '/history-blocking' - preLoaderRoute: typeof HistoryBlockingRouteImport - parentRoute: typeof rootRouteImport - } '/hover-preload-hash': { id: '/hover-preload-hash' path: '/hover-preload-hash' @@ -1711,7 +1650,7 @@ declare module '@tanstack/react-router' { '/(group)/_layout': { id: '/(group)/_layout' path: '' - fullPath: '/' + fullPath: '' preLoaderRoute: typeof groupLayoutRouteImport parentRoute: typeof rootRouteImport } @@ -2939,11 +2878,8 @@ const rootRouteChildren: RootRouteChildren = { LayoutRoute: LayoutRouteWithChildren, AnchorRoute: AnchorRoute, ComponentTypesTestRoute: ComponentTypesTestRoute, - DocumentNavigationRoute: DocumentNavigationRoute, - DocumentNavigationTargetRoute: DocumentNavigationTargetRoute, EditingARoute: EditingARoute, EditingBRoute: EditingBRoute, - HistoryBlockingRoute: HistoryBlockingRoute, HoverPreloadHashRoute: HoverPreloadHashRoute, LazyErrorRoute: LazyErrorRoute, MasksRoute: MasksRouteWithChildren, diff --git a/e2e/react-router/basic-file-based/src/routes/anchor.tsx b/e2e/react-router/basic-file-based/src/routes/anchor.tsx index cae0a3e583..aafad6cb6f 100644 --- a/e2e/react-router/basic-file-based/src/routes/anchor.tsx +++ b/e2e/react-router/basic-file-based/src/routes/anchor.tsx @@ -25,10 +25,6 @@ const anchors: Array<{ title: 'Smooth Scroll', hashScrollIntoView: { behavior: 'smooth' }, }, - { - id: '/\\section', - title: 'Fragment with slashes', - }, ] as const function AnchorSection({ id, title }: { id: string; title: string }) { diff --git a/e2e/react-router/basic-file-based/src/routes/document-navigation-target.tsx b/e2e/react-router/basic-file-based/src/routes/document-navigation-target.tsx deleted file mode 100644 index 905b0c31b9..0000000000 --- a/e2e/react-router/basic-file-based/src/routes/document-navigation-target.tsx +++ /dev/null @@ -1,3 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/document-navigation-target')({}) diff --git a/e2e/react-router/basic-file-based/src/routes/document-navigation.tsx b/e2e/react-router/basic-file-based/src/routes/document-navigation.tsx deleted file mode 100644 index 66c2b704d1..0000000000 --- a/e2e/react-router/basic-file-based/src/routes/document-navigation.tsx +++ /dev/null @@ -1,97 +0,0 @@ -import { Link, createFileRoute } from '@tanstack/react-router' -import type { AnyRouter } from '@tanstack/react-router' - -export const Route = createFileRoute('/document-navigation')({ - component: DocumentNavigation, -}) - -const adminHref = `http://127.0.0.1:${window.location.port}/external.html` - -function DocumentNavigation() { - const navigate = Route.useNavigate() - - return ( -
- - - - - - - - Navigate to admin - - Replace with admin - - - Reload admin - - - Navigate with external mask - - - Replace with external mask - - to={`${adminHref}?value=a+b&value=a%20b#raw%2f`}> - Navigate to absolute href - - - Reload relative href - -
- ) -} diff --git a/e2e/react-router/basic-file-based/src/routes/history-blocking.tsx b/e2e/react-router/basic-file-based/src/routes/history-blocking.tsx deleted file mode 100644 index 019893a628..0000000000 --- a/e2e/react-router/basic-file-based/src/routes/history-blocking.tsx +++ /dev/null @@ -1,119 +0,0 @@ -import * as React from 'react' -import { - Link, - createFileRoute, - useBlocker, - useRouter, -} from '@tanstack/react-router' - -export const Route = createFileRoute('/history-blocking')({ - validateSearch: (search: Record) => ({ - step: Number(search.step) || 0, - }), - component: HistoryBlocking, -}) - -function HistoryBlocking() { - const router = useRouter() - const { step } = Route.useSearch() - const [draft, setDraft] = React.useState('') - const [ignoreBlocker, setIgnoreBlocker] = React.useState(false) - const [documentHref, setDocumentHref] = React.useState('/') - const [navigationError, setNavigationError] = React.useState('') - const { status, reset, proceed } = useBlocker({ - shouldBlockFn: () => draft.length > 0, - enableBeforeUnload: draft.length > 0, - withResolver: true, - }) - - return ( -
-

History blocking

-

Step {step}

- - -

{draft ? 'Unsaved changes' : 'No changes'}

-

Blocker status: {status}

- {status === 'blocked' && ( - <> - - - - )} - - {[false, true].map((replace) => ( - - ))} - {navigationError &&

{navigationError}

} - - Add history entry - - - - {[-2, -1, 0, 1, 2].map((delta) => ( - - ))} - Leave document -
- ) -} diff --git a/e2e/react-router/basic-file-based/tests/app.spec.ts b/e2e/react-router/basic-file-based/tests/app.spec.ts index bd9c365484..ae87d350ce 100644 --- a/e2e/react-router/basic-file-based/tests/app.spec.ts +++ b/e2e/react-router/basic-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import type { Page } from '@playwright/test' test.beforeEach(async ({ page }) => { diff --git a/e2e/react-router/basic-file-based/tests/document-navigation.spec.ts b/e2e/react-router/basic-file-based/tests/document-navigation.spec.ts deleted file mode 100644 index bd81eaa44b..0000000000 --- a/e2e/react-router/basic-file-based/tests/document-navigation.spec.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' - -const appPort = Number(process.env.E2E_APP_PORT ?? 0) -const adminHref = `http://127.0.0.1:${appPort}/external.html` - -for (const role of ['button', 'link'] as const) { - for (const { name, href, replace } of [ - { name: 'Navigate to admin', href: adminHref, replace: false }, - { name: 'Replace with admin', href: adminHref, replace: true }, - { name: 'Reload admin', href: adminHref, replace: false }, - { name: 'Navigate with external mask', href: adminHref, replace: false }, - { name: 'Replace with external mask', href: adminHref, replace: true }, - { - name: 'Navigate to absolute href', - href: `${adminHref}?value=a+b&value=a%20b#raw%2f`, - replace: false, - }, - ]) { - test(`${role}: ${name}`, async ({ page }) => { - const errors: Array = [] - page.on('pageerror', (error) => errors.push(error)) - await page.goto('/') - await page.goto('/document-navigation') - const historyLength = await page.evaluate(() => window.history.length) - const response = page.waitForResponse(href.split('#')[0]) - - const control = page.getByRole(role, { name, exact: true }) - if (role === 'link') { - await expect(control).toHaveAttribute('href', href) - } - await control.click() - - expect((await response).request().isNavigationRequest()).toBe(true) - await expect(page).toHaveURL(href) - await expect(page.locator('body')).toHaveText('Hello World') - // Cross-origin Links use native anchors, which push even with replace=true. - const replacesHistory = role === 'button' && replace - expect(await page.evaluate(() => window.history.length)).toBe( - historyLength + (replacesHistory ? 0 : 1), - ) - expect(errors).toEqual([]) - - await page.goBack() - - await expect(page).toHaveURL( - replacesHistory ? '/' : '/document-navigation', - ) - }) - } - - test(`${role}: explicit reload resolves a raw relative href in the browser`, async ({ - page, - }) => { - await page.goto('/document-navigation') - const response = page.waitForResponse((candidate) => - candidate.request().isNavigationRequest(), - ) - - await page - .getByRole(role, { name: 'Reload relative href', exact: true }) - .click() - - expect((await response).request().resourceType()).toBe('document') - await expect(page).toHaveURL('/?value=a+b&value=a%20b#raw%2f') - await expect(page.getByRole('heading')).toContainText('Welcome Home!') - }) -} diff --git a/e2e/react-router/basic-file-based/tests/fullpath-types.spec.ts b/e2e/react-router/basic-file-based/tests/fullpath-types.spec.ts index 8f4df9f966..d1bd9c1c41 100644 --- a/e2e/react-router/basic-file-based/tests/fullpath-types.spec.ts +++ b/e2e/react-router/basic-file-based/tests/fullpath-types.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.describe('FullPath type/runtime match (Issues #4892, #2675, #6403)', () => { test.describe('Pathless layout routes should have parent fullPath, not empty string', () => { diff --git a/e2e/react-router/basic-file-based/tests/history-blocking.spec.ts b/e2e/react-router/basic-file-based/tests/history-blocking.spec.ts deleted file mode 100644 index df1f863a03..0000000000 --- a/e2e/react-router/basic-file-based/tests/history-blocking.spec.ts +++ /dev/null @@ -1,254 +0,0 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' -import type { Page } from '@playwright/test' - -async function prepareDocumentTraversal(page: Page, delta: number) { - if (delta < 0) { - for (let i = 0; i < Math.abs(delta); i++) { - await page.goto(`/?entry=${i}`) - } - await page.goto('/history-blocking') - } else { - await page.goto('/history-blocking') - for (let i = 0; i < delta; i++) { - await page.goto(`/?entry=${i}`) - } - for (let i = 0; i < delta; i++) { - await page.goBack() - } - } - await expect( - page.getByRole('heading', { name: 'History blocking' }), - ).toBeVisible() - await page.getByLabel('Draft', { exact: true }).fill('Unsaved draft') - await expect(page.getByText('Unsaved changes', { exact: true })).toBeVisible() -} - -async function prepareSameDocumentTraversal(page: Page, delta: number) { - await page.goto('/history-blocking') - for (let step = 1; step <= Math.abs(delta); step++) { - await page.getByRole('link', { name: 'Add history entry' }).click() - await expect(page.getByText(`Step ${step}`, { exact: true })).toBeVisible() - } - if (delta > 0) { - for (let step = delta - 1; step >= 0; step--) { - await page - .getByRole('button', { name: 'History back', exact: true }) - .click() - await expect( - page.getByText(`Step ${step}`, { exact: true }), - ).toBeVisible() - } - } - await page.getByLabel('Draft', { exact: true }).fill('Unsaved draft') - await expect(page.getByText('Unsaved changes', { exact: true })).toBeVisible() -} - -function dismissUnloadDialogs(page: Page) { - const dialogs: Array = [] - page.on('dialog', async (dialog) => { - dialogs.push(dialog.type()) - await dialog.dismiss() - }) - return dialogs -} - -for (const [direction, delta] of [ - ['back', -1], - ['forward', 1], - ['go(-1)', -1], - ['go(1)', 1], - ['go(-2)', -2], - ['go(2)', 2], -] as const) { - test(`history ${direction} to another document warns before losing edits`, async ({ - page, - }) => { - await prepareDocumentTraversal(page, delta) - const dialogs = dismissUnloadDialogs(page) - const originalUrl = page.url() - - await page - .getByRole('button', { name: `History ${direction}`, exact: true }) - .click() - - await expect.poll(() => dialogs).toEqual(['beforeunload']) - await expect(page).toHaveURL(originalUrl) - await expect(page.getByLabel('Draft', { exact: true })).toHaveValue( - 'Unsaved draft', - ) - }) - - test(`history ${direction} can explicitly bypass a document unload warning`, async ({ - page, - }) => { - await prepareDocumentTraversal(page, delta) - await page.getByLabel('Ignore blockers').check() - const dialogs = dismissUnloadDialogs(page) - - await page - .getByRole('button', { name: `History ${direction}`, exact: true }) - .click() - - await expect(page).toHaveURL(/\/\?entry=\d$/) - expect(dialogs).toEqual([]) - }) - - test(`ignored same-document ${direction} preserves the next document unload warning`, async ({ - page, - }) => { - await prepareSameDocumentTraversal(page, delta) - await page.getByLabel('Ignore blockers').check() - const dialogs = dismissUnloadDialogs(page) - - await page - .getByRole('button', { name: `History ${direction}`, exact: true }) - .click() - - await expect( - page.getByText(`Step ${delta < 0 ? 0 : delta}`, { - exact: true, - }), - ).toBeVisible() - await expect(page.getByLabel('Draft', { exact: true })).toHaveValue( - 'Unsaved draft', - ) - await expect( - page.getByText('Blocker status: idle', { exact: true }), - ).toBeVisible() - expect(dialogs).toEqual([]) - - await page.getByRole('link', { name: 'Leave document' }).click() - - await expect.poll(() => dialogs).toEqual(['beforeunload']) - await expect(page.getByLabel('Draft', { exact: true })).toHaveValue( - 'Unsaved draft', - ) - }) - - test(`same-document ${direction} still checks blockers by default`, async ({ - page, - }) => { - await prepareSameDocumentTraversal(page, delta) - const originalUrl = page.url() - - await page - .getByRole('button', { name: `History ${direction}`, exact: true }) - .click() - - await expect( - page.getByText('Blocker status: blocked', { exact: true }), - ).toBeVisible() - await expect( - page.getByText(`Step ${delta < 0 ? -delta : 0}`, { exact: true }), - ).toBeVisible() - await expect(page.getByLabel('Draft', { exact: true })).toHaveValue( - 'Unsaved draft', - ) - await page.getByRole('button', { name: 'Stay here' }).click() - await expect( - page.getByText('Blocker status: idle', { exact: true }), - ).toBeVisible() - await expect(page).toHaveURL(originalUrl) - await expect( - page.getByText(`Step ${delta < 0 ? -delta : 0}`, { exact: true }), - ).toBeVisible() - }) -} - -for (const ignoreBlocker of [false, true]) { - test(`history go(0) ${ignoreBlocker ? 'can bypass' : 'preserves'} the reload warning`, async ({ - page, - }) => { - await page.goto('/history-blocking') - await page.getByLabel('Draft', { exact: true }).fill('Unsaved draft') - await expect( - page.getByText('Unsaved changes', { exact: true }), - ).toBeVisible() - if (ignoreBlocker) { - await page.getByLabel('Ignore blockers').check() - } - const dialogs = dismissUnloadDialogs(page) - - await page - .getByRole('button', { name: 'History go(0)', exact: true }) - .click() - - if (ignoreBlocker) { - await expect(page.getByLabel('Draft', { exact: true })).toHaveValue('') - expect(dialogs).toEqual([]) - } else { - await expect.poll(() => dialogs).toEqual(['beforeunload']) - await expect(page.getByLabel('Draft', { exact: true })).toHaveValue( - 'Unsaved draft', - ) - } - }) -} - -for (const action of ['Navigate document', 'Replace document']) { - test(`${action}: invalid URLs preserve the next unload warning`, async ({ - page, - }) => { - await page.goto('/history-blocking') - await page.getByLabel('Draft', { exact: true }).fill('Unsaved draft') - await page.getByLabel('Ignore blockers').check() - await page.getByLabel('Document destination').fill('https://[') - const dialogs = dismissUnloadDialogs(page) - - await page.getByRole('button', { name: action, exact: true }).click() - - await expect(page.getByRole('status')).toBeVisible() - expect(dialogs).toEqual([]) - await page.getByRole('link', { name: 'Leave document' }).click() - - await expect.poll(() => dialogs).toEqual(['beforeunload']) - await expect(page.getByLabel('Draft', { exact: true })).toHaveValue( - 'Unsaved draft', - ) - }) - - test(`${action}: the current fragment preserves the next unload warning`, async ({ - page, - }) => { - await page.goto('/history-blocking?step=0#same') - await page.getByLabel('Draft', { exact: true }).fill('Unsaved draft') - await page.getByLabel('Ignore blockers').check() - await page.getByLabel('Document destination').fill('#same') - const dialogs = dismissUnloadDialogs(page) - - await page.getByRole('button', { name: action, exact: true }).click() - - await expect(page).toHaveURL('/history-blocking?step=0#same') - expect(dialogs).toEqual([]) - await page.getByRole('link', { name: 'Leave document' }).click() - - await expect.poll(() => dialogs).toEqual(['beforeunload']) - await expect(page.getByLabel('Draft', { exact: true })).toHaveValue( - 'Unsaved draft', - ) - }) - - for (const ignoreBlocker of [false, true]) { - test(`${action}: ${ignoreBlocker ? 'skipped' : 'accepted'} blockers need no native confirmation`, async ({ - page, - }) => { - await page.goto('/history-blocking') - await page.getByLabel('Draft', { exact: true }).fill('Unsaved draft') - if (ignoreBlocker) { - await page.getByLabel('Ignore blockers').check() - } - const dialogs = dismissUnloadDialogs(page) - - await page.getByRole('button', { name: action, exact: true }).click() - if (!ignoreBlocker) { - await page - .getByRole('button', { name: 'Continue navigation', exact: true }) - .click() - } - - await expect(page).toHaveURL('/') - expect(dialogs).toEqual([]) - }) - } -} diff --git a/e2e/react-router/basic-file-based/tests/hover-preload-hash.spec.ts b/e2e/react-router/basic-file-based/tests/hover-preload-hash.spec.ts index 1263faf391..b090c2a6b7 100644 --- a/e2e/react-router/basic-file-based/tests/hover-preload-hash.spec.ts +++ b/e2e/react-router/basic-file-based/tests/hover-preload-hash.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import { toRuntimePath } from '@tanstack/router-e2e-utils' test('clicking hash link then hovering another link does not scroll back to hash', async ({ diff --git a/e2e/react-router/basic-file-based/tests/mask.spec.ts b/e2e/react-router/basic-file-based/tests/mask.spec.ts index d5076a5854..1b77760de6 100644 --- a/e2e/react-router/basic-file-based/tests/mask.spec.ts +++ b/e2e/react-router/basic-file-based/tests/mask.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test('route masks transform params and expose masked pathname in the browser (react)', async ({ page, diff --git a/e2e/react-router/basic-file-based/tests/non-nested-paths.spec.ts b/e2e/react-router/basic-file-based/tests/non-nested-paths.spec.ts index ea0e585c75..dccdfd4acf 100644 --- a/e2e/react-router/basic-file-based/tests/non-nested-paths.spec.ts +++ b/e2e/react-router/basic-file-based/tests/non-nested-paths.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' const testCases: Array<{ name: string diff --git a/e2e/react-router/basic-file-based/tests/open-redirect-prevention.spec.ts b/e2e/react-router/basic-file-based/tests/open-redirect-prevention.spec.ts index bbb2dac7a1..2f0fe256cd 100644 --- a/e2e/react-router/basic-file-based/tests/open-redirect-prevention.spec.ts +++ b/e2e/react-router/basic-file-based/tests/open-redirect-prevention.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.describe('Open redirect prevention', () => { test.describe('CRLF injection attacks', () => { diff --git a/e2e/react-router/basic-file-based/tests/params.spec.ts b/e2e/react-router/basic-file-based/tests/params.spec.ts index fa0377f3ca..a867696ff8 100644 --- a/e2e/react-router/basic-file-based/tests/params.spec.ts +++ b/e2e/react-router/basic-file-based/tests/params.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import type { Page } from '@playwright/test' test.beforeEach(async ({ page }) => { diff --git a/e2e/react-router/basic-file-based/tests/redirect.spec.ts b/e2e/react-router/basic-file-based/tests/redirect.spec.ts index aaa9c1a6b6..1845cc16a4 100644 --- a/e2e/react-router/basic-file-based/tests/redirect.spec.ts +++ b/e2e/react-router/basic-file-based/tests/redirect.spec.ts @@ -1,13 +1,17 @@ import queryString from 'node:querystring' -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import combinateImport from 'combinate' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from '../package.json' with { type: 'json' } // somehow playwright does not correctly import default exports const combinate = (combinateImport as any).default as typeof combinateImport -const PORT = Number(process.env.E2E_APP_PORT ?? 0) -const EXTERNAL_ORIGIN = `http://127.0.0.1:${PORT}` +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_HOST_PORT = await getDummyServerPort(packageJson.name) test.describe('redirects', () => { const internalNavigationTestMatrix = combinate({ @@ -35,7 +39,7 @@ test.describe('redirects', () => { const requestPromise = new Promise((resolve) => { page.on('request', (request) => { if ( - request.url() === 'https://jsonplaceholder.typicode.com/posts' + request.url() === `http://localhost:${EXTERNAL_HOST_PORT}/posts` ) { requestHappened = true resolve() @@ -104,7 +108,7 @@ test.describe('redirects', () => { await page.waitForLoadState('networkidle') const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, }) if (scenario === 'navigate') { @@ -114,7 +118,7 @@ test.describe('redirects', () => { await page.goto(`/redirect/external/via-${thrower}?${q}`) } - const url = `${EXTERNAL_ORIGIN}/` + const url = `http://localhost:${EXTERNAL_HOST_PORT}/` await page.waitForURL(url) expect(page.url()).toBe(url) @@ -180,7 +184,7 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, }) if (scenario === 'navigate') { @@ -193,7 +197,7 @@ test.describe('redirects', () => { ) } - const url = `${EXTERNAL_ORIGIN}/` + const url = `http://localhost:${EXTERNAL_HOST_PORT}/` await page.waitForURL(url) expect(page.url()).toBe(url) }) @@ -250,7 +254,7 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, }) if (scenario === 'navigate') { @@ -263,7 +267,7 @@ test.describe('redirects', () => { ) } - const url = `${EXTERNAL_ORIGIN}/` + const url = `http://localhost:${EXTERNAL_HOST_PORT}/` await page.waitForURL(url) expect(page.url()).toBe(url) }) diff --git a/e2e/react-router/basic-file-based/tests/relative.spec.ts b/e2e/react-router/basic-file-based/tests/relative.spec.ts index f62c248680..4850d3630d 100644 --- a/e2e/react-router/basic-file-based/tests/relative.spec.ts +++ b/e2e/react-router/basic-file-based/tests/relative.spec.ts @@ -1,11 +1,12 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import combinateImport from 'combinate' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from '../package.json' with { type: 'json' } // somehow playwright does not correctly import default exports const combinate = (combinateImport as any).default as typeof combinateImport -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) test.describe('relative_routing', () => { const internalNavigationTestMatrix = combinate({ diff --git a/e2e/react-router/basic-file-based/tests/scroll-into-view.spec.ts b/e2e/react-router/basic-file-based/tests/scroll-into-view.spec.ts index 68dfededc2..d1af86adfb 100644 --- a/e2e/react-router/basic-file-based/tests/scroll-into-view.spec.ts +++ b/e2e/react-router/basic-file-based/tests/scroll-into-view.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import type { Page } from '@playwright/test' const anchors = { @@ -33,21 +32,6 @@ test.beforeEach(async ({ page }) => { await page.goto('/anchor') }) -test('slash and backslash fragment data selects the matching anchor', async ({ - page, -}) => { - const link = page.getByRole('link', { name: 'Fragment with slashes' }) - const heading = page.getByRole('heading', { name: 'Fragment with slashes' }) - await link.click() - await expect(page).toHaveURL(/#\/\\section$/) - await expect(link).toHaveClass(activeClass) - await expect(heading).toBeInViewport() - - await page.reload() - await expect(link).toHaveClass(activeClass) - await expect(heading).toBeInViewport() -}) - // Testing the `Link` component with the `hashScrollIntoView` prop test('Navigating via anchor `Link` with default hash scrolling behavior', async ({ page, diff --git a/e2e/react-router/basic-file-based/tests/search-params.spec.ts b/e2e/react-router/basic-file-based/tests/search-params.spec.ts index a99488a47a..d6307cbcf8 100644 --- a/e2e/react-router/basic-file-based/tests/search-params.spec.ts +++ b/e2e/react-router/basic-file-based/tests/search-params.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.describe('/search-params/default', () => { test('Directly visiting the route without search param set', async ({ diff --git a/e2e/react-router/basic-file-based/tests/setup/global.setup.ts b/e2e/react-router/basic-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/basic-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-router/basic-file-based/tests/setup/global.teardown.ts b/e2e/react-router/basic-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/basic-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-router/basic-react-query-file-based/package.json b/e2e/react-router/basic-react-query-file-based/package.json index 3a90a3cd6d..568313a6c3 100644 --- a/e2e/react-router/basic-react-query-file-based/package.json +++ b/e2e/react-router/basic-react-query-file-based/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/react-router/basic-react-query-file-based/playwright.config.ts b/e2e/react-router/basic-react-query-file-based/playwright.config.ts index fbda9bd451..f3083ff8b6 100644 --- a/e2e/react-router/basic-react-query-file-based/playwright.config.ts +++ b/e2e/react-router/basic-react-query-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -12,15 +17,17 @@ export default defineConfig({ workers: 1, reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/basic-react-query-file-based/src/posts.tsx b/e2e/react-router/basic-react-query-file-based/src/posts.tsx index 1f6cb8e308..1becc2c242 100644 --- a/e2e/react-router/basic-react-query-file-based/src/posts.tsx +++ b/e2e/react-router/basic-react-query-file-based/src/posts.tsx @@ -8,7 +8,11 @@ export type PostType = { export class PostNotFoundError extends Error {} -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/react-router/basic-react-query-file-based/tests/app.spec.ts b/e2e/react-router/basic-react-query-file-based/tests/app.spec.ts index 2b42d6d589..d80e8dada5 100644 --- a/e2e/react-router/basic-react-query-file-based/tests/app.spec.ts +++ b/e2e/react-router/basic-react-query-file-based/tests/app.spec.ts @@ -1,23 +1,24 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' +import { getDummyServerPort } from '@tanstack/router-e2e-utils' +import packageJson from '../package.json' with { type: 'json' } test.beforeEach(async ({ page }) => { await page.goto('/') }) -test('GetPosts with networking disabled', async ({ page, context }) => { - await page.goto('about:blank') - await context.setOffline(true) - const { status, posts, post } = await page.evaluate(async () => { - const response = await fetch('https://jsonplaceholder.typicode.com/posts') - const posts = await response.json() - const post = await fetch( - 'https://jsonplaceholder.typicode.com/posts/1', - ).then((r) => r.json()) - return { status: response.status, posts, post } - }) - expect(status).toBe(200) +test('GetPosts', async () => { + const port = await getDummyServerPort(packageJson.name) + const res = await fetch(`http://localhost:${port}/posts`) + + expect(res.status).toBe(200) + + const posts = await res.json() + expect(posts.length).toBeGreaterThan(0) + + const postRes = await fetch(`http://localhost:${port}/posts/1`) + expect(postRes.status).toBe(200) + const post = await postRes.json() expect(post).toEqual(posts[0]) }) diff --git a/e2e/react-router/basic-react-query-file-based/tests/setup/global.setup.ts b/e2e/react-router/basic-react-query-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/basic-react-query-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-router/basic-react-query-file-based/tests/setup/global.teardown.ts b/e2e/react-router/basic-react-query-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/basic-react-query-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-router/basic-react-query/package.json b/e2e/react-router/basic-react-query/package.json index 8f28340f56..a0af3b6c21 100644 --- a/e2e/react-router/basic-react-query/package.json +++ b/e2e/react-router/basic-react-query/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/react-router/basic-react-query/playwright.config.ts b/e2e/react-router/basic-react-query/playwright.config.ts index 4eead86444..ab42c7c607 100644 --- a/e2e/react-router/basic-react-query/playwright.config.ts +++ b/e2e/react-router/basic-react-query/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/basic-react-query/src/posts.ts b/e2e/react-router/basic-react-query/src/posts.ts index ffc5a274b7..5e2a2d3aa3 100644 --- a/e2e/react-router/basic-react-query/src/posts.ts +++ b/e2e/react-router/basic-react-query/src/posts.ts @@ -9,7 +9,11 @@ type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} const fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/react-router/basic-react-query/tests/app.spec.ts b/e2e/react-router/basic-react-query/tests/app.spec.ts index fbf093cd51..3e5a69ccaa 100644 --- a/e2e/react-router/basic-react-query/tests/app.spec.ts +++ b/e2e/react-router/basic-react-query/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/basic-react-query/tests/setup/global.setup.ts b/e2e/react-router/basic-react-query/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/basic-react-query/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-router/basic-react-query/tests/setup/global.teardown.ts b/e2e/react-router/basic-react-query/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/basic-react-query/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-router/basic-scroll-restoration/package.json b/e2e/react-router/basic-scroll-restoration/package.json index c13e92cec8..2ddbafc37f 100644 --- a/e2e/react-router/basic-scroll-restoration/package.json +++ b/e2e/react-router/basic-scroll-restoration/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/react-router/basic-scroll-restoration/playwright.config.ts b/e2e/react-router/basic-scroll-restoration/playwright.config.ts index 6a684ac89e..0c5cee43e4 100644 --- a/e2e/react-router/basic-scroll-restoration/playwright.config.ts +++ b/e2e/react-router/basic-scroll-restoration/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/basic-virtual-file-based/package.json b/e2e/react-router/basic-virtual-file-based/package.json index 0343de0846..65122dd2a7 100644 --- a/e2e/react-router/basic-virtual-file-based/package.json +++ b/e2e/react-router/basic-virtual-file-based/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/react-router/basic-virtual-file-based/playwright.config.ts b/e2e/react-router/basic-virtual-file-based/playwright.config.ts index 4eead86444..c5de6b5611 100644 --- a/e2e/react-router/basic-virtual-file-based/playwright.config.ts +++ b/e2e/react-router/basic-virtual-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,10 +22,13 @@ export default defineConfig({ baseURL, }, + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/basic-virtual-file-based/src/posts.tsx b/e2e/react-router/basic-virtual-file-based/src/posts.tsx index cc3cb0f9c8..01831e335c 100644 --- a/e2e/react-router/basic-virtual-file-based/src/posts.tsx +++ b/e2e/react-router/basic-virtual-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/react-router/basic-virtual-file-based/tests/app.spec.ts b/e2e/react-router/basic-virtual-file-based/tests/app.spec.ts index fbf093cd51..3e5a69ccaa 100644 --- a/e2e/react-router/basic-virtual-file-based/tests/app.spec.ts +++ b/e2e/react-router/basic-virtual-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/basic-virtual-file-based/tests/setup/global.setup.ts b/e2e/react-router/basic-virtual-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/basic-virtual-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-router/basic-virtual-file-based/tests/setup/global.teardown.ts b/e2e/react-router/basic-virtual-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/basic-virtual-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-router/basic-virtual-named-export-config-file-based/package.json b/e2e/react-router/basic-virtual-named-export-config-file-based/package.json index 6bdb1248f6..7738971eb6 100644 --- a/e2e/react-router/basic-virtual-named-export-config-file-based/package.json +++ b/e2e/react-router/basic-virtual-named-export-config-file-based/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/react-router/basic-virtual-named-export-config-file-based/playwright.config.ts b/e2e/react-router/basic-virtual-named-export-config-file-based/playwright.config.ts index 4eead86444..ab42c7c607 100644 --- a/e2e/react-router/basic-virtual-named-export-config-file-based/playwright.config.ts +++ b/e2e/react-router/basic-virtual-named-export-config-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/basic-virtual-named-export-config-file-based/src/posts.tsx b/e2e/react-router/basic-virtual-named-export-config-file-based/src/posts.tsx index 97c96d77eb..ae7142c5b6 100644 --- a/e2e/react-router/basic-virtual-named-export-config-file-based/src/posts.tsx +++ b/e2e/react-router/basic-virtual-named-export-config-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/react-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts b/e2e/react-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts index 7d2074182f..0aedada786 100644 --- a/e2e/react-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts +++ b/e2e/react-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts b/e2e/react-router/basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-router/basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts b/e2e/react-router/basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-router/basic/package.json b/e2e/react-router/basic/package.json index 4ff68f5cda..6eba409188 100644 --- a/e2e/react-router/basic/package.json +++ b/e2e/react-router/basic/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -17,8 +17,7 @@ "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "catalog:", - "tailwindcss": "^4.2.2", - "zod": "catalog:" + "tailwindcss": "^4.2.2" }, "devDependencies": { "@playwright/test": "^1.61.0", diff --git a/e2e/react-router/basic/playwright.config.ts b/e2e/react-router/basic/playwright.config.ts index 4eead86444..22c9bdcd7e 100644 --- a/e2e/react-router/basic/playwright.config.ts +++ b/e2e/react-router/basic/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/basic/src/main.tsx b/e2e/react-router/basic/src/main.tsx index 49fa054776..36e5106654 100644 --- a/e2e/react-router/basic/src/main.tsx +++ b/e2e/react-router/basic/src/main.tsx @@ -1,5 +1,3 @@ -import { useState } from 'react' -import { createPortal } from 'react-dom' import ReactDOM from 'react-dom/client' import { ErrorComponent, @@ -11,19 +9,12 @@ import { createRouter, redirect, } from '@tanstack/react-router' -import { - TanStackRouterDevtoolsInProd as TanStackRouterDevtools, - TanStackRouterDevtoolsPanelInProd as TanStackRouterDevtoolsPanel, -} from '@tanstack/react-router-devtools' -import { z } from 'zod' +import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' import { NotFoundError, fetchPost, fetchPosts } from './posts' import './styles.css' import type { ErrorComponentProps } from '@tanstack/react-router' const rootRoute = createRootRoute({ - validateSearch: z.object({ - devtools: z.enum(['panel', 'shadow']).optional().catch(undefined), - }), component: RootComponent, notFoundComponent: () => { return ( @@ -36,8 +27,6 @@ const rootRoute = createRootRoute({ }) function RootComponent() { - const { devtools } = rootRoute.useSearch() - return ( <>
@@ -97,57 +86,12 @@ function RootComponent() {
-
- Devtools: - {(['floating', 'panel', 'shadow'] as const).map((mode) => ( - ({ - ...prev, - devtools: mode === 'floating' ? undefined : mode, - })} - className={ - (devtools ?? 'floating') === mode ? 'font-bold' : undefined - } - > - {mode} - - ))} -
- {devtools === 'panel' ? ( - - ) : devtools === 'shadow' ? ( - - ) : ( - - )} + ) } - -function ShadowDevtoolsPanel() { - const [shadowRoot, setShadowRoot] = useState() - - return ( -
{ - if (host) { - setShadowRoot(host.shadowRoot ?? host.attachShadow({ mode: 'open' })) - } - }} - > - {shadowRoot - ? createPortal( - , - shadowRoot, - ) - : null} -
- ) -} const indexRoute = createRoute({ getParentRoute: () => rootRoute, path: '/', diff --git a/e2e/react-router/basic/src/posts.ts b/e2e/react-router/basic/src/posts.ts index f72d16fee3..e859645746 100644 --- a/e2e/react-router/basic/src/posts.ts +++ b/e2e/react-router/basic/src/posts.ts @@ -8,7 +8,11 @@ type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/react-router/basic/tests/app.spec.ts b/e2e/react-router/basic/tests/app.spec.ts index 9c0a6b6901..ec0e24d8a4 100644 --- a/e2e/react-router/basic/tests/app.spec.ts +++ b/e2e/react-router/basic/tests/app.spec.ts @@ -1,7 +1,8 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from '../package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/basic/tests/devtools.spec.ts b/e2e/react-router/basic/tests/devtools.spec.ts deleted file mode 100644 index b8a7e803e6..0000000000 --- a/e2e/react-router/basic/tests/devtools.spec.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' - -for (const mode of ['panel', 'shadow', 'floating']) { - test(`devtools preserve typography and explorer indentation in ${mode} mode`, async ({ - page, - }) => { - await page.goto(mode === 'floating' ? '/' : `/?devtools=${mode}`) - if (mode === 'floating') { - await page - .getByRole('button', { name: 'Open TanStack Router Devtools' }) - .click() - } - - const panel = page.locator('.TanStackRouterDevtoolsPanel') - const router = panel.getByRole('button', { name: /^Router\s*\d+ items/ }) - const state = panel.getByRole('button', { name: /^state\s*\d+ items/ }) - await expect(router).toBeVisible() - await expect(state).toBeVisible() - await expect(router).toHaveCSS('font-size', '12px') - await expect(router).toHaveCSS('gap', '4px') - await expect( - panel.getByText('Pathname', { exact: true }).locator('..'), - ).toHaveCSS('padding-left', '8px') - - const routerBox = await router.boundingBox() - const stateBox = await state.boundingBox() - expect(stateBox!.x - routerBox!.x).toBe(18) - - if (mode !== 'floating') { - await page.addStyleTag({ content: ':root { font-size: 20px; }' }) - await expect(router).toHaveCSS('font-size', '15px') - await expect(router).toHaveCSS('gap', '5px') - - await page.addStyleTag({ - content: ':root { --tsrd-font-size: 24px; }', - }) - await expect(router).toHaveCSS('font-size', '18px') - await expect(router).toHaveCSS('gap', '6px') - } - }) -} diff --git a/e2e/react-router/basic/tests/params.spec.ts b/e2e/react-router/basic/tests/params.spec.ts index f673138047..ac18f39864 100644 --- a/e2e/react-router/basic/tests/params.spec.ts +++ b/e2e/react-router/basic/tests/params.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.describe('params operations + prefix/suffix', () => { test.beforeEach(async ({ page }) => { diff --git a/e2e/react-router/basic/tests/setup/global.setup.ts b/e2e/react-router/basic/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/basic/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-router/basic/tests/setup/global.teardown.ts b/e2e/react-router/basic/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/basic/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-router/escaped-special-strings/package.json b/e2e/react-router/escaped-special-strings/package.json index af401c49d3..71a3cb08ca 100644 --- a/e2e/react-router/escaped-special-strings/package.json +++ b/e2e/react-router/escaped-special-strings/package.json @@ -9,7 +9,7 @@ "preview": "vite preview", "start": "vite", "test:e2e": "pnpm run test:e2e:default", - "test:e2e:default": "playwright test --project=chromium" + "test:e2e:default": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", diff --git a/e2e/react-router/escaped-special-strings/playwright.config.ts b/e2e/react-router/escaped-special-strings/playwright.config.ts index 629ddefccf..6e4e1d7703 100644 --- a/e2e/react-router/escaped-special-strings/playwright.config.ts +++ b/e2e/react-router/escaped-special-strings/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` const command = `pnpm build && pnpm preview --port ${PORT}` @@ -16,6 +21,9 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, @@ -23,12 +31,15 @@ export default defineConfig({ webServer: { command, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { MODE: process.env.MODE || '', VITE_MODE: process.env.MODE || '', + VITE_NODE_ENV: 'test', + VITE_EXTERNAL_PORT: String(EXTERNAL_PORT), + VITE_SERVER_PORT: String(PORT), PORT: String(PORT), }, }, diff --git a/e2e/react-router/escaped-special-strings/tests/setup/global.setup.ts b/e2e/react-router/escaped-special-strings/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/escaped-special-strings/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-router/escaped-special-strings/tests/setup/global.teardown.ts b/e2e/react-router/escaped-special-strings/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/escaped-special-strings/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-router/generator-cli-only/package.json b/e2e/react-router/generator-cli-only/package.json index 159ba05500..f7ff46d958 100644 --- a/e2e/react-router/generator-cli-only/package.json +++ b/e2e/react-router/generator-cli-only/package.json @@ -8,7 +8,7 @@ "build": "tsr generate && vite build && tsc --noEmit", "preview": "vite preview", "start": "tsr generate && vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/react-router/generator-cli-only/playwright.config.ts b/e2e/react-router/generator-cli-only/playwright.config.ts index 4eead86444..c9d9a76ae7 100644 --- a/e2e/react-router/generator-cli-only/playwright.config.ts +++ b/e2e/react-router/generator-cli-only/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/generator-cli-only/src/posts.ts b/e2e/react-router/generator-cli-only/src/posts.ts index f72d16fee3..e859645746 100644 --- a/e2e/react-router/generator-cli-only/src/posts.ts +++ b/e2e/react-router/generator-cli-only/src/posts.ts @@ -8,7 +8,11 @@ type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/react-router/generator-cli-only/tests/app.spec.ts b/e2e/react-router/generator-cli-only/tests/app.spec.ts index ced5ac9310..5a83a314f2 100644 --- a/e2e/react-router/generator-cli-only/tests/app.spec.ts +++ b/e2e/react-router/generator-cli-only/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/generator-cli-only/tests/setup/global.setup.ts b/e2e/react-router/generator-cli-only/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/generator-cli-only/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-router/generator-cli-only/tests/setup/global.teardown.ts b/e2e/react-router/generator-cli-only/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/generator-cli-only/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-router/i18n-paraglide/package.json b/e2e/react-router/i18n-paraglide/package.json index d1af160f10..a100d58e85 100644 --- a/e2e/react-router/i18n-paraglide/package.json +++ b/e2e/react-router/i18n-paraglide/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -29,23 +29,5 @@ "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" - }, - "nx": { - "targets": { - "build": { - "outputs": [ - "...", - "{projectRoot}/src/paraglide", - "{projectRoot}/project.inlang/cache" - ] - }, - "test:e2e": { - "outputs": [ - "...", - "{projectRoot}/src/paraglide", - "{projectRoot}/project.inlang/cache" - ] - } - } } } diff --git a/e2e/react-router/i18n-paraglide/playwright.config.ts b/e2e/react-router/i18n-paraglide/playwright.config.ts index 8e94d5f9a1..91ef8fbd9f 100644 --- a/e2e/react-router/i18n-paraglide/playwright.config.ts +++ b/e2e/react-router/i18n-paraglide/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/issue-4759/package.json b/e2e/react-router/issue-4759/package.json index ee6a105ad5..91a7a5053e 100644 --- a/e2e/react-router/issue-4759/package.json +++ b/e2e/react-router/issue-4759/package.json @@ -8,7 +8,7 @@ "dev:e2e": "vite", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", diff --git a/e2e/react-router/issue-4759/playwright.config.ts b/e2e/react-router/issue-4759/playwright.config.ts index a301f62881..b5e8249edc 100644 --- a/e2e/react-router/issue-4759/playwright.config.ts +++ b/e2e/react-router/issue-4759/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -11,8 +12,8 @@ export default defineConfig({ use: { baseURL }, webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm dev:e2e --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, projects: [ diff --git a/e2e/react-router/issue-7120/package.json b/e2e/react-router/issue-7120/package.json index 979b32556c..a16155eb61 100644 --- a/e2e/react-router/issue-7120/package.json +++ b/e2e/react-router/issue-7120/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", diff --git a/e2e/react-router/issue-7120/playwright.config.ts b/e2e/react-router/issue-7120/playwright.config.ts index a8ba116fb4..61a995a815 100644 --- a/e2e/react-router/issue-7120/playwright.config.ts +++ b/e2e/react-router/issue-7120/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -11,8 +12,8 @@ export default defineConfig({ use: { baseURL }, webServer: { command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm dev:e2e --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, projects: [ diff --git a/e2e/react-router/issue-7457/package.json b/e2e/react-router/issue-7457/package.json index 838f5173e2..3220a4dbb4 100644 --- a/e2e/react-router/issue-7457/package.json +++ b/e2e/react-router/issue-7457/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-query": "^5.99.0", diff --git a/e2e/react-router/issue-7457/playwright.config.ts b/e2e/react-router/issue-7457/playwright.config.ts index a8ba116fb4..61a995a815 100644 --- a/e2e/react-router/issue-7457/playwright.config.ts +++ b/e2e/react-router/issue-7457/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -11,8 +12,8 @@ export default defineConfig({ use: { baseURL }, webServer: { command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm dev:e2e --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, projects: [ diff --git a/e2e/react-router/js-only-file-based/package.json b/e2e/react-router/js-only-file-based/package.json index 39742d9c84..a8fbe87b8f 100644 --- a/e2e/react-router/js-only-file-based/package.json +++ b/e2e/react-router/js-only-file-based/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/react-router/js-only-file-based/playwright.config.ts b/e2e/react-router/js-only-file-based/playwright.config.ts index 0925936d55..4f93bc1413 100644 --- a/e2e/react-router/js-only-file-based/playwright.config.ts +++ b/e2e/react-router/js-only-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,15 +18,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/js-only-file-based/src/posts.js b/e2e/react-router/js-only-file-based/src/posts.js index 36c1c281f6..979e5e381c 100644 --- a/e2e/react-router/js-only-file-based/src/posts.js +++ b/e2e/react-router/js-only-file-based/src/posts.js @@ -2,7 +2,11 @@ import axios from 'redaxios' export class NotFoundError extends Error {} -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/react-router/js-only-file-based/tests/app.spec.ts b/e2e/react-router/js-only-file-based/tests/app.spec.ts index ced5ac9310..5a83a314f2 100644 --- a/e2e/react-router/js-only-file-based/tests/app.spec.ts +++ b/e2e/react-router/js-only-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/js-only-file-based/tests/setup/global.setup.ts b/e2e/react-router/js-only-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/js-only-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-router/js-only-file-based/tests/setup/global.teardown.ts b/e2e/react-router/js-only-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/js-only-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-router/match-params/package.json b/e2e/react-router/match-params/package.json index 908be67a9d..3282e5e5c2 100644 --- a/e2e/react-router/match-params/package.json +++ b/e2e/react-router/match-params/package.json @@ -6,7 +6,7 @@ "dev": "vite --port 3000", "build": "vite build && tsc --noEmit", "preview": "vite preview", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", diff --git a/e2e/react-router/match-params/playwright.config.ts b/e2e/react-router/match-params/playwright.config.ts index 9e8c1fab2b..246cf40060 100644 --- a/e2e/react-router/match-params/playwright.config.ts +++ b/e2e/react-router/match-params/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -13,8 +14,8 @@ export default defineConfig({ }, webServer: { command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, projects: [ diff --git a/e2e/react-router/react-compiler/package.json b/e2e/react-router/react-compiler/package.json index 82e6fbf86b..d4d0e6473a 100644 --- a/e2e/react-router/react-compiler/package.json +++ b/e2e/react-router/react-compiler/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", diff --git a/e2e/react-router/react-compiler/playwright.config.ts b/e2e/react-router/react-compiler/playwright.config.ts index a8ba116fb4..61a995a815 100644 --- a/e2e/react-router/react-compiler/playwright.config.ts +++ b/e2e/react-router/react-compiler/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -11,8 +12,8 @@ export default defineConfig({ use: { baseURL }, webServer: { command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm dev:e2e --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, projects: [ diff --git a/e2e/react-router/rspack-basic-file-based/package.json b/e2e/react-router/rspack-basic-file-based/package.json index 5ec9ed9862..af7c78ec7b 100644 --- a/e2e/react-router/rspack-basic-file-based/package.json +++ b/e2e/react-router/rspack-basic-file-based/package.json @@ -7,7 +7,7 @@ "build": "rsbuild build && tsc --noEmit", "preview": "rsbuild preview", "start": "rsbuild preview", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -18,7 +18,7 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-react": "^2.0.0", "@tailwindcss/postcss": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", diff --git a/e2e/react-router/rspack-basic-file-based/playwright.config.ts b/e2e/react-router/rspack-basic-file-based/playwright.config.ts index 4eead86444..decceaef2f 100644 --- a/e2e/react-router/rspack-basic-file-based/playwright.config.ts +++ b/e2e/react-router/rspack-basic-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `PUBLIC_NODE_ENV="test" PUBLIC_EXTERNAL_PORT=${EXTERNAL_PORT} PUBLIC_SERVER_PORT=${PORT} pnpm build && PUBLIC_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/rspack-basic-file-based/src/posts.tsx b/e2e/react-router/rspack-basic-file-based/src/posts.tsx index 97c96d77eb..a1225b7fe7 100644 --- a/e2e/react-router/rspack-basic-file-based/src/posts.tsx +++ b/e2e/react-router/rspack-basic-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.PUBLIC_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.PUBLIC_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/react-router/rspack-basic-file-based/tests/app.spec.ts b/e2e/react-router/rspack-basic-file-based/tests/app.spec.ts index d230263bfe..10beff655f 100644 --- a/e2e/react-router/rspack-basic-file-based/tests/app.spec.ts +++ b/e2e/react-router/rspack-basic-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/rspack-basic-file-based/tests/setup/global.setup.ts b/e2e/react-router/rspack-basic-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/rspack-basic-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-router/rspack-basic-file-based/tests/setup/global.teardown.ts b/e2e/react-router/rspack-basic-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/rspack-basic-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/package.json b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/package.json index 30c62d0af1..07daac365c 100644 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/package.json +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/package.json @@ -7,7 +7,7 @@ "build": "rsbuild build && tsc --noEmit", "preview": "rsbuild preview", "start": "rsbuild preview", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -18,7 +18,7 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-react": "^2.0.0", "@tailwindcss/postcss": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts index 1c1d021f2f..bf3adc082c 100644 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm start --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `PUBLIC_NODE_ENV="test" PUBLIC_EXTERNAL_PORT=${EXTERNAL_PORT} PUBLIC_SERVER_PORT=${PORT} pnpm build && PUBLIC_SERVER_PORT=${PORT} pnpm start --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx index cc3cb0f9c8..b196982420 100644 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.PUBLIC_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.PUBLIC_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts index 8b808782f6..a689f459e3 100644 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/package.json b/e2e/react-router/scroll-restoration-sandbox-vite/package.json index 51e9e70cc5..a4ad2e8121 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/package.json +++ b/e2e/react-router/scroll-restoration-sandbox-vite/package.json @@ -11,7 +11,7 @@ "start": "vite", "test:e2e:browser": "VITE_APP_HISTORY=browser playwright test --config=playwright.browser.config.ts --project=chromium", "test:e2e:hash": "VITE_APP_HISTORY=hash playwright test --config=playwright.hash.config.ts --project=chromium", - "test:e2e": "pnpm run test:e2e:browser && pnpm run test:e2e:hash" + "test:e2e": "rm -rf port*.txt; pnpm run test:e2e:browser && pnpm run test:e2e:hash" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -31,15 +31,5 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "vite": "^8.0.14" - }, - "nx": { - "targets": { - "test:e2e": { - "outputs": [ - "...", - "{projectRoot}/dist-hash" - ] - } - } } } diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts b/e2e/react-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts index eb31d94080..972124647c 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts +++ b/e2e/react-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts @@ -1,7 +1,15 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, + resolveRuntimeSuffix, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort( + packageJson.name + `-${resolveRuntimeSuffix('browser')}`, +) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,15 +21,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_APP_HISTORY=browser pnpm build && VITE_APP_HISTORY=browser pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=browser pnpm build && VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=browser pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts b/e2e/react-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts index 6b160e3908..a6fa77afbf 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts +++ b/e2e/react-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts @@ -1,7 +1,15 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, + resolveRuntimeSuffix, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort( + packageJson.name + `-${resolveRuntimeSuffix('hash')}`, +) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,15 +21,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_APP_HISTORY=hash vite build --outDir dist-hash && VITE_APP_HISTORY=hash pnpm preview --port ${PORT} --outDir dist-hash`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=hash vite build --outDir dist-hash && VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=hash pnpm preview --port ${PORT} --outDir dist-hash`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/src/posts.tsx b/e2e/react-router/scroll-restoration-sandbox-vite/src/posts.tsx index c4a2d0dcca..e45ef52969 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/src/posts.tsx +++ b/e2e/react-router/scroll-restoration-sandbox-vite/src/posts.tsx @@ -10,7 +10,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export class PostNotFoundError extends Error {} diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/tests/app.spec.ts b/e2e/react-router/scroll-restoration-sandbox-vite/tests/app.spec.ts index e396c28686..9c2d944dd5 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/tests/app.spec.ts +++ b/e2e/react-router/scroll-restoration-sandbox-vite/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import { linkOptions } from '@tanstack/react-router' import { toRuntimePath } from '@tanstack/router-e2e-utils' diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/tests/issue-7040.repro.spec.ts b/e2e/react-router/scroll-restoration-sandbox-vite/tests/issue-7040.repro.spec.ts index 2db25517c8..db335f8e2e 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/tests/issue-7040.repro.spec.ts +++ b/e2e/react-router/scroll-restoration-sandbox-vite/tests/issue-7040.repro.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import type { Page } from '@playwright/test' import { toRuntimePath } from '@tanstack/router-e2e-utils' @@ -27,7 +26,7 @@ type ReproAttempt = { async function openFreshSourcePage(page: Page) { await page.goto(toRuntimePath('/issue-7040-source')) - await expect(page.getByTestId('issue-7040-source-top')).toBeVisible() + await page.waitForLoadState('networkidle') await page.evaluate(() => { sessionStorage.clear() @@ -35,7 +34,7 @@ async function openFreshSourcePage(page: Page) { }) await page.reload() - await expect(page.getByTestId('issue-7040-source-top')).toBeVisible() + await page.waitForLoadState('networkidle') } async function fastScrollSourcePage(page: Page) { @@ -97,7 +96,7 @@ async function clickTargetLinkImmediatelyAfterScroll(page: Page) { async function waitForTargetPageToSettle(page: Page) { await page.waitForURL('**/issue-7040-target') - await expect(page.getByTestId('issue-7040-target-top')).toBeVisible() + await page.waitForLoadState('networkidle') await page.waitForFunction(() => window.scrollY === 0) } diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts b/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts b/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/tsconfig.json b/e2e/react-router/scroll-restoration-sandbox-vite/tsconfig.json index 5d58406b2e..f33b5a7aa3 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/tsconfig.json +++ b/e2e/react-router/scroll-restoration-sandbox-vite/tsconfig.json @@ -11,5 +11,5 @@ "allowJs": true, "types": ["vite/client", "node"] }, - "exclude": ["node_modules", "dist", "dist-hash"] + "exclude": ["node_modules", "dist"] } diff --git a/e2e/react-router/sentry-integration/package.json b/e2e/react-router/sentry-integration/package.json index 5ebbdf31d9..b136e4f9a4 100644 --- a/e2e/react-router/sentry-integration/package.json +++ b/e2e/react-router/sentry-integration/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@sentry/react": "^10.32.0", diff --git a/e2e/react-router/sentry-integration/playwright.config.ts b/e2e/react-router/sentry-integration/playwright.config.ts index 6a684ac89e..0c5cee43e4 100644 --- a/e2e/react-router/sentry-integration/playwright.config.ts +++ b/e2e/react-router/sentry-integration/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/view-transitions/package.json b/e2e/react-router/view-transitions/package.json index e2d7a181e1..03ed5c3be9 100644 --- a/e2e/react-router/view-transitions/package.json +++ b/e2e/react-router/view-transitions/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/react-router/view-transitions/playwright.config.ts b/e2e/react-router/view-transitions/playwright.config.ts index 4eead86444..c5de6b5611 100644 --- a/e2e/react-router/view-transitions/playwright.config.ts +++ b/e2e/react-router/view-transitions/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,10 +22,13 @@ export default defineConfig({ baseURL, }, + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/view-transitions/tests/app.spec.ts b/e2e/react-router/view-transitions/tests/app.spec.ts index 6c1ccf1a6e..472bd6ed0b 100644 --- a/e2e/react-router/view-transitions/tests/app.spec.ts +++ b/e2e/react-router/view-transitions/tests/app.spec.ts @@ -1,4 +1,4 @@ -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/view-transitions/tests/setup/global.setup.ts b/e2e/react-router/view-transitions/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/view-transitions/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-router/view-transitions/tests/setup/global.teardown.ts b/e2e/react-router/view-transitions/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/view-transitions/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-start/basic-auth/package.json b/e2e/react-start/basic-auth/package.json index f7ff609e76..b434d3f305 100644 --- a/e2e/react-start/basic-auth/package.json +++ b/e2e/react-start/basic-auth/package.json @@ -10,7 +10,7 @@ "preview": "vite preview", "start": "node .output/server/index.mjs", "prisma-generate": "prisma generate", - "test:e2e": "exit 0; pnpm run prisma-generate && playwright test --project=chromium" + "test:e2e": "exit 0; rm -rf port*.txt; pnpm run prisma-generate && playwright test --project=chromium" }, "dependencies": { "@libsql/client": "^0.15.15", @@ -19,7 +19,6 @@ "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", "@tanstack/react-start": "workspace:^", - "iron-session": "^9.0.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "catalog:", diff --git a/e2e/react-start/basic-auth/playwright.config.ts b/e2e/react-start/basic-auth/playwright.config.ts index 82678ac00b..18b8905468 100644 --- a/e2e/react-start/basic-auth/playwright.config.ts +++ b/e2e/react-start/basic-auth/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/basic-auth/src/routes/__root.tsx b/e2e/react-start/basic-auth/src/routes/__root.tsx index fb7868435d..76e5f8b1d6 100644 --- a/e2e/react-start/basic-auth/src/routes/__root.tsx +++ b/e2e/react-start/basic-auth/src/routes/__root.tsx @@ -14,18 +14,18 @@ import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary.js' import { NotFound } from '~/components/NotFound.js' import appCss from '~/styles/app.css?url' import { seo } from '~/utils/seo.js' -import { getAppSession } from '~/utils/session.js' +import { useAppSession } from '~/utils/session.js' const fetchUser = createServerFn({ method: 'GET' }).handler(async () => { // We need to auth on the server so we have access to secure cookies - const session = await getAppSession() + const session = await useAppSession() - if (!session.userEmail) { + if (!session.data.userEmail) { return null } return { - email: session.userEmail, + email: session.data.userEmail, } }) diff --git a/e2e/react-start/basic-auth/src/routes/_authed.tsx b/e2e/react-start/basic-auth/src/routes/_authed.tsx index fe73185136..0d87cfbacb 100644 --- a/e2e/react-start/basic-auth/src/routes/_authed.tsx +++ b/e2e/react-start/basic-auth/src/routes/_authed.tsx @@ -3,7 +3,7 @@ import { createServerFn } from '@tanstack/react-start' import { hashPassword, prismaClient } from '~/utils/prisma' import { Login } from '~/components/Login' -import { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' export const loginFn = createServerFn({ method: 'POST', @@ -37,11 +37,12 @@ export const loginFn = createServerFn({ } // Create a session - const session = await getAppSession() + const session = await useAppSession() // Store the user's email in the session - session.userEmail = user.email - await session.save() + await session.update({ + userEmail: user.email, + }) }) export const Route = createFileRoute('/_authed')({ diff --git a/e2e/react-start/basic-auth/src/routes/logout.tsx b/e2e/react-start/basic-auth/src/routes/logout.tsx index 0f86b0d4e3..a08f9c737e 100644 --- a/e2e/react-start/basic-auth/src/routes/logout.tsx +++ b/e2e/react-start/basic-auth/src/routes/logout.tsx @@ -1,12 +1,12 @@ import { redirect, createFileRoute } from '@tanstack/react-router' import { createServerFn } from '@tanstack/react-start' -import { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await getAppSession() + const session = await useAppSession() - session.destroy() + session.clear() throw redirect({ href: '/', diff --git a/e2e/react-start/basic-auth/src/routes/signup.tsx b/e2e/react-start/basic-auth/src/routes/signup.tsx index d7d5d40129..817362dc05 100644 --- a/e2e/react-start/basic-auth/src/routes/signup.tsx +++ b/e2e/react-start/basic-auth/src/routes/signup.tsx @@ -4,7 +4,7 @@ import { createServerFn, useServerFn } from '@tanstack/react-start' import { hashPassword, prismaClient } from '~/utils/prisma' import { useMutation } from '~/hooks/useMutation' import { Auth } from '~/components/Auth' -import { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' export const signupFn = createServerFn({ method: 'POST', @@ -24,7 +24,7 @@ export const signupFn = createServerFn({ const password = await hashPassword(payload.password) // Create a session - const session = await getAppSession() + const session = await useAppSession() if (found) { if (found.password !== password) { @@ -36,8 +36,9 @@ export const signupFn = createServerFn({ } // Store the user's email in the session - session.userEmail = found.email - await session.save() + await session.update({ + userEmail: found.email, + }) // Redirect to the prev page stored in the "redirect" search param throw redirect({ @@ -54,8 +55,9 @@ export const signupFn = createServerFn({ }) // Store the user's email in the session - session.userEmail = user.email - await session.save() + await session.update({ + userEmail: user.email, + }) // Redirect to the prev page stored in the "redirect" search param throw redirect({ diff --git a/e2e/react-start/basic-auth/src/utils/session.ts b/e2e/react-start/basic-auth/src/utils/session.ts index f1deacf85b..c38bac1e48 100644 --- a/e2e/react-start/basic-auth/src/utils/session.ts +++ b/e2e/react-start/basic-auth/src/utils/session.ts @@ -1,25 +1,13 @@ -import { getIronSession } from 'iron-session' -import { getCookie, setCookie } from '@tanstack/react-start/server' +// src/services/session.server.ts +import { useSession } from '@tanstack/react-start/server' import type { User } from '@prisma/client' type SessionUser = { userEmail: User['email'] } -export function getAppSession() { - return getIronSession( - { read: getCookie, write: setCookie }, - { - cookieName: 'test-auth-session', - // This fixture only runs locally with test credentials. - password: 'local-e2e-only-session-password-at-least-32-characters', - ttl: 60 * 60, - cookieOptions: { - httpOnly: true, - secure: false, - sameSite: 'lax', - path: '/', - }, - }, - ) +export function useAppSession() { + return useSession({ + password: 'ChangeThisBeforeShippingToProdOrYouWillBeFired', + }) } diff --git a/e2e/react-start/basic-cloudflare/package.json b/e2e/react-start/basic-cloudflare/package.json index b9b8031ac4..7baa24073b 100644 --- a/e2e/react-start/basic-cloudflare/package.json +++ b/e2e/react-start/basic-cloudflare/package.json @@ -10,7 +10,7 @@ "preview": "vite preview", "cf-typegen": "wrangler types", "postinstall": "WRANGLER_LOG=warn npm run --silent cf-typegen", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -33,15 +33,5 @@ "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "wrangler": "^4.74.0" - }, - "nx": { - "targets": { - "test:e2e": { - "outputs": [ - "...", - "{projectRoot}/.wrangler/deploy" - ] - } - } } } diff --git a/e2e/react-start/basic-cloudflare/playwright.config.ts b/e2e/react-start/basic-cloudflare/playwright.config.ts index 0925936d55..a545dff891 100644 --- a/e2e/react-start/basic-cloudflare/playwright.config.ts +++ b/e2e/react-start/basic-cloudflare/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,6 +14,9 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, @@ -20,8 +24,8 @@ export default defineConfig({ webServer: { command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/basic-cloudflare/tests/app.spec.ts b/e2e/react-start/basic-cloudflare/tests/app.spec.ts index c9497070dd..add28cb73e 100644 --- a/e2e/react-start/basic-cloudflare/tests/app.spec.ts +++ b/e2e/react-start/basic-cloudflare/tests/app.spec.ts @@ -1,5 +1,3 @@ -import { execFileSync } from 'node:child_process' -import { fileURLToPath } from 'node:url' import { existsSync } from 'node:fs' import { join } from 'node:path' import { expect } from '@playwright/test' @@ -31,19 +29,3 @@ test('prerender with Cloudflare Workers runtime', async ({ page }) => { 'The value is Hello from Cloudflare', ) }) - -test('the built Cloudflare app passes a deployment dry run', () => { - const wrangler = fileURLToPath( - new URL('../node_modules/wrangler/bin/wrangler.js', import.meta.url), - ) - const output = execFileSync( - process.execPath, - [wrangler, 'deploy', '--dry-run'], - { - encoding: 'utf8', - env: { ...process.env, WRANGLER_SEND_METRICS: 'false' }, - }, - ) - expect(output).toContain('dist/server/wrangler.json') - expect(output).toContain('--dry-run: exiting now.') -}) diff --git a/e2e/react-start/basic-cloudflare/tests/setup/global.setup.ts b/e2e/react-start/basic-cloudflare/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-start/basic-cloudflare/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-start/basic-cloudflare/tests/setup/global.teardown.ts b/e2e/react-start/basic-cloudflare/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-start/basic-cloudflare/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-start/basic-react-query/package.json b/e2e/react-start/basic-react-query/package.json index ee37b82ba6..87789282ec 100644 --- a/e2e/react-start/basic-react-query/package.json +++ b/e2e/react-start/basic-react-query/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-query": "^5.90.0", @@ -32,7 +32,7 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/react-start/basic-react-query/playwright.config.ts b/e2e/react-start/basic-react-query/playwright.config.ts index 216fade4d5..fd2150e435 100644 --- a/e2e/react-start/basic-react-query/playwright.config.ts +++ b/e2e/react-start/basic-react-query/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,19 +18,19 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', - env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, - }, }, projects: [ diff --git a/e2e/react-start/basic-react-query/src/routes/api.users.ts b/e2e/react-start/basic-react-query/src/routes/api.users.ts index 924c5b6860..bb37c6e68d 100644 --- a/e2e/react-start/basic-react-query/src/routes/api.users.ts +++ b/e2e/react-start/basic-react-query/src/routes/api.users.ts @@ -2,7 +2,11 @@ import { createFileRoute } from '@tanstack/react-router' import axios from 'redaxios' import type { User } from '../utils/users' -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const Route = createFileRoute('/api/users')({ server: { diff --git a/e2e/react-start/basic-react-query/src/routes/api/users.$id.ts b/e2e/react-start/basic-react-query/src/routes/api/users.$id.ts index febea309ea..e11e039652 100644 --- a/e2e/react-start/basic-react-query/src/routes/api/users.$id.ts +++ b/e2e/react-start/basic-react-query/src/routes/api/users.$id.ts @@ -2,7 +2,11 @@ import { createFileRoute } from '@tanstack/react-router' import axios from 'redaxios' import type { User } from '../../utils/users' -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const Route = createFileRoute('/api/users/$id')({ server: { diff --git a/e2e/react-start/basic-react-query/src/utils/posts.tsx b/e2e/react-start/basic-react-query/src/utils/posts.tsx index abb6e95b92..3fd16db69a 100644 --- a/e2e/react-start/basic-react-query/src/utils/posts.tsx +++ b/e2e/react-start/basic-react-query/src/utils/posts.tsx @@ -9,7 +9,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPosts = createServerFn({ method: 'GET' }).handler( async () => { diff --git a/e2e/react-start/basic-react-query/src/utils/users.tsx b/e2e/react-start/basic-react-query/src/utils/users.tsx index 15216680e9..26b934fcb3 100644 --- a/e2e/react-start/basic-react-query/src/utils/users.tsx +++ b/e2e/react-start/basic-react-query/src/utils/users.tsx @@ -1,6 +1,4 @@ import { queryOptions } from '@tanstack/react-query' -import { createIsomorphicFn } from '@tanstack/react-start' -import { getRequestUrl } from '@tanstack/react-start/server' import axios from 'redaxios' export type User = { @@ -9,16 +7,17 @@ export type User = { email: string } -const getOrigin = createIsomorphicFn() - .server(() => getRequestUrl().origin) - .client(() => window.location.origin) +const PORT = + import.meta.env.VITE_SERVER_PORT || process.env.VITE_SERVER_PORT || 3000 + +export const DEPLOY_URL = `http://localhost:${PORT}` export const usersQueryOptions = () => queryOptions({ queryKey: ['users'], queryFn: () => axios - .get>(getOrigin() + '/api/users') + .get>(DEPLOY_URL + '/api/users') .then((r) => r.data) .catch(() => { throw new Error('Failed to fetch users') @@ -30,7 +29,7 @@ export const userQueryOptions = (id: string) => queryKey: ['users', id], queryFn: () => axios - .get(getOrigin() + '/api/users/' + id) + .get(DEPLOY_URL + '/api/users/' + id) .then((r) => r.data) .catch(() => { throw new Error('Failed to fetch user') diff --git a/e2e/react-start/basic-react-query/tests/setup/global.setup.ts b/e2e/react-start/basic-react-query/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-start/basic-react-query/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-start/basic-react-query/tests/setup/global.teardown.ts b/e2e/react-start/basic-react-query/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-start/basic-react-query/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-start/basic-tsr-config/package.json b/e2e/react-start/basic-tsr-config/package.json index 99e681ac9d..6aaacfefd4 100644 --- a/e2e/react-start/basic-tsr-config/package.json +++ b/e2e/react-start/basic-tsr-config/package.json @@ -8,7 +8,7 @@ "dev:e2e": "vite dev", "build": "rimraf ./count.txt && vite build && tsc --noEmit", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -21,7 +21,7 @@ "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", diff --git a/e2e/react-start/basic-tsr-config/playwright.config.ts b/e2e/react-start/basic-tsr-config/playwright.config.ts index 82678ac00b..18b8905468 100644 --- a/e2e/react-start/basic-tsr-config/playwright.config.ts +++ b/e2e/react-start/basic-tsr-config/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/basic/package.json b/e2e/react-start/basic/package.json index 3a1a4ea9c8..f0a15aa274 100644 --- a/e2e/react-start/basic/package.json +++ b/e2e/react-start/basic/package.json @@ -14,6 +14,8 @@ "preview": "vite preview", "preview:rsbuild": "rsbuild preview", "start": "node server.js", + "test:e2e:startDummyServer": "node -e 'import(\"./tests/setup/global.setup.ts\").then(m => m.default())' & node -e 'import(\"./tests/setup/waitForDummyServer.ts\").then(m => m.default())'", + "test:e2e:stopDummyServer": "node -e 'import(\"./tests/setup/global.teardown.ts\").then(m => m.default())'", "test:e2e:local": "playwright test --project=chromium" }, "dependencies": { @@ -22,7 +24,6 @@ "@tanstack/react-start": "workspace:^", "express": "^5.2.1", "http-proxy-middleware": "^3.0.5", - "iron-session": "^9.0.1", "js-cookie": "^3.0.5", "react": "^19.0.0", "react-dom": "^19.0.0", @@ -31,7 +32,7 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-react": "^2.0.0", "@tailwindcss/postcss": "^4.2.2", "@tailwindcss/vite": "^4.2.2", @@ -42,7 +43,7 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "combinate": "^1.1.11", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", @@ -50,18 +51,6 @@ "zod": "^4.4.3" }, "nx": { - "targets": { - "test:e2e--vite-spa--dev": { - "dependsOn": [ - "^build" - ] - }, - "test:e2e--rsbuild-spa--dev": { - "dependsOn": [ - "^build" - ] - } - }, "metadata": { "playwrightModes": [ { @@ -74,18 +63,7 @@ }, { "toolchain": "vite", - "mode": "spa", - "name": "dev", - "env": { - "E2E_DEV_SERVER": "true" - } - }, - { - "toolchain": "vite", - "mode": "prerender", - "env": { - "NODE_OPTIONS": "--import=@tanstack/router-e2e-utils/mock-api" - } + "mode": "prerender" }, { "toolchain": "vite", @@ -109,18 +87,7 @@ }, { "toolchain": "rsbuild", - "mode": "spa", - "name": "dev", - "env": { - "E2E_DEV_SERVER": "true" - } - }, - { - "toolchain": "rsbuild", - "mode": "prerender", - "env": { - "NODE_OPTIONS": "--import=@tanstack/router-e2e-utils/mock-api" - } + "mode": "prerender" }, { "toolchain": "rsbuild", diff --git a/e2e/react-start/basic/playwright.config.ts b/e2e/react-start/basic/playwright.config.ts index bb4c2cb761..db07d18608 100644 --- a/e2e/react-start/basic/playwright.config.ts +++ b/e2e/react-start/basic/playwright.config.ts @@ -1,42 +1,48 @@ +import fs from 'node:fs' import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } const mode = process.env.MODE ?? 'ssr' const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' - +const e2ePortKey = process.env.E2E_PORT_KEY ?? packageJson.name const distDir = process.env.E2E_DIST_DIR ?? 'dist' -// The dev runs start the dev server and run only the SPA shell spec -const devServer = process.env.E2E_DEV_SERVER === 'true' -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +if (process.env.TEST_WORKER_INDEX === undefined) { + for (const portFile of [ + `port-${e2ePortKey}.txt`, + `port-${e2ePortKey}_start.txt`, + `port-${e2ePortKey}-external.txt`, + ]) { + fs.rmSync(portFile, { force: true }) + } +} + +const PORT = await getTestServerPort(e2ePortKey) +const START_PORT = await getTestServerPort(`${e2ePortKey}_start`) +const EXTERNAL_PORT = await getDummyServerPort(e2ePortKey) const baseURL = `http://localhost:${PORT}` const previewCommand = toolchain === 'rsbuild' - ? `pnpm preview:rsbuild --host 0.0.0.0 --port ${PORT}` - : `pnpm preview --host 0.0.0.0 --outDir ${distDir} --port ${PORT}` -const devCommand = - toolchain === 'rsbuild' - ? `pnpm dev:rsbuild --port ${PORT}` - : `pnpm dev:vite --port ${PORT}` -const commandByMode = devServer - ? devCommand - : mode === 'preview' - ? previewCommand - : 'pnpm start' + ? `pnpm preview:rsbuild --port ${PORT}` + : `pnpm preview --outDir ${distDir} --port ${PORT}` +const commandByMode = + mode === 'preview' + ? `pnpm run test:e2e:startDummyServer && ${previewCommand}` + : `pnpm run test:e2e:startDummyServer && pnpm start` /** * See https://playwright.dev/docs/test-configuration. */ export default defineConfig({ testDir: './tests', - ...(devServer - ? { - testMatch: 'spa-shell.spec.ts', - globalSetup: './tests/setup/dev-server.setup.ts', - } - : {}), workers: 1, reporter: [['line']], + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, @@ -44,16 +50,19 @@ export default defineConfig({ webServer: { command: commandByMode, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, MODE: mode, E2E_TOOLCHAIN: toolchain, - START_PORT: '0', + VITE_NODE_ENV: 'test', + VITE_EXTERNAL_PORT: String(EXTERNAL_PORT), + VITE_SERVER_PORT: String(PORT), + START_PORT: String(START_PORT), PORT: String(PORT), E2E_DIST_DIR: distDir, + E2E_PORT_KEY: e2ePortKey, ...(process.env.TSS_RSB_CLIENT_OUTPUT ? { TSS_RSB_CLIENT_OUTPUT: process.env.TSS_RSB_CLIENT_OUTPUT } : {}), diff --git a/e2e/react-start/basic/server.js b/e2e/react-start/basic/server.js index 3e1ddab400..69c1e4ca91 100644 --- a/e2e/react-start/basic/server.js +++ b/e2e/react-start/basic/server.js @@ -1,12 +1,12 @@ +import { toNodeHandler } from 'srvx/node' import fs from 'node:fs' import path from 'node:path' -import { toNodeHandler } from 'srvx/node' import express from 'express' import { createProxyMiddleware } from 'http-proxy-middleware' -const port = Number(process.env.PORT ?? 3000) +const port = process.env.PORT || 3000 -const startPort = Number(process.env.START_PORT ?? 0) +const startPort = process.env.START_PORT || 3001 const isSpaMode = process.env.MODE === 'spa' const isPrerender = process.env.MODE === 'prerender' @@ -49,13 +49,13 @@ export async function createStartServer() { return { app } } -export async function createSpaServer(backendPort) { +export async function createSpaServer() { const app = express() app.use( '/api', createProxyMiddleware({ - target: `http://localhost:${backendPort}/api`, // Replace with your target server's URL + target: `http://localhost:${startPort}/api`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) @@ -63,7 +63,7 @@ export async function createSpaServer(backendPort) { app.use( '/_serverFn', createProxyMiddleware({ - target: `http://localhost:${backendPort}/_serverFn`, // Replace with your target server's URL + target: `http://localhost:${startPort}/_serverFn`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) @@ -71,28 +71,31 @@ export async function createSpaServer(backendPort) { app.use(express.static(distClientDir)) app.get('/{*splat}', (req, res) => { - res.sendFile('index.html', { root: distClientDir }) + res.sendFile(path.resolve(distClientDir, 'index.html')) }) return { app } } -// Bind the backend first so the SPA proxy receives the port actually held by it. -const { app: startApp } = await createStartServer() -const backend = startApp.listen(isSpaMode ? startPort : port, async (error) => { - if (error) { - throw error - } - const backendPort = backend.address().port - if (isSpaMode) { - const { app } = await createSpaServer(backendPort) - const frontend = app.listen(port, (frontendError) => { - if (frontendError) { - throw frontendError - } - console.info(`E2E app: http://localhost:${frontend.address().port}`) - }) - } else { - console.info(`E2E app: http://localhost:${backendPort}`) - } -}) +if (isSpaMode) { + createSpaServer().then(async ({ app }) => + app.listen(port, (error) => { + if (error) throw error + console.info(`Client Server: http://localhost:${port}`) + }), + ) + + createStartServer().then(async ({ app }) => + app.listen(startPort, (error) => { + if (error) throw error + console.info(`Start Server: http://localhost:${startPort}`) + }), + ) +} else { + createStartServer().then(async ({ app }) => + app.listen(port, (error) => { + if (error) throw error + console.info(`Start Server: http://localhost:${port}`) + }), + ) +} diff --git a/e2e/react-start/basic/src/routeTree.gen.ts b/e2e/react-start/basic/src/routeTree.gen.ts index b6603dd01d..ea09864d8e 100644 --- a/e2e/react-start/basic/src/routeTree.gen.ts +++ b/e2e/react-start/basic/src/routeTree.gen.ts @@ -12,11 +12,8 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' import { Route as LayoutRouteImport } from './routes/_layout' import { Route as AsyncScriptsRouteImport } from './routes/async-scripts' -import { Route as AuthDocsRouteImport } from './routes/auth-docs' import { Route as ClientOnlyRouteImport } from './routes/client-only' import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as ExecutionLocalRouteImport } from './routes/execution-local' -import { Route as ExecutionRpcRouteImport } from './routes/execution-rpc' import { Route as InlineScriptsRouteImport } from './routes/inline-scripts' import { Route as LinksRouteImport } from './routes/links' import { Route as NotFoundRouteRouteImport } from './routes/not-found/route' @@ -32,7 +29,6 @@ import { Route as TypeOnlyReexportRouteImport } from './routes/type-only-reexpor import { Route as UsersRouteImport } from './routes/users' import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' import { Route as ApiUsersRouteImport } from './routes/api.users' -import { Route as AuthDocsPrivateRouteImport } from './routes/auth-docs.private' import { Route as Issue6221DashboardRouteImport } from './routes/issue-6221.dashboard' import { Route as MultiCookieRedirectIndexRouteImport } from './routes/multi-cookie-redirect/index' import { Route as MultiCookieRedirectTargetRouteImport } from './routes/multi-cookie-redirect/target' @@ -100,11 +96,6 @@ const AsyncScriptsRoute = AsyncScriptsRouteImport.update({ path: '/async-scripts', getParentRoute: () => rootRouteImport, } as any) -const AuthDocsRoute = AuthDocsRouteImport.update({ - id: '/auth-docs', - path: '/auth-docs', - getParentRoute: () => rootRouteImport, -} as any) const ClientOnlyRoute = ClientOnlyRouteImport.update({ id: '/client-only', path: '/client-only', @@ -115,16 +106,6 @@ const DeferredRoute = DeferredRouteImport.update({ path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const ExecutionLocalRoute = ExecutionLocalRouteImport.update({ - id: '/execution-local', - path: '/execution-local', - getParentRoute: () => rootRouteImport, -} as any) -const ExecutionRpcRoute = ExecutionRpcRouteImport.update({ - id: '/execution-rpc', - path: '/execution-rpc', - getParentRoute: () => rootRouteImport, -} as any) const InlineScriptsRoute = InlineScriptsRouteImport.update({ id: '/inline-scripts', path: '/inline-scripts', @@ -200,11 +181,6 @@ const ApiUsersRoute = ApiUsersRouteImport.update({ path: '/api/users', getParentRoute: () => rootRouteImport, } as any) -const AuthDocsPrivateRoute = AuthDocsPrivateRouteImport.update({ - id: '/private', - path: '/private', - getParentRoute: () => AuthDocsRoute, -} as any) const Issue6221DashboardRoute = Issue6221DashboardRouteImport.update({ id: '/issue-6221/dashboard', path: '/issue-6221/dashboard', @@ -488,11 +464,8 @@ export interface FileRoutesByFullPath { '/search-params': typeof SearchParamsRouteRouteWithChildren '/specialChars': typeof SpecialCharsRouteRouteWithChildren '/async-scripts': typeof AsyncScriptsRoute - '/auth-docs': typeof AuthDocsRouteWithChildren '/client-only': typeof ClientOnlyRoute '/deferred': typeof DeferredRoute - '/execution-local': typeof ExecutionLocalRoute - '/execution-rpc': typeof ExecutionRpcRoute '/inline-scripts': typeof InlineScriptsRoute '/links': typeof LinksRoute '/plain-ts-type-assertion': typeof PlainTsTypeAssertionRoute @@ -507,7 +480,6 @@ export interface FileRoutesByFullPath { '/not-found/parent-boundary': typeof NotFoundParentBoundaryRouteRouteWithChildren '/specialChars/malformed': typeof SpecialCharsMalformedRouteRouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren - '/auth-docs/private': typeof AuthDocsPrivateRoute '/issue-6221/dashboard': typeof Issue6221DashboardRoute '/multi-cookie-redirect/target': typeof MultiCookieRedirectTargetRoute '/not-found/via-beforeLoad': typeof NotFoundViaBeforeLoadRoute @@ -562,11 +534,8 @@ export interface FileRoutesByTo { '/': typeof IndexRoute '/specialChars': typeof SpecialCharsRouteRouteWithChildren '/async-scripts': typeof AsyncScriptsRoute - '/auth-docs': typeof AuthDocsRouteWithChildren '/client-only': typeof ClientOnlyRoute '/deferred': typeof DeferredRoute - '/execution-local': typeof ExecutionLocalRoute - '/execution-rpc': typeof ExecutionRpcRoute '/inline-scripts': typeof InlineScriptsRoute '/links': typeof LinksRoute '/plain-ts-type-assertion': typeof PlainTsTypeAssertionRoute @@ -576,7 +545,6 @@ export interface FileRoutesByTo { '/type-only-reexport': typeof TypeOnlyReexportRoute '/specialChars/malformed': typeof SpecialCharsMalformedRouteRouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren - '/auth-docs/private': typeof AuthDocsPrivateRoute '/issue-6221/dashboard': typeof Issue6221DashboardRoute '/multi-cookie-redirect/target': typeof MultiCookieRedirectTargetRoute '/not-found/via-beforeLoad': typeof NotFoundViaBeforeLoadRoute @@ -633,11 +601,8 @@ export interface FileRoutesById { '/specialChars': typeof SpecialCharsRouteRouteWithChildren '/_layout': typeof LayoutRouteWithChildren '/async-scripts': typeof AsyncScriptsRoute - '/auth-docs': typeof AuthDocsRouteWithChildren '/client-only': typeof ClientOnlyRoute '/deferred': typeof DeferredRoute - '/execution-local': typeof ExecutionLocalRoute - '/execution-rpc': typeof ExecutionRpcRoute '/inline-scripts': typeof InlineScriptsRoute '/links': typeof LinksRoute '/plain-ts-type-assertion': typeof PlainTsTypeAssertionRoute @@ -653,7 +618,6 @@ export interface FileRoutesById { '/specialChars/malformed': typeof SpecialCharsMalformedRouteRouteWithChildren '/_layout/_layout-2': typeof LayoutLayout2RouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren - '/auth-docs/private': typeof AuthDocsPrivateRoute '/issue-6221/dashboard': typeof Issue6221DashboardRoute '/multi-cookie-redirect/target': typeof MultiCookieRedirectTargetRoute '/not-found/via-beforeLoad': typeof NotFoundViaBeforeLoadRoute @@ -712,11 +676,8 @@ export interface FileRouteTypes { | '/search-params' | '/specialChars' | '/async-scripts' - | '/auth-docs' | '/client-only' | '/deferred' - | '/execution-local' - | '/execution-rpc' | '/inline-scripts' | '/links' | '/plain-ts-type-assertion' @@ -731,7 +692,6 @@ export interface FileRouteTypes { | '/not-found/parent-boundary' | '/specialChars/malformed' | '/api/users' - | '/auth-docs/private' | '/issue-6221/dashboard' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' @@ -786,11 +746,8 @@ export interface FileRouteTypes { | '/' | '/specialChars' | '/async-scripts' - | '/auth-docs' | '/client-only' | '/deferred' - | '/execution-local' - | '/execution-rpc' | '/inline-scripts' | '/links' | '/plain-ts-type-assertion' @@ -800,7 +757,6 @@ export interface FileRouteTypes { | '/type-only-reexport' | '/specialChars/malformed' | '/api/users' - | '/auth-docs/private' | '/issue-6221/dashboard' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' @@ -856,11 +812,8 @@ export interface FileRouteTypes { | '/specialChars' | '/_layout' | '/async-scripts' - | '/auth-docs' | '/client-only' | '/deferred' - | '/execution-local' - | '/execution-rpc' | '/inline-scripts' | '/links' | '/plain-ts-type-assertion' @@ -876,7 +829,6 @@ export interface FileRouteTypes { | '/specialChars/malformed' | '/_layout/_layout-2' | '/api/users' - | '/auth-docs/private' | '/issue-6221/dashboard' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' @@ -935,11 +887,8 @@ export interface RootRouteChildren { SpecialCharsRouteRoute: typeof SpecialCharsRouteRouteWithChildren LayoutRoute: typeof LayoutRouteWithChildren AsyncScriptsRoute: typeof AsyncScriptsRoute - AuthDocsRoute: typeof AuthDocsRouteWithChildren ClientOnlyRoute: typeof ClientOnlyRoute DeferredRoute: typeof DeferredRoute - ExecutionLocalRoute: typeof ExecutionLocalRoute - ExecutionRpcRoute: typeof ExecutionRpcRoute InlineScriptsRoute: typeof InlineScriptsRoute LinksRoute: typeof LinksRoute PlainTsTypeAssertionRoute: typeof PlainTsTypeAssertionRoute @@ -984,13 +933,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AsyncScriptsRouteImport parentRoute: typeof rootRouteImport } - '/auth-docs': { - id: '/auth-docs' - path: '/auth-docs' - fullPath: '/auth-docs' - preLoaderRoute: typeof AuthDocsRouteImport - parentRoute: typeof rootRouteImport - } '/client-only': { id: '/client-only' path: '/client-only' @@ -1005,20 +947,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DeferredRouteImport parentRoute: typeof rootRouteImport } - '/execution-local': { - id: '/execution-local' - path: '/execution-local' - fullPath: '/execution-local' - preLoaderRoute: typeof ExecutionLocalRouteImport - parentRoute: typeof rootRouteImport - } - '/execution-rpc': { - id: '/execution-rpc' - path: '/execution-rpc' - fullPath: '/execution-rpc' - preLoaderRoute: typeof ExecutionRpcRouteImport - parentRoute: typeof rootRouteImport - } '/inline-scripts': { id: '/inline-scripts' path: '/inline-scripts' @@ -1124,13 +1052,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } - '/auth-docs/private': { - id: '/auth-docs/private' - path: '/private' - fullPath: '/auth-docs/private' - preLoaderRoute: typeof AuthDocsPrivateRouteImport - parentRoute: typeof AuthDocsRoute - } '/issue-6221/dashboard': { id: '/issue-6221/dashboard' path: '/issue-6221/dashboard' @@ -1649,18 +1570,6 @@ const LayoutRouteChildren: LayoutRouteChildren = { const LayoutRouteWithChildren = LayoutRoute._addFileChildren(LayoutRouteChildren) -interface AuthDocsRouteChildren { - AuthDocsPrivateRoute: typeof AuthDocsPrivateRoute -} - -const AuthDocsRouteChildren: AuthDocsRouteChildren = { - AuthDocsPrivateRoute: AuthDocsPrivateRoute, -} - -const AuthDocsRouteWithChildren = AuthDocsRoute._addFileChildren( - AuthDocsRouteChildren, -) - interface PostsRouteChildren { PostsPostIdRoute: typeof PostsPostIdRoute PostsIndexRoute: typeof PostsIndexRoute @@ -1766,11 +1675,8 @@ const rootRouteChildren: RootRouteChildren = { SpecialCharsRouteRoute: SpecialCharsRouteRouteWithChildren, LayoutRoute: LayoutRouteWithChildren, AsyncScriptsRoute: AsyncScriptsRoute, - AuthDocsRoute: AuthDocsRouteWithChildren, ClientOnlyRoute: ClientOnlyRoute, DeferredRoute: DeferredRoute, - ExecutionLocalRoute: ExecutionLocalRoute, - ExecutionRpcRoute: ExecutionRpcRoute, InlineScriptsRoute: InlineScriptsRoute, LinksRoute: LinksRoute, PlainTsTypeAssertionRoute: PlainTsTypeAssertionRoute, diff --git a/e2e/react-start/basic/src/routes/__root.tsx b/e2e/react-start/basic/src/routes/__root.tsx index ed521817d6..d8fc0d3b24 100644 --- a/e2e/react-start/basic/src/routes/__root.tsx +++ b/e2e/react-start/basic/src/routes/__root.tsx @@ -197,9 +197,6 @@ function RootDocument({ children }: { children: React.ReactNode }) { > Client Only {' '} - - Server function loader - {' '} { console.info('Fetching users... @', request.url) - const res = await axios.get>( - 'https://jsonplaceholder.typicode.com/users', - ) + const res = await axios.get>(`${queryURL}/users`) const list = res.data.slice(0, 10) diff --git a/e2e/react-start/basic/src/routes/api/users.$id.ts b/e2e/react-start/basic/src/routes/api/users.$id.ts index 797dffb637..ac665381f1 100644 --- a/e2e/react-start/basic/src/routes/api/users.$id.ts +++ b/e2e/react-start/basic/src/routes/api/users.$id.ts @@ -2,15 +2,19 @@ import { createFileRoute } from '@tanstack/react-router' import axios from 'redaxios' import type { User } from '~/utils/users' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} + export const Route = createFileRoute('/api/users/$id')({ server: { handlers: { GET: async ({ request, params }) => { console.info(`Fetching users by id=${params.id}... @`, request.url) try { - const res = await axios.get( - `https://jsonplaceholder.typicode.com/users/${params.id}`, - ) + const res = await axios.get(`${queryURL}/users/` + params.id) return Response.json({ id: res.data.id, diff --git a/e2e/react-start/basic/src/routes/auth-docs.private.tsx b/e2e/react-start/basic/src/routes/auth-docs.private.tsx deleted file mode 100644 index 85fc8a0fc9..0000000000 --- a/e2e/react-start/basic/src/routes/auth-docs.private.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { createFileRoute, redirect } from '@tanstack/react-router' -import { getPrivateDataFn } from '../utils/auth-docs' - -export const Route = createFileRoute('/auth-docs/private')({ - beforeLoad: ({ context }) => { - if (!context.user) { - throw redirect({ to: '/auth-docs' }) - } - }, - loader: () => getPrivateDataFn(), - component: PrivatePage, -}) - -function PrivatePage() { - const message = Route.useLoaderData() - return

{message}

-} diff --git a/e2e/react-start/basic/src/routes/auth-docs.tsx b/e2e/react-start/basic/src/routes/auth-docs.tsx deleted file mode 100644 index 6ea1b813ef..0000000000 --- a/e2e/react-start/basic/src/routes/auth-docs.tsx +++ /dev/null @@ -1,100 +0,0 @@ -import { - createFileRoute, - Outlet, - useHydrated, - useRouter, -} from '@tanstack/react-router' -import { useServerFn } from '@tanstack/react-start' -import { useState } from 'react' -import type { FormEvent } from 'react' -import { - getCurrentUserFn, - getPrivateDataFn, - loginFn, - logoutFn, -} from '../utils/auth-docs' - -export const Route = createFileRoute('/auth-docs')({ - beforeLoad: async () => ({ user: await getCurrentUserFn() }), - headers: () => ({ 'Cache-Control': 'private, no-store' }), - component: AuthDocs, -}) - -function AuthDocs() { - const hydrated = useHydrated() - const { user } = Route.useRouteContext() - const router = useRouter() - const login = useServerFn(loginFn) - const logout = useServerFn(logoutFn) - const getPrivateData = useServerFn(getPrivateDataFn) - const [isLoading, setIsLoading] = useState(false) - const [error, setError] = useState('') - const [privateResult, setPrivateResult] = useState('') - - const handleSubmit = async (event: FormEvent) => { - event.preventDefault() - const formData = new FormData(event.currentTarget) - const email = formData.get('email') - const password = formData.get('password') - if (typeof email !== 'string' || typeof password !== 'string') { - return - } - setIsLoading(true) - setError('') - try { - const result = await login({ data: { email, password } }) - if (result?.error) { - setError(result.error) - return - } - await router.invalidate() - } catch { - setError('Login failed. Please try again.') - } finally { - setIsLoading(false) - } - } - - return ( -
-

{user?.email ?? 'Signed out'}

-
-
- - - -
-

{error}

-
- - -

{privateResult}

- -
- ) -} diff --git a/e2e/react-start/basic/src/routes/execution-local.tsx b/e2e/react-start/basic/src/routes/execution-local.tsx deleted file mode 100644 index 477cd81740..0000000000 --- a/e2e/react-start/basic/src/routes/execution-local.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { readOnlyOnServer } from '~/utils/execution-functions' - -// This intentionally fails during browser navigation. It is the negative case -// for the environment-functions troubleshooting guide. -export const Route = createFileRoute('/execution-local')({ - loader: () => readOnlyOnServer(), - component: Result, - errorComponent: ({ error }) => ( -

{error instanceof Error ? error.message : String(error)}

- ), -}) - -function Result() { - return

{Route.useLoaderData()}

-} diff --git a/e2e/react-start/basic/src/routes/execution-rpc.tsx b/e2e/react-start/basic/src/routes/execution-rpc.tsx deleted file mode 100644 index f934015522..0000000000 --- a/e2e/react-start/basic/src/routes/execution-rpc.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { createFileRoute, Link } from '@tanstack/react-router' -import { readThroughRpc } from '~/utils/execution-functions' - -export const Route = createFileRoute('/execution-rpc')({ - loader: () => readThroughRpc(), - component: Result, -}) - -function Result() { - return ( - <> -

{Route.useLoaderData()}

- - Call the server-only helper directly - - - ) -} diff --git a/e2e/react-start/basic/src/utils/auth-docs.ts b/e2e/react-start/basic/src/utils/auth-docs.ts deleted file mode 100644 index 22b36ee808..0000000000 --- a/e2e/react-start/basic/src/utils/auth-docs.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { createServerFn } from '@tanstack/react-start' -import { redirect } from '@tanstack/react-router' -import { getCookie, setCookie } from '@tanstack/react-start/server' -import { getIronSession } from 'iron-session' - -function getSession() { - return getIronSession<{ email: string }>( - { read: getCookie, write: setCookie }, - { - cookieName: 'auth-docs-test', - password: 'authentication-docs-browser-test-secret-only-2026', - ttl: 60 * 60, - cookieOptions: { - httpOnly: true, - secure: false, - sameSite: 'lax', - path: '/', - }, - }, - ) -} - -export const getCurrentUserFn = createServerFn({ method: 'GET' }).handler( - async () => { - const session = await getSession() - return session.email ? { email: session.email } : null - }, -) - -export const loginFn = createServerFn({ method: 'POST' }) - .validator((data: { email: string; password: string }) => data) - .handler(async ({ data }) => { - // Fixed credentials belong only to this browser-test fixture. - if ( - data.email !== 'reader@example.com' || - data.password !== 'test-password' - ) { - return { error: 'Invalid credentials' } - } - const session = await getSession() - session.email = data.email - await session.save() - throw redirect({ to: '/auth-docs/private' }) - }) - -export const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await getSession() - session.destroy() - throw redirect({ to: '/auth-docs' }) -}) - -export const getPrivateDataFn = createServerFn({ method: 'GET' }).handler( - async () => { - const session = await getSession() - if (!session.email) { - throw new Error('Unauthorized') - } - return 'Private account data' - }, -) diff --git a/e2e/react-start/basic/src/utils/execution-functions.ts b/e2e/react-start/basic/src/utils/execution-functions.ts deleted file mode 100644 index 97e66573d8..0000000000 --- a/e2e/react-start/basic/src/utils/execution-functions.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { createServerFn, createServerOnlyFn } from '@tanstack/react-start' - -export const readOnlyOnServer = createServerOnlyFn(() => 'Read on the server') - -export const readThroughRpc = createServerFn().handler(() => readOnlyOnServer()) diff --git a/e2e/react-start/basic/src/utils/posts.tsx b/e2e/react-start/basic/src/utils/posts.tsx index 9fdff27673..4cc5dcc4c6 100644 --- a/e2e/react-start/basic/src/utils/posts.tsx +++ b/e2e/react-start/basic/src/utils/posts.tsx @@ -8,12 +8,18 @@ export type PostType = { body: string } +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} + export const fetchPost = createServerFn({ method: 'GET' }) .validator((postId: string) => postId) .handler(async ({ data: postId }) => { console.info(`Fetching post with id ${postId}...`) const post = await axios - .get(`https://jsonplaceholder.typicode.com/posts/${postId}`) + .get(`${queryURL}/posts/${postId}`) .then((r) => r.data) .catch((err) => { console.error(err) @@ -30,7 +36,7 @@ export const fetchPosts = createServerFn({ method: 'GET' }).handler( async () => { console.info('Fetching posts...') return axios - .get>('https://jsonplaceholder.typicode.com/posts') + .get>(`${queryURL}/posts`) .then((r) => r.data.slice(0, 10)) }, ) diff --git a/e2e/react-start/basic/src/utils/users.tsx b/e2e/react-start/basic/src/utils/users.tsx index 7ba645b383..46be4b1580 100644 --- a/e2e/react-start/basic/src/utils/users.tsx +++ b/e2e/react-start/basic/src/utils/users.tsx @@ -3,3 +3,7 @@ export type User = { name: string email: string } + +const PORT = process.env.VITE_SERVER_PORT || 3000 + +export const DEPLOY_URL = `http://localhost:${PORT}` diff --git a/e2e/react-start/basic/tests/auth-docs.spec.ts b/e2e/react-start/basic/tests/auth-docs.spec.ts deleted file mode 100644 index 47a57c9da2..0000000000 --- a/e2e/react-start/basic/tests/auth-docs.spec.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { expect, test } from '@playwright/test' -import { isSpaMode } from './utils/isSpaMode' - -test('authentication docs pattern handles login, logout, route context, and server authorization', async ({ - page, -}) => { - await page.goto('/auth-docs/private') - await expect(page).toHaveURL(/\/auth-docs$/) - await expect(page.getByTestId('auth-docs-user')).toHaveText('Signed out') - - await page - .getByRole('button', { name: 'Request private data directly' }) - .click() - await expect(page.getByTestId('auth-docs-private-result')).toHaveText( - 'Access denied', - ) - - await page.getByLabel('Email', { exact: true }).fill('reader@example.com') - await page.getByLabel('Password', { exact: true }).fill('wrong-password') - await page.getByRole('button', { name: 'Login', exact: true }).click() - await expect(page.getByRole('alert')).toHaveText('Invalid credentials') - await expect(page.getByTestId('auth-docs-user')).toHaveText('Signed out') - - await page.getByLabel('Password', { exact: true }).fill('test-password') - await page.getByRole('button', { name: 'Login', exact: true }).click() - await expect(page).toHaveURL(/\/auth-docs\/private$/) - await expect(page.getByTestId('auth-docs-user')).toHaveText( - 'reader@example.com', - ) - await expect(page.getByTestId('auth-docs-private-page')).toHaveText( - 'Private account data', - ) - - const response = await page.reload() - expect(response?.status()).toBe(200) - if (isSpaMode) { - // The shared SPA shell must not contain authenticated account data. - expect(await response?.text()).not.toContain('reader@example.com') - expect(await response?.text()).not.toContain('Private account data') - } else { - expect(response?.headers()['cache-control']).toBe('private, no-store') - } - await expect(page.getByTestId('auth-docs-user')).toHaveText( - 'reader@example.com', - ) - await page.getByRole('button', { name: 'Logout', exact: true }).click() - await expect(page).toHaveURL(/\/auth-docs$/) - await expect(page.getByTestId('auth-docs-user')).toHaveText('Signed out') - await page - .getByRole('button', { name: 'Request private data directly' }) - .click() - await expect(page.getByTestId('auth-docs-private-result')).toHaveText( - 'Access denied', - ) - await page.goto('/auth-docs/private') - await expect(page).toHaveURL(/\/auth-docs$/) -}) - -test('the authentication form cannot submit credentials before hydration', async ({ - browser, - baseURL, -}) => { - const context = await browser.newContext({ - javaScriptEnabled: false, - baseURL, - }) - const page = await context.newPage() - try { - await page.goto('/auth-docs') - if (isSpaMode) { - // Without JavaScript, the SPA shell cannot render credential controls. - await expect(page.locator('form')).toHaveCount(0) - await expect(page.getByLabel('Email', { exact: true })).toHaveCount(0) - await expect(page.getByLabel('Password', { exact: true })).toHaveCount(0) - await expect( - page.getByRole('button', { name: 'Login', exact: true }), - ).toHaveCount(0) - } else { - await expect(page.locator('form')).toHaveAttribute('method', 'post') - await expect(page.getByLabel('Email', { exact: true })).toBeDisabled() - await expect(page.getByLabel('Password', { exact: true })).toBeDisabled() - await expect( - page.getByRole('button', { name: 'Login', exact: true }), - ).toBeDisabled() - } - } finally { - await context.close() - } -}) diff --git a/e2e/react-start/basic/tests/client-only.spec.ts b/e2e/react-start/basic/tests/client-only.spec.ts index 299744f636..a3b6f99442 100644 --- a/e2e/react-start/basic/tests/client-only.spec.ts +++ b/e2e/react-start/basic/tests/client-only.spec.ts @@ -1,6 +1,5 @@ import { expect } from '@playwright/test' import { test } from '@tanstack/router-e2e-utils' -import { isSpaMode } from './utils/isSpaMode' /** * These tests verify the compiler optimization. @@ -16,15 +15,7 @@ import { isSpaMode } from './utils/isSpaMode' test('ClientOnly renders fallback on server, then client content after hydration', async ({ page, - request, }) => { - const response = await request.get('/client-only') - expect(response.status()).toBe(200) - const html = await response.text() - expect(html).not.toContain('data-testid="window-size"') - if (!isSpaMode) { - expect(html).toContain('Loading window size...') - } // Navigate directly to the client-only route // If the compiler optimization isn't working, this would crash the server // because WindowSize.tsx accesses `window` at module scope diff --git a/e2e/react-start/basic/tests/environment-functions.spec.ts b/e2e/react-start/basic/tests/environment-functions.spec.ts deleted file mode 100644 index 410b1d999e..0000000000 --- a/e2e/react-start/basic/tests/environment-functions.spec.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { expect, test } from '@playwright/test' -import { isSpaMode } from './utils/isSpaMode' - -const guardError = - 'createServerOnlyFn() functions can only be called on the server!' - -test('a server-only loader works on the server but rejects client navigation', async ({ - page, - request, -}) => { - const direct = await request.get('/execution-local') - expect(direct.status()).toBe(200) - if (!isSpaMode) { - expect(await direct.text()).toContain('Read on the server') - } - await page.goto('/execution-rpc') - await expect(page.getByTestId('execution-result')).toHaveText( - 'Read on the server', - ) - await page - .getByRole('link', { name: 'Call the server-only helper directly' }) - .click() - await expect(page.getByRole('alert')).toHaveText(guardError) -}) - -test('a server function preserves the loader result on direct requests and navigation', async ({ - page, - request, -}) => { - const direct = await request.get('/execution-rpc') - expect(direct.status()).toBe(200) - if (!isSpaMode) { - expect(await direct.text()).toContain('Read on the server') - } - await page.goto('/') - await page - .getByRole('link', { name: 'Server function loader', exact: true }) - .click() - await expect(page.getByTestId('execution-result')).toHaveText( - 'Read on the server', - ) - await page.reload() - await expect(page.getByTestId('execution-result')).toHaveText( - 'Read on the server', - ) -}) diff --git a/e2e/react-start/basic/tests/fixture-api.spec.ts b/e2e/react-start/basic/tests/fixture-api.spec.ts deleted file mode 100644 index 6c9b26dc4c..0000000000 --- a/e2e/react-start/basic/tests/fixture-api.spec.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { expect, test } from '@playwright/test' - -test('server API receives canned users without a fixture listener', async ({ - request, -}) => { - const response = await request.get('/api/users') - expect(response.ok()).toBe(true) - const users = await response.json() - expect(users).toHaveLength(10) - expect(users[0]).toMatchObject({ id: 1, name: 'Leanne Graham' }) -}) diff --git a/e2e/react-start/basic/tests/redirect.spec.ts b/e2e/react-start/basic/tests/redirect.spec.ts index 010ecec155..34ba7b6ea9 100644 --- a/e2e/react-start/basic/tests/redirect.spec.ts +++ b/e2e/react-start/basic/tests/redirect.spec.ts @@ -1,15 +1,20 @@ import queryString from 'node:querystring' -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' +import { expect, type Page } from '@playwright/test' import combinateImport from 'combinate' -import type { Page } from '@playwright/test' +import { + getDummyServerPort, + getTestServerPort, + test, +} from '@tanstack/router-e2e-utils' +import { getE2EPortKey } from './utils/getE2EPortKey.ts' // somehow playwright does not correctly import default exports const combinate = (combinateImport as any).default as typeof combinateImport +const e2ePortKey = getE2EPortKey() -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(e2ePortKey) -const EXTERNAL_ORIGIN = `http://127.0.0.1:${PORT}` +const EXTERNAL_HOST_PORT = await getDummyServerPort(e2ePortKey) const POSTS_URL = `http://localhost:${PORT}/posts` async function waitForRouterIdle(page: Page) { @@ -106,7 +111,7 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, }) if (scenario === 'navigate') { @@ -119,7 +124,7 @@ test.describe('redirects', () => { await page.goto(`/redirect/external/via-${thrower}?${q}`) } - const url = `${EXTERNAL_ORIGIN}/` + const url = `http://localhost:${EXTERNAL_HOST_PORT}/` await page.waitForURL(url) expect(page.url()).toBe(url) @@ -142,7 +147,7 @@ test.describe('redirects', () => { }) => { let fullPageLoad = false const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, reloadDocument, }) @@ -165,7 +170,10 @@ test.describe('redirects', () => { await page.goto(`/redirect/${target}/serverFn/via-${thrower}?${q}`) } - const url = target === 'internal' ? POSTS_URL : `${EXTERNAL_ORIGIN}/` + const url = + target === 'internal' + ? POSTS_URL + : `http://localhost:${EXTERNAL_HOST_PORT}/` await page.waitForURL(url) @@ -194,7 +202,7 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, reloadDocument, }) @@ -211,7 +219,10 @@ test.describe('redirects', () => { await button.click() - const url = target === 'internal' ? POSTS_URL : `${EXTERNAL_ORIGIN}/` + const url = + target === 'internal' + ? POSTS_URL + : `http://localhost:${EXTERNAL_HOST_PORT}/` await page.waitForURL(url) expect(page.url()).toBe(url) if (target === 'internal') { diff --git a/e2e/react-start/basic/tests/setup/dev-server.setup.ts b/e2e/react-start/basic/tests/setup/dev-server.setup.ts deleted file mode 100644 index d16ff0bb54..0000000000 --- a/e2e/react-start/basic/tests/setup/dev-server.setup.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' - -export default async function setup() { - const port = Number(process.env.E2E_APP_PORT ?? 0) - const baseURL = `http://localhost:${port}` - - await waitForServer(baseURL) - await preOptimizeDevServer({ - baseURL, - warmup: async (page) => { - await page.getByRole('heading').getByText('Welcome Home').waitFor() - await page.goto(`${baseURL}/specialChars/search?searchParam=warmup`) - await page.getByTestId('special-search-loaded-info').waitFor() - await page.goto(`${baseURL}/posts`) - await page.getByRole('link', { name: 'sunt aut facere repe' }).waitFor() - await page.waitForLoadState('networkidle') - }, - }) -} diff --git a/e2e/react-start/basic/tests/setup/global.setup.ts b/e2e/react-start/basic/tests/setup/global.setup.ts new file mode 100644 index 0000000000..cd38c35885 --- /dev/null +++ b/e2e/react-start/basic/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import { getE2EPortKey } from '../utils/getE2EPortKey.ts' + +export default async function setup() { + await e2eStartDummyServer(getE2EPortKey()) +} diff --git a/e2e/react-start/basic/tests/setup/global.teardown.ts b/e2e/react-start/basic/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..36e5c92858 --- /dev/null +++ b/e2e/react-start/basic/tests/setup/global.teardown.ts @@ -0,0 +1,8 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import { getE2EPortKey } from '../utils/getE2EPortKey.ts' + +export default async function teardown() { + try { + await e2eStopDummyServer(getE2EPortKey()) + } catch {} +} diff --git a/e2e/react-start/basic/tests/setup/waitForDummyServer.ts b/e2e/react-start/basic/tests/setup/waitForDummyServer.ts new file mode 100644 index 0000000000..88c18fd79e --- /dev/null +++ b/e2e/react-start/basic/tests/setup/waitForDummyServer.ts @@ -0,0 +1,24 @@ +import { getDummyServerPort } from '@tanstack/router-e2e-utils' +import { getE2EPortKey } from '../utils/getE2EPortKey.ts' + +const timeoutMs = 10_000 +const retryIntervalMs = 100 + +export default async function waitForDummyServer() { + const port = await getDummyServerPort(getE2EPortKey()) + const deadline = Date.now() + timeoutMs + + while (Date.now() < deadline) { + try { + const response = await fetch(`http://localhost:${port}/`) + + if (response.ok) { + return + } + } catch {} + + await new Promise((resolve) => setTimeout(resolve, retryIntervalMs)) + } + + throw new Error(`Timed out waiting for dummy server on port ${port}`) +} diff --git a/e2e/react-start/basic/tests/spa-shell.spec.ts b/e2e/react-start/basic/tests/spa-shell.spec.ts deleted file mode 100644 index f42195e762..0000000000 --- a/e2e/react-start/basic/tests/spa-shell.spec.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' -import { isSpaMode } from './utils/isSpaMode' - -// The prod SPA run and the dev SPA runs (`E2E_DEV_SERVER`) all run this file. -// The dev runs run nothing else. -test.skip(!isSpaMode, 'only SPA mode answers documents with the shell') - -// Its loader and beforeLoad report where they ran. -const searchRoute = '/specialChars/search?searchParam=shell' - -test('a document request gets the shell, not the rendered route', async ({ - request, -}) => { - const response = await request.get(searchRoute) - - expect(response.status()).toBe(200) - const html = await response.text() - // The root route's document renders... - expect(html).toContain('This Route Does Not Exist') - // ...but not the matched route, nor its loader's output. - expect(html).not.toContain('special-search-loaded-info') - expect(html).not.toContain('Loaded on: server') -}) - -test('the route loads in the browser', async ({ page }) => { - await page.goto(searchRoute) - - await expect(page.getByTestId('special-search-loaded-info')).toHaveText( - 'Loaded on: client', - ) - await expect(page.getByTestId('special-search-before-load-info')).toHaveText( - 'Before load on: client', - ) - await expect(page.getByTestId('special-search-param')).toHaveText('shell') -}) - -test('client navigation works from the shell', async ({ page }) => { - await page.goto('/') - await expect(page.getByRole('heading')).toContainText('Welcome Home') - await expect(page.getByTestId('router-status')).toHaveText('idle') - - // A full page load would drop this. - await page.evaluate(() => { - ;(window as any).__spaShellPage = true - }) - await page.getByRole('link', { name: 'Posts' }).click() - await page.waitForURL('/posts') - await expect( - page.getByRole('link', { name: 'sunt aut facere repe' }), - ).toBeVisible() - expect(await page.evaluate(() => (window as any).__spaShellPage)).toBe(true) -}) diff --git a/e2e/react-start/basic/tests/utils/getE2EPortKey.ts b/e2e/react-start/basic/tests/utils/getE2EPortKey.ts new file mode 100644 index 0000000000..48be6a9027 --- /dev/null +++ b/e2e/react-start/basic/tests/utils/getE2EPortKey.ts @@ -0,0 +1,5 @@ +import { getPackageName } from './getPackageName.ts' + +export function getE2EPortKey() { + return process.env.E2E_PORT_KEY ?? getPackageName() +} diff --git a/e2e/react-start/clerk-basic/package.json b/e2e/react-start/clerk-basic/package.json index 7838b4cee1..65f405eb69 100644 --- a/e2e/react-start/clerk-basic/package.json +++ b/e2e/react-start/clerk-basic/package.json @@ -8,7 +8,7 @@ "dev:e2e": "vite dev", "build": "exit 0; vite build", "start": "node .output/server/index.mjs", - "test:e2e": "exit 0; playwright test --project=chromium" + "test:e2e": "exit 0; rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@clerk/tanstack-react-start": "^0.19.0", diff --git a/e2e/react-start/clerk-basic/playwright.config.ts b/e2e/react-start/clerk-basic/playwright.config.ts index 82678ac00b..18b8905468 100644 --- a/e2e/react-start/clerk-basic/playwright.config.ts +++ b/e2e/react-start/clerk-basic/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/csp/package.json b/e2e/react-start/csp/package.json index fd8987bcef..bbe4df9bbc 100644 --- a/e2e/react-start/csp/package.json +++ b/e2e/react-start/csp/package.json @@ -8,7 +8,7 @@ "dev:e2e": "vite dev", "build": "vite build && tsc --noEmit", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -22,7 +22,7 @@ "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" diff --git a/e2e/react-start/csp/playwright.config.ts b/e2e/react-start/csp/playwright.config.ts index 87b32e1f50..5f9de5709e 100644 --- a/e2e/react-start/csp/playwright.config.ts +++ b/e2e/react-start/csp/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/css-inline/package.json b/e2e/react-start/css-inline/package.json index 6c5dd031c6..7d9c0520fc 100644 --- a/e2e/react-start/css-inline/package.json +++ b/e2e/react-start/css-inline/package.json @@ -20,11 +20,11 @@ "express": "^5.2.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "srvx": "^1.0.0" + "srvx": "^0.11.9" }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-react": "^2.0.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", @@ -38,47 +38,7 @@ "nx": { "targets": { "test:e2e": { - "parallelism": false, - "outputs": [ - "...", - "{projectRoot}/dist-vite-ssr", - "{projectRoot}/dist-vite-ssr-transform-assets", - "{projectRoot}/dist-vite-transform-assets-ssr", - "{projectRoot}/dist-rsbuild-ssr", - "{projectRoot}/dist-rsbuild-ssr-transform-assets", - "{projectRoot}/dist-rsbuild-transform-assets-ssr" - ] - }, - "build": { - "outputs": [ - "...", - "{projectRoot}/dist-vite-ssr", - "{projectRoot}/dist-rsbuild-ssr" - ] - }, - "test:e2e--vite-ssr": { - "outputs": [ - "...", - "{projectRoot}/dist-vite-ssr" - ] - }, - "test:e2e--vite-ssr--transform-assets": { - "outputs": [ - "...", - "{projectRoot}/dist-vite-ssr-transform-assets" - ] - }, - "test:e2e--rsbuild-ssr": { - "outputs": [ - "...", - "{projectRoot}/dist-rsbuild-ssr" - ] - }, - "test:e2e--rsbuild-ssr--transform-assets": { - "outputs": [ - "...", - "{projectRoot}/dist-rsbuild-ssr-transform-assets" - ] + "parallelism": false } }, "metadata": { diff --git a/e2e/react-start/css-inline/playwright.config.ts b/e2e/react-start/css-inline/playwright.config.ts index 78e7b75252..b5d78f3608 100644 --- a/e2e/react-start/css-inline/playwright.config.ts +++ b/e2e/react-start/css-inline/playwright.config.ts @@ -1,5 +1,7 @@ +import fs from 'node:fs' import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' const inlineCssTransformAssets = @@ -16,8 +18,15 @@ const transformAssetsSuffix = isInlineCssTransformAssets : '' const distDir = process.env.E2E_DIST_DIR ?? `dist-${toolchain}${transformAssetsSuffix}-ssr` +const e2ePortKey = + process.env.E2E_PORT_KEY ?? + `${packageJson.name}-${toolchain}${transformAssetsSuffix}` -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +if (process.env.TEST_WORKER_INDEX === undefined) { + fs.rmSync(`port-${e2ePortKey}.txt`, { force: true }) +} + +const PORT = await getTestServerPort(e2ePortKey) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -31,8 +40,8 @@ export default defineConfig({ webServer: { command: `pnpm build:${toolchain} && pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { E2E_DIST_DIR: distDir, diff --git a/e2e/react-start/css-inline/server.js b/e2e/react-start/css-inline/server.js index 27b2357284..fcdec3b888 100644 --- a/e2e/react-start/css-inline/server.js +++ b/e2e/react-start/css-inline/server.js @@ -3,7 +3,7 @@ import path from 'node:path' import express from 'express' import { toNodeHandler } from 'srvx/node' -const port = Number(process.env.PORT ?? 3000) +const port = process.env.PORT || 3000 const distDir = process.env.E2E_DIST_DIR || 'dist-vite-ssr' const distClientDir = path.resolve(distDir, 'client') @@ -37,10 +37,8 @@ async function createStartServer() { } createStartServer().then((app) => { - const httpServer = app.listen(port, (error) => { - if (error) { - throw error - } - console.info(`E2E app: http://localhost:${httpServer.address().port}`) + app.listen(port, (error) => { + if (error) throw error + console.info(`Start Server: http://localhost:${port}`) }) }) diff --git a/e2e/react-start/css-inline/src/routes/app/dashboard/index.tsx b/e2e/react-start/css-inline/src/routes/app/dashboard/index.tsx index 35205cc9cf..a796656b3d 100644 --- a/e2e/react-start/css-inline/src/routes/app/dashboard/index.tsx +++ b/e2e/react-start/css-inline/src/routes/app/dashboard/index.tsx @@ -3,9 +3,6 @@ import { NestedPanel } from '~/components/NestedPanel' import styles from '~/styles/dashboard-index.module.css' export const Route = createFileRoute('/app/dashboard/')({ - head: () => ({ - meta: [{ title: 'Inline CSS dashboard' }], - }), component: DashboardIndex, }) diff --git a/e2e/react-start/css-inline/tests/css-inline.spec.ts b/e2e/react-start/css-inline/tests/css-inline.spec.ts index 89d7d3992f..339fedd4ca 100644 --- a/e2e/react-start/css-inline/tests/css-inline.spec.ts +++ b/e2e/react-start/css-inline/tests/css-inline.spec.ts @@ -1,5 +1,5 @@ import { expect } from '@playwright/test' -import { collectBrowserErrors, test } from '@tanstack/router-e2e-utils' +import { test } from '@tanstack/router-e2e-utils' const buildUrl = (baseURL: string, pathname: string) => baseURL.replace(/\/$/, '') + pathname @@ -151,23 +151,6 @@ test('client navigation preserves the SSR inline shell stylesheet', async ({ await page.goto(buildUrl(baseURL!, '/')) await waitForHydration(page) - const inlineStyle = page.locator('style[data-tsr-inline-css]') - await expect(inlineStyle).toHaveCount(1) - const original = await inlineStyle.evaluateHandle( - (style: HTMLStyleElement) => { - const mutations: Array = [] - const observer = new MutationObserver((records) => { - mutations.push(...records) - }) - observer.observe(style, { - childList: true, - characterData: true, - subtree: true, - }) - return { style, sheet: style.sheet, observer, mutations } - }, - ) - await expect.poll(() => getInlineCssTexts(page)).toHaveLength(1) await expect .poll(() => getInlineCssTexts(page)) @@ -178,28 +161,6 @@ test('client navigation preserves the SSR inline shell stylesheet', async ({ await page.getByTestId('nav-dashboard').click() await page.waitForURL('**/app/dashboard') - await expect(page).toHaveTitle('Inline CSS dashboard') - await expect(page.getByTestId('dashboard-card')).toBeVisible() - - await page.getByTestId('nav-home').click() - await expect(page).toHaveTitle('Inline CSS E2E') - await expect(page.getByTestId('home')).toBeVisible() - - // #8250: unchanged CSS text can hide a redundant innerHTML write that - // replaces the stylesheet or fails under Trusted Types. Observe native DOM - // mutations and CSSOM identity without patching the innerHTML setter. - expect( - await original.evaluate(({ style, sheet, observer, mutations }) => { - const mutationCount = mutations.length + observer.takeRecords().length - observer.disconnect() - return { - connected: style.isConnected, - sameSheet: style.sheet === sheet, - mutationCount, - } - }), - ).toEqual({ connected: true, sameSheet: true, mutationCount: 0 }) - await original.dispose() await expect.poll(() => getInlineCssTexts(page)).toHaveLength(1) await expect @@ -209,45 +170,3 @@ test('client navigation preserves the SSR inline shell stylesheet', async ({ .poll(() => getStyle(page, 'shell', 'background-color')) .toBe('rgb(240, 249, 255)') }) - -test('client navigation preserves inline CSS with Trusted Types enforced', async ({ - page, -}) => { - const browserErrors = collectBrowserErrors(page) - const csp = "require-trusted-types-for 'script'; trusted-types 'none'" - await page.route('/', async (route) => { - const response = await route.fetch() - await route.fulfill({ - response, - headers: { ...response.headers(), 'content-security-policy': csp }, - }) - }) - - const response = await page.goto('/') - expect(response?.headers()['content-security-policy']).toBe(csp) - expect(await page.evaluate(() => 'trustedTypes' in window)).toBe(true) - await waitForHydration(page) - - const violations = await page.evaluateHandle(() => { - const directives: Array = [] - document.addEventListener('securitypolicyviolation', (event) => { - directives.push(event.effectiveDirective) - }) - return directives - }) - - await page.getByTestId('nav-dashboard').click() - await expect(page).toHaveTitle('Inline CSS dashboard') - await expect(page.getByTestId('dashboard-card')).toBeVisible() - await expect - .poll(() => getStyle(page, 'shell', 'background-color')) - .toBe('rgb(240, 249, 255)') - - await page.getByTestId('nav-home').click() - await expect(page).toHaveTitle('Inline CSS E2E') - await expect(page.getByTestId('home')).toBeVisible() - - expect(await violations.jsonValue()).toEqual([]) - expect(browserErrors).toEqual([]) - await violations.dispose() -}) diff --git a/e2e/react-start/css-modules/.gitignore b/e2e/react-start/css-modules/.gitignore index a1fbca128d..229709a89d 100644 --- a/e2e/react-start/css-modules/.gitignore +++ b/e2e/react-start/css-modules/.gitignore @@ -3,4 +3,3 @@ dist test-results playwright-report port*.txt -.cloudflare diff --git a/e2e/react-start/css-modules/cloudflare.config.ts b/e2e/react-start/css-modules/cloudflare.config.ts deleted file mode 100644 index e2bd5e13f1..0000000000 --- a/e2e/react-start/css-modules/cloudflare.config.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { defineConfig } from 'cf/config' - -// Used by rsbuild-plugin-cloudflare (E2E_RSBUILD_CLOUDFLARE=true). -// The Vite Cloudflare variant still reads wrangler.jsonc. -export default defineConfig({ - worker: { - name: 'tanstack-start-css-modules', - entrypoint: '@tanstack/react-start/server-entry', - compatibilityDate: '2026-11-01', - }, -}) diff --git a/e2e/react-start/css-modules/package.json b/e2e/react-start/css-modules/package.json index 25c11d7321..2591161d66 100644 --- a/e2e/react-start/css-modules/package.json +++ b/e2e/react-start/css-modules/package.json @@ -12,8 +12,6 @@ "dev:e2e:basepath": "VITE_BASE_PATH=/my-app vite dev --port $PORT", "dev:cloudflare": "echo 'Cloudflare dev mode has React duplication issues - use build+preview instead' && exit 1", "dev:e2e:cloudflare": "echo 'Cloudflare dev mode has React duplication issues - use build+preview instead' && exit 1", - "dev:e2e:rsbuild": "rsbuild dev --port $PORT", - "dev:e2e:rsbuild-cloudflare": "E2E_RSBUILD_CLOUDFLARE=true rsbuild dev --port $PORT", "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", @@ -21,16 +19,13 @@ "test:e2e:dev:nitro": "MODE=dev VITE_CONFIG=nitro playwright test --project=chromium", "test:e2e:dev:basepath": "MODE=dev VITE_CONFIG=basepath playwright test --project=chromium", "_test:e2e:dev:cloudflare": "MODE=dev VITE_CONFIG=cloudflare playwright test --project=chromium", - "test:e2e:dev:rsbuild": "MODE=dev VITE_CONFIG=rsbuild playwright test --project=chromium", - "test:e2e:dev:rsbuild-cloudflare": "MODE=dev VITE_CONFIG=rsbuild-cloudflare playwright test --project=chromium", "test:e2e:prod:default": "MODE=prod playwright test --project=chromium", "test:e2e:prod": "pnpm run test:e2e:prod:default && pnpm run test:e2e:prod:css-code-split-false", "test:e2e:prod:css-code-split-false": "MODE=prod VITE_CSS_CODE_SPLIT=false playwright test tests/css.prod.spec.ts --project=chromium", - "test:e2e": "pnpm run test:e2e:dev && pnpm run test:e2e:prod", - "test:e2e:nitro": "pnpm run test:e2e:dev:nitro", - "test:e2e:basepath": "pnpm run test:e2e:dev:basepath", - "_test:e2e:cloudflare": "echo 'Cloudflare dev mode disabled - React duplication issues' && exit 0", - "build:rsbuild": "rsbuild build && tsc --noEmit" + "test:e2e": "rm -rf port*.txt; pnpm run test:e2e:dev && pnpm run test:e2e:prod", + "test:e2e:nitro": "rm -rf port*.txt; pnpm run test:e2e:dev:nitro", + "test:e2e:basepath": "rm -rf port*.txt; pnpm run test:e2e:dev:basepath", + "_test:e2e:cloudflare": "echo 'Cloudflare dev mode disabled - React duplication issues' && exit 0" }, "dependencies": { "@tanstack/react-router": "workspace:*", @@ -41,36 +36,17 @@ "devDependencies": { "@cloudflare/vite-plugin": "^1.29.0", "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", - "@rsbuild/plugin-react": "^2.0.0", - "@rsbuild/plugin-sass": "^2.0.1", "@tanstack/router-e2e-utils": "workspace:*", "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@typescript/native": "npm:typescript@^7.0.2", "@vitejs/plugin-react": "^6.0.1", - "cf": "1.0.0-beta.28", - "nitro": "^3.0.260903-beta", - "rsbuild-plugin-cloudflare": "^0.0.4", + "nitro": "^3.0.260311-beta", "sass": "^1.97.2", - "srvx": "^1.0.0", + "srvx": "^0.11.9", + "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "wrangler": "^4.74.0" - }, - "nx": { - "metadata": { - "playwrightModes": [ - { - "toolchain": "vite", - "mode": "ssr" - }, - { - "toolchain": "rsbuild", - "mode": "ssr" - } - ] - } } } diff --git a/e2e/react-start/css-modules/playwright.config.ts b/e2e/react-start/css-modules/playwright.config.ts index 7e7ad3d9b3..644798ca99 100644 --- a/e2e/react-start/css-modules/playwright.config.ts +++ b/e2e/react-start/css-modules/playwright.config.ts @@ -1,41 +1,37 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } const mode = process.env.MODE ?? 'prod' const isDev = mode === 'dev' -const distDir = process.env.E2E_DIST_DIR const viteConfig = process.env.VITE_CONFIG // 'nitro' | 'basepath' | 'cloudflare' | undefined -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort( + viteConfig ? `${packageJson.name}-${viteConfig}` : packageJson.name, +) // When using basepath config, the app is served at /my-app const basePath = viteConfig === 'basepath' ? '/my-app' : '' const baseURL = `http://localhost:${PORT}${basePath}` // Select the appropriate dev command based on VITE_CONFIG -const devCommand = viteConfig - ? `pnpm dev:e2e:${viteConfig}` - : 'pnpm dev:e2e --port 0' +const devCommand = viteConfig ? `pnpm dev:e2e:${viteConfig}` : 'pnpm dev:e2e' export default defineConfig({ testDir: './tests', - testMatch: isDev ? '**/*.dev.spec.ts' : '**/*.prod.spec.ts', workers: 1, reporter: [['line']], globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', use: { baseURL, }, webServer: { - command: isDev - ? devCommand - : distDir - ? `pnpm exec srvx --prod --dir=. -s ${distDir}/client --entry ${distDir}/server/server.js` - : `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: isDev ? devCommand : `pnpm build && PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { VITE_NODE_ENV: 'test', diff --git a/e2e/react-start/css-modules/rsbuild.config.ts b/e2e/react-start/css-modules/rsbuild.config.ts deleted file mode 100644 index 499ed67ebc..0000000000 --- a/e2e/react-start/css-modules/rsbuild.config.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { defineConfig } from '@rsbuild/core' -import { pluginReact } from '@rsbuild/plugin-react' -import { pluginSass } from '@rsbuild/plugin-sass' -import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' -import { cloudflare } from 'rsbuild-plugin-cloudflare' - -// E2E_RSBUILD_CLOUDFLARE: Set to 'true' to run the SSR environment in workerd -const useCloudflare = process.env.E2E_RSBUILD_CLOUDFLARE === 'true' - -export default defineConfig({ - plugins: [ - pluginReact(), - pluginSass(), - ...(useCloudflare - ? [ - cloudflare({ - rsbuildEnvironment: { name: 'ssr' }, - inspectorPort: false, - }), - ] - : []), - tanstackStart(), - ], - output: { - distPath: { - root: process.env.E2E_DIST_DIR ?? 'dist-rsbuild-ssr', - }, - }, - tools: { - rspack(config, { environment }) { - if (environment.name === 'ssr') { - config.output ??= {} - config.output.filename = 'server.js' - } - if (environment.name !== 'client') { - return - } - config.optimization ??= {} - // Extract the shared component and its helper into their own chunks so - // a route depends on a shared chunk that depends on another shared chunk. - config.optimization.splitChunks = { - cacheGroups: { - sharedHeader: { - test: /[\\/]src[\\/]components[\\/]/, - chunks: 'async', - minChunks: 2, - minSize: 0, - enforce: true, - name: 'shared-header', - }, - sharedFormat: { - test: /[\\/]src[\\/]utils[\\/]/, - chunks: 'async', - minChunks: 2, - minSize: 0, - enforce: true, - name: 'shared-format', - }, - }, - } - }, - }, -}) diff --git a/e2e/react-start/css-modules/src/components/Header.module.css b/e2e/react-start/css-modules/src/components/Header.module.css deleted file mode 100644 index e6878a5410..0000000000 --- a/e2e/react-start/css-modules/src/components/Header.module.css +++ /dev/null @@ -1,14 +0,0 @@ -.header { - --repro-shared-header: 1; - display: grid; - grid-template-columns: minmax(0, 1fr) auto; - align-items: center; - height: 64px; - padding-inline: 16px; - background: #e4f2e9; -} - -.header h1 { - margin: 0; - font-size: 24px; -} diff --git a/e2e/react-start/css-modules/src/components/Header.tsx b/e2e/react-start/css-modules/src/components/Header.tsx deleted file mode 100644 index f16b12e8ff..0000000000 --- a/e2e/react-start/css-modules/src/components/Header.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { formatTitle } from '../utils/formatTitle' -import styles from './Header.module.css' - -export function Header({ title }: { title: string }) { - return ( -
-

{formatTitle(title)}

- -
- ) -} diff --git a/e2e/react-start/css-modules/src/routeTree.gen.ts b/e2e/react-start/css-modules/src/routeTree.gen.ts index 2789a3490a..822118990d 100644 --- a/e2e/react-start/css-modules/src/routeTree.gen.ts +++ b/e2e/react-start/css-modules/src/routeTree.gen.ts @@ -10,9 +10,6 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as AlphaRouteImport } from './routes/alpha' -import { Route as BetaRouteImport } from './routes/beta' -import { Route as GammaRouteImport } from './routes/gamma' import { Route as ModulesRouteImport } from './routes/modules' import { Route as QuotesRouteImport } from './routes/quotes' import { Route as SassMixinRouteImport } from './routes/sass-mixin' @@ -22,21 +19,6 @@ const IndexRoute = IndexRouteImport.update({ path: '/', getParentRoute: () => rootRouteImport, } as any) -const AlphaRoute = AlphaRouteImport.update({ - id: '/alpha', - path: '/alpha', - getParentRoute: () => rootRouteImport, -} as any) -const BetaRoute = BetaRouteImport.update({ - id: '/beta', - path: '/beta', - getParentRoute: () => rootRouteImport, -} as any) -const GammaRoute = GammaRouteImport.update({ - id: '/gamma', - path: '/gamma', - getParentRoute: () => rootRouteImport, -} as any) const ModulesRoute = ModulesRouteImport.update({ id: '/modules', path: '/modules', @@ -55,18 +37,12 @@ const SassMixinRoute = SassMixinRouteImport.update({ export interface FileRoutesByFullPath { '/': typeof IndexRoute - '/alpha': typeof AlphaRoute - '/beta': typeof BetaRoute - '/gamma': typeof GammaRoute '/modules': typeof ModulesRoute '/quotes': typeof QuotesRoute '/sass-mixin': typeof SassMixinRoute } export interface FileRoutesByTo { '/': typeof IndexRoute - '/alpha': typeof AlphaRoute - '/beta': typeof BetaRoute - '/gamma': typeof GammaRoute '/modules': typeof ModulesRoute '/quotes': typeof QuotesRoute '/sass-mixin': typeof SassMixinRoute @@ -74,36 +50,20 @@ export interface FileRoutesByTo { export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute - '/alpha': typeof AlphaRoute - '/beta': typeof BetaRoute - '/gamma': typeof GammaRoute '/modules': typeof ModulesRoute '/quotes': typeof QuotesRoute '/sass-mixin': typeof SassMixinRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - '/' | '/alpha' | '/beta' | '/gamma' | '/modules' | '/quotes' | '/sass-mixin' + fullPaths: '/' | '/modules' | '/quotes' | '/sass-mixin' fileRoutesByTo: FileRoutesByTo - to: - '/' | '/alpha' | '/beta' | '/gamma' | '/modules' | '/quotes' | '/sass-mixin' - id: - | '__root__' - | '/' - | '/alpha' - | '/beta' - | '/gamma' - | '/modules' - | '/quotes' - | '/sass-mixin' + to: '/' | '/modules' | '/quotes' | '/sass-mixin' + id: '__root__' | '/' | '/modules' | '/quotes' | '/sass-mixin' fileRoutesById: FileRoutesById } export interface RootRouteChildren { IndexRoute: typeof IndexRoute - AlphaRoute: typeof AlphaRoute - BetaRoute: typeof BetaRoute - GammaRoute: typeof GammaRoute ModulesRoute: typeof ModulesRoute QuotesRoute: typeof QuotesRoute SassMixinRoute: typeof SassMixinRoute @@ -118,27 +78,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/alpha': { - id: '/alpha' - path: '/alpha' - fullPath: '/alpha' - preLoaderRoute: typeof AlphaRouteImport - parentRoute: typeof rootRouteImport - } - '/beta': { - id: '/beta' - path: '/beta' - fullPath: '/beta' - preLoaderRoute: typeof BetaRouteImport - parentRoute: typeof rootRouteImport - } - '/gamma': { - id: '/gamma' - path: '/gamma' - fullPath: '/gamma' - preLoaderRoute: typeof GammaRouteImport - parentRoute: typeof rootRouteImport - } '/modules': { id: '/modules' path: '/modules' @@ -165,9 +104,6 @@ declare module '@tanstack/react-router' { const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, - AlphaRoute: AlphaRoute, - BetaRoute: BetaRoute, - GammaRoute: GammaRoute, ModulesRoute: ModulesRoute, QuotesRoute: QuotesRoute, SassMixinRoute: SassMixinRoute, diff --git a/e2e/react-start/css-modules/src/routes/alpha.tsx b/e2e/react-start/css-modules/src/routes/alpha.tsx deleted file mode 100644 index e894cd758f..0000000000 --- a/e2e/react-start/css-modules/src/routes/alpha.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { Header } from '../components/Header' -import styles from '../styles/alpha.module.css' - -export const Route = createFileRoute('/alpha')({ component: Alpha }) - -function Alpha() { - return ( -
-
-
- ) -} diff --git a/e2e/react-start/css-modules/src/routes/beta.tsx b/e2e/react-start/css-modules/src/routes/beta.tsx deleted file mode 100644 index 4f139ac41a..0000000000 --- a/e2e/react-start/css-modules/src/routes/beta.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { Header } from '../components/Header' -import styles from '../styles/beta.module.css' - -export const Route = createFileRoute('/beta')({ component: Beta }) - -function Beta() { - return ( -
-
-
- ) -} diff --git a/e2e/react-start/css-modules/src/routes/gamma.tsx b/e2e/react-start/css-modules/src/routes/gamma.tsx deleted file mode 100644 index a8e036b85f..0000000000 --- a/e2e/react-start/css-modules/src/routes/gamma.tsx +++ /dev/null @@ -1,8 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { formatTitle } from '../utils/formatTitle' - -export const Route = createFileRoute('/gamma')({ component: Gamma }) - -function Gamma() { - return
{formatTitle('Gamma')}
-} diff --git a/e2e/react-start/css-modules/src/styles/alpha.module.css b/e2e/react-start/css-modules/src/styles/alpha.module.css deleted file mode 100644 index 12a606a8d3..0000000000 --- a/e2e/react-start/css-modules/src/styles/alpha.module.css +++ /dev/null @@ -1,4 +0,0 @@ -.page { - --repro-alpha: 1; - border: 4px solid #226844; -} diff --git a/e2e/react-start/css-modules/src/styles/beta.module.css b/e2e/react-start/css-modules/src/styles/beta.module.css deleted file mode 100644 index 719686a76b..0000000000 --- a/e2e/react-start/css-modules/src/styles/beta.module.css +++ /dev/null @@ -1,4 +0,0 @@ -.page { - --repro-beta: 1; - border: 4px solid #ac344c; -} diff --git a/e2e/react-start/css-modules/src/utils/formatTitle.ts b/e2e/react-start/css-modules/src/utils/formatTitle.ts deleted file mode 100644 index d0325ac63e..0000000000 --- a/e2e/react-start/css-modules/src/utils/formatTitle.ts +++ /dev/null @@ -1,3 +0,0 @@ -export function formatTitle(title: string) { - return `${title} (repro-format-title)` -} diff --git a/e2e/react-start/css-modules/tests/setup/global.setup.ts b/e2e/react-start/css-modules/tests/setup/global.setup.ts index 7c0fce762a..e8879c0165 100644 --- a/e2e/react-start/css-modules/tests/setup/global.setup.ts +++ b/e2e/react-start/css-modules/tests/setup/global.setup.ts @@ -1,10 +1,20 @@ -import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' +import { + e2eStartDummyServer, + getTestServerPort, + preOptimizeDevServer, + waitForServer, +} from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } export default async function setup() { + await e2eStartDummyServer(packageJson.name) + if (process.env.MODE !== 'dev') return const viteConfig = process.env.VITE_CONFIG // 'nitro' | 'basepath' | 'cloudflare' | undefined - const port = Number(process.env.E2E_APP_PORT ?? 0) + const port = await getTestServerPort( + viteConfig ? `${packageJson.name}-${viteConfig}` : packageJson.name, + ) const basePath = viteConfig === 'basepath' ? '/my-app' : '' const baseURL = `http://localhost:${port}${basePath}` diff --git a/e2e/react-start/css-modules/tests/setup/global.teardown.ts b/e2e/react-start/css-modules/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-start/css-modules/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-start/css-modules/tests/shared-css.prod.spec.ts b/e2e/react-start/css-modules/tests/shared-css.prod.spec.ts deleted file mode 100644 index 9a9595f819..0000000000 --- a/e2e/react-start/css-modules/tests/shared-css.prod.spec.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' -import type { Page } from '@playwright/test' - -test.skip( - process.env.VITE_CSS_CODE_SPLIT === 'false', - 'Route stylesheet isolation requires CSS code splitting', -) -test.use({ javaScriptEnabled: false }) - -async function getStylesheetContent(page: Page) { - const hrefs = await page - .locator('link[rel="stylesheet"]') - .evaluateAll((links: Array) => - links.map((link) => link.href), - ) - expect(hrefs.length).toBeGreaterThan(0) - const stylesheets = await Promise.all( - hrefs.map(async (href) => { - const response = await page.request.get(href) - expect(response.ok()).toBe(true) - return response.text() - }), - ) - return stylesheets.join('\n') -} - -for (const route of ['alpha', 'beta']) { - test(`${route} has complete and isolated CSS without JavaScript`, async ({ - page, - }) => { - await page.goto(`/${route}`) - - const header = page.getByTestId('shared-header') - await expect(header).toHaveCSS('display', 'grid') - await expect(header).toHaveCSS('height', '64px') - await expect(page.getByTestId('route-page')).toHaveCSS( - `--repro-${route}`, - '1', - ) - - const css = await getStylesheetContent(page) - expect(css).toContain('--repro-shared-header') - expect(css).toContain(`--repro-${route}`) - expect(css).not.toContain(`--repro-${route === 'alpha' ? 'beta' : 'alpha'}`) - }) -} - -function getScriptPreloadHrefs(html: string) { - return Array.from(html.matchAll(/]*>/g), (match) => match[0]) - .filter( - (tag) => - /\brel="modulepreload"/.test(tag) || - (/\brel="preload"/.test(tag) && /\bas="script"/.test(tag)), - ) - .map((tag) => tag.match(/\bhref="([^"]+)"/)?.[1]) - .filter((href): href is string => !!href) -} - -test('alpha preloads the shared header chunk and the chunk it depends on', async ({ - page, -}) => { - const response = await page.request.get('/alpha') - expect(response.ok()).toBe(true) - - const hrefs = getScriptPreloadHrefs(await response.text()) - expect(hrefs.length).toBeGreaterThan(0) - - const scripts = await Promise.all( - hrefs.map(async (href) => { - const script = await page.request.get(href) - expect(script.ok()).toBe(true) - return script.text() - }), - ) - - expect(scripts.some((code) => code.includes('shared-header'))).toBe(true) - expect(scripts.some((code) => code.includes('repro-format-title'))).toBe(true) -}) - -test('home does not load the shared header or route styles', async ({ - page, -}) => { - await page.goto('/') - await expect(page.getByTestId('global-styled')).toHaveCSS( - 'background-color', - 'rgb(59, 130, 246)', - ) - - const css = await getStylesheetContent(page) - expect(css).not.toContain('--repro-shared-header') - expect(css).not.toContain('--repro-alpha') - expect(css).not.toContain('--repro-beta') -}) diff --git a/e2e/react-start/css-modules/vite.config.ts b/e2e/react-start/css-modules/vite.config.ts index c9c27f7f9a..9923ab3384 100644 --- a/e2e/react-start/css-modules/vite.config.ts +++ b/e2e/react-start/css-modules/vite.config.ts @@ -21,7 +21,6 @@ export default defineConfig(async () => { port: 3000, }, build: { - outDir: process.env.E2E_DIST_DIR ?? 'dist', cssCodeSplit, }, plugins: [ diff --git a/e2e/react-start/custom-basepath/express-server.ts b/e2e/react-start/custom-basepath/express-server.ts index b9bf393466..1884c5eb5a 100644 --- a/e2e/react-start/custom-basepath/express-server.ts +++ b/e2e/react-start/custom-basepath/express-server.ts @@ -1,6 +1,5 @@ import express from 'express' import { toNodeHandler } from 'srvx/node' -import type { AddressInfo } from 'node:net' import type { NodeHttp1Handler } from 'srvx' const DEVELOPMENT = process.env.NODE_ENV === 'development' @@ -41,11 +40,7 @@ if (DEVELOPMENT) { }) } -const httpServer = app.listen(PORT, (error) => { - if (error) { - throw error - } - console.log( - `E2E app: http://localhost:${(httpServer.address() as AddressInfo).port}`, - ) +app.listen(PORT, (error) => { + if (error) throw error + console.log(`Server is running on http://localhost:${PORT}`) }) diff --git a/e2e/react-start/custom-basepath/package.json b/e2e/react-start/custom-basepath/package.json index e93949eea2..f665ba0598 100644 --- a/e2e/react-start/custom-basepath/package.json +++ b/e2e/react-start/custom-basepath/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "tsx express-server.ts", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -29,7 +29,7 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "cross-env": "^10.0.0", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "tsx": "^4.20.3", "@typescript/native": "npm:typescript@^7.0.2", diff --git a/e2e/react-start/custom-basepath/playwright.config.ts b/e2e/react-start/custom-basepath/playwright.config.ts index e113ce64ad..5095425f47 100644 --- a/e2e/react-start/custom-basepath/playwright.config.ts +++ b/e2e/react-start/custom-basepath/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}/custom/basepath` /** @@ -13,19 +18,19 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', - env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, - }, }, projects: [ diff --git a/e2e/react-start/custom-basepath/src/routes/api.users.ts b/e2e/react-start/custom-basepath/src/routes/api.users.ts index 6fc8cde830..9e055549ef 100644 --- a/e2e/react-start/custom-basepath/src/routes/api.users.ts +++ b/e2e/react-start/custom-basepath/src/routes/api.users.ts @@ -3,7 +3,11 @@ import axios from 'redaxios' import type { User } from '~/utils/users' -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const Route = createFileRoute('/api/users')({ server: { diff --git a/e2e/react-start/custom-basepath/src/routes/api/users.$id.ts b/e2e/react-start/custom-basepath/src/routes/api/users.$id.ts index 81c071afb5..57682660fd 100644 --- a/e2e/react-start/custom-basepath/src/routes/api/users.$id.ts +++ b/e2e/react-start/custom-basepath/src/routes/api/users.$id.ts @@ -2,7 +2,11 @@ import axios from 'redaxios' import type { User } from '~/utils/users' import { createFileRoute } from '@tanstack/react-router' -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const Route = createFileRoute('/api/users/$id')({ server: { diff --git a/e2e/react-start/custom-basepath/src/utils/posts.tsx b/e2e/react-start/custom-basepath/src/utils/posts.tsx index d9b98a8c9c..4cc5dcc4c6 100644 --- a/e2e/react-start/custom-basepath/src/utils/posts.tsx +++ b/e2e/react-start/custom-basepath/src/utils/posts.tsx @@ -8,7 +8,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = createServerFn({ method: 'GET' }) .validator((postId: string) => postId) diff --git a/e2e/react-start/custom-basepath/src/utils/users.tsx b/e2e/react-start/custom-basepath/src/utils/users.tsx index 7ba645b383..46be4b1580 100644 --- a/e2e/react-start/custom-basepath/src/utils/users.tsx +++ b/e2e/react-start/custom-basepath/src/utils/users.tsx @@ -3,3 +3,7 @@ export type User = { name: string email: string } + +const PORT = process.env.VITE_SERVER_PORT || 3000 + +export const DEPLOY_URL = `http://localhost:${PORT}` diff --git a/e2e/react-start/custom-basepath/tests/setup/global.setup.ts b/e2e/react-start/custom-basepath/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-start/custom-basepath/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-start/custom-basepath/tests/setup/global.teardown.ts b/e2e/react-start/custom-basepath/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-start/custom-basepath/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-start/custom-server-rsbuild/express-server.ts b/e2e/react-start/custom-server-rsbuild/express-server.ts index 68537956b4..23784f2efc 100644 --- a/e2e/react-start/custom-server-rsbuild/express-server.ts +++ b/e2e/react-start/custom-server-rsbuild/express-server.ts @@ -1,6 +1,5 @@ import express from 'express' import { toNodeHandler } from 'srvx/node' -import type { AddressInfo } from 'node:net' import type { NodeHttp1Handler } from 'srvx' const DEVELOPMENT = process.env.NODE_ENV === 'development' @@ -59,13 +58,9 @@ if (DEVELOPMENT) { }) const httpServer = app.listen(PORT, async (error) => { - if (error) { - throw error - } + if (error) throw error await devServer.afterListen() - console.log( - `E2E app: http://localhost:${(httpServer.address() as AddressInfo).port}`, - ) + console.log(`Server is running on http://localhost:${PORT}`) }) devServer.connectWebSocket({ server: httpServer }) } else { @@ -80,12 +75,8 @@ if (DEVELOPMENT) { next(error) } }) - const httpServer = app.listen(PORT, (error) => { - if (error) { - throw error - } - console.log( - `E2E app: http://localhost:${(httpServer.address() as AddressInfo).port}`, - ) + app.listen(PORT, (error) => { + if (error) throw error + console.log(`Server is running on http://localhost:${PORT}`) }) } diff --git a/e2e/react-start/custom-server-rsbuild/package.json b/e2e/react-start/custom-server-rsbuild/package.json index 1c5b3af393..865e424daa 100644 --- a/e2e/react-start/custom-server-rsbuild/package.json +++ b/e2e/react-start/custom-server-rsbuild/package.json @@ -10,7 +10,7 @@ "start": "tsx express-server.ts", "test:e2e:dev": "cross-env MODE=dev playwright test --project=chromium", "test:e2e:prod": "cross-env MODE=prod playwright test --project=chromium", - "test:e2e": "pnpm run test:e2e:dev && pnpm run test:e2e:prod" + "test:e2e": "rm -rf port*.txt && pnpm run test:e2e:dev && pnpm run test:e2e:prod" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -21,7 +21,7 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-react": "^2.0.0", "@tailwindcss/postcss": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", @@ -30,7 +30,7 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "cross-env": "^10.0.0", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "tsx": "^4.20.3", "@typescript/native": "npm:typescript@^7.0.2", diff --git a/e2e/react-start/custom-server-rsbuild/playwright.config.ts b/e2e/react-start/custom-server-rsbuild/playwright.config.ts index f0542500fd..eb8b43f648 100644 --- a/e2e/react-start/custom-server-rsbuild/playwright.config.ts +++ b/e2e/react-start/custom-server-rsbuild/playwright.config.ts @@ -1,9 +1,11 @@ import { defineConfig, devices } from '@playwright/test' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } const mode = process.env.MODE ?? 'prod' const isDev = mode === 'dev' -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(`${packageJson.name}-${mode}`) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -13,8 +15,8 @@ export default defineConfig({ use: { baseURL }, webServer: { command: isDev ? 'pnpm dev:e2e' : 'pnpm build && pnpm start', - wait: { stdout: /E2E app: http:\/\/localhost:(?\d+)/ }, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { PORT: String(PORT), diff --git a/e2e/react-start/deferred-hydration/package.json b/e2e/react-start/deferred-hydration/package.json index 5a33407435..fb8a99c8e3 100644 --- a/e2e/react-start/deferred-hydration/package.json +++ b/e2e/react-start/deferred-hydration/package.json @@ -26,14 +26,14 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-react": "^2.0.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" @@ -42,12 +42,6 @@ "targets": { "test:e2e": { "parallelism": false - }, - "build": { - "outputs": [ - "...", - "{projectRoot}/dist-vite-ssr" - ] } }, "metadata": { diff --git a/e2e/react-start/deferred-hydration/playwright.config.ts b/e2e/react-start/deferred-hydration/playwright.config.ts index d88c59fc9d..0125792d4b 100644 --- a/e2e/react-start/deferred-hydration/playwright.config.ts +++ b/e2e/react-start/deferred-hydration/playwright.config.ts @@ -1,9 +1,12 @@ +import fs from 'node:fs' import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' const distDir = process.env.E2E_DIST_DIR ?? `dist-${toolchain}-ssr` - +const e2ePortKey = + process.env.E2E_PORT_KEY ?? `${packageJson.name}-${toolchain}` const mode = process.env.MODE ?? 'prod' const isDev = mode === 'dev' const serverEntryFile = toolchain === 'rsbuild' ? 'index.js' : 'server.js' @@ -11,7 +14,11 @@ const startCommand = `pnpm exec srvx --prod --dir=. -s ${distDir}/client --entry const devCommand = toolchain === 'rsbuild' ? 'pnpm dev:rsbuild' : 'pnpm dev:vite' -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +if (process.env.TEST_WORKER_INDEX === undefined) { + fs.rmSync(`port-${e2ePortKey}.txt`, { force: true }) +} + +const PORT = await getTestServerPort(e2ePortKey) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -19,11 +26,12 @@ export default defineConfig({ workers: 1, reporter: [['line']], globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', use: { baseURL }, webServer: { command: isDev ? `${devCommand} --port ${PORT}` : startCommand, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { E2E_DIST_DIR: distDir, @@ -32,6 +40,7 @@ export default defineConfig({ PORT: String(PORT), VITE_SERVER_PORT: String(PORT), E2E_TOOLCHAIN: toolchain, + E2E_PORT_KEY: e2ePortKey, }, }, projects: [ diff --git a/e2e/react-start/deferred-hydration/tests/setup/global.setup.ts b/e2e/react-start/deferred-hydration/tests/setup/global.setup.ts index 704bbef3e2..1117664a14 100644 --- a/e2e/react-start/deferred-hydration/tests/setup/global.setup.ts +++ b/e2e/react-start/deferred-hydration/tests/setup/global.setup.ts @@ -1,11 +1,24 @@ -import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' +import { + e2eStartDummyServer, + getTestServerPort, + preOptimizeDevServer, + waitForServer, +} from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +function getE2EPortKey() { + const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' + return process.env.E2E_PORT_KEY ?? `${packageJson.name}-${toolchain}` +} export default async function setup() { - if (process.env.MODE !== 'dev') { - return - } + if (process.env.MODE !== 'dev') return - const port = Number(process.env.E2E_APP_PORT ?? 0) + const e2ePortKey = getE2EPortKey() + + await e2eStartDummyServer(e2ePortKey) + + const port = await getTestServerPort(e2ePortKey) const baseURL = `http://localhost:${port}` await waitForServer(baseURL) diff --git a/e2e/react-start/deferred-hydration/tests/setup/global.teardown.ts b/e2e/react-start/deferred-hydration/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..df79f50e82 --- /dev/null +++ b/e2e/react-start/deferred-hydration/tests/setup/global.teardown.ts @@ -0,0 +1,13 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +function getE2EPortKey() { + const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' + return process.env.E2E_PORT_KEY ?? `${packageJson.name}-${toolchain}` +} + +export default async function teardown() { + if (process.env.MODE !== 'dev') return + + await e2eStopDummyServer(getE2EPortKey()) +} diff --git a/e2e/react-start/dev-ssr-styles/package.json b/e2e/react-start/dev-ssr-styles/package.json index a5300e836e..c9c14943d4 100644 --- a/e2e/react-start/dev-ssr-styles/package.json +++ b/e2e/react-start/dev-ssr-styles/package.json @@ -22,9 +22,13 @@ "test:e2e:dev:nitro": "MODE=dev VITE_USE_NITRO=true playwright test --project=chromium", "test:e2e:dev:disabled:nitro": "MODE=dev SSR_STYLES=disabled VITE_USE_NITRO=true playwright test --project=chromium", "test:e2e:dev:custom-basepath:nitro": "MODE=dev SSR_STYLES=custom-basepath VITE_USE_NITRO=true playwright test --project=chromium", + "test:e2e:dev:bundled-dev:nitro": "MODE=dev VITE_USE_NITRO=true E2E_VITE_BUNDLED_DEV=true playwright test --project=chromium", + "test:e2e:dev:disabled:bundled-dev:nitro": "MODE=dev SSR_STYLES=disabled VITE_USE_NITRO=true E2E_VITE_BUNDLED_DEV=true playwright test --project=chromium", + "test:e2e:dev:custom-basepath:bundled-dev:nitro": "MODE=dev SSR_STYLES=custom-basepath VITE_USE_NITRO=true E2E_VITE_BUNDLED_DEV=true playwright test --project=chromium", "test:e2e:bundled-dev": "pnpm run test:e2e:dev:bundled-dev && pnpm run test:e2e:dev:disabled:bundled-dev && pnpm run test:e2e:dev:custom-basepath:bundled-dev", - "test:e2e": "pnpm run test:e2e:dev && pnpm run test:e2e:dev:disabled && pnpm run test:e2e:dev:custom-basepath && pnpm run test:e2e:bundled-dev", - "test:e2e:nitro": "pnpm run test:e2e:dev:nitro && pnpm run test:e2e:dev:disabled:nitro && pnpm run test:e2e:dev:custom-basepath:nitro" + "test:e2e:nitro:bundled-dev": "pnpm run test:e2e:dev:bundled-dev:nitro && pnpm run test:e2e:dev:disabled:bundled-dev:nitro && pnpm run test:e2e:dev:custom-basepath:bundled-dev:nitro", + "test:e2e": "rm -rf port*.txt; pnpm run test:e2e:dev && pnpm run test:e2e:dev:disabled && pnpm run test:e2e:dev:custom-basepath && pnpm run test:e2e:bundled-dev", + "test:e2e:nitro": "rm -rf port*.txt; pnpm run test:e2e:dev:nitro && pnpm run test:e2e:dev:disabled:nitro && pnpm run test:e2e:dev:custom-basepath:nitro && pnpm run test:e2e:nitro:bundled-dev" }, "dependencies": { "@tanstack/react-router": "workspace:*", @@ -40,8 +44,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "nitro": "^3.0.260903-beta", - "srvx": "^1.0.0", + "nitro": "^3.0.260311-beta", + "srvx": "^0.11.9", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", diff --git a/e2e/react-start/dev-ssr-styles/playwright.config.ts b/e2e/react-start/dev-ssr-styles/playwright.config.ts index 71cc8ed2da..a1fdd7c3ef 100644 --- a/e2e/react-start/dev-ssr-styles/playwright.config.ts +++ b/e2e/react-start/dev-ssr-styles/playwright.config.ts @@ -1,5 +1,6 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } import { ssrStylesMode, useNitro, viteBundledDev } from './env' const mode = process.env.MODE ?? 'prod' @@ -8,13 +9,24 @@ const isDev = mode === 'dev' // Build a unique port key per dimension combination (ssrStyles mode + nitro) // e.g. "...dev-ssr-styles", "...dev-ssr-styles-disabled", "...dev-ssr-styles-nitro", // "...dev-ssr-styles-disabled-nitro" +function getPortKey() { + let key = packageJson.name + if (ssrStylesMode !== 'default') { + key += `-${ssrStylesMode}` + } + if (useNitro) { + key += '-nitro' + } + if (viteBundledDev) { + key += '-bundled-dev' + } + return key +} -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(getPortKey()) const baseURL = `http://localhost:${PORT}` // Select the appropriate dev command based on SSR_STYLES + VITE_USE_NITRO -// package.json omits bundled Nitro runs because its asset plugin produces -// invalid Vite client code. Re-enable those tests once the upstream fix lands. function getDevCommand() { const scriptParts = ['dev:e2e'] if (ssrStylesMode !== 'default') { @@ -32,6 +44,7 @@ export default defineConfig({ reporter: [['line']], globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', use: { baseURL, @@ -39,8 +52,8 @@ export default defineConfig({ webServer: { command: isDev ? getDevCommand() : `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { VITE_NODE_ENV: 'test', diff --git a/e2e/react-start/dev-ssr-styles/src/components/CodeSplitStyledBox.tsx b/e2e/react-start/dev-ssr-styles/src/components/CodeSplitStyledBox.tsx deleted file mode 100644 index 49d2f96c39..0000000000 --- a/e2e/react-start/dev-ssr-styles/src/components/CodeSplitStyledBox.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import styles from '../styles/code-split-route.module.css' - -export function CodeSplitStyledBox() { - return ( -
- This box should have a blue background when dev styles are enabled. -
- ) -} diff --git a/e2e/react-start/dev-ssr-styles/src/routeTree.gen.ts b/e2e/react-start/dev-ssr-styles/src/routeTree.gen.ts index 96c0a37142..dceedffdc1 100644 --- a/e2e/react-start/dev-ssr-styles/src/routeTree.gen.ts +++ b/e2e/react-start/dev-ssr-styles/src/routeTree.gen.ts @@ -10,63 +10,33 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as CssImportOrderRouteImport } from './routes/css-import-order' -import { Route as InlineCssRouteImport } from './routes/inline-css' -import { Route as ModuleStateRouteImport } from './routes/module-state' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const CssImportOrderRoute = CssImportOrderRouteImport.update({ - id: '/css-import-order', - path: '/css-import-order', - getParentRoute: () => rootRouteImport, -} as any) -const InlineCssRoute = InlineCssRouteImport.update({ - id: '/inline-css', - path: '/inline-css', - getParentRoute: () => rootRouteImport, -} as any) -const ModuleStateRoute = ModuleStateRouteImport.update({ - id: '/module-state', - path: '/module-state', - getParentRoute: () => rootRouteImport, -} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute - '/css-import-order': typeof CssImportOrderRoute - '/inline-css': typeof InlineCssRoute - '/module-state': typeof ModuleStateRoute } export interface FileRoutesByTo { '/': typeof IndexRoute - '/css-import-order': typeof CssImportOrderRoute - '/inline-css': typeof InlineCssRoute - '/module-state': typeof ModuleStateRoute } export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute - '/css-import-order': typeof CssImportOrderRoute - '/inline-css': typeof InlineCssRoute - '/module-state': typeof ModuleStateRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/css-import-order' | '/inline-css' | '/module-state' + fullPaths: '/' fileRoutesByTo: FileRoutesByTo - to: '/' | '/css-import-order' | '/inline-css' | '/module-state' - id: '__root__' | '/' | '/css-import-order' | '/inline-css' | '/module-state' + to: '/' + id: '__root__' | '/' fileRoutesById: FileRoutesById } export interface RootRouteChildren { IndexRoute: typeof IndexRoute - CssImportOrderRoute: typeof CssImportOrderRoute - InlineCssRoute: typeof InlineCssRoute - ModuleStateRoute: typeof ModuleStateRoute } declare module '@tanstack/react-router' { @@ -78,35 +48,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/css-import-order': { - id: '/css-import-order' - path: '/css-import-order' - fullPath: '/css-import-order' - preLoaderRoute: typeof CssImportOrderRouteImport - parentRoute: typeof rootRouteImport - } - '/inline-css': { - id: '/inline-css' - path: '/inline-css' - fullPath: '/inline-css' - preLoaderRoute: typeof InlineCssRouteImport - parentRoute: typeof rootRouteImport - } - '/module-state': { - id: '/module-state' - path: '/module-state' - fullPath: '/module-state' - preLoaderRoute: typeof ModuleStateRouteImport - parentRoute: typeof rootRouteImport - } } } const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, - CssImportOrderRoute: CssImportOrderRoute, - InlineCssRoute: InlineCssRoute, - ModuleStateRoute: ModuleStateRoute, } export const routeTree = rootRouteImport ._addFileChildren(rootRouteChildren) diff --git a/e2e/react-start/dev-ssr-styles/src/routes/css-import-order.tsx b/e2e/react-start/dev-ssr-styles/src/routes/css-import-order.tsx deleted file mode 100644 index 345254bb8c..0000000000 --- a/e2e/react-start/dev-ssr-styles/src/routes/css-import-order.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import '../styles/css-import-order.css' - -export const Route = createFileRoute('/css-import-order')({ - component: CssImportOrder, -}) - -function CssImportOrder() { - return ( -
-

CSS import order

-
- The route stylesheet should override its imported base stylesheet. -
-
- ) -} diff --git a/e2e/react-start/dev-ssr-styles/src/routes/index.tsx b/e2e/react-start/dev-ssr-styles/src/routes/index.tsx index 62fb237750..f5fadf464d 100644 --- a/e2e/react-start/dev-ssr-styles/src/routes/index.tsx +++ b/e2e/react-start/dev-ssr-styles/src/routes/index.tsx @@ -1,5 +1,4 @@ import { createFileRoute } from '@tanstack/react-router' -import { CodeSplitStyledBox } from '../components/CodeSplitStyledBox' export const Route = createFileRoute('/')({ component: Home, @@ -9,7 +8,9 @@ function Home() { return (

Dev SSR Styles Test

- +
+ This box should have a blue background when dev styles are enabled. +
) } diff --git a/e2e/react-start/dev-ssr-styles/src/routes/inline-css.tsx b/e2e/react-start/dev-ssr-styles/src/routes/inline-css.tsx deleted file mode 100644 index ffc59128e0..0000000000 --- a/e2e/react-start/dev-ssr-styles/src/routes/inline-css.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import embeddedCss from '../styles/embedded.css?inline' - -export const Route = createFileRoute('/inline-css')({ - loader: () => embeddedCss, - component: InlineCss, -}) - -function InlineCss() { - const css = Route.useLoaderData() - return ( -
-
- Inline styles must not change the page layout. -
-
{css}
-
- ) -} diff --git a/e2e/react-start/dev-ssr-styles/src/routes/module-state.ts b/e2e/react-start/dev-ssr-styles/src/routes/module-state.ts deleted file mode 100644 index 546217efc3..0000000000 --- a/e2e/react-start/dev-ssr-styles/src/routes/module-state.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -const instanceId = crypto.randomUUID() - -export const Route = createFileRoute('/module-state')({ - server: { - handlers: { - GET: () => new Response(instanceId), - }, - }, -}) diff --git a/e2e/react-start/dev-ssr-styles/src/styles/app.css b/e2e/react-start/dev-ssr-styles/src/styles/app.css index 4285da0c86..06b48f8a7c 100644 --- a/e2e/react-start/dev-ssr-styles/src/styles/app.css +++ b/e2e/react-start/dev-ssr-styles/src/styles/app.css @@ -5,10 +5,9 @@ body { background-color: #f0f4f8; } -@layer utilities { - .inline-css-layout { - margin: 12px; - padding: 24px; - border: 3px solid black; - } +.styled-box { + background-color: #3b82f6; + color: white; + padding: 24px; + border-radius: 12px; } diff --git a/e2e/react-start/dev-ssr-styles/src/styles/code-split-route.module.css b/e2e/react-start/dev-ssr-styles/src/styles/code-split-route.module.css deleted file mode 100644 index d6a50211ee..0000000000 --- a/e2e/react-start/dev-ssr-styles/src/styles/code-split-route.module.css +++ /dev/null @@ -1,7 +0,0 @@ -.styledBox { - background-color: #3b82f6; - background-image: url('./ssr-background.svg?no-inline'); - color: white; - padding: 24px; - border-radius: 12px; -} diff --git a/e2e/react-start/dev-ssr-styles/src/styles/css-import-base.css b/e2e/react-start/dev-ssr-styles/src/styles/css-import-base.css deleted file mode 100644 index 4f73ddab9c..0000000000 --- a/e2e/react-start/dev-ssr-styles/src/styles/css-import-base.css +++ /dev/null @@ -1,5 +0,0 @@ -.css-import-order { - --css-import-base-marker: issue-7794; - background-color: #ffffff; - color: #000000; -} diff --git a/e2e/react-start/dev-ssr-styles/src/styles/css-import-order.css b/e2e/react-start/dev-ssr-styles/src/styles/css-import-order.css deleted file mode 100644 index afcb4797d9..0000000000 --- a/e2e/react-start/dev-ssr-styles/src/styles/css-import-order.css +++ /dev/null @@ -1,7 +0,0 @@ -@import './css-import-base.css'; - -.css-import-order { - background-color: #111827; - color: #ffffff; - padding: 24px; -} diff --git a/e2e/react-start/dev-ssr-styles/src/styles/embedded-preflight.css b/e2e/react-start/dev-ssr-styles/src/styles/embedded-preflight.css deleted file mode 100644 index 13810d6c98..0000000000 --- a/e2e/react-start/dev-ssr-styles/src/styles/embedded-preflight.css +++ /dev/null @@ -1,6 +0,0 @@ -* { - --embedded-preflight-marker: 1; - margin: 0; - padding: 0; - border: 0 solid; -} diff --git a/e2e/react-start/dev-ssr-styles/src/styles/embedded-theme.css b/e2e/react-start/dev-ssr-styles/src/styles/embedded-theme.css deleted file mode 100644 index 171ed5e174..0000000000 --- a/e2e/react-start/dev-ssr-styles/src/styles/embedded-theme.css +++ /dev/null @@ -1,3 +0,0 @@ -:root { - --embedded-theme-marker: 1; -} diff --git a/e2e/react-start/dev-ssr-styles/src/styles/embedded-utilities.css b/e2e/react-start/dev-ssr-styles/src/styles/embedded-utilities.css deleted file mode 100644 index 01f81c3b86..0000000000 --- a/e2e/react-start/dev-ssr-styles/src/styles/embedded-utilities.css +++ /dev/null @@ -1,3 +0,0 @@ -.embedded-utility { - --embedded-utilities-marker: 1; -} diff --git a/e2e/react-start/dev-ssr-styles/src/styles/embedded.css b/e2e/react-start/dev-ssr-styles/src/styles/embedded.css deleted file mode 100644 index 7b6b68c48d..0000000000 --- a/e2e/react-start/dev-ssr-styles/src/styles/embedded.css +++ /dev/null @@ -1,3 +0,0 @@ -@import './embedded-theme.css' layer(theme); -@import './embedded-preflight.css' layer(base); -@import './embedded-utilities.css' layer(utilities); diff --git a/e2e/react-start/dev-ssr-styles/src/styles/ssr-background.svg b/e2e/react-start/dev-ssr-styles/src/styles/ssr-background.svg deleted file mode 100644 index 7916b3ef16..0000000000 --- a/e2e/react-start/dev-ssr-styles/src/styles/ssr-background.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/e2e/react-start/dev-ssr-styles/tests/app.spec.ts b/e2e/react-start/dev-ssr-styles/tests/app.spec.ts index f5b72a1bca..cb1ba0b29b 100644 --- a/e2e/react-start/dev-ssr-styles/tests/app.spec.ts +++ b/e2e/react-start/dev-ssr-styles/tests/app.spec.ts @@ -1,6 +1,6 @@ import { expect } from '@playwright/test' import { DEV_STYLES_ATTR } from '@tanstack/router-core' -import { createHmrFileEditor, test } from '@tanstack/router-e2e-utils' +import { test } from '@tanstack/router-e2e-utils' import { ssrStylesMode } from '../env' // Whitelist errors that can occur in CI: @@ -14,60 +14,14 @@ const whitelistErrors = [ test.describe(`dev.ssrStyles (mode=${ssrStylesMode})`, () => { test.use({ whitelistErrors }) - test('unchanged SSR requests reuse evaluated modules', async ({ - request, - }) => { - const first = await request.get('/module-state') - const second = await request.get('/module-state') - expect(first.ok()).toBeTruthy() - expect(second.ok()).toBeTruthy() - expect(await second.text()).toBe(await first.text()) - }) - test('page renders correctly', async ({ page }) => { - const runtimeErrors: Array = [] - page.on('pageerror', (error) => { - runtimeErrors.push(error.message) - }) await page.goto('/') await expect(page.getByTestId('home-heading')).toHaveText( 'Dev SSR Styles Test', ) - expect(runtimeErrors).toEqual([]) }) if (ssrStylesMode === 'default') { - test('dev CSS order is stable after client modules load', async ({ - page, - }) => { - const cssBodies: Array> = [] - page.on('response', (response) => { - if ( - new URL(response.url()).pathname.endsWith( - '/@tanstack-start/styles.css', - ) - ) { - cssBodies.push(response.text()) - } - }) - - await page.goto('/css-import-order') - await expect(page.getByTestId('css-import-order')).toBeVisible() - await expect.poll(() => cssBodies.length).toBeGreaterThanOrEqual(1) - - await page.reload() - await expect(page.getByTestId('css-import-order')).toBeVisible() - await expect.poll(() => cssBodies.length).toBeGreaterThanOrEqual(2) - - const [initialCss, reloadedCss] = await Promise.all(cssBodies.slice(0, 2)) - expect(reloadedCss).toBe(initialCss) - expect(initialCss).toContain('/* /src/styles/app.css */') - expect(initialCss).toContain('/* /src/styles/css-import-order.css */') - expect(initialCss.indexOf('/* /src/styles/app.css */')).toBeLessThan( - initialCss.indexOf('/* /src/styles/css-import-order.css */'), - ) - }) - test.describe('default (enabled, basepath = vite base)', () => { test.use({ javaScriptEnabled: false, whitelistErrors }) @@ -98,9 +52,7 @@ test.describe(`dev.ssrStyles (mode=${ssrStylesMode})`, () => { expect(href).toMatch(/^\/@tanstack-start\/styles\.css/) }) - test('CSS from a code-split route component is applied during SSR', async ({ - page, - }) => { + test('CSS is applied on initial page load (SSR)', async ({ page }) => { await page.goto('/') const element = page.getByTestId('styled-box') @@ -112,81 +64,6 @@ test.describe(`dev.ssrStyles (mode=${ssrStylesMode})`, () => { ) expect(backgroundColor).toBe('rgb(59, 130, 246)') }) - - test('SSR CSS updates after a stylesheet edit', async ({ page }) => { - const editor = createHmrFileEditor({ - rootDir: import.meta.dirname, - files: { css: '../src/styles/code-split-route.module.css' }, - }) - await editor.capturePromise - const expectSsrColor = async (color: string) => { - await expect(async () => { - await page.reload() - await expect(page.getByTestId('styled-box')).toHaveCSS( - 'background-color', - color, - ) - }).toPass({ timeout: 20_000 }) - } - try { - await page.goto('/') - await expect(page.getByTestId('styled-box')).toHaveCSS( - 'background-color', - 'rgb(59, 130, 246)', - ) - await editor.replaceText('css', '#3b82f6', '#ef4444') - await expectSsrColor('rgb(239, 68, 68)') - } finally { - await editor.restoreFiles() - // Finish the restore before another test reads the SSR stylesheet. - await expectSsrColor('rgb(59, 130, 246)') - } - }) - - test('assets referenced by SSR CSS are available before hydration', async ({ - page, - }) => { - await page.goto('/') - const backgroundImage = await page - .getByTestId('styled-box') - .evaluate((element) => getComputedStyle(element).backgroundImage) - const assetUrl = backgroundImage.match(/^url\("(.+)"\)$/)?.[1] - expect(assetUrl).toBeDefined() - const response = await page.request.get(assetUrl!) - expect(response.ok()).toBeTruthy() - expect(response.headers()['content-type']).toContain('image/svg+xml') - expect(await response.text()).toContain(' { - await page.goto('/css-import-order') - - const element = page.getByTestId('css-import-order') - await expect(element).toBeVisible() - - // css-import-order.css imports a white base rule, then overrides it - // with this dark background. Collecting the imported file separately - // appends the white rule and reverses the intended cascade. - const backgroundColor = await element.evaluate( - (el) => getComputedStyle(el).backgroundColor, - ) - expect(backgroundColor).toBe('rgb(17, 24, 39)') - - const devStylesHref = await page - .locator(`link[${DEV_STYLES_ATTR}]`) - .getAttribute('href') - expect(devStylesHref).toBeTruthy() - - const cssResponse = await page.request.get( - new URL(devStylesHref!, page.url()).href, - ) - expect(cssResponse.ok()).toBeTruthy() - - const css = await cssResponse.text() - expect(css.match(/--css-import-base-marker/g)).toHaveLength(1) - }) }) } diff --git a/e2e/react-start/dev-ssr-styles/tests/inline-css.spec.ts b/e2e/react-start/dev-ssr-styles/tests/inline-css.spec.ts deleted file mode 100644 index c564a9977a..0000000000 --- a/e2e/react-start/dev-ssr-styles/tests/inline-css.spec.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { expect } from '@playwright/test' -import { DEV_STYLES_ATTR } from '@tanstack/router-core' -import { test } from '@tanstack/router-e2e-utils' -import { ssrStylesMode } from '../env' - -test.describe('server inline CSS with layered imports', () => { - test.skip(ssrStylesMode !== 'default', 'Requires the default dev stylesheet') - test.use({ javaScriptEnabled: false }) - - test('keeps layered inline imports out of the global dev stylesheet', async ({ - page, - }) => { - await page.goto('/inline-css') - const embeddedCss = await page.getByTestId('embedded-css').textContent() - for (const layer of ['theme', 'base', 'utilities']) { - expect(embeddedCss).toContain(`@layer ${layer}`) - } - for (const marker of ['theme', 'preflight', 'utilities']) { - expect(embeddedCss).toContain(`--embedded-${marker}-marker`) - } - - const href = await page - .locator(`link[${DEV_STYLES_ATTR}]`) - .getAttribute('href') - expect(href).toBeTruthy() - const response = await page.request.get(new URL(href!, page.url()).href) - expect(response.ok()).toBeTruthy() - expect(await response.text()).not.toContain('--embedded-') - - const layout = page.getByTestId('inline-css-layout') - await expect(layout).toHaveCSS('padding-top', '24px') - await expect(layout).toHaveCSS('margin-top', '12px') - await expect(layout).toHaveCSS('border-top-width', '3px') - }) -}) diff --git a/e2e/react-start/dev-ssr-styles/tests/setup/global.setup.ts b/e2e/react-start/dev-ssr-styles/tests/setup/global.setup.ts index 43fad46254..2bfd33163d 100644 --- a/e2e/react-start/dev-ssr-styles/tests/setup/global.setup.ts +++ b/e2e/react-start/dev-ssr-styles/tests/setup/global.setup.ts @@ -1,45 +1,39 @@ -import { chromium, expect } from '@playwright/test' -import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' -import { ssrStylesMode } from '../../env' +import { + e2eStartDummyServer, + getTestServerPort, + preOptimizeDevServer, + waitForServer, +} from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } +import { ssrStylesMode, useNitro, viteBundledDev } from '../../env' + +function getPortKey() { + let key = packageJson.name + if (ssrStylesMode !== 'default') { + key += `-${ssrStylesMode}` + } + if (useNitro) { + key += '-nitro' + } + if (viteBundledDev) { + key += '-bundled-dev' + } + return key +} export default async function setup() { - if (process.env.MODE !== 'dev') { - return - } + const portKey = getPortKey() - const port = Number(process.env.E2E_APP_PORT ?? 0) + await e2eStartDummyServer(portKey) + + if (process.env.MODE !== 'dev') return + + const port = await getTestServerPort(portKey) const baseURL = `http://localhost:${port}` await waitForServer(baseURL) - - // Check cold SSR before the browser warmup can populate the client graph. - const browser = await chromium.launch() - try { - const page = await browser.newPage({ javaScriptEnabled: false }) - const backgroundAsset = - ssrStylesMode !== 'disabled' - ? page.waitForResponse( - (response) => - new URL(response.url()).pathname.includes('ssr-background'), - { timeout: 60_000 }, - ) - : undefined - await page.goto(baseURL, { timeout: 60_000 }) - await expect(page.getByTestId('home-heading')).toHaveText( - 'Dev SSR Styles Test', - { timeout: 30_000 }, - ) - if (ssrStylesMode !== 'disabled') { - expect((await backgroundAsset!).ok()).toBeTruthy() - await expect(page.getByTestId('styled-box')).toHaveCSS( - 'background-color', - 'rgb(59, 130, 246)', - { timeout: 30_000 }, - ) - } - } finally { - await browser.close() - } - - await preOptimizeDevServer({ baseURL, readyTestId: 'home-heading' }) + await preOptimizeDevServer({ + baseURL, + readyTestId: 'home-heading', + }) } diff --git a/e2e/react-start/dev-ssr-styles/tests/setup/global.teardown.ts b/e2e/react-start/dev-ssr-styles/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..0e44fca325 --- /dev/null +++ b/e2e/react-start/dev-ssr-styles/tests/setup/global.teardown.ts @@ -0,0 +1,21 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } +import { ssrStylesMode, useNitro, viteBundledDev } from '../../env' + +function getPortKey() { + let key = packageJson.name + if (ssrStylesMode !== 'default') { + key += `-${ssrStylesMode}` + } + if (useNitro) { + key += '-nitro' + } + if (viteBundledDev) { + key += '-bundled-dev' + } + return key +} + +export default async function teardown() { + await e2eStopDummyServer(getPortKey()) +} diff --git a/e2e/react-start/dev-ssr-styles/vite.config.ts b/e2e/react-start/dev-ssr-styles/vite.config.ts index df5ea34504..555137b543 100644 --- a/e2e/react-start/dev-ssr-styles/vite.config.ts +++ b/e2e/react-start/dev-ssr-styles/vite.config.ts @@ -20,7 +20,7 @@ export default defineConfig(async () => { return { resolve: { tsconfigPaths: true }, - experimental: { bundledDev: viteBundledDev }, + experimental: viteBundledDev ? { bundledDev: true } : undefined, server: { port: 3000, }, diff --git a/e2e/react-start/early-hints/package.json b/e2e/react-start/early-hints/package.json index 1615b99430..2945148950 100644 --- a/e2e/react-start/early-hints/package.json +++ b/e2e/react-start/early-hints/package.json @@ -10,7 +10,7 @@ "preview": "vite preview", "gen-certs": "node --import tsx tests/gen-certs.ts", "start": "pnpm gen-certs && srvx --prod --tls --cert=tests/.tmp/tls/server.crt --key=tests/.tmp/tls/server.key -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -27,20 +27,10 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "node-forge": "^1.3.1", - "srvx": "^1.0.0", + "srvx": "0.11.15", "tsx": "4.20.3", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" - }, - "nx": { - "targets": { - "test:e2e": { - "outputs": [ - "...", - "{projectRoot}/tests/.tmp/tls" - ] - } - } } } diff --git a/e2e/react-start/early-hints/playwright.config.ts b/e2e/react-start/early-hints/playwright.config.ts index b3606d5586..a2435bcf7b 100644 --- a/e2e/react-start/early-hints/playwright.config.ts +++ b/e2e/react-start/early-hints/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `https://localhost:${PORT}` export default defineConfig({ @@ -16,8 +17,8 @@ export default defineConfig({ webServer: { command: `pnpm build && pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', ignoreHTTPSErrors: true, env: { diff --git a/e2e/react-start/early-hints/tests/early-hints-protocol.spec.ts b/e2e/react-start/early-hints/tests/early-hints-protocol.spec.ts index 6d2d31d836..df0984079e 100644 --- a/e2e/react-start/early-hints/tests/early-hints-protocol.spec.ts +++ b/e2e/react-start/early-hints/tests/early-hints-protocol.spec.ts @@ -1,5 +1,7 @@ -import { connect } from 'node:http2' import { expect, test } from '@playwright/test' +import { connect } from 'node:http2' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from '../package.json' with { type: 'json' } import type { IncomingHttpHeaders } from 'node:http2' type Http2Response = { @@ -46,14 +48,14 @@ function linkHeader(headers: IncomingHttpHeaders): string { function earlyHintsLinkHeader(response: Http2Response): string { expect(response.earlyHints.length).toBe(1) - return linkHeader(response.earlyHints[0]) + return linkHeader(response.earlyHints[0]!) } test.describe('Early Hints - HTTP/2 Protocol', () => { let baseURL: string test.beforeAll(async () => { - const PORT = Number(process.env.E2E_APP_PORT ?? 0) + const PORT = await getTestServerPort(packageJson.name) baseURL = `https://localhost:${PORT}` }) @@ -103,9 +105,7 @@ test.describe('Early Hints - HTTP/2 Protocol', () => { const response = await makeRequest(baseURL, '/') const link = earlyHintsLinkHeader(response) - expect(link).toMatch( - /<[^>]+>;\s*rel=modulepreload;\s*as=script;\s*fetchpriority=low/, - ) + expect(link).toMatch(/<[^>]+>;\s*rel=modulepreload;\s*as=script/) }) test('CSS module assets are included in early hints', async () => { @@ -137,7 +137,7 @@ test.describe('Early Hints - HTTP/2 Protocol', () => { expect(response.earlyHints.length).toBe(1) - const link = linkHeader(response.earlyHints[0]) + const link = linkHeader(response.earlyHints[0]!) expect(link).toContain('rel=modulepreload; as=script') expect(link).toContain('; rel=preconnect') @@ -147,7 +147,7 @@ test.describe('Early Hints - HTTP/2 Protocol', () => { const response = await makeRequest(baseURL, '/') const link = linkHeader(response.finalHeaders) - expect(link).toContain('rel=modulepreload; as=script; fetchpriority=low') + expect(link).toContain('rel=modulepreload; as=script') expect(link).toContain('; rel=preconnect') }) diff --git a/e2e/react-start/flamegraph-bench/package.json b/e2e/react-start/flamegraph-bench/package.json index 72410b13e1..eb72de699a 100644 --- a/e2e/react-start/flamegraph-bench/package.json +++ b/e2e/react-start/flamegraph-bench/package.json @@ -14,12 +14,12 @@ "@tanstack/react-start": "workspace:*", "react": "^19.0.0", "react-dom": "^19.0.0", - "srvx": "^1.0.0" + "srvx": "^0.11.9" }, "devDependencies": { "@platformatic/flame": "latest", "@vitejs/plugin-react": "^6.0.1", - "nitro": "^3.0.260903-beta", + "nitro": "^3.0.260311-beta", "autocannon": "^8.0.0", "concurrently": "9.2.1", "@typescript/native": "npm:typescript@^7.0.2", diff --git a/e2e/react-start/hmr/package.json b/e2e/react-start/hmr/package.json index 76a5d86b1f..7a6dc23f76 100644 --- a/e2e/react-start/hmr/package.json +++ b/e2e/react-start/hmr/package.json @@ -21,7 +21,7 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-react": "^2.0.0", "@tailwindcss/postcss": "^4.2.2", "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/react-start/hmr/playwright.config.ts b/e2e/react-start/hmr/playwright.config.ts index 5840ec157a..c159aad328 100644 --- a/e2e/react-start/hmr/playwright.config.ts +++ b/e2e/react-start/hmr/playwright.config.ts @@ -1,11 +1,13 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' - +const e2ePortKey = + process.env.E2E_PORT_KEY ?? `${packageJson.name}-${toolchain}` const distDir = process.env.E2E_DIST_DIR ?? 'dist' const viteBundledDev = process.env.E2E_VITE_BUNDLED_DEV === 'true' -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(e2ePortKey) const baseURL = `http://localhost:${PORT}` const devCommand = toolchain === 'rsbuild' ? 'pnpm dev:rsbuild' : 'pnpm dev:vite' @@ -16,6 +18,7 @@ export default defineConfig({ reporter: [['line']], globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', use: { baseURL, @@ -23,14 +26,15 @@ export default defineConfig({ webServer: { command: `${devCommand} --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { VITE_NODE_ENV: 'test', PORT: String(PORT), E2E_TOOLCHAIN: toolchain, E2E_DIST_DIR: distDir, + E2E_PORT_KEY: e2ePortKey, E2E_VITE_BUNDLED_DEV: String(viteBundledDev), }, }, diff --git a/e2e/react-start/hmr/tests/app.spec.ts b/e2e/react-start/hmr/tests/app.spec.ts index 645c9b06f3..fe6dd99389 100644 --- a/e2e/react-start/hmr/tests/app.spec.ts +++ b/e2e/react-start/hmr/tests/app.spec.ts @@ -607,18 +607,8 @@ test.describe('react-start hmr', () => { test('preserves local state for code-split route component HMR', async ({ page, }) => { - // Hydration can finish before Vite connects its HMR socket. - const hmrReady = - (process.env.E2E_TOOLCHAIN ?? 'vite') === 'vite' - ? page.waitForEvent('websocket').then((socket) => { - return socket.waitForEvent('framereceived', ({ payload }) => { - return JSON.parse(String(payload)).type === 'connected' - }) - }) - : Promise.resolve() await page.goto('/') await page.getByTestId('hydrated').waitFor({ state: 'visible' }) - await hmrReady await page.getByTestId('increment').click() await page.getByTestId('message').fill('hmr state') @@ -932,7 +922,6 @@ test.describe('react-start hmr', () => { await waitForRouteModuleUpdate(page, '/child', 'Child Updated') }, ) - await waitForHydrationSafeReload(page, '/child', 'Child Updated') // Second edit: change child loader again while still on / await replaceRouteTextAndWait( diff --git a/e2e/react-start/hmr/tests/setup/global.setup.ts b/e2e/react-start/hmr/tests/setup/global.setup.ts index 32207ab79f..fb9aad22ae 100644 --- a/e2e/react-start/hmr/tests/setup/global.setup.ts +++ b/e2e/react-start/hmr/tests/setup/global.setup.ts @@ -1,7 +1,22 @@ -import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' +import { + e2eStartDummyServer, + getTestServerPort, + preOptimizeDevServer, + waitForServer, +} from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +function getE2EPortKey() { + const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' + return process.env.E2E_PORT_KEY ?? `${packageJson.name}-${toolchain}` +} export default async function setup() { - const port = Number(process.env.E2E_APP_PORT ?? 0) + const e2ePortKey = getE2EPortKey() + + await e2eStartDummyServer(e2ePortKey) + + const port = await getTestServerPort(e2ePortKey) const baseURL = `http://localhost:${port}` await waitForServer(baseURL) diff --git a/e2e/react-start/hmr/tests/setup/global.teardown.ts b/e2e/react-start/hmr/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..e17856dd82 --- /dev/null +++ b/e2e/react-start/hmr/tests/setup/global.teardown.ts @@ -0,0 +1,11 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +function getE2EPortKey() { + const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' + return process.env.E2E_PORT_KEY ?? `${packageJson.name}-${toolchain}` +} + +export default async function teardown() { + await e2eStopDummyServer(getE2EPortKey()) +} diff --git a/e2e/react-start/i18n-paraglide/package.json b/e2e/react-start/i18n-paraglide/package.json index ca65ead76d..5b525891a6 100644 --- a/e2e/react-start/i18n-paraglide/package.json +++ b/e2e/react-start/i18n-paraglide/package.json @@ -8,7 +8,7 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js", "build": "vite build && tsc --noEmit", "preview": "vite preview", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -30,23 +30,5 @@ "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" - }, - "nx": { - "targets": { - "build": { - "outputs": [ - "...", - "{projectRoot}/src/paraglide", - "{projectRoot}/project.inlang/cache" - ] - }, - "test:e2e": { - "outputs": [ - "...", - "{projectRoot}/src/paraglide", - "{projectRoot}/project.inlang/cache" - ] - } - } } } diff --git a/e2e/react-start/i18n-paraglide/playwright.config.ts b/e2e/react-start/i18n-paraglide/playwright.config.ts index 972522350e..38690f09d8 100644 --- a/e2e/react-start/i18n-paraglide/playwright.config.ts +++ b/e2e/react-start/i18n-paraglide/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/import-protection-custom-config/package.json b/e2e/react-start/import-protection-custom-config/package.json index c088eff106..25ff3f2738 100644 --- a/e2e/react-start/import-protection-custom-config/package.json +++ b/e2e/react-start/import-protection-custom-config/package.json @@ -8,8 +8,8 @@ "dev:e2e": "vite dev", "build": "vite build && tsc --noEmit", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e:mockMode": "playwright test --project=chromium", - "test:e2e:errorMode": "BEHAVIOR=error playwright test --project=chromium", + "test:e2e:mockMode": "rm -rf port*.txt; playwright test --project=chromium", + "test:e2e:errorMode": "rm -rf port*.txt; BEHAVIOR=error playwright test --project=chromium", "test:e2e": "pnpm run test:e2e:mockMode && pnpm run test:e2e:errorMode" }, "dependencies": { @@ -25,23 +25,9 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" - }, - "nx": { - "targets": { - "test:e2e": { - "outputs": [ - "{projectRoot}/dist", - "{projectRoot}/test-results", - "{projectRoot}/webserver-build.log", - "{projectRoot}/violations.*.json", - "{projectRoot}/error-build.log", - "{projectRoot}/error-*-result.json" - ] - } - } } } diff --git a/e2e/react-start/import-protection-custom-config/playwright.config.ts b/e2e/react-start/import-protection-custom-config/playwright.config.ts index ab90f2911f..31a55ba3bc 100644 --- a/e2e/react-start/import-protection-custom-config/playwright.config.ts +++ b/e2e/react-start/import-protection-custom-config/playwright.config.ts @@ -1,8 +1,9 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' import { isErrorMode } from './tests/utils/isErrorMode' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` console.log('running in error mode:', isErrorMode.toString()) @@ -26,8 +27,8 @@ export default defineConfig({ : { webServer: { command: `rm -f webserver-build.log violations.build.json violations.dev.json && VITE_SERVER_PORT=${PORT} pnpm build > webserver-build.log 2>&1 && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', cwd: import.meta.dirname, }, diff --git a/e2e/react-start/import-protection-custom-config/tests/error-mode.setup.ts b/e2e/react-start/import-protection-custom-config/tests/error-mode.setup.ts index 5032988d0c..3e666ca1df 100644 --- a/e2e/react-start/import-protection-custom-config/tests/error-mode.setup.ts +++ b/e2e/react-start/import-protection-custom-config/tests/error-mode.setup.ts @@ -1,14 +1,14 @@ -import { execSync, spawn } from 'node:child_process' import fs from 'node:fs' import path from 'node:path' -import { stripVTControlCharacters } from 'node:util' -import { appServerReadyPattern } from '@tanstack/router-e2e-utils' -import { chromium, expect } from '@playwright/test' +import { execSync, spawn } from 'node:child_process' +import { chromium } from '@playwright/test' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from '../package.json' with { type: 'json' } import type { FullConfig } from '@playwright/test' async function waitForHttpOk(url: string, timeoutMs: number): Promise { const start = Date.now() - + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (true) { if (Date.now() - start > timeoutMs) { throw new Error(`Timed out waiting for ${url}`) @@ -84,7 +84,8 @@ function captureBuild(cwd: string): void { } async function captureDevErrors(cwd: string): Promise { - const port = 0 + const port = await getTestServerPort(`${packageJson.name}_error_dev`) + const baseURL = `http://localhost:${port}` const logChunks: Array = [] const child = spawn('pnpm', ['exec', 'vite', 'dev', '--port', String(port)], { @@ -98,23 +99,10 @@ async function captureDevErrors(cwd: string): Promise { stdio: ['ignore', 'pipe', 'pipe'], }) - child.stdout.on('data', (d: Buffer) => logChunks.push(d.toString())) - child.stderr.on('data', (d: Buffer) => logChunks.push(d.toString())) + child.stdout?.on('data', (d: Buffer) => logChunks.push(d.toString())) + child.stderr?.on('data', (d: Buffer) => logChunks.push(d.toString())) try { - await expect - .poll( - () => - appServerReadyPattern.exec( - stripVTControlCharacters(logChunks.join('')), - )?.groups?.E2E_APP_PORT, - { timeout: 30_000 }, - ) - .toBeTruthy() - const port = appServerReadyPattern.exec( - stripVTControlCharacters(logChunks.join('')), - )!.groups!.E2E_APP_PORT - const baseURL = `http://localhost:${port}` await waitForHttpOk(baseURL, 30_000) const browser = await chromium.launch() diff --git a/e2e/react-start/import-protection-custom-config/tests/violations.setup.ts b/e2e/react-start/import-protection-custom-config/tests/violations.setup.ts index 89c8bb2b9a..c5187fe074 100644 --- a/e2e/react-start/import-protection-custom-config/tests/violations.setup.ts +++ b/e2e/react-start/import-protection-custom-config/tests/violations.setup.ts @@ -1,9 +1,9 @@ -import { spawn } from 'node:child_process' import fs from 'node:fs' import path from 'node:path' -import { stripVTControlCharacters } from 'node:util' -import { chromium, expect } from '@playwright/test' -import { appServerReadyPattern } from '@tanstack/router-e2e-utils' +import { spawn } from 'node:child_process' +import { chromium } from '@playwright/test' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from '../package.json' with { type: 'json' } import { extractViolationsFromLog } from './violations.utils' import type { FullConfig } from '@playwright/test' @@ -12,6 +12,7 @@ import type { Violation } from './violations.utils' async function waitForHttpOk(url: string, timeoutMs: number): Promise { const start = Date.now() + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (true) { if (Date.now() - start > timeoutMs) { throw new Error(`Timed out waiting for ${url}`) @@ -118,6 +119,7 @@ async function runDevPass( cwd: string, port: number, ): Promise> { + const baseURL = `http://localhost:${port}` const logChunks: Array = [] const child = startDevServer(cwd, port) @@ -125,19 +127,6 @@ async function runDevPass( child.stderr?.on('data', (d: Buffer) => logChunks.push(d.toString())) try { - await expect - .poll( - () => - appServerReadyPattern.exec( - stripVTControlCharacters(logChunks.join('')), - )?.groups?.E2E_APP_PORT, - { timeout: 30_000 }, - ) - .toBeTruthy() - const port = appServerReadyPattern.exec( - stripVTControlCharacters(logChunks.join('')), - )!.groups!.E2E_APP_PORT - const baseURL = `http://localhost:${port}` await waitForHttpOk(baseURL, 30_000) const browser = await chromium.launch() @@ -157,7 +146,7 @@ async function runDevPass( } async function captureDevViolations(cwd: string): Promise { - const port = 0 + const port = await getTestServerPort(`${packageJson.name}_dev`) const coldViolations = await runDevPass(cwd, port) diff --git a/e2e/react-start/import-protection/package.json b/e2e/react-start/import-protection/package.json index ad06ba41ea..5459b84437 100644 --- a/e2e/react-start/import-protection/package.json +++ b/e2e/react-start/import-protection/package.json @@ -22,14 +22,14 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-react": "^2.0.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" diff --git a/e2e/react-start/import-protection/playwright.config.ts b/e2e/react-start/import-protection/playwright.config.ts index 6a3df630c3..778e865125 100644 --- a/e2e/react-start/import-protection/playwright.config.ts +++ b/e2e/react-start/import-protection/playwright.config.ts @@ -1,12 +1,16 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' import { isErrorMode } from './tests/utils/isErrorMode' import { getViolationArtifactName } from './tests/violations.utils' +import packageJson from './package.json' with { type: 'json' } +const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' const viteBundledDev = process.env.E2E_VITE_BUNDLED_DEV === 'true' - +const e2ePortKey = + process.env.E2E_PORT_KEY ?? + `${packageJson.name}-${toolchain}${viteBundledDev ? '-bundled-dev' : ''}` const distDir = process.env.E2E_DIST_DIR ?? 'dist' -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(e2ePortKey) const baseURL = `http://localhost:${PORT}` const violationArtifacts = [ getViolationArtifactName('build'), @@ -38,14 +42,15 @@ export default defineConfig({ : { webServer: { command: `rm -f webserver-dev.log ${violationArtifacts} && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', cwd: import.meta.dirname, env: { PORT: String(PORT), VITE_SERVER_PORT: String(PORT), E2E_DIST_DIR: distDir, + E2E_PORT_KEY: e2ePortKey, E2E_VITE_BUNDLED_DEV: String(viteBundledDev), }, }, diff --git a/e2e/react-start/import-protection/src/routes/index.tsx b/e2e/react-start/import-protection/src/routes/index.tsx index ef8544dc3c..c05ed1a7e3 100644 --- a/e2e/react-start/import-protection/src/routes/index.tsx +++ b/e2e/react-start/import-protection/src/routes/index.tsx @@ -1,4 +1,4 @@ -import { createFileRoute, useHydrated } from '@tanstack/react-router' +import { createFileRoute } from '@tanstack/react-router' // This import chain triggers a file-based violation in the CLIENT env: // index.tsx -> violations/edge-a.ts -> violations/secret.server.ts import { getWrappedSecret } from '../violations/edge-a' @@ -25,12 +25,10 @@ export const Route = createFileRoute('/')({ }) function Home() { - const hydrated = useHydrated() return (

Import Protection E2E

App loaded successfully with mock mode

-

{hydrated ? 'hydrated' : 'ssr'}

{getWrappedSecret()}

{getWrappedSecret1()}

{getServerOnlyDataViaEdge()}

diff --git a/e2e/react-start/import-protection/src/violations/cross-boundary-safe/session-util.ts b/e2e/react-start/import-protection/src/violations/cross-boundary-safe/session-util.ts index d74bc6430b..ab44237539 100644 --- a/e2e/react-start/import-protection/src/violations/cross-boundary-safe/session-util.ts +++ b/e2e/react-start/import-protection/src/violations/cross-boundary-safe/session-util.ts @@ -6,7 +6,7 @@ import { getRequest } from '@tanstack/react-start/server' // so the compiler should prune this import from the client bundle. // // This mirrors the real-world pattern of a session utility that wraps -// `getCookie` from `@tanstack/react-start/server`. +// `useSession` from `@tanstack/react-start/server`. export function getSessionData() { const req = getRequest() return { method: req.method } diff --git a/e2e/react-start/import-protection/tests/error-mode.setup.ts b/e2e/react-start/import-protection/tests/error-mode.setup.ts index e562128eea..c844d59e73 100644 --- a/e2e/react-start/import-protection/tests/error-mode.setup.ts +++ b/e2e/react-start/import-protection/tests/error-mode.setup.ts @@ -1,9 +1,9 @@ -import { execSync, spawn } from 'node:child_process' import fs from 'node:fs' import path from 'node:path' -import { stripVTControlCharacters } from 'node:util' -import { appServerReadyPattern } from '@tanstack/router-e2e-utils' -import { chromium, expect } from '@playwright/test' +import { execSync, spawn } from 'node:child_process' +import { chromium } from '@playwright/test' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from '../package.json' with { type: 'json' } import type { FullConfig } from '@playwright/test' /** @@ -20,10 +20,14 @@ import type { FullConfig } from '@playwright/test' */ const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' +const viteBundledDev = process.env.E2E_VITE_BUNDLED_DEV === 'true' +const e2ePortKey = + process.env.E2E_PORT_KEY ?? + `${packageJson.name}-${toolchain}${viteBundledDev ? '-bundled-dev' : ''}` async function waitForHttpOk(url: string, timeoutMs: number): Promise { const start = Date.now() - + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (true) { if (Date.now() - start > timeoutMs) { throw new Error(`Timed out waiting for ${url}`) @@ -118,7 +122,8 @@ async function captureDev(cwd: string): Promise { if (fs.existsSync(p)) fs.unlinkSync(p) } - const port = 0 + const port = await getTestServerPort(`${e2ePortKey}-error-dev`) + const baseURL = `http://localhost:${port}` const logFile = path.resolve(cwd, 'error-dev.log') const out = fs.createWriteStream(logFile) @@ -140,28 +145,10 @@ async function captureDev(cwd: string): Promise { stdio: ['ignore', 'pipe', 'pipe'], }) - const logChunks: Array = [] - const record = (data: Buffer) => { - logChunks.push(data.toString()) - out.write(data) - } - child.stdout.on('data', record) - child.stderr.on('data', record) + child.stdout?.on('data', (d: Buffer) => out.write(d)) + child.stderr?.on('data', (d: Buffer) => out.write(d)) try { - await expect - .poll( - () => - appServerReadyPattern.exec( - stripVTControlCharacters(logChunks.join('')), - )?.groups?.E2E_APP_PORT, - { timeout: 30_000 }, - ) - .toBeTruthy() - const port = appServerReadyPattern.exec( - stripVTControlCharacters(logChunks.join('')), - )!.groups!.E2E_APP_PORT - const baseURL = `http://localhost:${port}` await waitForHttpOk(baseURL, 30_000) const browser = await chromium.launch() diff --git a/e2e/react-start/import-protection/tests/violations.setup.ts b/e2e/react-start/import-protection/tests/violations.setup.ts index d0f4f70d03..2f863b398e 100644 --- a/e2e/react-start/import-protection/tests/violations.setup.ts +++ b/e2e/react-start/import-protection/tests/violations.setup.ts @@ -1,9 +1,9 @@ -import { spawn } from 'node:child_process' import fs from 'node:fs' import path from 'node:path' -import { stripVTControlCharacters } from 'node:util' -import { chromium, expect } from '@playwright/test' -import { appServerReadyPattern } from '@tanstack/router-e2e-utils' +import { spawn } from 'node:child_process' +import { chromium } from '@playwright/test' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from '../package.json' with { type: 'json' } import { extractViolationsFromLog, @@ -12,11 +12,16 @@ import { import type { FullConfig } from '@playwright/test' import type { Violation } from './violations.utils' +const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' const viteBundledDev = process.env.E2E_VITE_BUNDLED_DEV === 'true' +const e2ePortKey = + process.env.E2E_PORT_KEY ?? + `${packageJson.name}-${toolchain}${viteBundledDev ? '-bundled-dev' : ''}` async function waitForHttpOk(url: string, timeoutMs: number): Promise { const start = Date.now() + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (true) { if (Date.now() - start > timeoutMs) { throw new Error(`Timed out waiting for ${url}`) @@ -172,20 +177,6 @@ async function navigateAllRoutes( const context = await browser.newContext() const page = await context.newPage() - // Safe factory imports must actually compile and hydrate. A crashed lazy - // compiler must not pass simply because it emitted no violation diagnostics. - await page.goto(baseURL) - await expect(page.getByTestId('hydration-status')).toHaveText('hydrated', { - timeout: 30_000, - }) - for (const testId of [ - 'factory-safe', - 'cross-boundary-safe-sf', - 'cross-boundary-safe-mw', - ]) { - await expect(page.getByTestId(testId)).toHaveText('function') - } - for (const [route, testId, expectedViolation] of routeDefinitions) { try { // Prefer 'networkidle' (ensures route chunks are actually fetched), but @@ -223,6 +214,7 @@ async function runDevPass( cwd: string, port: number, ): Promise> { + const baseURL = `http://localhost:${port}` const logChunks: Array = [] const child = startDevServer(cwd, port) @@ -230,19 +222,6 @@ async function runDevPass( child.stderr?.on('data', (d: Buffer) => logChunks.push(d.toString())) try { - await expect - .poll( - () => - appServerReadyPattern.exec( - stripVTControlCharacters(logChunks.join('')), - )?.groups?.E2E_APP_PORT, - { timeout: 30_000 }, - ) - .toBeTruthy() - const port = appServerReadyPattern.exec( - stripVTControlCharacters(logChunks.join('')), - )!.groups!.E2E_APP_PORT - const baseURL = `http://localhost:${port}` await waitForHttpOk(baseURL, 30_000) const browser = await chromium.launch() @@ -268,7 +247,10 @@ async function runDevPass( * modules are pre-transformed so resolveId/transform paths differ. */ async function captureDevViolations(cwd: string): Promise { - const coldViolations = await runDevPass(cwd, 0) + const coldViolations = await runDevPass( + cwd, + await getTestServerPort(`${e2ePortKey}-violations-cold`), + ) fs.writeFileSync( path.resolve(cwd, getViolationArtifactName('dev')), @@ -280,7 +262,10 @@ async function captureDevViolations(cwd: string): Promise { ) // Warm pass: the .vite cache from the cold run is still on disk. - const warmViolations = await runDevPass(cwd, 0) + const warmViolations = await runDevPass( + cwd, + await getTestServerPort(`${e2ePortKey}-violations-warm`), + ) fs.writeFileSync( path.resolve(cwd, getViolationArtifactName('dev.warm')), diff --git a/e2e/react-start/issue-8049/package.json b/e2e/react-start/issue-8049/package.json index be848d434c..d76b23fc3b 100644 --- a/e2e/react-start/issue-8049/package.json +++ b/e2e/react-start/issue-8049/package.json @@ -6,7 +6,7 @@ "build": "vite build && tsc --noEmit", "dev": "vite dev --port 3000", "dev:e2e": "vite dev", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", diff --git a/e2e/react-start/issue-8049/playwright.config.ts b/e2e/react-start/issue-8049/playwright.config.ts index 46bfbe552e..04fa904ba6 100644 --- a/e2e/react-start/issue-8049/playwright.config.ts +++ b/e2e/react-start/issue-8049/playwright.config.ts @@ -1,8 +1,10 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } const PORT = - Number(process.env.VITE_SERVER_PORT) || Number(process.env.E2E_APP_PORT ?? 0) + Number(process.env.VITE_SERVER_PORT) || + (await getTestServerPort(packageJson.name)) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -12,8 +14,8 @@ export default defineConfig({ use: { baseURL }, webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm dev:e2e --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, projects: [ diff --git a/e2e/react-start/query-integration/package.json b/e2e/react-start/query-integration/package.json index 694289ccc2..4ad1839537 100644 --- a/e2e/react-start/query-integration/package.json +++ b/e2e/react-start/query-integration/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-query": "^5.90.0", diff --git a/e2e/react-start/query-integration/playwright.config.ts b/e2e/react-start/query-integration/playwright.config.ts index 82678ac00b..4d86a1dbe7 100644 --- a/e2e/react-start/query-integration/playwright.config.ts +++ b/e2e/react-start/query-integration/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { derivePort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await derivePort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/response-reconciliation/.gitignore b/e2e/react-start/response-reconciliation/.gitignore deleted file mode 100644 index 16187ac1de..0000000000 --- a/e2e/react-start/response-reconciliation/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -node_modules -package-lock.json -yarn.lock - -.DS_Store -.cache -.tanstack -.env -.vercel -.output -/build/ -/api/ -/server/build -/public/build - -# Sentry Config File -.env.sentry-build-plugin -/test-results/ -/playwright-report/ -/blob-report/ -/playwright/.cache/ -/dist/ -/dist-*/ -/port-*.txt diff --git a/e2e/react-start/response-reconciliation/.prettierignore b/e2e/react-start/response-reconciliation/.prettierignore deleted file mode 100644 index 40a96e8819..0000000000 --- a/e2e/react-start/response-reconciliation/.prettierignore +++ /dev/null @@ -1,4 +0,0 @@ -**/build -**/public -pnpm-lock.yaml -routeTree.gen.ts diff --git a/e2e/react-start/response-reconciliation/package.json b/e2e/react-start/response-reconciliation/package.json deleted file mode 100644 index 7ba0224962..0000000000 --- a/e2e/react-start/response-reconciliation/package.json +++ /dev/null @@ -1,84 +0,0 @@ -{ - "name": "tanstack-react-start-e2e-response-reconciliation", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "pnpm dev:vite --port 3000", - "dev:e2e": "pnpm dev:vite", - "dev:vite": "vite dev", - "dev:rsbuild": "rsbuild dev", - "build": "pnpm build:vite", - "build:vite": "vite build && tsc --noEmit", - "build:rsbuild": "rsbuild build && tsc --noEmit", - "preview": "vite preview", - "start": "node server.js", - "test:e2e:local": "pnpm build && playwright test --project=chromium" - }, - "dependencies": { - "@tanstack/react-router": "workspace:*", - "@tanstack/react-start": "workspace:*", - "react": "^19.2.3", - "react-dom": "^19.2.3" - }, - "devDependencies": { - "@playwright/test": "^1.57.0", - "@rsbuild/core": "^2.3.1", - "@rsbuild/plugin-react": "^2.0.0", - "@tanstack/router-e2e-utils": "workspace:^", - "@types/node": "25.0.9", - "@types/react": "^19.2.8", - "@types/react-dom": "^19.2.3", - "@vitejs/plugin-react": "^6.0.1", - "srvx": "^1.0.0", - "typescript": "^6.0.2", - "vite": "^8.0.14" - }, - "nx": { - "targets": { - "test:e2e": { - "parallelism": false - }, - "test:e2e--vite-ssr": { - "parallelism": false - }, - "test:e2e--vite-ssr--custom-entry": { - "parallelism": false - }, - "test:e2e--rsbuild-ssr": { - "parallelism": false - }, - "test:e2e--rsbuild-ssr--custom-entry": { - "parallelism": false - } - }, - "metadata": { - "playwrightModes": [ - { - "toolchain": "vite", - "mode": "ssr" - }, - { - "toolchain": "vite", - "mode": "ssr", - "name": "custom-entry", - "env": { - "TSS_E2E_SERVER_ENTRY": "server-entry" - } - }, - { - "toolchain": "rsbuild", - "mode": "ssr" - }, - { - "toolchain": "rsbuild", - "mode": "ssr", - "name": "custom-entry", - "env": { - "TSS_E2E_SERVER_ENTRY": "server-entry" - } - } - ] - } - } -} diff --git a/e2e/react-start/response-reconciliation/playwright.config.ts b/e2e/react-start/response-reconciliation/playwright.config.ts deleted file mode 100644 index d4c9c58f43..0000000000 --- a/e2e/react-start/response-reconciliation/playwright.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' - -const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' -const distDir = process.env.E2E_DIST_DIR ?? 'dist' -const serverEntry = process.env.TSS_E2E_SERVER_ENTRY ?? '' - -export const PORT = Number(process.env.E2E_APP_PORT ?? 0) -const baseURL = `http://localhost:${PORT}` - -export default defineConfig({ - testDir: './tests', - workers: 1, - reporter: [['line']], - use: { - baseURL, - }, - webServer: { - command: `pnpm start`, - wait: appServerReady, - reuseExistingServer: false, - stdout: 'pipe', - env: { - PORT: String(PORT), - VITE_SERVER_PORT: String(PORT), - E2E_DIST_DIR: distDir, - E2E_TOOLCHAIN: toolchain, - TSS_E2E_SERVER_ENTRY: serverEntry, - }, - }, - projects: [ - { - name: 'chromium', - use: { ...devices['Desktop Chrome'] }, - }, - ], -}) diff --git a/e2e/react-start/response-reconciliation/rsbuild.config.ts b/e2e/react-start/response-reconciliation/rsbuild.config.ts deleted file mode 100644 index 38f44ef9fb..0000000000 --- a/e2e/react-start/response-reconciliation/rsbuild.config.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { defineConfig } from '@rsbuild/core' -import { pluginReact } from '@rsbuild/plugin-react' -import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' - -const serverEntry = process.env.TSS_E2E_SERVER_ENTRY -const outDir = process.env.E2E_DIST_DIR ?? 'dist' - -export default defineConfig({ - plugins: [ - pluginReact(), - tanstackStart({ - server: serverEntry ? { entry: serverEntry } : undefined, - }), - ], - output: { - distPath: { - root: outDir, - }, - }, -}) diff --git a/e2e/react-start/response-reconciliation/server.js b/e2e/react-start/response-reconciliation/server.js deleted file mode 100644 index 324a462bec..0000000000 --- a/e2e/react-start/response-reconciliation/server.js +++ /dev/null @@ -1,62 +0,0 @@ -import fs from 'node:fs' -import path from 'node:path' -import { spawn } from 'node:child_process' -import { pathToFileURL } from 'node:url' - -const distDir = process.env.E2E_DIST_DIR || 'dist' - -function resolveDistClientDir() { - return path.resolve(distDir, 'client') -} - -function resolveDistServerEntryPath() { - if (process.env.TSS_E2E_SERVER_ENTRY) { - const customEntryPath = path.resolve( - distDir, - 'server', - `${process.env.TSS_E2E_SERVER_ENTRY}.js`, - ) - if (fs.existsSync(customEntryPath)) { - return customEntryPath - } - } - - const serverJsPath = path.resolve(distDir, 'server', 'server.js') - if (fs.existsSync(serverJsPath)) { - return serverJsPath - } - - const indexJsPath = path.resolve(distDir, 'server', 'index.js') - if (fs.existsSync(indexJsPath)) { - return indexJsPath - } - - return serverJsPath -} - -export function start() { - const child = spawn( - 'srvx', - ['--prod', '-s', resolveDistClientDir(), resolveDistServerEntryPath()], - { - stdio: 'inherit', - shell: process.platform === 'win32', - }, - ) - - child.on('exit', (code, signal) => { - if (signal) { - process.kill(process.pid, signal) - return - } - - process.exit(code ?? 0) - }) -} - -if ( - process.argv[1] && - import.meta.url === pathToFileURL(process.argv[1]).href -) { - start() -} diff --git a/e2e/react-start/response-reconciliation/src/components/DefaultCatchBoundary.tsx b/e2e/react-start/response-reconciliation/src/components/DefaultCatchBoundary.tsx deleted file mode 100644 index f3d691814f..0000000000 --- a/e2e/react-start/response-reconciliation/src/components/DefaultCatchBoundary.tsx +++ /dev/null @@ -1,20 +0,0 @@ -import { ErrorComponent, Link, useRouter } from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' - -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - - return ( -
- - - Home -
- ) -} diff --git a/e2e/react-start/response-reconciliation/src/components/NotFound.tsx b/e2e/react-start/response-reconciliation/src/components/NotFound.tsx deleted file mode 100644 index 0b720f0e37..0000000000 --- a/e2e/react-start/response-reconciliation/src/components/NotFound.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { Link } from '@tanstack/react-router' - -export function NotFound({ children }: { children?: React.ReactNode }) { - return ( -
- {children ||

The page you are looking for does not exist.

} - Start Over -
- ) -} diff --git a/e2e/react-start/response-reconciliation/src/response-wrapper.ts b/e2e/react-start/response-reconciliation/src/response-wrapper.ts deleted file mode 100644 index db9733d5e6..0000000000 --- a/e2e/react-start/response-reconciliation/src/response-wrapper.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { getRequestHeader } from '@tanstack/react-start/server' - -let installed = false - -/** - * Stand-in for libraries that wrap the global Response and pipe stream bodies, - * such as varlock's leak prevention: afterwards `new Response(stream).body` is - * a new stream that reads `stream`. Only requests that send - * `x-wrap-response: true` are affected. - */ -export function installResponseWrapper() { - if (installed) { - return - } - installed = true - globalThis.Response = new Proxy(globalThis.Response, { - construct(target, [body, init], newTarget) { - if (body instanceof ReadableStream && wrapsResponses()) { - body = body.pipeThrough(new TransformStream()) - } - return Reflect.construct(target, [body, init], newTarget) - }, - }) -} - -function wrapsResponses() { - try { - return getRequestHeader('x-wrap-response') === 'true' - } catch { - // Responses created outside a request are never wrapped. - return false - } -} diff --git a/e2e/react-start/response-reconciliation/src/routeTree.gen.ts b/e2e/react-start/response-reconciliation/src/routeTree.gen.ts deleted file mode 100644 index 3dbb6301c3..0000000000 --- a/e2e/react-start/response-reconciliation/src/routeTree.gen.ts +++ /dev/null @@ -1,625 +0,0 @@ -/* 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 ServerFunctionsRouteImport } from './routes/server-functions' -import { Route as SsrRouteImport } from './routes/ssr' -import { Route as StreamedRouteImport } from './routes/streamed' -import { Route as ApiBaseRouteImport } from './routes/api/base' -import { Route as ApiBulkHeadersRouteImport } from './routes/api/bulk-headers' -import { Route as ApiClearReturnedHeadersRouteImport } from './routes/api/clear-returned-headers' -import { Route as ApiDirectMutationVisibleRouteImport } from './routes/api/direct-mutation-visible' -import { Route as ApiExplicitSetCookieHeaderRouteImport } from './routes/api/explicit-set-cookie-header' -import { Route as ApiFramingErrorRouteImport } from './routes/api/framing-error' -import { Route as ApiGetResponseHeaderHelperRouteImport } from './routes/api/get-response-header-helper' -import { Route as ApiGetResponseHeadersHelperRouteImport } from './routes/api/get-response-headers-helper' -import { Route as ApiMultipleCookiesRouteImport } from './routes/api/multiple-cookies' -import { Route as ApiNullBodyStatusRouteImport } from './routes/api/null-body-status' -import { Route as ApiReadonlyAfterNextRouteImport } from './routes/api/readonly-after-next' -import { Route as ApiRedirectWithCookiesRouteImport } from './routes/api/redirect-with-cookies' -import { Route as ApiRemoveReturnedHeaderRouteImport } from './routes/api/remove-returned-header' -import { Route as ApiReplaceAfterDirectMutationRouteImport } from './routes/api/replace-after-direct-mutation' -import { Route as ApiReplaceExplicitSetCookieRouteImport } from './routes/api/replace-explicit-set-cookie' -import { Route as ApiRouteAfterNextRouteImport } from './routes/api/route-after-next' -import { Route as ApiRouteBeforeNextRouteImport } from './routes/api/route-before-next' -import { Route as ApiSameBoundaryConflictRouteImport } from './routes/api/same-boundary-conflict' -import { Route as ApiStatusContractsRouteImport } from './routes/api/status-contracts' -import { Route as ApiThrowAfterStatusRouteImport } from './routes/api/throw-after-status' -import { Route as ApiTrackedStreamRouteImport } from './routes/api/tracked-stream' -import { Route as ApiTrackedStreamStatusRouteImport } from './routes/api/tracked-stream-status' -import { Route as ApiTwoReturnedResponsesRouteImport } from './routes/api/two-returned-responses' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ServerFunctionsRoute = ServerFunctionsRouteImport.update({ - id: '/server-functions', - path: '/server-functions', - getParentRoute: () => rootRouteImport, -} as any) -const SsrRoute = SsrRouteImport.update({ - id: '/ssr', - path: '/ssr', - getParentRoute: () => rootRouteImport, -} as any) -const StreamedRoute = StreamedRouteImport.update({ - id: '/streamed', - path: '/streamed', - getParentRoute: () => rootRouteImport, -} as any) -const ApiBaseRoute = ApiBaseRouteImport.update({ - id: '/api/base', - path: '/api/base', - getParentRoute: () => rootRouteImport, -} as any) -const ApiBulkHeadersRoute = ApiBulkHeadersRouteImport.update({ - id: '/api/bulk-headers', - path: '/api/bulk-headers', - getParentRoute: () => rootRouteImport, -} as any) -const ApiClearReturnedHeadersRoute = ApiClearReturnedHeadersRouteImport.update({ - id: '/api/clear-returned-headers', - path: '/api/clear-returned-headers', - getParentRoute: () => rootRouteImport, -} as any) -const ApiDirectMutationVisibleRoute = - ApiDirectMutationVisibleRouteImport.update({ - id: '/api/direct-mutation-visible', - path: '/api/direct-mutation-visible', - getParentRoute: () => rootRouteImport, - } as any) -const ApiExplicitSetCookieHeaderRoute = - ApiExplicitSetCookieHeaderRouteImport.update({ - id: '/api/explicit-set-cookie-header', - path: '/api/explicit-set-cookie-header', - getParentRoute: () => rootRouteImport, - } as any) -const ApiFramingErrorRoute = ApiFramingErrorRouteImport.update({ - id: '/api/framing-error', - path: '/api/framing-error', - getParentRoute: () => rootRouteImport, -} as any) -const ApiGetResponseHeaderHelperRoute = - ApiGetResponseHeaderHelperRouteImport.update({ - id: '/api/get-response-header-helper', - path: '/api/get-response-header-helper', - getParentRoute: () => rootRouteImport, - } as any) -const ApiGetResponseHeadersHelperRoute = - ApiGetResponseHeadersHelperRouteImport.update({ - id: '/api/get-response-headers-helper', - path: '/api/get-response-headers-helper', - getParentRoute: () => rootRouteImport, - } as any) -const ApiMultipleCookiesRoute = ApiMultipleCookiesRouteImport.update({ - id: '/api/multiple-cookies', - path: '/api/multiple-cookies', - getParentRoute: () => rootRouteImport, -} as any) -const ApiNullBodyStatusRoute = ApiNullBodyStatusRouteImport.update({ - id: '/api/null-body-status', - path: '/api/null-body-status', - getParentRoute: () => rootRouteImport, -} as any) -const ApiReadonlyAfterNextRoute = ApiReadonlyAfterNextRouteImport.update({ - id: '/api/readonly-after-next', - path: '/api/readonly-after-next', - getParentRoute: () => rootRouteImport, -} as any) -const ApiRedirectWithCookiesRoute = ApiRedirectWithCookiesRouteImport.update({ - id: '/api/redirect-with-cookies', - path: '/api/redirect-with-cookies', - getParentRoute: () => rootRouteImport, -} as any) -const ApiRemoveReturnedHeaderRoute = ApiRemoveReturnedHeaderRouteImport.update({ - id: '/api/remove-returned-header', - path: '/api/remove-returned-header', - getParentRoute: () => rootRouteImport, -} as any) -const ApiReplaceAfterDirectMutationRoute = - ApiReplaceAfterDirectMutationRouteImport.update({ - id: '/api/replace-after-direct-mutation', - path: '/api/replace-after-direct-mutation', - getParentRoute: () => rootRouteImport, - } as any) -const ApiReplaceExplicitSetCookieRoute = - ApiReplaceExplicitSetCookieRouteImport.update({ - id: '/api/replace-explicit-set-cookie', - path: '/api/replace-explicit-set-cookie', - getParentRoute: () => rootRouteImport, - } as any) -const ApiRouteAfterNextRoute = ApiRouteAfterNextRouteImport.update({ - id: '/api/route-after-next', - path: '/api/route-after-next', - getParentRoute: () => rootRouteImport, -} as any) -const ApiRouteBeforeNextRoute = ApiRouteBeforeNextRouteImport.update({ - id: '/api/route-before-next', - path: '/api/route-before-next', - getParentRoute: () => rootRouteImport, -} as any) -const ApiSameBoundaryConflictRoute = ApiSameBoundaryConflictRouteImport.update({ - id: '/api/same-boundary-conflict', - path: '/api/same-boundary-conflict', - getParentRoute: () => rootRouteImport, -} as any) -const ApiStatusContractsRoute = ApiStatusContractsRouteImport.update({ - id: '/api/status-contracts', - path: '/api/status-contracts', - getParentRoute: () => rootRouteImport, -} as any) -const ApiThrowAfterStatusRoute = ApiThrowAfterStatusRouteImport.update({ - id: '/api/throw-after-status', - path: '/api/throw-after-status', - getParentRoute: () => rootRouteImport, -} as any) -const ApiTrackedStreamRoute = ApiTrackedStreamRouteImport.update({ - id: '/api/tracked-stream', - path: '/api/tracked-stream', - getParentRoute: () => rootRouteImport, -} as any) -const ApiTrackedStreamStatusRoute = ApiTrackedStreamStatusRouteImport.update({ - id: '/api/tracked-stream-status', - path: '/api/tracked-stream-status', - getParentRoute: () => rootRouteImport, -} as any) -const ApiTwoReturnedResponsesRoute = ApiTwoReturnedResponsesRouteImport.update({ - id: '/api/two-returned-responses', - path: '/api/two-returned-responses', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/server-functions': typeof ServerFunctionsRoute - '/ssr': typeof SsrRoute - '/streamed': typeof StreamedRoute - '/api/base': typeof ApiBaseRoute - '/api/bulk-headers': typeof ApiBulkHeadersRoute - '/api/clear-returned-headers': typeof ApiClearReturnedHeadersRoute - '/api/direct-mutation-visible': typeof ApiDirectMutationVisibleRoute - '/api/explicit-set-cookie-header': typeof ApiExplicitSetCookieHeaderRoute - '/api/framing-error': typeof ApiFramingErrorRoute - '/api/get-response-header-helper': typeof ApiGetResponseHeaderHelperRoute - '/api/get-response-headers-helper': typeof ApiGetResponseHeadersHelperRoute - '/api/multiple-cookies': typeof ApiMultipleCookiesRoute - '/api/null-body-status': typeof ApiNullBodyStatusRoute - '/api/readonly-after-next': typeof ApiReadonlyAfterNextRoute - '/api/redirect-with-cookies': typeof ApiRedirectWithCookiesRoute - '/api/remove-returned-header': typeof ApiRemoveReturnedHeaderRoute - '/api/replace-after-direct-mutation': typeof ApiReplaceAfterDirectMutationRoute - '/api/replace-explicit-set-cookie': typeof ApiReplaceExplicitSetCookieRoute - '/api/route-after-next': typeof ApiRouteAfterNextRoute - '/api/route-before-next': typeof ApiRouteBeforeNextRoute - '/api/same-boundary-conflict': typeof ApiSameBoundaryConflictRoute - '/api/status-contracts': typeof ApiStatusContractsRoute - '/api/throw-after-status': typeof ApiThrowAfterStatusRoute - '/api/tracked-stream': typeof ApiTrackedStreamRoute - '/api/tracked-stream-status': typeof ApiTrackedStreamStatusRoute - '/api/two-returned-responses': typeof ApiTwoReturnedResponsesRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/server-functions': typeof ServerFunctionsRoute - '/ssr': typeof SsrRoute - '/streamed': typeof StreamedRoute - '/api/base': typeof ApiBaseRoute - '/api/bulk-headers': typeof ApiBulkHeadersRoute - '/api/clear-returned-headers': typeof ApiClearReturnedHeadersRoute - '/api/direct-mutation-visible': typeof ApiDirectMutationVisibleRoute - '/api/explicit-set-cookie-header': typeof ApiExplicitSetCookieHeaderRoute - '/api/framing-error': typeof ApiFramingErrorRoute - '/api/get-response-header-helper': typeof ApiGetResponseHeaderHelperRoute - '/api/get-response-headers-helper': typeof ApiGetResponseHeadersHelperRoute - '/api/multiple-cookies': typeof ApiMultipleCookiesRoute - '/api/null-body-status': typeof ApiNullBodyStatusRoute - '/api/readonly-after-next': typeof ApiReadonlyAfterNextRoute - '/api/redirect-with-cookies': typeof ApiRedirectWithCookiesRoute - '/api/remove-returned-header': typeof ApiRemoveReturnedHeaderRoute - '/api/replace-after-direct-mutation': typeof ApiReplaceAfterDirectMutationRoute - '/api/replace-explicit-set-cookie': typeof ApiReplaceExplicitSetCookieRoute - '/api/route-after-next': typeof ApiRouteAfterNextRoute - '/api/route-before-next': typeof ApiRouteBeforeNextRoute - '/api/same-boundary-conflict': typeof ApiSameBoundaryConflictRoute - '/api/status-contracts': typeof ApiStatusContractsRoute - '/api/throw-after-status': typeof ApiThrowAfterStatusRoute - '/api/tracked-stream': typeof ApiTrackedStreamRoute - '/api/tracked-stream-status': typeof ApiTrackedStreamStatusRoute - '/api/two-returned-responses': typeof ApiTwoReturnedResponsesRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/server-functions': typeof ServerFunctionsRoute - '/ssr': typeof SsrRoute - '/streamed': typeof StreamedRoute - '/api/base': typeof ApiBaseRoute - '/api/bulk-headers': typeof ApiBulkHeadersRoute - '/api/clear-returned-headers': typeof ApiClearReturnedHeadersRoute - '/api/direct-mutation-visible': typeof ApiDirectMutationVisibleRoute - '/api/explicit-set-cookie-header': typeof ApiExplicitSetCookieHeaderRoute - '/api/framing-error': typeof ApiFramingErrorRoute - '/api/get-response-header-helper': typeof ApiGetResponseHeaderHelperRoute - '/api/get-response-headers-helper': typeof ApiGetResponseHeadersHelperRoute - '/api/multiple-cookies': typeof ApiMultipleCookiesRoute - '/api/null-body-status': typeof ApiNullBodyStatusRoute - '/api/readonly-after-next': typeof ApiReadonlyAfterNextRoute - '/api/redirect-with-cookies': typeof ApiRedirectWithCookiesRoute - '/api/remove-returned-header': typeof ApiRemoveReturnedHeaderRoute - '/api/replace-after-direct-mutation': typeof ApiReplaceAfterDirectMutationRoute - '/api/replace-explicit-set-cookie': typeof ApiReplaceExplicitSetCookieRoute - '/api/route-after-next': typeof ApiRouteAfterNextRoute - '/api/route-before-next': typeof ApiRouteBeforeNextRoute - '/api/same-boundary-conflict': typeof ApiSameBoundaryConflictRoute - '/api/status-contracts': typeof ApiStatusContractsRoute - '/api/throw-after-status': typeof ApiThrowAfterStatusRoute - '/api/tracked-stream': typeof ApiTrackedStreamRoute - '/api/tracked-stream-status': typeof ApiTrackedStreamStatusRoute - '/api/two-returned-responses': typeof ApiTwoReturnedResponsesRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/server-functions' - | '/ssr' - | '/streamed' - | '/api/base' - | '/api/bulk-headers' - | '/api/clear-returned-headers' - | '/api/direct-mutation-visible' - | '/api/explicit-set-cookie-header' - | '/api/framing-error' - | '/api/get-response-header-helper' - | '/api/get-response-headers-helper' - | '/api/multiple-cookies' - | '/api/null-body-status' - | '/api/readonly-after-next' - | '/api/redirect-with-cookies' - | '/api/remove-returned-header' - | '/api/replace-after-direct-mutation' - | '/api/replace-explicit-set-cookie' - | '/api/route-after-next' - | '/api/route-before-next' - | '/api/same-boundary-conflict' - | '/api/status-contracts' - | '/api/throw-after-status' - | '/api/tracked-stream' - | '/api/tracked-stream-status' - | '/api/two-returned-responses' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/server-functions' - | '/ssr' - | '/streamed' - | '/api/base' - | '/api/bulk-headers' - | '/api/clear-returned-headers' - | '/api/direct-mutation-visible' - | '/api/explicit-set-cookie-header' - | '/api/framing-error' - | '/api/get-response-header-helper' - | '/api/get-response-headers-helper' - | '/api/multiple-cookies' - | '/api/null-body-status' - | '/api/readonly-after-next' - | '/api/redirect-with-cookies' - | '/api/remove-returned-header' - | '/api/replace-after-direct-mutation' - | '/api/replace-explicit-set-cookie' - | '/api/route-after-next' - | '/api/route-before-next' - | '/api/same-boundary-conflict' - | '/api/status-contracts' - | '/api/throw-after-status' - | '/api/tracked-stream' - | '/api/tracked-stream-status' - | '/api/two-returned-responses' - id: - | '__root__' - | '/' - | '/server-functions' - | '/ssr' - | '/streamed' - | '/api/base' - | '/api/bulk-headers' - | '/api/clear-returned-headers' - | '/api/direct-mutation-visible' - | '/api/explicit-set-cookie-header' - | '/api/framing-error' - | '/api/get-response-header-helper' - | '/api/get-response-headers-helper' - | '/api/multiple-cookies' - | '/api/null-body-status' - | '/api/readonly-after-next' - | '/api/redirect-with-cookies' - | '/api/remove-returned-header' - | '/api/replace-after-direct-mutation' - | '/api/replace-explicit-set-cookie' - | '/api/route-after-next' - | '/api/route-before-next' - | '/api/same-boundary-conflict' - | '/api/status-contracts' - | '/api/throw-after-status' - | '/api/tracked-stream' - | '/api/tracked-stream-status' - | '/api/two-returned-responses' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ServerFunctionsRoute: typeof ServerFunctionsRoute - SsrRoute: typeof SsrRoute - StreamedRoute: typeof StreamedRoute - ApiBaseRoute: typeof ApiBaseRoute - ApiBulkHeadersRoute: typeof ApiBulkHeadersRoute - ApiClearReturnedHeadersRoute: typeof ApiClearReturnedHeadersRoute - ApiDirectMutationVisibleRoute: typeof ApiDirectMutationVisibleRoute - ApiExplicitSetCookieHeaderRoute: typeof ApiExplicitSetCookieHeaderRoute - ApiFramingErrorRoute: typeof ApiFramingErrorRoute - ApiGetResponseHeaderHelperRoute: typeof ApiGetResponseHeaderHelperRoute - ApiGetResponseHeadersHelperRoute: typeof ApiGetResponseHeadersHelperRoute - ApiMultipleCookiesRoute: typeof ApiMultipleCookiesRoute - ApiNullBodyStatusRoute: typeof ApiNullBodyStatusRoute - ApiReadonlyAfterNextRoute: typeof ApiReadonlyAfterNextRoute - ApiRedirectWithCookiesRoute: typeof ApiRedirectWithCookiesRoute - ApiRemoveReturnedHeaderRoute: typeof ApiRemoveReturnedHeaderRoute - ApiReplaceAfterDirectMutationRoute: typeof ApiReplaceAfterDirectMutationRoute - ApiReplaceExplicitSetCookieRoute: typeof ApiReplaceExplicitSetCookieRoute - ApiRouteAfterNextRoute: typeof ApiRouteAfterNextRoute - ApiRouteBeforeNextRoute: typeof ApiRouteBeforeNextRoute - ApiSameBoundaryConflictRoute: typeof ApiSameBoundaryConflictRoute - ApiStatusContractsRoute: typeof ApiStatusContractsRoute - ApiThrowAfterStatusRoute: typeof ApiThrowAfterStatusRoute - ApiTrackedStreamRoute: typeof ApiTrackedStreamRoute - ApiTrackedStreamStatusRoute: typeof ApiTrackedStreamStatusRoute - ApiTwoReturnedResponsesRoute: typeof ApiTwoReturnedResponsesRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/server-functions': { - id: '/server-functions' - path: '/server-functions' - fullPath: '/server-functions' - preLoaderRoute: typeof ServerFunctionsRouteImport - parentRoute: typeof rootRouteImport - } - '/ssr': { - id: '/ssr' - path: '/ssr' - fullPath: '/ssr' - preLoaderRoute: typeof SsrRouteImport - parentRoute: typeof rootRouteImport - } - '/streamed': { - id: '/streamed' - path: '/streamed' - fullPath: '/streamed' - preLoaderRoute: typeof StreamedRouteImport - parentRoute: typeof rootRouteImport - } - '/api/base': { - id: '/api/base' - path: '/api/base' - fullPath: '/api/base' - preLoaderRoute: typeof ApiBaseRouteImport - parentRoute: typeof rootRouteImport - } - '/api/bulk-headers': { - id: '/api/bulk-headers' - path: '/api/bulk-headers' - fullPath: '/api/bulk-headers' - preLoaderRoute: typeof ApiBulkHeadersRouteImport - parentRoute: typeof rootRouteImport - } - '/api/clear-returned-headers': { - id: '/api/clear-returned-headers' - path: '/api/clear-returned-headers' - fullPath: '/api/clear-returned-headers' - preLoaderRoute: typeof ApiClearReturnedHeadersRouteImport - parentRoute: typeof rootRouteImport - } - '/api/direct-mutation-visible': { - id: '/api/direct-mutation-visible' - path: '/api/direct-mutation-visible' - fullPath: '/api/direct-mutation-visible' - preLoaderRoute: typeof ApiDirectMutationVisibleRouteImport - parentRoute: typeof rootRouteImport - } - '/api/explicit-set-cookie-header': { - id: '/api/explicit-set-cookie-header' - path: '/api/explicit-set-cookie-header' - fullPath: '/api/explicit-set-cookie-header' - preLoaderRoute: typeof ApiExplicitSetCookieHeaderRouteImport - parentRoute: typeof rootRouteImport - } - '/api/framing-error': { - id: '/api/framing-error' - path: '/api/framing-error' - fullPath: '/api/framing-error' - preLoaderRoute: typeof ApiFramingErrorRouteImport - parentRoute: typeof rootRouteImport - } - '/api/get-response-header-helper': { - id: '/api/get-response-header-helper' - path: '/api/get-response-header-helper' - fullPath: '/api/get-response-header-helper' - preLoaderRoute: typeof ApiGetResponseHeaderHelperRouteImport - parentRoute: typeof rootRouteImport - } - '/api/get-response-headers-helper': { - id: '/api/get-response-headers-helper' - path: '/api/get-response-headers-helper' - fullPath: '/api/get-response-headers-helper' - preLoaderRoute: typeof ApiGetResponseHeadersHelperRouteImport - parentRoute: typeof rootRouteImport - } - '/api/multiple-cookies': { - id: '/api/multiple-cookies' - path: '/api/multiple-cookies' - fullPath: '/api/multiple-cookies' - preLoaderRoute: typeof ApiMultipleCookiesRouteImport - parentRoute: typeof rootRouteImport - } - '/api/null-body-status': { - id: '/api/null-body-status' - path: '/api/null-body-status' - fullPath: '/api/null-body-status' - preLoaderRoute: typeof ApiNullBodyStatusRouteImport - parentRoute: typeof rootRouteImport - } - '/api/readonly-after-next': { - id: '/api/readonly-after-next' - path: '/api/readonly-after-next' - fullPath: '/api/readonly-after-next' - preLoaderRoute: typeof ApiReadonlyAfterNextRouteImport - parentRoute: typeof rootRouteImport - } - '/api/redirect-with-cookies': { - id: '/api/redirect-with-cookies' - path: '/api/redirect-with-cookies' - fullPath: '/api/redirect-with-cookies' - preLoaderRoute: typeof ApiRedirectWithCookiesRouteImport - parentRoute: typeof rootRouteImport - } - '/api/remove-returned-header': { - id: '/api/remove-returned-header' - path: '/api/remove-returned-header' - fullPath: '/api/remove-returned-header' - preLoaderRoute: typeof ApiRemoveReturnedHeaderRouteImport - parentRoute: typeof rootRouteImport - } - '/api/replace-after-direct-mutation': { - id: '/api/replace-after-direct-mutation' - path: '/api/replace-after-direct-mutation' - fullPath: '/api/replace-after-direct-mutation' - preLoaderRoute: typeof ApiReplaceAfterDirectMutationRouteImport - parentRoute: typeof rootRouteImport - } - '/api/replace-explicit-set-cookie': { - id: '/api/replace-explicit-set-cookie' - path: '/api/replace-explicit-set-cookie' - fullPath: '/api/replace-explicit-set-cookie' - preLoaderRoute: typeof ApiReplaceExplicitSetCookieRouteImport - parentRoute: typeof rootRouteImport - } - '/api/route-after-next': { - id: '/api/route-after-next' - path: '/api/route-after-next' - fullPath: '/api/route-after-next' - preLoaderRoute: typeof ApiRouteAfterNextRouteImport - parentRoute: typeof rootRouteImport - } - '/api/route-before-next': { - id: '/api/route-before-next' - path: '/api/route-before-next' - fullPath: '/api/route-before-next' - preLoaderRoute: typeof ApiRouteBeforeNextRouteImport - parentRoute: typeof rootRouteImport - } - '/api/same-boundary-conflict': { - id: '/api/same-boundary-conflict' - path: '/api/same-boundary-conflict' - fullPath: '/api/same-boundary-conflict' - preLoaderRoute: typeof ApiSameBoundaryConflictRouteImport - parentRoute: typeof rootRouteImport - } - '/api/status-contracts': { - id: '/api/status-contracts' - path: '/api/status-contracts' - fullPath: '/api/status-contracts' - preLoaderRoute: typeof ApiStatusContractsRouteImport - parentRoute: typeof rootRouteImport - } - '/api/throw-after-status': { - id: '/api/throw-after-status' - path: '/api/throw-after-status' - fullPath: '/api/throw-after-status' - preLoaderRoute: typeof ApiThrowAfterStatusRouteImport - parentRoute: typeof rootRouteImport - } - '/api/tracked-stream': { - id: '/api/tracked-stream' - path: '/api/tracked-stream' - fullPath: '/api/tracked-stream' - preLoaderRoute: typeof ApiTrackedStreamRouteImport - parentRoute: typeof rootRouteImport - } - '/api/tracked-stream-status': { - id: '/api/tracked-stream-status' - path: '/api/tracked-stream-status' - fullPath: '/api/tracked-stream-status' - preLoaderRoute: typeof ApiTrackedStreamStatusRouteImport - parentRoute: typeof rootRouteImport - } - '/api/two-returned-responses': { - id: '/api/two-returned-responses' - path: '/api/two-returned-responses' - fullPath: '/api/two-returned-responses' - preLoaderRoute: typeof ApiTwoReturnedResponsesRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ServerFunctionsRoute: ServerFunctionsRoute, - SsrRoute: SsrRoute, - StreamedRoute: StreamedRoute, - ApiBaseRoute: ApiBaseRoute, - ApiBulkHeadersRoute: ApiBulkHeadersRoute, - ApiClearReturnedHeadersRoute: ApiClearReturnedHeadersRoute, - ApiDirectMutationVisibleRoute: ApiDirectMutationVisibleRoute, - ApiExplicitSetCookieHeaderRoute: ApiExplicitSetCookieHeaderRoute, - ApiFramingErrorRoute: ApiFramingErrorRoute, - ApiGetResponseHeaderHelperRoute: ApiGetResponseHeaderHelperRoute, - ApiGetResponseHeadersHelperRoute: ApiGetResponseHeadersHelperRoute, - ApiMultipleCookiesRoute: ApiMultipleCookiesRoute, - ApiNullBodyStatusRoute: ApiNullBodyStatusRoute, - ApiReadonlyAfterNextRoute: ApiReadonlyAfterNextRoute, - ApiRedirectWithCookiesRoute: ApiRedirectWithCookiesRoute, - ApiRemoveReturnedHeaderRoute: ApiRemoveReturnedHeaderRoute, - ApiReplaceAfterDirectMutationRoute: ApiReplaceAfterDirectMutationRoute, - ApiReplaceExplicitSetCookieRoute: ApiReplaceExplicitSetCookieRoute, - ApiRouteAfterNextRoute: ApiRouteAfterNextRoute, - ApiRouteBeforeNextRoute: ApiRouteBeforeNextRoute, - ApiSameBoundaryConflictRoute: ApiSameBoundaryConflictRoute, - ApiStatusContractsRoute: ApiStatusContractsRoute, - ApiThrowAfterStatusRoute: ApiThrowAfterStatusRoute, - ApiTrackedStreamRoute: ApiTrackedStreamRoute, - ApiTrackedStreamStatusRoute: ApiTrackedStreamStatusRoute, - ApiTwoReturnedResponsesRoute: ApiTwoReturnedResponsesRoute, -} -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/response-reconciliation/src/router.tsx b/e2e/react-start/response-reconciliation/src/router.tsx deleted file mode 100644 index c5c2209e5a..0000000000 --- a/e2e/react-start/response-reconciliation/src/router.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' -import { DefaultCatchBoundary } from './components/DefaultCatchBoundary' -import { NotFound } from './components/NotFound' - -export function getRouter() { - return createRouter({ - routeTree, - defaultErrorComponent: DefaultCatchBoundary, - defaultNotFoundComponent: () => , - scrollRestoration: true, - }) -} diff --git a/e2e/react-start/response-reconciliation/src/routes/__root.tsx b/e2e/react-start/response-reconciliation/src/routes/__root.tsx deleted file mode 100644 index a562991887..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/__root.tsx +++ /dev/null @@ -1,57 +0,0 @@ -/// -import * as React from 'react' -import { - HeadContent, - Link, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' -import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary' -import { NotFound } from '~/components/NotFound' -import '~/styles/app.css' - -export const Route = createRootRoute({ - head: () => ({ - meta: [ - { charSet: 'utf-8' }, - { name: 'viewport', content: 'width=device-width, initial-scale=1' }, - ], - }), - errorComponent: (props) => { - return ( - - - - ) - }, - notFoundComponent: () => , - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - ) -} - -function RootDocument({ children }: { children: React.ReactNode }) { - return ( - - - - - - - {children} - - - - ) -} diff --git a/e2e/react-start/response-reconciliation/src/routes/api/-response.ts b/e2e/react-start/response-reconciliation/src/routes/api/-response.ts deleted file mode 100644 index 54082c10f6..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/-response.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { createMiddleware } from '@tanstack/react-start' -import { - getResponseHeader, - setResponseHeader, - setResponseStatus, -} from '@tanstack/react-start/server' - -function getScenario(request: Request) { - const url = new URL(request.url) - return url.pathname.split('/').pop() || '' -} - -export function baseResponse(scenario: string) { - return new Response(scenario, { - headers: { 'x-handler': scenario, 'x-base': 'yes' }, - }) -} - -export const routeBoundaryMiddleware = createMiddleware().server( - async ({ next, request }) => { - const scenario = getScenario(request) - - if (scenario === 'route-before-next') { - setResponseHeader('x-route-before', 'yes') - setResponseStatus(234, 'route-before') - return next() - } - - if (scenario === 'route-after-next') { - const result = await next() - setResponseHeader('x-route-after', 'yes') - setResponseStatus(233, 'route-after') - return result - } - - if (scenario === 'direct-mutation-visible') { - const result = await next() - result.response.headers.set('x-direct-visible', 'yes') - setResponseHeader( - 'x-direct-read', - getResponseHeader('x-direct-visible') || 'missing', - ) - return result - } - - if (scenario === 'replace-after-direct-mutation') { - const result = await next() - result.response.headers.set('x-direct-a', 'yes') - setResponseHeader('x-helper-delta', 'yes') - return new Response('replacement', { - status: 202, - headers: { 'x-response-b': 'yes' }, - }) - } - - if (scenario === 'two-returned-responses') { - await next() - setResponseHeader('x-helper-after-a', 'yes') - return new Response('response-b', { - headers: { 'x-response-b': 'yes' }, - }) - } - - if (scenario === 'readonly-after-next') { - const result = await next() - setResponseHeader('x-readonly-after', 'yes') - return result - } - - return next() - }, -) - -export const returnedResponseMiddleware = createMiddleware().server( - async ({ next, request }) => { - if (getScenario(request) === 'two-returned-responses') { - await next() - return new Response('response-a', { - headers: { 'x-response-a': 'yes' }, - }) - } - - return next() - }, -) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/-tracked-streams.ts b/e2e/react-start/response-reconciliation/src/routes/api/-tracked-streams.ts deleted file mode 100644 index 1ccde76367..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/-tracked-streams.ts +++ /dev/null @@ -1,2 +0,0 @@ -// Ids of tracked response streams that were cancelled, kept by the server. -export const cancelledStreams = new Set() diff --git a/e2e/react-start/response-reconciliation/src/routes/api/-upstream.ts b/e2e/react-start/response-reconciliation/src/routes/api/-upstream.ts deleted file mode 100644 index 0018376035..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/-upstream.ts +++ /dev/null @@ -1,14 +0,0 @@ -// An upstream reply whose headers describe its own body and client. Start must -// not copy them onto the error body it generates for this failure. -export function createUpstreamFailure() { - return new Response('

upstream

', { - status: 502, - headers: { - 'content-encoding': 'gzip', - 'content-length': '999', - 'content-type': 'text/html', - 'set-cookie': 'upstream-session=leaked; Path=/', - 'x-upstream': 'yes', - }, - }) -} diff --git a/e2e/react-start/response-reconciliation/src/routes/api/base.ts b/e2e/react-start/response-reconciliation/src/routes/api/base.ts deleted file mode 100644 index 62f706a9f1..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/base.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { baseResponse } from './-response' - -export const Route = createFileRoute('/api/base')({ - server: { - handlers: { - GET: () => baseResponse('base'), - }, - }, -}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/bulk-headers.ts b/e2e/react-start/response-reconciliation/src/routes/api/bulk-headers.ts deleted file mode 100644 index db7ded6c54..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/bulk-headers.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { setResponseHeaders } from '@tanstack/react-start/server' - -export const Route = createFileRoute('/api/bulk-headers')({ - server: { - handlers: { - GET: () => { - const headers = new Headers({ - 'x-bulk-one': '1', - 'x-bulk-two': '2', - }) - headers.append('set-cookie', 'bulk-one=1; Path=/') - headers.append('set-cookie', 'bulk-two=2; Path=/') - setResponseHeaders(headers) - return new Response('bulk', { headers: { 'x-keep': 'yes' } }) - }, - }, - }, -}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/clear-returned-headers.ts b/e2e/react-start/response-reconciliation/src/routes/api/clear-returned-headers.ts deleted file mode 100644 index fd3b88c172..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/clear-returned-headers.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { clearResponseHeaders } from '@tanstack/react-start/server' - -export const Route = createFileRoute('/api/clear-returned-headers')({ - server: { - handlers: { - GET: () => { - clearResponseHeaders() - return new Response('clear', { - headers: { 'x-clear-one': '1', 'x-clear-two': '2' }, - }) - }, - }, - }, -}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/direct-mutation-visible.ts b/e2e/react-start/response-reconciliation/src/routes/api/direct-mutation-visible.ts deleted file mode 100644 index 96823887e5..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/direct-mutation-visible.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { baseResponse, routeBoundaryMiddleware } from './-response' - -export const Route = createFileRoute('/api/direct-mutation-visible')({ - server: { - middleware: [routeBoundaryMiddleware], - handlers: { - GET: () => baseResponse('direct-mutation-visible'), - }, - }, -}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/explicit-set-cookie-header.ts b/e2e/react-start/response-reconciliation/src/routes/api/explicit-set-cookie-header.ts deleted file mode 100644 index 3ea2bc6d75..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/explicit-set-cookie-header.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { setResponseHeader } from '@tanstack/react-start/server' - -export const Route = createFileRoute('/api/explicit-set-cookie-header')({ - server: { - handlers: { - GET: () => { - setResponseHeader('set-cookie', [ - 'explicit-one=1; Path=/', - 'explicit-two=2; Path=/', - ]) - return new Response('explicit') - }, - }, - }, -}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/framing-error.ts b/e2e/react-start/response-reconciliation/src/routes/api/framing-error.ts deleted file mode 100644 index baeab15780..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/framing-error.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { setResponseHeader } from '@tanstack/react-start/server' - -export const Route = createFileRoute('/api/framing-error')({ - server: { - handlers: { - GET: async () => { - // Headers for a compressed file whose read then fails. - setResponseHeader('content-encoding', 'gzip') - setResponseHeader('content-length', '2') - await Promise.resolve() - throw new Error('File read failed') - }, - }, - }, -}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/get-response-header-helper.ts b/e2e/react-start/response-reconciliation/src/routes/api/get-response-header-helper.ts deleted file mode 100644 index b597882ff6..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/get-response-header-helper.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { - getResponseHeader, - setResponseHeader, -} from '@tanstack/react-start/server' - -export const Route = createFileRoute('/api/get-response-header-helper')({ - server: { - handlers: { - GET: () => { - setResponseHeader('x-helper-visible', 'yes') - const value = getResponseHeader('x-helper-visible') || 'missing' - return new Response(value, { headers: { 'x-read-after-set': value } }) - }, - }, - }, -}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/get-response-headers-helper.ts b/e2e/react-start/response-reconciliation/src/routes/api/get-response-headers-helper.ts deleted file mode 100644 index 168d38bad4..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/get-response-headers-helper.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { - getResponseHeaders, - setResponseHeader, -} from '@tanstack/react-start/server' - -export const Route = createFileRoute('/api/get-response-headers-helper')({ - server: { - handlers: { - GET: () => { - setResponseHeader('x-headers-helper-visible', 'yes') - // Exercise an untyped caller mutating its detached snapshot. - const headers = getResponseHeaders() as Headers - const value = headers.get('x-headers-helper-visible') || 'missing' - headers.set('x-headers-snapshot-write', 'ignored') - return new Response(value, { headers: { 'x-headers-read': value } }) - }, - }, - }, -}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/multiple-cookies.ts b/e2e/react-start/response-reconciliation/src/routes/api/multiple-cookies.ts deleted file mode 100644 index eebf7a167e..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/multiple-cookies.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { setCookie } from '@tanstack/react-start/server' - -export const Route = createFileRoute('/api/multiple-cookies')({ - server: { - handlers: { - GET: () => { - setCookie('route-one', '1', { path: '/' }) - setCookie('route-two', '2', { path: '/' }) - return new Response('cookies') - }, - }, - }, -}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/null-body-status.ts b/e2e/react-start/response-reconciliation/src/routes/api/null-body-status.ts deleted file mode 100644 index d11056e7a8..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/null-body-status.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { setResponseStatus } from '@tanstack/react-start/server' - -export const Route = createFileRoute('/api/null-body-status')({ - server: { - handlers: { - GET: ({ request }) => { - const statusParam = new URL(request.url).searchParams.get('status') - const status = - statusParam === '205' ? 205 : statusParam === '304' ? 304 : 204 - setResponseStatus(status) - return new Response('should-drop', { - headers: { 'x-null-body': 'yes' }, - }) - }, - }, - }, -}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/readonly-after-next.ts b/e2e/react-start/response-reconciliation/src/routes/api/readonly-after-next.ts deleted file mode 100644 index 7b42955052..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/readonly-after-next.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { routeBoundaryMiddleware } from './-response' - -export const Route = createFileRoute('/api/readonly-after-next')({ - server: { - middleware: [routeBoundaryMiddleware], - handlers: { - GET: () => fetch('data:text/plain,readonly'), - }, - }, -}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/redirect-with-cookies.ts b/e2e/react-start/response-reconciliation/src/routes/api/redirect-with-cookies.ts deleted file mode 100644 index 5b0072f35a..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/redirect-with-cookies.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { setCookie } from '@tanstack/react-start/server' - -export const Route = createFileRoute('/api/redirect-with-cookies')({ - server: { - handlers: { - GET: () => { - setCookie('redirect-one', '1', { path: '/' }) - setCookie('redirect-two', '2', { path: '/' }) - setCookie('redirect-three', '3', { path: '/' }) - return new Response(null, { - status: 307, - headers: { Location: '/api/base' }, - }) - }, - }, - }, -}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/remove-returned-header.ts b/e2e/react-start/response-reconciliation/src/routes/api/remove-returned-header.ts deleted file mode 100644 index 96f82bf98d..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/remove-returned-header.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { removeResponseHeader } from '@tanstack/react-start/server' - -export const Route = createFileRoute('/api/remove-returned-header')({ - server: { - handlers: { - GET: () => { - removeResponseHeader('x-remove-me') - return new Response('remove', { - headers: { 'x-remove-me': 'response', 'x-keep': 'yes' }, - }) - }, - }, - }, -}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/replace-after-direct-mutation.ts b/e2e/react-start/response-reconciliation/src/routes/api/replace-after-direct-mutation.ts deleted file mode 100644 index 890280483d..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/replace-after-direct-mutation.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { baseResponse, routeBoundaryMiddleware } from './-response' - -export const Route = createFileRoute('/api/replace-after-direct-mutation')({ - server: { - middleware: [routeBoundaryMiddleware], - handlers: { - GET: () => baseResponse('replace-after-direct-mutation'), - }, - }, -}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/replace-explicit-set-cookie.ts b/e2e/react-start/response-reconciliation/src/routes/api/replace-explicit-set-cookie.ts deleted file mode 100644 index 97df27d915..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/replace-explicit-set-cookie.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { setResponseHeader } from '@tanstack/react-start/server' - -export const Route = createFileRoute('/api/replace-explicit-set-cookie')({ - server: { - handlers: { - GET: () => { - setResponseHeader('set-cookie', 'explicit-new=1; Path=/') - return new Response('explicit', { - headers: { 'set-cookie': 'explicit-old=1; Path=/' }, - }) - }, - }, - }, -}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/route-after-next.ts b/e2e/react-start/response-reconciliation/src/routes/api/route-after-next.ts deleted file mode 100644 index 7d3650147f..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/route-after-next.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { baseResponse, routeBoundaryMiddleware } from './-response' - -export const Route = createFileRoute('/api/route-after-next')({ - server: { - middleware: [routeBoundaryMiddleware], - handlers: { - GET: () => baseResponse('route-after-next'), - }, - }, -}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/route-before-next.ts b/e2e/react-start/response-reconciliation/src/routes/api/route-before-next.ts deleted file mode 100644 index b52c7642af..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/route-before-next.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { baseResponse, routeBoundaryMiddleware } from './-response' - -export const Route = createFileRoute('/api/route-before-next')({ - server: { - middleware: [routeBoundaryMiddleware], - handlers: { - GET: () => baseResponse('route-before-next'), - }, - }, -}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/same-boundary-conflict.ts b/e2e/react-start/response-reconciliation/src/routes/api/same-boundary-conflict.ts deleted file mode 100644 index 7ac086d652..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/same-boundary-conflict.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { - setResponseHeader, - setResponseStatus, -} from '@tanstack/react-start/server' - -export const Route = createFileRoute('/api/same-boundary-conflict')({ - server: { - handlers: { - GET: () => { - setResponseStatus(235, 'same-boundary') - setResponseHeader('x-conflict', 'helper') - return new Response('conflict', { - status: 201, - statusText: 'response-status', - headers: { 'x-conflict': 'response' }, - }) - }, - }, - }, -}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/status-contracts.ts b/e2e/react-start/response-reconciliation/src/routes/api/status-contracts.ts deleted file mode 100644 index 43fd72ec07..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/status-contracts.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { setResponseStatus } from '@tanstack/react-start/server' -import { createUpstreamFailure } from './-upstream' - -export const Route = createFileRoute('/api/status-contracts')({ - server: { - handlers: { - GET: async ({ request }) => { - const scenario = new URL(request.url).searchParams.get('scenario') - - if (scenario === 'invalid-status-return') { - setResponseStatus(999, 'Ignored') - return new Response('missing', { - status: 404, - statusText: 'Not Found', - }) - } - - if (scenario === 'invalid-status-throw') { - setResponseStatus(101) - throw new Error('Unexpected status contract failure') - } - - if (scenario === 'slow') { - await new Promise((resolve) => setTimeout(resolve, 150)) - return new Response('slow result') - } - - if (scenario === 'helper-success-crash') { - setResponseStatus(201, 'Created') - throw new Error('Crash after a success status') - } - - if (scenario === 'upstream-error-cause') { - throw new Error('Upstream failed', { cause: createUpstreamFailure() }) - } - - return new Response(`Unknown scenario: ${scenario}`, { status: 400 }) - }, - }, - }, -}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/throw-after-status.ts b/e2e/react-start/response-reconciliation/src/routes/api/throw-after-status.ts deleted file mode 100644 index 9d93d75b61..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/throw-after-status.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { - setCookie, - setResponseHeader, - setResponseStatus, -} from '@tanstack/react-start/server' - -export const Route = createFileRoute('/api/throw-after-status')({ - server: { - handlers: { - GET: ({ request }) => { - const url = new URL(request.url) - setResponseStatus(401, 'Unauthorized') - setResponseHeader('x-error-helper', 'yes') - setCookie('throw-after-status', '1', { path: '/' }) - if (url.searchParams.get('throw') === 'response') { - throw new Response('Unauthorized response', { - status: 200, - headers: { 'x-thrown-response': 'yes' }, - }) - } - throw new Error('Unauthorized route') - }, - }, - }, -}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/tracked-stream-status.ts b/e2e/react-start/response-reconciliation/src/routes/api/tracked-stream-status.ts deleted file mode 100644 index 1aaffd8d36..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/tracked-stream-status.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { cancelledStreams } from './-tracked-streams' - -export const Route = createFileRoute('/api/tracked-stream-status')({ - server: { - handlers: { - GET: ({ request }) => { - const id = new URL(request.url).searchParams.get('id') ?? '' - return Response.json({ cancelled: cancelledStreams.has(id) }) - }, - }, - }, -}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/tracked-stream.ts b/e2e/react-start/response-reconciliation/src/routes/api/tracked-stream.ts deleted file mode 100644 index 640074a035..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/tracked-stream.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { cancelledStreams } from './-tracked-streams' - -export const Route = createFileRoute('/api/tracked-stream')({ - server: { - handlers: { - // A body that never ends, like a live feed. Only cancellation stops it. - GET: ({ request }) => { - const id = new URL(request.url).searchParams.get('id') ?? '' - return new Response( - new ReadableStream({ - start(controller) { - controller.enqueue(new TextEncoder().encode('tracked')) - }, - cancel() { - cancelledStreams.add(id) - }, - }), - ) - }, - }, - }, -}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/two-returned-responses.ts b/e2e/react-start/response-reconciliation/src/routes/api/two-returned-responses.ts deleted file mode 100644 index f433778fd8..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/two-returned-responses.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { - baseResponse, - returnedResponseMiddleware, - routeBoundaryMiddleware, -} from './-response' - -export const Route = createFileRoute('/api/two-returned-responses')({ - server: { - middleware: [routeBoundaryMiddleware, returnedResponseMiddleware], - handlers: { - GET: () => baseResponse('two-returned-responses'), - }, - }, -}) diff --git a/e2e/react-start/response-reconciliation/src/routes/index.tsx b/e2e/react-start/response-reconciliation/src/routes/index.tsx deleted file mode 100644 index ab938397e9..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/index.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - headers: () => ({ 'x-route-header': 'present' }), - component: Home, -}) - -function Home() { - return ( -
-

Response Reconciliation E2E

-

This app contains HTTP-level regression tests.

-
- ) -} diff --git a/e2e/react-start/response-reconciliation/src/routes/server-functions.tsx b/e2e/react-start/response-reconciliation/src/routes/server-functions.tsx deleted file mode 100644 index 580309b31e..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/server-functions.tsx +++ /dev/null @@ -1,285 +0,0 @@ -import { ClientOnly, createFileRoute, redirect } from '@tanstack/react-router' -import { - createMiddleware, - createServerFn, - useServerFn, -} from '@tanstack/react-start' -import * as React from 'react' -import { - getResponseHeader, - setCookie, - setResponseHeader, - setResponseHeaders, - setResponseStatus, -} from '@tanstack/react-start/server' - -const functionAfterNextMiddleware = createMiddleware({ - type: 'function', -}).server(async ({ next }) => { - const result = await next() - setResponseHeader('x-function-after', 'yes') - setResponseStatus(236, 'function-after') - return result -}) - -const rawResponseAfterNextMiddleware = createMiddleware({ - type: 'function', -}).server(async ({ next }) => { - const result = await next() - setResponseHeader('x-function-raw-after', 'yes') - setResponseStatus(237, 'function-raw-after') - return result -}) - -const throwStatusMiddleware = createMiddleware({ - type: 'function', -}).server(() => { - setResponseStatus(401, 'Unauthorized') - setResponseHeader('x-function-error-middleware', 'yes') - throw new Error('Unauthorized function middleware') -}) - -const replacementMiddleware = createMiddleware({ - type: 'function', -}).server(async ({ next }) => { - const result = await next() - const resultWithResponse = result as typeof result & { result?: unknown } - if (!(resultWithResponse.result instanceof Response)) { - throw new Error('Expected replacement test to observe a Response') - } - resultWithResponse.result.headers.set('x-function-a', 'yes') - setResponseHeader('x-function-helper-delta', 'yes') - // Function middleware types don't model raw Response replacement, but the - // middleware executor supports it; this fixture deliberately exercises that - // runtime path. - return new Response('function-b', { - headers: { 'x-function-b': 'yes' }, - }) as never -}) - -const globalSerializedFn = createServerFn().handler(() => { - return { ok: true } -}) - -const functionAfterNextFn = createServerFn() - .middleware([functionAfterNextMiddleware]) - .handler(() => { - return { ok: true } - }) - -const rawResponseAfterNextFn = createServerFn() - .middleware([rawResponseAfterNextMiddleware]) - .handler(() => { - return new Response('raw function body', { - headers: { 'x-function-raw': 'yes' }, - }) - }) - -const replacementFn = createServerFn() - .middleware([replacementMiddleware]) - .handler(() => { - return new Response('function-a') - }) - -const multipleCookiesFn = createServerFn().handler(() => { - setCookie('fn-one', '1', { path: '/' }) - setCookie('fn-two', '2', { path: '/' }) - return { ok: true } -}) - -const rawMultipleCookiesFn = createServerFn().handler(() => { - setCookie('fn-raw-helper-one', '1', { path: '/' }) - setCookie('fn-raw-helper-two', '2', { path: '/' }) - const headers = new Headers() - headers.append('set-cookie', 'fn-raw-returned-one=1; Path=/') - headers.append('set-cookie', 'fn-raw-returned-two=2; Path=/') - return new Response('raw cookie body', { headers }) -}) - -const explicitCookieHeaderFn = createServerFn().handler(() => { - setResponseHeader('set-cookie', [ - 'fn-explicit-one=1; Path=/', - 'fn-explicit-two=2; Path=/', - ]) - return { ok: true } -}) - -const throwAfterStatusFn = createServerFn().handler(() => { - setResponseStatus(401, 'Unauthorized') - setResponseHeader('x-function-error', 'yes') - throw new Error('Unauthorized function') -}) - -const throwAfterFramingFn = createServerFn().handler(async () => { - // Headers for a compressed file whose read then fails. - setResponseHeader('content-encoding', 'gzip') - setResponseHeader('content-length', '2') - await Promise.resolve() - throw new Error('File read failed') -}) - -const throwAfterMiddlewareStatusFn = createServerFn() - .middleware([throwStatusMiddleware]) - .handler(() => { - return { ok: true } - }) - -const transportProtectedFn = createServerFn().handler(() => { - setResponseHeaders( - new Headers({ - 'content-type': 'text/plain', - 'x-tss-serialized': 'false', - 'x-user-header': 'yes', - }), - ) - return { ok: true } -}) - -const readAfterSetFn = createServerFn().handler(() => { - setResponseHeader('x-read-after-set', 'yes') - setResponseHeader( - 'x-read-after-set-value', - getResponseHeader('x-read-after-set') || 'missing', - ) - return { ok: true } -}) - -const returnRedirectFn = createServerFn().handler(() => { - setResponseStatus(302, 'Continue') - setResponseHeaders( - new Headers({ - 'content-type': 'text/plain', - 'x-tss-raw': 'true', - 'x-tss-serialized': 'true', - location: '/middleware-target', - }), - ) - setCookie('rpc-redirect', 'committed', { path: '/' }) - return redirect({ to: '/' }) -}) - -const throwRedirectFn = createServerFn().handler(() => { - setResponseStatus(302, 'Continue') - setResponseHeaders( - new Headers({ - 'content-type': 'text/plain', - 'x-tss-raw': 'true', - 'x-tss-serialized': 'true', - location: '/middleware-target', - }), - ) - setCookie('rpc-redirect', 'committed', { path: '/' }) - throw redirect({ to: '/' }) -}) - -const bodylessStatusFn = createServerFn().handler(() => { - setResponseStatus(204, 'No Content') - setResponseHeader('x-bodyless-status', 'ignored') - return { ok: true } -}) - -const throwZeroFn = createServerFn().handler(() => { - throw 0 -}) - -const throwResponseFn = createServerFn().handler(() => { - throw new Response('teapot', { status: 418 }) -}) - -const helperLocationFn = createServerFn().handler(() => { - setResponseStatus(302) - setResponseHeader('location', '/api/base') - return { ok: true } -}) - -export const Route = createFileRoute('/server-functions')({ - component: ServerFunctions, -}) - -function ServerFunctions() { - return ( -
-

Server Functions

- - - - - - - - - - - - - - - - - - - - -
- ) -} - -function ServerFunctionButton({ - name, - fn, -}: { - name: string - fn: (...args: Array) => Promise -}) { - const serverFn = useServerFn(fn) - const [result, setResult] = React.useState('idle') - - return ( -
- - {result} -
- ) -} diff --git a/e2e/react-start/response-reconciliation/src/routes/ssr.tsx b/e2e/react-start/response-reconciliation/src/routes/ssr.tsx deleted file mode 100644 index c0cb69c8ec..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/ssr.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { createServerFn } from '@tanstack/react-start' -import { - setCookie, - setResponseHeader, - setResponseStatus, -} from '@tanstack/react-start/server' - -const setSsrResponseFn = createServerFn().handler(() => { - setResponseStatus(238, 'ssr-loader') - setResponseHeader('x-ssr-loader', 'yes') - setCookie('ssr-one', '1', { path: '/' }) - setCookie('ssr-two', '2', { path: '/' }) - return { message: 'ssr response' } -}) - -export const Route = createFileRoute('/ssr')({ - loader: () => setSsrResponseFn(), - component: SsrRoute, -}) - -function SsrRoute() { - const data = Route.useLoaderData() - return ( -
-

{data.message}

-
- ) -} diff --git a/e2e/react-start/response-reconciliation/src/routes/streamed.tsx b/e2e/react-start/response-reconciliation/src/routes/streamed.tsx deleted file mode 100644 index 8d6a6227cd..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/streamed.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { Await, createFileRoute } from '@tanstack/react-router' -import { Suspense } from 'react' - -export const Route = createFileRoute('/streamed')({ - loader: () => ({ - deferred: new Promise((resolve) => - setTimeout(() => resolve('streamed after the shell'), 100), - ), - }), - component: StreamedRoute, -}) - -function StreamedRoute() { - const { deferred } = Route.useLoaderData() - return ( -
-

Streamed document

- loading

}> - - {(value) =>

{value}

} -
-
-
- ) -} diff --git a/e2e/react-start/response-reconciliation/src/server-entry.ts b/e2e/react-start/response-reconciliation/src/server-entry.ts deleted file mode 100644 index cbee8ad31a..0000000000 --- a/e2e/react-start/response-reconciliation/src/server-entry.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { - createStartHandler, - defaultStreamHandler, - getResponseStatus, - handleStartError, -} from '@tanstack/react-start/server' -import handler, { createServerEntry } from '@tanstack/react-start/server-entry' - -const uncaughtFetch = createStartHandler(defaultStreamHandler) - -// Reproduce #7647's custom stream handler that preserves middleware status. -const preserveStatusFetch = createStartHandler(async (ctx) => { - const result = await defaultStreamHandler(ctx) - const response = result instanceof Response ? result : result.response - const status = getResponseStatus() - if (status === response.status) { - return result - } - - const headers = new Headers(response.headers) - headers.set('x-stream-response-rebuilt', 'yes') - const replacement = new Response(response.body, { - status, - statusText: response.statusText, - headers, - }) - return result instanceof Response - ? replacement - : { ...result, response: replacement } -}) - -function markCustomServerEntry(response: Response): Response { - try { - response.headers.set('x-custom-server-entry', 'yes') - return response - } catch { - const headers = new Headers(response.headers) - headers.set('x-custom-server-entry', 'yes') - return new Response(response.body, { - status: response.status, - statusText: response.statusText, - headers, - }) - } -} - -export default createServerEntry({ - async fetch(request, opts) { - if (request.headers.get('x-reconciliation-scenario') === 'issue-7647') { - return markCustomServerEntry(await preserveStatusFetch(request, opts)) - } - - if (request.headers.get('x-custom-handle-errors') === 'false') { - try { - return markCustomServerEntry(await uncaughtFetch(request, opts)) - } catch (error) { - if (request.headers.get('x-custom-handle-start-error') === 'true') { - return markCustomServerEntry(handleStartError(error)) - } - return markCustomServerEntry( - new Response(error instanceof Error ? error.message : 'error', { - status: 555, - headers: { - 'x-custom-entry-catch': 'yes', - }, - }), - ) - } - } - - try { - return markCustomServerEntry(await handler.fetch(request, opts)) - } catch (error) { - return markCustomServerEntry( - new Response(error instanceof Error ? error.message : 'error', { - status: 556, - headers: { - 'x-custom-entry-catch': 'unexpected', - }, - }), - ) - } - }, -}) diff --git a/e2e/react-start/response-reconciliation/src/start.ts b/e2e/react-start/response-reconciliation/src/start.ts deleted file mode 100644 index 2ac158b799..0000000000 --- a/e2e/react-start/response-reconciliation/src/start.ts +++ /dev/null @@ -1,170 +0,0 @@ -import { createMiddleware, createStart } from '@tanstack/react-start' -import { - clearResponseHeaders, - setCookie, - getCookie, - setResponseHeader, - setResponseHeaders, - setResponseStatus, -} from '@tanstack/react-start/server' -import { createUpstreamFailure } from './routes/api/-upstream' -import { installResponseWrapper } from './response-wrapper' - -const globalResponseMiddleware = createMiddleware().server( - async ({ next, request }) => { - if (request.headers.get('x-wrap-response') === 'true') { - installResponseWrapper() - } - - const scenario = - request.headers.get('x-reconciliation-scenario') || - getCookie('reconciliation-scenario') - - if (scenario === 'issue-7647') { - setResponseStatus(418) - setResponseHeader('x-middleware-header', 'present') - setResponseHeader('cache-control', 'no-store') - return next() - } - - if (scenario === 'global-before') { - setResponseHeaders( - new Headers({ - 'x-global-before': 'yes', - 'x-global-common': 'before', - }), - ) - setResponseStatus(231, 'global-before') - return next() - } - - if (scenario === 'global-after') { - const result = await next() - setResponseHeader('x-global-after', 'yes') - setResponseHeader('x-global-common', 'after') - setResponseStatus(232, 'global-after') - return result - } - - if (scenario === 'global-multiple-cookies') { - setCookie('global-one', '1', { path: '/' }) - setCookie('global-two', '2', { path: '/' }) - return next() - } - - if (scenario === 'global-upstream-cause') { - throw new Error('Upstream failed', { cause: createUpstreamFailure() }) - } - - if (scenario === 'global-location-error') { - throw Object.assign(new Error('Moved error'), { - status: 302, - headers: { location: '/api/base' }, - }) - } - - if (scenario === 'global-same-body-wrapper') { - const result = await next() - const wrapped = new Response(result.response.body, result.response) - clearResponseHeaders() - setResponseHeader('x-same-body-wrapper', 'yes') - return { ...result, response: wrapped } - } - - if (scenario === 'global-copy') { - // Session middleware copies the response to add a header (#8627). - const result = await next() - const headers = new Headers(result.response.headers) - headers.set('x-global-copy', 'yes') - return { - ...result, - response: new Response(result.response.body, { - status: result.response.status, - statusText: result.response.statusText, - headers, - }), - } - } - - if (scenario === 'global-piped-copy') { - const result = await next() - const response = new Response( - result.response.body!.pipeThrough(new TransformStream()), - result.response, - ) - response.headers.set('x-global-piped-copy', 'yes') - return { ...result, response } - } - - if (scenario === 'global-representation') { - // Representation metadata computed from the body, as by ETag middleware. - const result = await next() - const body = await result.response.text() - const response = new Response(body, result.response) - response.headers.set('x-body-length', String(body.length)) - return { ...result, response } - } - - if (scenario === 'global-assigned-transform-not-modified') { - // Transform the body in place, then answer an ETag match instead. - const result = await next() - result.response = new Response( - result.response.body!.pipeThrough(new TransformStream()), - result.response, - ) - return new Response(null, { status: 304 }) - } - - if (scenario === 'global-timeout') { - // Keep working after next() while the handler the inner timeout - // abandoned is still running. - const result = await next() - await sleep(400) - return result - } - - if (scenario === 'global-throw') { - setResponseStatus(401, 'Unauthorized') - setResponseHeader('x-global-error', 'yes') - throw new Error('Unauthorized global middleware') - } - - if (scenario === 'global-throw-string') { - throw 'global string' - } - - if (scenario === 'global-throw-response') { - throw Response.json({ denied: true }, { status: 403 }) - } - - return next() - }, -) - -const sleep = (ms: number) => - new Promise((resolve) => setTimeout(resolve, ms)) - -const globalTimeoutMiddleware = createMiddleware().server( - ({ next, request }) => { - const scenario = - request.headers.get('x-reconciliation-scenario') || - getCookie('reconciliation-scenario') - if (scenario !== 'global-timeout') { - return next() - } - return Promise.race([ - next(), - sleep(50).then( - () => - new Response('timeout', { - status: 504, - headers: { 'x-timeout-fallback': 'yes' }, - }), - ), - ]) - }, -) - -export const startInstance = createStart(() => ({ - requestMiddleware: [globalResponseMiddleware, globalTimeoutMiddleware], -})) diff --git a/e2e/react-start/response-reconciliation/src/styles/app.css b/e2e/react-start/response-reconciliation/src/styles/app.css deleted file mode 100644 index a38fb439a6..0000000000 --- a/e2e/react-start/response-reconciliation/src/styles/app.css +++ /dev/null @@ -1,12 +0,0 @@ -html { - color-scheme: light dark; - font-family: system-ui, sans-serif; -} - -body { - margin: 0; -} - -main { - padding: 16px; -} diff --git a/e2e/react-start/response-reconciliation/tests/response-reconciliation.spec.ts b/e2e/react-start/response-reconciliation/tests/response-reconciliation.spec.ts deleted file mode 100644 index 728b0782c5..0000000000 --- a/e2e/react-start/response-reconciliation/tests/response-reconciliation.spec.ts +++ /dev/null @@ -1,1038 +0,0 @@ -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' -import type { APIResponse, Page, Response } from '@playwright/test' - -type TestResponse = APIResponse | Response - -function header(response: TestResponse, name: string) { - return response.headers()[name.toLowerCase()] ?? null -} - -async function setCookieValues(response: TestResponse) { - return (await Promise.resolve(response.headersArray())) - .filter((item) => item.name.toLowerCase() === 'set-cookie') - .map((item) => item.value) -} - -function expectCookie(cookies: Array, name: string, value: string) { - expect( - cookies.filter((cookie) => cookie.startsWith(`${name}=${value};`)), - ).toHaveLength(1) -} - -async function invokeServerFunction( - page: Page, - name: string, - scenario?: string, -) { - await page.goto( - scenario - ? `/server-functions?scenario=${encodeURIComponent(scenario)}` - : '/server-functions', - ) - await expect(page.getByTestId('server-functions-hydrated')).toBeAttached() - await page.evaluate((value) => { - document.cookie = value - ? `reconciliation-scenario=${value}; Path=/` - : 'reconciliation-scenario=; Max-Age=0; Path=/' - }, scenario) - const responsePromise = page.waitForResponse((response) => - response.url().includes('/_serverFn/'), - ) - await page.getByTestId(`server-function-${name}`).click() - const response = await responsePromise - await expect( - page.getByTestId(`server-function-${name}-result`), - ).not.toHaveText('pending') - return response -} - -async function invokeJsonServerFunction( - page: Page, - name: string, - scenario?: string, -) { - const response = await invokeServerFunction(page, name, scenario) - const request = response.request() - expect(request.headers()['x-tsr-serverfn']).toBe('true') - const postData = request.postData() - if (postData) { - expect(postData).not.toContain('x-reconciliation-scenario') - } - return response -} - -async function expectServerFunctionResult( - page: Page, - name: string, - result: string | RegExp, -) { - await expect(page.getByTestId(`server-function-${name}-result`)).toHaveText( - result, - ) -} - -test.describe('server routes', () => { - test('uses expected server entry mode', async ({ request }) => { - const response = await request.get('/api/base') - - if (process.env.TSS_E2E_SERVER_ENTRY) { - expect(header(response, 'x-custom-server-entry')).toBe('yes') - } else { - expect(header(response, 'x-custom-server-entry')).toBe(null) - } - }) - - test('global request middleware cookies are preserved on server routes', async ({ - request, - }) => { - const response = await request.get('/api/base', { - headers: { 'x-reconciliation-scenario': 'global-multiple-cookies' }, - }) - const cookies = await setCookieValues(response) - - expectCookie(cookies, 'global-one', '1') - expectCookie(cookies, 'global-two', '2') - }) - - test('regression #5407: global middleware setResponseHeaders and status apply before next', async ({ - request, - }) => { - const response = await request.get('/api/base', { - headers: { 'x-reconciliation-scenario': 'global-before' }, - }) - - expect(response.status()).toBe(231) - expect(response.statusText()).toBe('global-before') - expect(header(response, 'x-global-before')).toBe('yes') - expect(header(response, 'x-global-common')).toBe('before') - expect(header(response, 'x-base')).toBe('yes') - }) - - test('global middleware helper changes apply after next', async ({ - request, - }) => { - const response = await request.get('/api/base', { - headers: { 'x-reconciliation-scenario': 'global-after' }, - }) - - expect(response.status()).toBe(232) - expect(response.statusText()).toBe('global-after') - expect(header(response, 'x-global-after')).toBe('yes') - expect(header(response, 'x-global-common')).toBe('after') - expect(header(response, 'x-base')).toBe('yes') - }) - - test('route middleware helper changes apply before and after next', async ({ - request, - }) => { - const before = await request.get('/api/route-before-next') - expect(before.status()).toBe(234) - expect(before.statusText()).toBe('route-before') - expect(header(before, 'x-route-before')).toBe('yes') - expect(header(before, 'x-handler')).toBe('route-before-next') - - const after = await request.get('/api/route-after-next') - expect(after.status()).toBe(233) - expect(after.statusText()).toBe('route-after') - expect(header(after, 'x-route-after')).toBe('yes') - expect(header(after, 'x-handler')).toBe('route-after-next') - }) - - test('helper changes overlay same-boundary returned response conflicts', async ({ - request, - }) => { - const response = await request.get('/api/same-boundary-conflict') - - expect(response.status()).toBe(235) - expect(response.statusText()).toBe('same-boundary') - expect(header(response, 'x-conflict')).toBe('helper') - await expect(response.text()).resolves.toBe('conflict') - }) - - test('setResponseHeaders accepts Headers and preserves multiple cookies', async ({ - request, - }) => { - const response = await request.get('/api/bulk-headers') - const cookies = await setCookieValues(response) - - expect(header(response, 'x-bulk-one')).toBe('1') - expect(header(response, 'x-bulk-two')).toBe('2') - expect(header(response, 'x-keep')).toBe('yes') - expectCookie(cookies, 'bulk-one', '1') - expectCookie(cookies, 'bulk-two', '2') - }) - - test('remove and clear helpers can remove returned response headers', async ({ - request, - }) => { - const removed = await request.get('/api/remove-returned-header') - expect(header(removed, 'x-remove-me')).toBe(null) - expect(header(removed, 'x-keep')).toBe('yes') - - const cleared = await request.get('/api/clear-returned-headers') - expect(header(cleared, 'x-clear-one')).toBe(null) - expect(header(cleared, 'x-clear-two')).toBe(null) - }) - - test('getResponseHeader and getResponseHeaders read helper writes immediately', async ({ - request, - }) => { - const headerResponse = await request.get('/api/get-response-header-helper') - expect(header(headerResponse, 'x-read-after-set')).toBe('yes') - await expect(headerResponse.text()).resolves.toBe('yes') - - const headersResponse = await request.get( - '/api/get-response-headers-helper', - ) - expect(header(headersResponse, 'x-headers-read')).toBe('yes') - expect(header(headersResponse, 'x-headers-snapshot-write')).toBe(null) - await expect(headersResponse.text()).resolves.toBe('yes') - }) - - test('getResponseHeader sees direct current response header mutation', async ({ - request, - }) => { - const response = await request.get('/api/direct-mutation-visible') - - expect(header(response, 'x-direct-visible')).toBe('yes') - expect(header(response, 'x-direct-read')).toBe('yes') - }) - - test('response replacement carries helper deltas but not old response mutations', async ({ - request, - }) => { - const response = await request.get('/api/replace-after-direct-mutation') - - expect(response.status()).toBe(202) - expect(header(response, 'x-direct-a')).toBe(null) - expect(header(response, 'x-helper-delta')).toBe('yes') - expect(header(response, 'x-response-b')).toBe('yes') - await expect(response.text()).resolves.toBe('replacement') - }) - - test('later returned response replaces earlier response metadata', async ({ - request, - }) => { - const response = await request.get('/api/two-returned-responses') - - expect(header(response, 'x-response-a')).toBe(null) - expect(header(response, 'x-response-b')).toBe('yes') - expect(header(response, 'x-helper-after-a')).toBe('yes') - await expect(response.text()).resolves.toBe('response-b') - }) - - test('readonly responses reconcile through clone fallback', async ({ - request, - }) => { - const response = await request.get('/api/readonly-after-next') - - expect(header(response, 'x-readonly-after')).toBe('yes') - await expect(response.text()).resolves.toBe('readonly') - }) - - for (const status of [204, 205, 304]) { - test(`null-body status ${status} drops the response body`, async ({ - request, - }) => { - const response = await request.get( - `/api/null-body-status?status=${status}`, - ) - - expect(response.status()).toBe(status) - expect(header(response, 'x-null-body')).toBe('yes') - await expect(response.text()).resolves.toBe('') - }) - } - - test('out-of-range setResponseStatus keeps the returned status', async ({ - request, - }) => { - const response = await request.get( - '/api/status-contracts?scenario=invalid-status-return', - ) - - expect(response.status()).toBe(404) - expect(response.statusText()).toBe('Not Found') - await expect(response.text()).resolves.toBe('missing') - }) - - test('out-of-range setResponseStatus keeps the uncaught error status', async ({ - request, - }) => { - const response = await request.get( - '/api/status-contracts?scenario=invalid-status-throw', - ) - - expect(response.status()).toBe(500) - await expect(response.json()).resolves.toMatchObject({ - status: 500, - unhandled: true, - }) - }) - - test('a timeout fallback survives the handler it abandoned while an outer middleware awaits', async ({ - request, - }) => { - const response = await request.get('/api/status-contracts?scenario=slow', { - headers: { 'x-reconciliation-scenario': 'global-timeout' }, - }) - - expect(response.status()).toBe(504) - expect(header(response, 'x-timeout-fallback')).toBe('yes') - await expect(response.text()).resolves.toBe('timeout') - }) - - test('a helper success status does not hide an uncaught error', async ({ - request, - }) => { - const response = await request.get( - '/api/status-contracts?scenario=helper-success-crash', - ) - - expect(response.status()).toBe(500) - await expect(response.json()).resolves.toMatchObject({ - status: 500, - unhandled: true, - }) - }) - - test('errors caused by an upstream response adopt only its status', async ({ - request, - }) => { - const response = await request.get( - '/api/status-contracts?scenario=upstream-error-cause', - ) - const body = await response.body() - - expect(response.status()).toBe(502) - expect(header(response, 'x-upstream')).toBeNull() - expect(header(response, 'content-type')).toContain('application/json') - expect(header(response, 'content-encoding')).toBeNull() - const contentLength = header(response, 'content-length') - if (contentLength !== null) { - expect(Number(contentLength)).toBe(body.byteLength) - } - expect(await setCookieValues(response)).toEqual([]) - expect(JSON.parse(body.toString())).toMatchObject({ status: 502 }) - }) - - test('regression #5107: thrown errors preserve explicit response status and headers', async ({ - request, - }) => { - const response = await request.get('/api/throw-after-status') - - expect(response.status()).toBe(401) - expect(response.statusText()).toBe('Unauthorized') - expect(header(response, 'x-error-helper')).toBe('yes') - expect(header(response, 'content-type')).toContain('application/json') - if (process.env.TSS_E2E_SERVER_ENTRY) { - expect(header(response, 'x-custom-server-entry')).toBe('yes') - expect(header(response, 'x-custom-entry-catch')).toBe(null) - } - await expect(response.json()).resolves.toMatchObject({ status: 401 }) - }) - - test('thrown responses preserve explicit response status and headers', async ({ - request, - }) => { - const response = await request.get('/api/throw-after-status?throw=response') - - expect(response.status()).toBe(401) - expect(response.statusText()).toBe('Unauthorized') - expect(header(response, 'x-error-helper')).toBe('yes') - expect(header(response, 'x-thrown-response')).toBe('yes') - if (process.env.TSS_E2E_SERVER_ENTRY) { - expect(header(response, 'x-custom-server-entry')).toBe('yes') - expect(header(response, 'x-custom-entry-catch')).toBe(null) - } - await expect(response.text()).resolves.toBe('Unauthorized response') - }) - - test('custom server entry can opt out of automatic error responses', async ({ - request, - }) => { - test.skip(!process.env.TSS_E2E_SERVER_ENTRY, 'custom server entry only') - - const response = await request.get('/api/throw-after-status', { - headers: { 'x-custom-handle-errors': 'false' }, - }) - - expect(response.status()).toBe(555) - expect(header(response, 'x-custom-server-entry')).toBe('yes') - expect(header(response, 'x-custom-entry-catch')).toBe('yes') - await expect(response.text()).resolves.toBe('Unauthorized route') - }) - - test('custom server entry can recover Start error response state', async ({ - request, - }) => { - test.skip(!process.env.TSS_E2E_SERVER_ENTRY, 'custom server entry only') - - const response = await request.get('/api/throw-after-status', { - headers: { - 'x-custom-handle-errors': 'false', - 'x-custom-handle-start-error': 'true', - }, - }) - const cookies = await setCookieValues(response) - - expect(response.status()).toBe(401) - expect(response.statusText()).toBe('Unauthorized') - expect(header(response, 'x-error-helper')).toBe('yes') - expect(header(response, 'x-custom-server-entry')).toBe('yes') - expect(header(response, 'x-custom-entry-catch')).toBe(null) - expectCookie(cookies, 'throw-after-status', '1') - await expect(response.json()).resolves.toMatchObject({ status: 401 }) - }) - - test('custom server entry can recover thrown response state', async ({ - request, - }) => { - test.skip(!process.env.TSS_E2E_SERVER_ENTRY, 'custom server entry only') - - const response = await request.get( - '/api/throw-after-status?throw=response', - { - headers: { - 'x-custom-handle-errors': 'false', - 'x-custom-handle-start-error': 'true', - }, - }, - ) - const cookies = await setCookieValues(response) - - expect(response.status()).toBe(401) - expect(response.statusText()).toBe('Unauthorized') - expect(header(response, 'x-error-helper')).toBe('yes') - expect(header(response, 'x-thrown-response')).toBe('yes') - expect(header(response, 'x-custom-server-entry')).toBe('yes') - expect(header(response, 'x-custom-entry-catch')).toBe(null) - expectCookie(cookies, 'throw-after-status', '1') - await expect(response.text()).resolves.toBe('Unauthorized response') - }) - - test('custom server entry can opt out of SSR request middleware error responses', async ({ - request, - }) => { - test.skip(!process.env.TSS_E2E_SERVER_ENTRY, 'custom server entry only') - - const response = await request.get('/ssr', { - headers: { - 'x-custom-handle-errors': 'false', - 'x-reconciliation-scenario': 'global-throw', - }, - }) - - expect(response.status()).toBe(555) - expect(header(response, 'x-custom-server-entry')).toBe('yes') - expect(header(response, 'x-custom-entry-catch')).toBe('yes') - await expect(response.text()).resolves.toBe( - 'Unauthorized global middleware', - ) - }) - - test('regression #5464: multiple Set-Cookie headers are preserved', async ({ - request, - }) => { - const response = await request.get('/api/multiple-cookies') - const cookies = await setCookieValues(response) - - expectCookie(cookies, 'route-one', '1') - expectCookie(cookies, 'route-two', '2') - }) - - test('explicit Set-Cookie header values are preserved and replace response values', async ({ - request, - }) => { - const explicit = await request.get('/api/explicit-set-cookie-header') - const explicitCookies = await setCookieValues(explicit) - expectCookie(explicitCookies, 'explicit-one', '1') - expectCookie(explicitCookies, 'explicit-two', '2') - - const replaced = await request.get('/api/replace-explicit-set-cookie') - const replacedCookies = await setCookieValues(replaced) - expectCookie(replacedCookies, 'explicit-new', '1') - expect( - replacedCookies.some((cookie) => cookie.startsWith('explicit-old=1;')), - ).toBe(false) - }) - - test('cookies survive redirect responses', async ({ request }) => { - const response = await request.get('/api/redirect-with-cookies', { - maxRedirects: 0, - }) - const cookies = await setCookieValues(response) - - expect(response.status()).toBe(307) - expect(header(response, 'location')).toBe('/api/base') - expectCookie(cookies, 'redirect-one', '1') - expectCookie(cookies, 'redirect-two', '2') - expectCookie(cookies, 'redirect-three', '3') - }) - - test('generated errors drop framing headers that helpers set for the failed body', async ({ - request, - }) => { - const response = await request.get('/api/framing-error') - - expect(response.status()).toBe(500) - expect(header(response, 'content-encoding')).toBeNull() - expect(header(response, 'content-length')).not.toBe('2') - expect(await response.json()).toMatchObject({ - status: 500, - unhandled: true, - }) - }) - - test('HEAD keeps the body for middleware until the response leaves the pipeline', async ({ - request, - }) => { - const headers = { 'x-reconciliation-scenario': 'global-representation' } - const get = await request.get('/api/base', { headers }) - const head = await request.head('/api/base', { headers }) - - expect(head.status()).toBe(get.status()) - expect(Number(header(get, 'x-body-length'))).toBeGreaterThan(0) - expect(header(head, 'x-body-length')).toBe(header(get, 'x-body-length')) - expect(await head.body()).toHaveLength(0) - }) - - test('a response that middleware assigned is disposed when it returns another', async ({ - request, - }) => { - const id = crypto.randomUUID() - const response = await request.get(`/api/tracked-stream?id=${id}`, { - headers: { - 'x-reconciliation-scenario': 'global-assigned-transform-not-modified', - }, - }) - - expect(response.status()).toBe(304) - await expect - .poll(async () => - (await request.get(`/api/tracked-stream-status?id=${id}`)).json(), - ) - .toEqual({ cancelled: true }) - }) -}) - -test.describe('SSR document responses', () => { - test('regression #7647: middleware status and headers survive alongside route headers', async ({ - request, - }) => { - const response = await request.get('/', { - headers: { - accept: 'text/html', - 'x-reconciliation-scenario': 'issue-7647', - }, - }) - - expect(response.status()).toBe(418) - expect(header(response, 'x-middleware-header')).toBe('present') - expect(header(response, 'cache-control')).toBe('no-store') - expect(header(response, 'x-route-header')).toBe('present') - expect(header(response, 'content-type')).toContain('text/html') - // Custom-entry modes must actually reconstruct the streamed response. - expect(header(response, 'x-stream-response-rebuilt')).toBe( - process.env.TSS_E2E_SERVER_ENTRY ? 'yes' : null, - ) - const html = await response.text() - expect(html).toContain('Response Reconciliation E2E') - }) - - test('loader helper headers, status, and cookies reconcile onto document response', async ({ - request, - }) => { - const response = await request.get('/ssr') - const cookies = await setCookieValues(response) - - expect(response.status()).toBe(238) - expect(response.statusText()).toBe('ssr-loader') - expect(header(response, 'x-ssr-loader')).toBe('yes') - expect(header(response, 'content-type')).toContain('text/html') - expectCookie(cookies, 'ssr-one', '1') - expectCookie(cookies, 'ssr-two', '2') - await expect(response.text()).resolves.toContain('ssr response') - }) - - test('regression #5464: SSR document responses preserve multiple Set-Cookie headers', async ({ - request, - }) => { - const response = await request.get('/ssr', { - headers: { 'x-reconciliation-scenario': 'global-multiple-cookies' }, - }) - const cookies = await setCookieValues(response) - - expectCookie(cookies, 'global-one', '1') - expectCookie(cookies, 'global-two', '2') - expectCookie(cookies, 'ssr-one', '1') - expectCookie(cookies, 'ssr-two', '2') - }) - - test('global middleware after next reconciles onto document response', async ({ - request, - }) => { - const response = await request.get('/ssr', { - headers: { 'x-reconciliation-scenario': 'global-after' }, - }) - - expect(response.status()).toBe(232) - expect(response.statusText()).toBe('global-after') - expect(header(response, 'x-global-after')).toBe('yes') - expect(header(response, 'x-ssr-loader')).toBe('yes') - }) - - test('middleware can stream the document through a body transform', async ({ - request, - }) => { - const response = await request.get('/streamed', { - headers: { 'x-reconciliation-scenario': 'global-piped-copy' }, - }) - - expect(response.status()).toBe(200) - expect(header(response, 'x-global-piped-copy')).toBe('yes') - const html = await response.text() - expect(html).toContain('streamed after the shell') - expect(html).toContain('') - }) - - test('HEAD documents keep their body for middleware until the response leaves the pipeline', async ({ - request, - }) => { - const headers = { 'x-reconciliation-scenario': 'global-representation' } - const get = await request.get('/', { headers }) - const head = await request.head('/', { headers }) - - expect(head.status()).toBe(get.status()) - expect(Number(header(get, 'x-body-length'))).toBeGreaterThan(0) - expect(header(head, 'x-body-length')).toBe(header(get, 'x-body-length')) - expect(await head.body()).toHaveLength(0) - }) - - test('regression #8627: middleware can copy the document when Response is wrapped', async ({ - request, - }) => { - const response = await request.get('/streamed', { - headers: { - 'x-reconciliation-scenario': 'global-copy', - 'x-wrap-response': 'true', - }, - }) - - expect(response.status()).toBe(200) - expect(header(response, 'x-global-copy')).toBe('yes') - const html = await response.text() - expect(html).toContain('streamed after the shell') - expect(html).toContain('') - }) - - test('regression #8627: loader helpers reconcile onto the document when Response is wrapped', async ({ - request, - }) => { - const response = await request.get('/ssr', { - headers: { 'x-wrap-response': 'true' }, - }) - const cookies = await setCookieValues(response) - - expect(response.status()).toBe(238) - expect(header(response, 'x-ssr-loader')).toBe('yes') - expectCookie(cookies, 'ssr-one', '1') - const html = await response.text() - expect(html).toContain('ssr response') - expect(html).toContain('') - }) -}) - -test.describe('server functions', () => { - test('global request middleware helper changes reconcile onto serialized responses', async ({ - page, - }) => { - const response = await invokeJsonServerFunction( - page, - 'globalSerialized', - 'global-before', - ) - - expect(response.status()).toBe(231) - expect(response.statusText()).toBe('global-before') - expect(header(response, 'x-global-before')).toBe('yes') - expect(header(response, 'x-tss-serialized')).toBe('true') - await expectServerFunctionResult(page, 'globalSerialized', '{"ok":true}') - }) - - test('global request middleware helper changes after next reconcile onto serialized responses', async ({ - page, - }) => { - const response = await invokeJsonServerFunction( - page, - 'globalSerialized', - 'global-after', - ) - - expect(response.status()).toBe(232) - expect(response.statusText()).toBe('global-after') - expect(header(response, 'x-global-after')).toBe('yes') - expect(header(response, 'x-tss-serialized')).toBe('true') - await expectServerFunctionResult(page, 'globalSerialized', '{"ok":true}') - }) - - test('function middleware helper changes after next reconcile onto serialized responses', async ({ - page, - }) => { - const response = await invokeJsonServerFunction(page, 'functionAfterNext') - - expect(response.status()).toBe(236) - expect(response.statusText()).toBe('function-after') - expect(header(response, 'x-function-after')).toBe('yes') - expect(header(response, 'x-tss-serialized')).toBe('true') - await expectServerFunctionResult(page, 'functionAfterNext', '{"ok":true}') - }) - - test('raw server function responses reconcile helper changes after next', async ({ - page, - }) => { - const response = await invokeJsonServerFunction( - page, - 'rawResponseAfterNext', - ) - - expect(response.status()).toBe(237) - expect(response.statusText()).toBe('function-raw-after') - expect(header(response, 'x-function-raw')).toBe('yes') - expect(header(response, 'x-function-raw-after')).toBe('yes') - expect(header(response, 'x-tss-raw')).toBe('true') - await expect(response.text()).resolves.toBe('raw function body') - await expectServerFunctionResult( - page, - 'rawResponseAfterNext', - '237:raw function body', - ) - }) - - test('function response replacement carries helper deltas only', async ({ - page, - }) => { - const response = await invokeJsonServerFunction(page, 'replacement') - - expect(header(response, 'x-function-a')).toBe(null) - expect(header(response, 'x-function-b')).toBe('yes') - expect(header(response, 'x-function-helper-delta')).toBe('yes') - await expect(response.text()).resolves.toBe('function-b') - await expectServerFunctionResult(page, 'replacement', '200:function-b') - }) - - test('server function preserves multiple Set-Cookie headers', async ({ - page, - }) => { - const response = await invokeJsonServerFunction(page, 'multipleCookies') - const cookies = await setCookieValues(response) - - expectCookie(cookies, 'fn-one', '1') - expectCookie(cookies, 'fn-two', '2') - await expectServerFunctionResult(page, 'multipleCookies', '{"ok":true}') - }) - - test('raw server function responses preserve multiple Set-Cookie headers', async ({ - page, - }) => { - const response = await invokeJsonServerFunction(page, 'rawMultipleCookies') - const cookies = await setCookieValues(response) - - expect(header(response, 'x-tss-raw')).toBe('true') - expectCookie(cookies, 'fn-raw-returned-one', '1') - expectCookie(cookies, 'fn-raw-returned-two', '2') - expectCookie(cookies, 'fn-raw-helper-one', '1') - expectCookie(cookies, 'fn-raw-helper-two', '2') - await expect(response.text()).resolves.toBe('raw cookie body') - await expectServerFunctionResult( - page, - 'rawMultipleCookies', - '200:raw cookie body', - ) - }) - - test('server function explicit Set-Cookie header arrays are preserved', async ({ - page, - }) => { - const response = await invokeJsonServerFunction( - page, - 'explicitCookieHeader', - ) - const cookies = await setCookieValues(response) - - expectCookie(cookies, 'fn-explicit-one', '1') - expectCookie(cookies, 'fn-explicit-two', '2') - await expectServerFunctionResult( - page, - 'explicitCookieHeader', - '{"ok":true}', - ) - }) - - test.describe('expected error responses', () => { - test.use({ - // A second RegExp would make Playwright read the array as a fixture - // tuple, so all expected statuses share one pattern. - whitelistErrors: [ - /Failed to load resource: the server responded with a status of (401 \(Unauthorized\)|403 \([^)]*\)|418 \([^)]*\)|500 \([^)]*\)|502 \([^)]*\))/, - ], - }) - - test('a server function that throws a Response rejects with it on the client', async ({ - page, - }) => { - const response = await invokeServerFunction(page, 'throwResponse') - - expect(response.status()).toBe(418) - expect(header(response, 'x-tss-raw')).toBe('thrown') - await expectServerFunctionResult( - page, - 'throwResponse', - 'thrown 418:teapot', - ) - }) - - test('server function thrown errors preserve explicit response status', async ({ - page, - }) => { - const response = await invokeJsonServerFunction(page, 'throwAfterStatus') - - expect(response.status()).toBe(401) - expect(response.statusText()).toBe('Unauthorized') - expect(header(response, 'x-function-error')).toBe('yes') - expect(header(response, 'x-tss-serialized')).toBe('true') - await expectServerFunctionResult(page, 'throwAfterStatus', /Unauthorized/) - }) - - test('server function errors drop framing headers that helpers set for the failed body', async ({ - page, - }) => { - const response = await invokeJsonServerFunction(page, 'throwAfterFraming') - - expect(header(response, 'content-encoding')).toBeNull() - expect(header(response, 'content-length')).not.toBe('2') - expect(header(response, 'x-tss-serialized')).toBe('true') - await expectServerFunctionResult( - page, - 'throwAfterFraming', - 'File read failed', - ) - }) - - test('server function request middleware errors caused by an upstream response adopt only its status', async ({ - page, - context, - }) => { - const response = await invokeJsonServerFunction( - page, - 'globalSerialized', - 'global-upstream-cause', - ) - - expect(response.status()).toBe(502) - expect(header(response, 'x-upstream')).toBeNull() - expect(header(response, 'content-type')).toContain('application/json') - expect(header(response, 'content-encoding')).toBeNull() - expect(await setCookieValues(response)).toEqual([]) - expect(await context.cookies()).not.toEqual( - expect.arrayContaining([ - expect.objectContaining({ name: 'upstream-session' }), - ]), - ) - await expectServerFunctionResult( - page, - 'globalSerialized', - 'Upstream failed', - ) - }) - - test('serialized errors drop a Location from error metadata', async ({ - page, - }) => { - const response = await invokeJsonServerFunction( - page, - 'globalSerialized', - 'global-location-error', - ) - - // Error metadata below 400 falls back to 500, and Location is dropped. - expect(response.status()).toBe(500) - expect(header(response, 'location')).toBeNull() - expect(response.request().redirectedTo()).toBeNull() - await expectServerFunctionResult(page, 'globalSerialized', 'Moved error') - }) - - test('server function request middleware errors are serialized', async ({ - page, - }) => { - const response = await invokeJsonServerFunction( - page, - 'globalSerialized', - 'global-throw', - ) - - expect(response.status()).toBe(401) - expect(response.statusText()).toBe('Unauthorized') - expect(header(response, 'x-global-error')).toBe('yes') - expect(header(response, 'x-tss-serialized')).toBe('true') - await expectServerFunctionResult(page, 'globalSerialized', /Unauthorized/) - }) - - test('a string thrown by request middleware rejects the server function call with it', async ({ - page, - }) => { - const response = await invokeJsonServerFunction( - page, - 'globalSerialized', - 'global-throw-string', - ) - - expect(response.status()).toBe(500) - expect(header(response, 'x-tss-serialized')).toBe('true') - await expectServerFunctionResult( - page, - 'globalSerialized', - 'thrown:"global string"', - ) - }) - - test('a Response thrown by request middleware rejects the server function call with it', async ({ - page, - }) => { - const response = await invokeServerFunction( - page, - 'globalSerialized', - 'global-throw-response', - ) - - expect(response.status()).toBe(403) - expect(header(response, 'x-tss-raw')).toBe('thrown') - await expectServerFunctionResult( - page, - 'globalSerialized', - 'thrown 403:{"denied":true}', - ) - }) - - test('regression #5107: function middleware thrown errors preserve explicit response status', async ({ - page, - }) => { - const response = await invokeJsonServerFunction( - page, - 'throwAfterMiddlewareStatus', - ) - - expect(response.status()).toBe(401) - expect(response.statusText()).toBe('Unauthorized') - expect(header(response, 'x-function-error-middleware')).toBe('yes') - expect(header(response, 'x-tss-serialized')).toBe('true') - await expectServerFunctionResult( - page, - 'throwAfterMiddlewareStatus', - /Unauthorized/, - ) - }) - }) - - test('a server function that throws 0 rejects on the client', async ({ - page, - }) => { - const response = await invokeJsonServerFunction(page, 'throwZero') - - expect(header(response, 'x-tss-serialized')).toBe('true') - await expectServerFunctionResult(page, 'throwZero', 'thrown:0') - }) - - test('serialized server function replies keep their body when a helper selects 204', async ({ - page, - }) => { - const response = await invokeJsonServerFunction(page, 'bodylessStatus') - - expect(response.status()).toBe(200) - expect(header(response, 'x-bodyless-status')).toBe('ignored') - expect(header(response, 'x-tss-serialized')).toBe('true') - await expectServerFunctionResult(page, 'bodylessStatus', '{"ok":true}') - }) - - test('serialized replies drop a helper Location so fetch does not follow it', async ({ - page, - }) => { - const response = await invokeJsonServerFunction(page, 'helperLocation') - - expect(response.status()).toBe(302) - expect(header(response, 'location')).toBeNull() - expect(response.request().redirectedTo()).toBeNull() - await expectServerFunctionResult(page, 'helperLocation', '{"ok":true}') - }) - - test('same-body wrapper responses keep serialized transport headers', async ({ - page, - }) => { - const response = await invokeJsonServerFunction( - page, - 'globalSerialized', - 'global-same-body-wrapper', - ) - - expect(header(response, 'x-same-body-wrapper')).toBe('yes') - expect(header(response, 'x-tss-serialized')).toBe('true') - expect(header(response, 'content-type')).toContain('application/json') - await expectServerFunctionResult(page, 'globalSerialized', '{"ok":true}') - }) - - test('transport headers win over user helpers while user headers persist', async ({ - page, - }) => { - const response = await invokeJsonServerFunction(page, 'transportProtected') - - expect(header(response, 'x-user-header')).toBe('yes') - expect(header(response, 'x-tss-serialized')).toBe('true') - expect(header(response, 'content-type')).toContain('application/json') - await expectServerFunctionResult(page, 'transportProtected', '{"ok":true}') - }) - - for (const name of ['returnRedirect', 'throwRedirect']) { - test(`server function ${name} navigates through the client with helper status and headers`, async ({ - page, - context, - }) => { - await page.goto('/server-functions') - await expect(page.getByTestId('server-functions-hydrated')).toBeAttached() - const responsePromise = page.waitForResponse((response) => - response.url().includes('/_serverFn/'), - ) - await page.getByTestId(`server-function-${name}`).click() - const response = await responsePromise - - expect(response.status()).toBe(302) - expect(header(response, 'location')).toBeNull() - expect(header(response, 'content-type')).toContain('application/json') - expect(header(response, 'x-tss-raw')).toBeNull() - expect(header(response, 'x-tss-serialized')).toBeNull() - expect(response.request().redirectedTo()).toBeNull() - // Playwright cannot expose a 302 body, even without Location. Successful - // client navigation verifies that Start decoded the redirect envelope. - await expect(page).toHaveURL('/') - await expect( - page.getByRole('heading', { name: 'Response Reconciliation E2E' }), - ).toBeVisible() - expect(await context.cookies()).toEqual( - expect.arrayContaining([ - expect.objectContaining({ name: 'rpc-redirect', value: 'committed' }), - ]), - ) - }) - } - - test('server function getResponseHeader sees helper writes immediately', async ({ - page, - }) => { - const response = await invokeJsonServerFunction(page, 'readAfterSet') - - expect(header(response, 'x-read-after-set')).toBe('yes') - expect(header(response, 'x-read-after-set-value')).toBe('yes') - await expectServerFunctionResult(page, 'readAfterSet', '{"ok":true}') - }) -}) diff --git a/e2e/react-start/response-reconciliation/tsconfig.json b/e2e/react-start/response-reconciliation/tsconfig.json deleted file mode 100644 index 3824b148e1..0000000000 --- a/e2e/react-start/response-reconciliation/tsconfig.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "include": ["**/*.ts", "**/*.tsx", "public/script*.js"], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "react-jsx", - "module": "ESNext", - "moduleResolution": "Bundler", - "lib": ["DOM", "DOM.Iterable", "ES2022"], - "isolatedModules": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "target": "ES2022", - "allowJs": true, - "forceConsistentCasingInFileNames": true, - "paths": { - "~/*": ["./src/*"] - }, - "noEmit": true, - "types": ["vite/client"] - } -} diff --git a/e2e/react-start/response-reconciliation/vite.config.ts b/e2e/react-start/response-reconciliation/vite.config.ts deleted file mode 100644 index 355e12a2f7..0000000000 --- a/e2e/react-start/response-reconciliation/vite.config.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { defineConfig } from 'vite' -import { tanstackStart } from '@tanstack/react-start/plugin/vite' -import viteReact from '@vitejs/plugin-react' - -const serverEntry = process.env.TSS_E2E_SERVER_ENTRY -const outDir = process.env.E2E_DIST_DIR ?? 'dist' - -export default defineConfig({ - resolve: { tsconfigPaths: true }, - build: { - outDir, - }, - plugins: [ - tanstackStart({ - server: serverEntry ? { entry: serverEntry } : undefined, - }), - viteReact(), - ], -}) diff --git a/e2e/react-start/root-document-hydration/package.json b/e2e/react-start/root-document-hydration/package.json index 9dcfcb6fbc..d69ddfc0bf 100644 --- a/e2e/react-start/root-document-hydration/package.json +++ b/e2e/react-start/root-document-hydration/package.json @@ -10,7 +10,7 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js", "test:e2e:dev": "MODE=dev playwright test --project=chromium", "test:e2e:prod": "MODE=prod playwright test --project=chromium", - "test:e2e": "pnpm run test:e2e:dev && pnpm run test:e2e:prod" + "test:e2e": "rm -rf port*.txt; pnpm run test:e2e:dev && pnpm run test:e2e:prod" }, "dependencies": { "@tanstack/react-router": "workspace:*", @@ -25,7 +25,7 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" diff --git a/e2e/react-start/root-document-hydration/playwright.config.ts b/e2e/react-start/root-document-hydration/playwright.config.ts index 13dda4e328..18abea0ab1 100644 --- a/e2e/react-start/root-document-hydration/playwright.config.ts +++ b/e2e/react-start/root-document-hydration/playwright.config.ts @@ -1,8 +1,9 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } const isDev = process.env.MODE === 'dev' -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -15,11 +16,9 @@ export default defineConfig({ }, webServer: { - command: isDev - ? 'pnpm dev:e2e --port 0' - : `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: isDev ? 'pnpm dev:e2e' : `pnpm build && PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { PORT: String(PORT), diff --git a/e2e/react-start/rsbuild/package.json b/e2e/react-start/rsbuild/package.json index d03ef22542..d0b7566489 100644 --- a/e2e/react-start/rsbuild/package.json +++ b/e2e/react-start/rsbuild/package.json @@ -8,7 +8,7 @@ "dev:e2e": "rsbuild dev --port $PORT", "build": "rsbuild build && tsc --noEmit", "start": "node server.js", - "test:e2e-full": "pnpm build && playwright test --project=chromium" + "test:e2e-full": "pnpm build && sh -c 'rm -f \"port-${E2E_PORT_KEY:-$npm_package_name}.txt\" \"port-${E2E_PORT_KEY:-$npm_package_name}-syntax-error-overlay.txt\"' && playwright test --project=chromium" }, "nx": { "metadata": { @@ -28,13 +28,13 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-react": "^2.0.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "srvx": "^1.0.0", + "srvx": "^0.10.0", "typescript": "^5.7.2" } } diff --git a/e2e/react-start/rsbuild/playwright.config.ts b/e2e/react-start/rsbuild/playwright.config.ts index e5c9004335..6e8f176361 100644 --- a/e2e/react-start/rsbuild/playwright.config.ts +++ b/e2e/react-start/rsbuild/playwright.config.ts @@ -1,4 +1,17 @@ +import fs from 'node:fs' import { defineConfig, devices } from '@playwright/test' +import packageJson from './package.json' with { type: 'json' } + +const e2ePortKey = process.env.E2E_PORT_KEY ?? packageJson.name + +if (process.env.TEST_WORKER_INDEX === undefined) { + for (const portFile of [ + `port-${e2ePortKey}.txt`, + `port-${e2ePortKey}-syntax-error-overlay.txt`, + ]) { + fs.rmSync(portFile, { force: true }) + } +} export default defineConfig({ testDir: './tests', diff --git a/e2e/react-start/rsbuild/tests/error-overlay.spec.ts b/e2e/react-start/rsbuild/tests/error-overlay.spec.ts index d90647314a..5d6497f740 100644 --- a/e2e/react-start/rsbuild/tests/error-overlay.spec.ts +++ b/e2e/react-start/rsbuild/tests/error-overlay.spec.ts @@ -1,11 +1,12 @@ -import { spawn } from 'node:child_process' import fs from 'node:fs' import path from 'node:path' -import { stripVTControlCharacters } from 'node:util' -import { appServerReadyPattern, test } from '@tanstack/router-e2e-utils' +import { spawn } from 'node:child_process' import { expect } from '@playwright/test' +import { getTestServerPort, test } from '@tanstack/router-e2e-utils' +import packageJson from '../package.json' with { type: 'json' } import type { Page } from '@playwright/test' +const e2ePortKey = process.env.E2E_PORT_KEY ?? packageJson.name const fixtureRoot = path.resolve(import.meta.dirname, '..') const workspaceRoot = path.resolve(import.meta.dirname, '../../../..') const errorOverlaySelector = 'rsbuild-error-overlay' @@ -14,7 +15,7 @@ const syntaxErrorRoutePatch = '\nexport const broken = ;\n' const devServerTimeout = 30_000 class DevServer { - url = '' + readonly url: string private stopPromise: Promise | null = null private startupError: Error | null = null private readonly startupErrorPromise: Promise @@ -23,16 +24,7 @@ class DevServer { readonly port: number, private readonly childProcess: ReturnType, ) { - let log = '' - const captureAddress = (data: Buffer) => { - log += data.toString() - const match = appServerReadyPattern.exec(stripVTControlCharacters(log)) - if (match?.groups?.E2E_APP_PORT) { - this.url = `http://localhost:${match.groups.E2E_APP_PORT}` - } - } - this.childProcess.stdout?.on('data', captureAddress) - this.childProcess.stderr?.on('data', captureAddress) + this.url = `http://localhost:${port}` this.startupErrorPromise = new Promise((_, reject) => { this.childProcess.once('error', (error) => { this.startupError = error @@ -53,7 +45,7 @@ class DevServer { VITE_SERVER_PORT: String(port), VITE_NODE_ENV: 'test', }, - stdio: ['ignore', 'pipe', 'pipe'], + stdio: 'ignore', }), ) @@ -359,7 +351,7 @@ test('shows a module syntax error through the error overlay', async ({ }) => { const homeRouteFile = path.resolve(fixtureRoot, 'src/routes/index.tsx') const originalSource = await fs.promises.readFile(homeRouteFile, 'utf-8') - const port = 0 + const port = await getTestServerPort(`${e2ePortKey}-syntax-error-overlay`) await using devServer = await DevServer.start(port) try { diff --git a/e2e/react-start/rsc-deferred-hydration/package.json b/e2e/react-start/rsc-deferred-hydration/package.json index 06317e59d0..434cabb24b 100644 --- a/e2e/react-start/rsc-deferred-hydration/package.json +++ b/e2e/react-start/rsc-deferred-hydration/package.json @@ -22,14 +22,6 @@ "shards": 1 } ] - }, - "targets": { - "test:e2e--vite-ssr": { - "outputs": [ - "...", - "{projectRoot}/dist-vite-ssr" - ] - } } }, "dependencies": { @@ -45,8 +37,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "@vitejs/plugin-rsc": "^0.5.39", - "srvx": "^1.0.0", + "@vitejs/plugin-rsc": "^0.5.30", + "srvx": "^0.11.9", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" diff --git a/e2e/react-start/rsc-deferred-hydration/playwright.config.ts b/e2e/react-start/rsc-deferred-hydration/playwright.config.ts index f3a22f1fff..10f41cd911 100644 --- a/e2e/react-start/rsc-deferred-hydration/playwright.config.ts +++ b/e2e/react-start/rsc-deferred-hydration/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` const mode = process.env.MODE ?? 'prod' const isDev = mode === 'dev' @@ -11,11 +12,12 @@ export default defineConfig({ workers: 1, reporter: [['line']], globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', use: { baseURL }, webServer: { - command: isDev ? 'pnpm dev:e2e --port 0' : 'pnpm build && pnpm start', - wait: appServerReady, - reuseExistingServer: false, + command: isDev ? 'pnpm dev:e2e' : 'pnpm build && pnpm start', + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { VITE_NODE_ENV: 'test', diff --git a/e2e/react-start/rsc-deferred-hydration/tests/setup/global.setup.ts b/e2e/react-start/rsc-deferred-hydration/tests/setup/global.setup.ts index 40acaec113..3d1579ee87 100644 --- a/e2e/react-start/rsc-deferred-hydration/tests/setup/global.setup.ts +++ b/e2e/react-start/rsc-deferred-hydration/tests/setup/global.setup.ts @@ -1,9 +1,17 @@ -import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' +import { + e2eStartDummyServer, + getTestServerPort, + preOptimizeDevServer, + waitForServer, +} from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } export default async function setup() { + await e2eStartDummyServer(packageJson.name) + if (process.env.MODE !== 'dev') return - const port = Number(process.env.E2E_APP_PORT ?? 0) + const port = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${port}` await waitForServer(baseURL) diff --git a/e2e/react-start/rsc-deferred-hydration/tests/setup/global.teardown.ts b/e2e/react-start/rsc-deferred-hydration/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-start/rsc-deferred-hydration/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-start/rsc-query/package.json b/e2e/react-start/rsc-query/package.json index 68a99cd432..24c7b488f6 100644 --- a/e2e/react-start/rsc-query/package.json +++ b/e2e/react-start/rsc-query/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-query": "^5.90.0", @@ -28,8 +28,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "@vitejs/plugin-rsc": "^0.5.39", - "srvx": "^1.0.0", + "@vitejs/plugin-rsc": "^0.5.30", + "srvx": "^0.10.0", "typescript": "^5.7.2", "vite": "^8.0.14" } diff --git a/e2e/react-start/rsc-query/playwright.config.ts b/e2e/react-start/rsc-query/playwright.config.ts index 235a59f889..2cf7c1fe9b 100644 --- a/e2e/react-start/rsc-query/playwright.config.ts +++ b/e2e/react-start/rsc-query/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -9,15 +10,18 @@ export default defineConfig({ workers: 1, reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { baseURL, }, webServer: { // RSC production builds are not yet supported, use dev mode - command: `pnpm dev:e2e --port 0`, - wait: appServerReady, - reuseExistingServer: false, + command: `pnpm dev:e2e`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { VITE_NODE_ENV: 'test', diff --git a/e2e/react-start/rsc-query/tests/setup/global.setup.ts b/e2e/react-start/rsc-query/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-start/rsc-query/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-start/rsc-query/tests/setup/global.teardown.ts b/e2e/react-start/rsc-query/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-start/rsc-query/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-start/rsc-rsbuild/package.json b/e2e/react-start/rsc-rsbuild/package.json index 067394fc08..e3800f291a 100644 --- a/e2e/react-start/rsc-rsbuild/package.json +++ b/e2e/react-start/rsc-rsbuild/package.json @@ -8,7 +8,7 @@ "dev:e2e": "rsbuild dev --port $PORT", "build": "rsbuild build && tsc --noEmit", "start": "node server.js", - "test:e2e-full": "pnpm build && playwright test --project=chromium" + "test:e2e-full": "pnpm build && sh -c 'rm -f \"port-${E2E_PORT_KEY:-$npm_package_name}.txt\" \"port-${E2E_PORT_KEY:-$npm_package_name}-external.txt\"' && playwright test --project=chromium" }, "nx": { "metadata": { @@ -28,13 +28,13 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-react": "^2.0.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "srvx": "^1.0.0", + "srvx": "^0.10.0", "typescript": "^5.7.2" } } diff --git a/e2e/react-start/rsc-rsbuild/playwright.config.ts b/e2e/react-start/rsc-rsbuild/playwright.config.ts index dd356709b8..9bb7586df5 100644 --- a/e2e/react-start/rsc-rsbuild/playwright.config.ts +++ b/e2e/react-start/rsc-rsbuild/playwright.config.ts @@ -1,9 +1,25 @@ +import fs from 'node:fs' import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } +const e2ePortKey = process.env.E2E_PORT_KEY ?? packageJson.name const distDir = process.env.E2E_DIST_DIR ?? 'dist' -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +if (process.env.TEST_WORKER_INDEX === undefined) { + for (const portFile of [ + `port-${e2ePortKey}.txt`, + `port-${e2ePortKey}-external.txt`, + ]) { + fs.rmSync(portFile, { force: true }) + } +} + +const PORT = await getTestServerPort(e2ePortKey) +const EXTERNAL_PORT = await getDummyServerPort(e2ePortKey) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -11,18 +27,23 @@ export default defineConfig({ workers: 1, reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { baseURL, }, webServer: { command: 'pnpm start', - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { PORT: String(PORT), E2E_DIST_DIR: distDir, + E2E_PORT_KEY: e2ePortKey, + EXTERNAL_SERVER_URL: `http://localhost:${EXTERNAL_PORT}`, }, }, diff --git a/e2e/react-start/rsc-rsbuild/tests/setup/global.setup.ts b/e2e/react-start/rsc-rsbuild/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3def5f6941 --- /dev/null +++ b/e2e/react-start/rsc-rsbuild/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(process.env.E2E_PORT_KEY ?? packageJson.name) +} diff --git a/e2e/react-start/rsc-rsbuild/tests/setup/global.teardown.ts b/e2e/react-start/rsc-rsbuild/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..a9ad1445f7 --- /dev/null +++ b/e2e/react-start/rsc-rsbuild/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(process.env.E2E_PORT_KEY ?? packageJson.name) +} diff --git a/e2e/react-start/rsc/package.json b/e2e/react-start/rsc/package.json index a30227d509..0e7414e2aa 100644 --- a/e2e/react-start/rsc/package.json +++ b/e2e/react-start/rsc/package.json @@ -13,8 +13,7 @@ "build:vite": "vite build && tsc --noEmit", "preview": "vite preview", "start": "node server.js", - "test:e2e-full": "pnpm build && playwright test --project=chromium", - "test:e2e:dev:rsbuild": "MODE=dev E2E_TOOLCHAIN=rsbuild playwright test --project=chromium" + "test:e2e-full": "pnpm build && sh -c 'rm -f \"port-${E2E_PORT_KEY:-$npm_package_name}.txt\" \"port-${E2E_PORT_KEY:-$npm_package_name}-external.txt\"' && playwright test --project=chromium" }, "nx": { "metadata": { @@ -41,7 +40,7 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-react": "^2.0.0", "@tanstack/eslint-plugin-start": "workspace:^", "@tanstack/router-e2e-utils": "workspace:^", @@ -50,9 +49,9 @@ "@types/react-dom": "^19.0.3", "@typescript-eslint/parser": "^8.23.0", "@vitejs/plugin-react": "^6.0.1", - "@vitejs/plugin-rsc": "^0.5.39", + "@vitejs/plugin-rsc": "^0.5.30", "eslint": "^9.22.0", - "srvx": "^1.0.0", + "srvx": "^0.10.0", "typescript": "^5.7.2", "vite": "^8.0.14" } diff --git a/e2e/react-start/rsc/playwright.config.ts b/e2e/react-start/rsc/playwright.config.ts index 075efdc5b9..9bb7586df5 100644 --- a/e2e/react-start/rsc/playwright.config.ts +++ b/e2e/react-start/rsc/playwright.config.ts @@ -1,11 +1,25 @@ +import fs from 'node:fs' import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } +const e2ePortKey = process.env.E2E_PORT_KEY ?? packageJson.name const distDir = process.env.E2E_DIST_DIR ?? 'dist' -// MODE=dev runs the suite against the Rsbuild dev server instead of a build -const isRsbuildDev = process.env.MODE === 'dev' -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +if (process.env.TEST_WORKER_INDEX === undefined) { + for (const portFile of [ + `port-${e2ePortKey}.txt`, + `port-${e2ePortKey}-external.txt`, + ]) { + fs.rmSync(portFile, { force: true }) + } +} + +const PORT = await getTestServerPort(e2ePortKey) +const EXTERNAL_PORT = await getDummyServerPort(e2ePortKey) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -13,19 +27,23 @@ export default defineConfig({ workers: 1, reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { baseURL, }, webServer: { - command: isRsbuildDev ? 'pnpm dev:rsbuild --port 0' : 'pnpm start', - wait: appServerReady, - reuseExistingServer: false, + command: 'pnpm start', + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, PORT: String(PORT), E2E_DIST_DIR: distDir, + E2E_PORT_KEY: e2ePortKey, + EXTERNAL_SERVER_URL: `http://localhost:${EXTERNAL_PORT}`, }, }, diff --git a/e2e/react-start/rsc/src/routes/rsc-external.tsx b/e2e/react-start/rsc/src/routes/rsc-external.tsx index 352f086b60..d6da119b26 100644 --- a/e2e/react-start/rsc/src/routes/rsc-external.tsx +++ b/e2e/react-start/rsc/src/routes/rsc-external.tsx @@ -109,7 +109,11 @@ const getExternalDataServerComponent = createServerFn({ method: 'GET' }) ) }) -const EXTERNAL_SERVER_URL = 'https://jsonplaceholder.typicode.com' +// The external server URL is provided by the e2e test setup +const EXTERNAL_SERVER_URL = + typeof process !== 'undefined' && process.env.EXTERNAL_SERVER_URL + ? process.env.EXTERNAL_SERVER_URL + : 'http://localhost:65003' export const Route = createFileRoute('/rsc-external')({ loader: async () => { diff --git a/e2e/react-start/rsc/tests/rsc-css-preload-complex.spec.ts b/e2e/react-start/rsc/tests/rsc-css-preload-complex.spec.ts index 35db86eca9..f5d8e04928 100644 --- a/e2e/react-start/rsc/tests/rsc-css-preload-complex.spec.ts +++ b/e2e/react-start/rsc/tests/rsc-css-preload-complex.spec.ts @@ -116,16 +116,15 @@ test.describe('RSC Complex CSS Preload Tests', () => { test('CSS module classes are scoped for all widgets', async ({ page }) => { await page.goto('/rsc-css-preload-complex') - // Widget A classes should be hashed (accept Vite `_widget_xxx`, Rspack - // `widget-xxx`, and Rsbuild dev `src-...-module__widget-xxx` scoped names) + // Widget A classes should be hashed (accept Vite `_widget_xxx` or Rspack `widget-xxx` scoped names) const widgetA = page.locator('[data-testid="client-widget-a"]') const widgetAClass = await widgetA.getAttribute('class') - expect(widgetAClass).toMatch(/(^|\s|__)(_widget_|widget[-_])[\w-]+/) + expect(widgetAClass).toMatch(/(^|\s)(_widget_|widget[-_])[\w-]+/) // Widget B classes should be hashed const widgetB = page.locator('[data-testid="client-widget-b"]') const widgetBClass = await widgetB.getAttribute('class') - expect(widgetBClass).toMatch(/(^|\s|__)(_widget_|widget[-_])[\w-]+/) + expect(widgetBClass).toMatch(/(^|\s)(_widget_|widget[-_])[\w-]+/) // Classes should be different (different modules) expect(widgetAClass).not.toBe(widgetBClass) diff --git a/e2e/react-start/rsc/tests/rsc-external.spec.ts b/e2e/react-start/rsc/tests/rsc-external.spec.ts index ae16ef7c43..7ce4bd3c18 100644 --- a/e2e/react-start/rsc/tests/rsc-external.spec.ts +++ b/e2e/react-start/rsc/tests/rsc-external.spec.ts @@ -19,9 +19,13 @@ test.describe('RSC External API Tests - External data fetching', () => { await page.goto('/rsc-external') await page.waitForURL(/\/rsc-external/) - await expect(page.getByTestId('external-server-url')).toHaveText( - 'https://jsonplaceholder.typicode.com', - ) + // Verify the external server URL contains expected pattern + const serverUrl = await page + .getByTestId('external-server-url') + .textContent() + expect(serverUrl).toBeTruthy() + // Should be localhost with a port + expect(serverUrl).toMatch(/localhost:\d+/) }) test('Loader timestamp is present', async ({ page }) => { diff --git a/e2e/react-start/rsc/tests/rsc-stream-generator.spec.ts b/e2e/react-start/rsc/tests/rsc-stream-generator.spec.ts index 842c9358c0..5faa6b1508 100644 --- a/e2e/react-start/rsc/tests/rsc-stream-generator.spec.ts +++ b/e2e/react-start/rsc/tests/rsc-stream-generator.spec.ts @@ -67,22 +67,29 @@ test.describe('RSC Stream Generator Tests - Streaming RSCs via async generator', // Start streaming await page.getByTestId('start-stream-btn').click() - const notifications = page + // First 3 should appear quickly (initial batch) + await expect(page.getByTestId('notification-list')).toBeVisible() + + // Wait a bit and check that notifications are accumulating + await page.waitForTimeout(500) + const initialCount = await page .getByTestId('notification-list') .locator('[data-testid^="notification-notif_"]') + .count() + expect(initialCount).toBeGreaterThanOrEqual(3) - // The initial batch of 3 renders while the stream is still open - await expect(notifications.nth(2)).toBeVisible() - await expect(page.getByTestId('streaming-status')).toBeVisible() - const initialCount = await notifications.count() - expect(initialCount).toBeLessThan(7) + // Wait for more to stream in + await page.waitForTimeout(2000) + const laterCount = await page + .getByTestId('notification-list') + .locator('[data-testid^="notification-notif_"]') + .count() + expect(laterCount).toBeGreaterThan(initialCount) - // The remaining notifications stream in afterwards - await expect(notifications.nth(initialCount)).toBeVisible() + // Wait for completion await expect(page.getByTestId('stream-complete')).toBeVisible({ timeout: 10000, }) - await expect(notifications).toHaveCount(7) }) test('Each notification is a complete RSC with server data', async ({ diff --git a/e2e/react-start/rsc/tests/rsc-stream-readable.spec.ts b/e2e/react-start/rsc/tests/rsc-stream-readable.spec.ts index dc21f8d9c5..356907e311 100644 --- a/e2e/react-start/rsc/tests/rsc-stream-readable.spec.ts +++ b/e2e/react-start/rsc/tests/rsc-stream-readable.spec.ts @@ -67,22 +67,29 @@ test.describe('RSC Stream Readable Tests - Streaming RSCs via ReadableStream', ( // Start streaming await page.getByTestId('start-stream-btn').click() - const notifications = page + // First 3 should appear quickly (initial batch) + await expect(page.getByTestId('notification-list')).toBeVisible() + + // Wait a bit and check that notifications are accumulating + await page.waitForTimeout(500) + const initialCount = await page .getByTestId('notification-list') .locator('[data-testid^="notification-notif_"]') + .count() + expect(initialCount).toBeGreaterThanOrEqual(3) - // The initial batch of 3 renders while the stream is still open - await expect(notifications.nth(2)).toBeVisible() - await expect(page.getByTestId('streaming-status')).toBeVisible() - const initialCount = await notifications.count() - expect(initialCount).toBeLessThan(7) + // Wait for more to stream in + await page.waitForTimeout(2000) + const laterCount = await page + .getByTestId('notification-list') + .locator('[data-testid^="notification-notif_"]') + .count() + expect(laterCount).toBeGreaterThan(initialCount) - // The remaining notifications stream in afterwards - await expect(notifications.nth(initialCount)).toBeVisible() + // Wait for completion await expect(page.getByTestId('stream-complete')).toBeVisible({ timeout: 10000, }) - await expect(notifications).toHaveCount(7) }) test('Each notification is a complete RSC with server data', async ({ diff --git a/e2e/react-start/rsc/tests/setup/global.setup.ts b/e2e/react-start/rsc/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3def5f6941 --- /dev/null +++ b/e2e/react-start/rsc/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(process.env.E2E_PORT_KEY ?? packageJson.name) +} diff --git a/e2e/react-start/rsc/tests/setup/global.teardown.ts b/e2e/react-start/rsc/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..a9ad1445f7 --- /dev/null +++ b/e2e/react-start/rsc/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(process.env.E2E_PORT_KEY ?? packageJson.name) +} diff --git a/e2e/react-start/scroll-restoration/package.json b/e2e/react-start/scroll-restoration/package.json index 9e90871158..17bf2b2449 100644 --- a/e2e/react-start/scroll-restoration/package.json +++ b/e2e/react-start/scroll-restoration/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -30,7 +30,7 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "combinate": "^1.1.11", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/react-start/scroll-restoration/playwright.config.ts b/e2e/react-start/scroll-restoration/playwright.config.ts index 1862174905..1e33c9ae5e 100644 --- a/e2e/react-start/scroll-restoration/playwright.config.ts +++ b/e2e/react-start/scroll-restoration/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,19 +18,19 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', - env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, - }, }, projects: [ diff --git a/e2e/react-start/scroll-restoration/src/client.tsx b/e2e/react-start/scroll-restoration/src/client.tsx deleted file mode 100644 index 25a0ebf7e7..0000000000 --- a/e2e/react-start/scroll-restoration/src/client.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import { StrictMode, startTransition } from 'react' -import { hydrateRoot } from 'react-dom/client' -import { StartClient } from '@tanstack/react-start/client' - -async function bootstrap() { - // Fixture-only gate: leave SSR markup, CSS and inline restoration intact. - // Waiting here allows load to finish before StartClient constructs the router. - if ((window as any).__holdScrollBootstrap) { - await new Promise((resolve) => { - ;(window as any).__releaseScrollBootstrap = resolve - }) - } - startTransition(() => { - hydrateRoot( - document, - - - , - ) - }) -} - -void bootstrap() diff --git a/e2e/react-start/scroll-restoration/src/routes/__root.tsx b/e2e/react-start/scroll-restoration/src/routes/__root.tsx index 875bff34e0..563d9208ec 100644 --- a/e2e/react-start/scroll-restoration/src/routes/__root.tsx +++ b/e2e/react-start/scroll-restoration/src/routes/__root.tsx @@ -65,10 +65,6 @@ export const Route = createRootRoute({ }) function RootComponent() { - React.useEffect(() => { - dispatchEvent(new Event('test-scroll-hydrated')) - }, []) - return ( diff --git a/e2e/react-start/scroll-restoration/src/utils/posts.tsx b/e2e/react-start/scroll-restoration/src/utils/posts.tsx index bc56dff904..c6cba486ab 100644 --- a/e2e/react-start/scroll-restoration/src/utils/posts.tsx +++ b/e2e/react-start/scroll-restoration/src/utils/posts.tsx @@ -12,7 +12,11 @@ export type PostType = { export class PostNotFoundError extends Error {} -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/react-start/scroll-restoration/src/utils/users.tsx b/e2e/react-start/scroll-restoration/src/utils/users.tsx index 7ba645b383..79b45867d5 100644 --- a/e2e/react-start/scroll-restoration/src/utils/users.tsx +++ b/e2e/react-start/scroll-restoration/src/utils/users.tsx @@ -3,3 +3,8 @@ export type User = { name: string email: string } + +const PORT = + import.meta.env.VITE_SERVER_PORT || process.env.VITE_SERVER_PORT || 3000 + +export const DEPLOY_URL = `http://localhost:${PORT}` diff --git a/e2e/react-start/scroll-restoration/tests/scroll-restoration-lifecycle.spec.ts b/e2e/react-start/scroll-restoration/tests/scroll-restoration-lifecycle.spec.ts deleted file mode 100644 index 6c1e1693b6..0000000000 --- a/e2e/react-start/scroll-restoration/tests/scroll-restoration-lifecycle.spec.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { writeFile } from 'node:fs/promises' -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' -import { scrollRestorationLifecycleTests } from '../../../scroll-restoration-lifecycle' - -scrollRestorationLifecycleTests(test) - -test('hands native scroll restoration back to the browser on reload', async ({ - page, -}, testInfo) => { - const errors: Array = [] - page.on('pageerror', (error) => errors.push(error.message)) - const key = 'test-scroll-pagehide' - const token = testInfo.testId - await page.addInitScript(() => { - ;(window as any).__initialScrollRestoration = history.scrollRestoration - }) - await page.goto('/') - await page.getByRole('link', { name: '/reset-scroll-false-a' }).click() - await page.waitForLoadState('networkidle') - expect(await page.evaluate(() => history.scrollRestoration)).toBe('manual') - - const position = await page.evaluate( - async ({ key, token }) => { - sessionStorage.removeItem(key) - const scrolled = new Promise((resolve) => { - addEventListener('scroll', () => resolve(), { once: true }) - }) - scrollTo(0, 500) - await scrolled - // Registered after router setup, so this observes the router's handoff. - window.addEventListener( - 'pagehide', - (event) => { - sessionStorage.setItem( - key, - JSON.stringify({ - token, - mode: history.scrollRestoration, - persisted: (event as PageTransitionEvent).persisted, - trusted: event.isTrusted, - x: scrollX, - y: scrollY, - }), - ) - }, - { once: true }, - ) - return { x: scrollX, y: scrollY } - }, - { key, token }, - ) - expect(position.y).toBeGreaterThan(0) - - await page.reload() - const observation = await page.evaluate( - (key) => ({ - outgoing: JSON.parse(sessionStorage.getItem(key)!), - initialMode: (window as any).__initialScrollRestoration, - }), - key, - ) - const snapshotPath = testInfo.outputPath('reload-handoff.json') - await writeFile( - snapshotPath, - JSON.stringify({ ...observation, errors }, null, 2), - ) - await testInfo.attach('reload-handoff', { - path: snapshotPath, - contentType: 'application/json', - }) - expect(observation.outgoing).toMatchObject({ - token, - trusted: true, - mode: 'auto', - }) - expect(observation.initialMode).toBe('auto') - expect(Math.abs(observation.outgoing.x - position.x)).toBeLessThanOrEqual(1) - expect(Math.abs(observation.outgoing.y - position.y)).toBeLessThanOrEqual(1) - await expect - .poll(() => page.evaluate(() => history.scrollRestoration)) - .toBe('manual') - await expect.poll(() => page.evaluate(() => scrollY)).toBe(position.y) - expect(errors).toEqual([]) -}) diff --git a/e2e/react-start/scroll-restoration/tests/scroll-restoration-reload.spec.ts b/e2e/react-start/scroll-restoration/tests/scroll-restoration-reload.spec.ts deleted file mode 100644 index 767f02a39c..0000000000 --- a/e2e/react-start/scroll-restoration/tests/scroll-restoration-reload.spec.ts +++ /dev/null @@ -1,191 +0,0 @@ -import { writeFile } from 'node:fs/promises' -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' - -// A frame recorder is diagnostic evidence, not proof of compositor-frame pixels. -for (const holdBootstrap of [false, true]) { - test(`reload keeps rendered SSR scroll stable (bootstrap held=${holdBootstrap})`, async ({ - page, - }, testInfo) => { - const errors: Array = [] - page.on('pageerror', (error) => errors.push(error.message)) - await page.addInitScript(() => { - const holdKey = 'test-hold-scroll-bootstrap' - ;(window as any).__holdScrollBootstrap = - sessionStorage.getItem(holdKey) === 'true' - sessionStorage.removeItem(holdKey) - const samples: Array<{ - time: number - phase: string - x: number - y: number - mode: ScrollRestoration - scrollHeight: number - viewportHeight: number - anchorTop: number | null - visibility: DocumentVisibilityState - }> = [] - let phase = 'initial' - let frame = 0 - const sample = () => { - samples.push({ - time: performance.now(), - phase, - x: scrollX, - y: scrollY, - mode: history.scrollRestoration, - scrollHeight: document.documentElement?.scrollHeight ?? 0, - viewportHeight: innerHeight, - anchorTop: - document - .querySelector('[data-testid="reset-scroll-false-link-6"]') - ?.getBoundingClientRect().top ?? null, - visibility: document.visibilityState, - }) - } - const mark = (next: string) => { - phase = next - sample() - } - const tick = () => { - sample() - if (samples.length < 600) { - frame = requestAnimationFrame(tick) - } - } - sample() - frame = requestAnimationFrame(tick) - for (const event of [ - 'DOMContentLoaded', - 'load', - 'pageshow', - 'test-scroll-hydrated', - 'test-scroll-bootstrap-release', - ]) { - addEventListener(event, () => mark(event)) - } - ;(window as any).__scrollProbe = { - samples, - stop: () => { - cancelAnimationFrame(frame) - return { - samples, - paints: performance - .getEntriesByType('paint') - .map(({ name, startTime }) => ({ name, startTime })), - } - }, - } - }) - await page.goto('/') - await page.getByRole('link', { name: '/reset-scroll-false-a' }).click() - await page.waitForLoadState('networkidle') - const before = await page.evaluate(async (holdBootstrap) => { - scrollTo(0, 500) - await new Promise((resolve) => - requestAnimationFrame(() => requestAnimationFrame(() => resolve())), - ) - sessionStorage.setItem( - 'test-hold-scroll-bootstrap', - String(holdBootstrap), - ) - return { - y: scrollY, - anchorTop: document - .querySelector('[data-testid="reset-scroll-false-link-6"]')! - .getBoundingClientRect().top, - } - }, holdBootstrap) - expect(before.y).toBeGreaterThan(0) - await page.reload() - // This window starts at document readiness, independently of scroll correctness. - await page.evaluate(async () => { - await Promise.all( - Array.from( - document.querySelectorAll('link[rel="stylesheet"]'), - (link) => { - if (link.sheet) { - return - } - return new Promise((resolve) => - link.addEventListener('load', () => resolve(), { once: true }), - ) - }, - ), - ) - for (let i = 0; i < 4; i++) { - await new Promise((resolve) => - requestAnimationFrame(() => resolve()), - ) - } - }) - if (holdBootstrap) { - expect( - await page.evaluate( - () => typeof (window as any).__releaseScrollBootstrap, - ), - ).toBe('function') - expect( - await page.evaluate(() => - (window as any).__scrollProbe.samples.some( - (sample: any) => sample.phase === 'test-scroll-hydrated', - ), - ), - ).toBe(false) - } - const screenshotPath = testInfo.outputPath('SSR-viewport.png') - await page.screenshot({ path: screenshotPath }) - await testInfo.attach('SSR-viewport', { - path: screenshotPath, - contentType: 'image/png', - }) - const held = await page.evaluate(() => ({ - y: scrollY, - anchorTop: document - .querySelector('[data-testid="reset-scroll-false-link-6"]')! - .getBoundingClientRect().top, - })) - if (holdBootstrap) { - await page.evaluate(() => { - dispatchEvent(new Event('test-scroll-bootstrap-release')) - ;(window as any).__releaseScrollBootstrap() - }) - } - await expect - .poll(() => page.evaluate(() => history.scrollRestoration)) - .toBe('manual') - await page.waitForLoadState('networkidle') - await page.evaluate(async () => { - for (let i = 0; i < 8; i++) { - await new Promise((resolve) => - requestAnimationFrame(() => resolve()), - ) - } - }) - const timeline = await page.evaluate(() => - (window as any).__scrollProbe.stop(), - ) - const timelinePath = testInfo.outputPath('scroll-timeline.json') - await writeFile( - timelinePath, - JSON.stringify({ before, held, ...timeline, errors }, null, 2), - ) - await testInfo.attach('scroll-timeline', { - path: timelinePath, - contentType: 'application/json', - }) - expect(held.y).toBe(before.y) - expect(held.anchorTop).toBeCloseTo(before.anchorTop, 0) - const renderedSamples = timeline.samples.filter( - (sample: any) => sample.phase !== 'initial' && sample.anchorTop !== null, - ) - expect(renderedSamples.length).toBeGreaterThan(0) - for (const sample of renderedSamples) { - expect(Math.abs(sample.y - before.y)).toBeLessThanOrEqual(1) - expect(Math.abs(sample.anchorTop - before.anchorTop)).toBeLessThanOrEqual( - 1, - ) - } - expect(errors).toEqual([]) - }) -} diff --git a/e2e/react-start/scroll-restoration/tests/setup/global.setup.ts b/e2e/react-start/scroll-restoration/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-start/scroll-restoration/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-start/scroll-restoration/tests/setup/global.teardown.ts b/e2e/react-start/scroll-restoration/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-start/scroll-restoration/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-start/selective-ssr/package.json b/e2e/react-start/selective-ssr/package.json index 87e8e3cf42..1eb903c183 100644 --- a/e2e/react-start/selective-ssr/package.json +++ b/e2e/react-start/selective-ssr/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -26,7 +26,7 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/react-start/selective-ssr/playwright.config.ts b/e2e/react-start/selective-ssr/playwright.config.ts index 630989e41f..badd6db0eb 100644 --- a/e2e/react-start/selective-ssr/playwright.config.ts +++ b/e2e/react-start/selective-ssr/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/serialization-adapters/package.json b/e2e/react-start/serialization-adapters/package.json index 5bf4b29a80..0e0d157733 100644 --- a/e2e/react-start/serialization-adapters/package.json +++ b/e2e/react-start/serialization-adapters/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -26,7 +26,7 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/react-start/serialization-adapters/playwright.config.ts b/e2e/react-start/serialization-adapters/playwright.config.ts index 630989e41f..badd6db0eb 100644 --- a/e2e/react-start/serialization-adapters/playwright.config.ts +++ b/e2e/react-start/serialization-adapters/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/server-functions-global-middleware/package.json b/e2e/react-start/server-functions-global-middleware/package.json index 4aab99e22c..5898097c81 100644 --- a/e2e/react-start/server-functions-global-middleware/package.json +++ b/e2e/react-start/server-functions-global-middleware/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -25,7 +25,7 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/react-start/server-functions-global-middleware/playwright.config.ts b/e2e/react-start/server-functions-global-middleware/playwright.config.ts index 7b9ac2ceb5..8330e023ee 100644 --- a/e2e/react-start/server-functions-global-middleware/playwright.config.ts +++ b/e2e/react-start/server-functions-global-middleware/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -export const PORT = Number(process.env.E2E_APP_PORT ?? 0) +export const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/server-functions-global-middleware/src/routeTree.gen.ts b/e2e/react-start/server-functions-global-middleware/src/routeTree.gen.ts index e909a808f2..739df05d7a 100644 --- a/e2e/react-start/server-functions-global-middleware/src/routeTree.gen.ts +++ b/e2e/react-start/server-functions-global-middleware/src/routeTree.gen.ts @@ -13,7 +13,6 @@ import { Route as IndexRouteImport } from './routes/index' import { Route as ContextCollisionRouteImport } from './routes/context-collision' import { Route as MultipleServerFunctionsRouteImport } from './routes/multiple-server-functions' import { Route as PathnameMiddlewareRouteImport } from './routes/pathname-middleware' -import { Route as SendContextContractRouteImport } from './routes/send-context-contract' import { Route as SimpleRouteImport } from './routes/simple' const IndexRoute = IndexRouteImport.update({ @@ -36,11 +35,6 @@ const PathnameMiddlewareRoute = PathnameMiddlewareRouteImport.update({ path: '/pathname-middleware', getParentRoute: () => rootRouteImport, } as any) -const SendContextContractRoute = SendContextContractRouteImport.update({ - id: '/send-context-contract', - path: '/send-context-contract', - getParentRoute: () => rootRouteImport, -} as any) const SimpleRoute = SimpleRouteImport.update({ id: '/simple', path: '/simple', @@ -52,7 +46,6 @@ export interface FileRoutesByFullPath { '/context-collision': typeof ContextCollisionRoute '/multiple-server-functions': typeof MultipleServerFunctionsRoute '/pathname-middleware': typeof PathnameMiddlewareRoute - '/send-context-contract': typeof SendContextContractRoute '/simple': typeof SimpleRoute } export interface FileRoutesByTo { @@ -60,7 +53,6 @@ export interface FileRoutesByTo { '/context-collision': typeof ContextCollisionRoute '/multiple-server-functions': typeof MultipleServerFunctionsRoute '/pathname-middleware': typeof PathnameMiddlewareRoute - '/send-context-contract': typeof SendContextContractRoute '/simple': typeof SimpleRoute } export interface FileRoutesById { @@ -69,7 +61,6 @@ export interface FileRoutesById { '/context-collision': typeof ContextCollisionRoute '/multiple-server-functions': typeof MultipleServerFunctionsRoute '/pathname-middleware': typeof PathnameMiddlewareRoute - '/send-context-contract': typeof SendContextContractRoute '/simple': typeof SimpleRoute } export interface FileRouteTypes { @@ -79,7 +70,6 @@ export interface FileRouteTypes { | '/context-collision' | '/multiple-server-functions' | '/pathname-middleware' - | '/send-context-contract' | '/simple' fileRoutesByTo: FileRoutesByTo to: @@ -87,7 +77,6 @@ export interface FileRouteTypes { | '/context-collision' | '/multiple-server-functions' | '/pathname-middleware' - | '/send-context-contract' | '/simple' id: | '__root__' @@ -95,7 +84,6 @@ export interface FileRouteTypes { | '/context-collision' | '/multiple-server-functions' | '/pathname-middleware' - | '/send-context-contract' | '/simple' fileRoutesById: FileRoutesById } @@ -104,7 +92,6 @@ export interface RootRouteChildren { ContextCollisionRoute: typeof ContextCollisionRoute MultipleServerFunctionsRoute: typeof MultipleServerFunctionsRoute PathnameMiddlewareRoute: typeof PathnameMiddlewareRoute - SendContextContractRoute: typeof SendContextContractRoute SimpleRoute: typeof SimpleRoute } @@ -138,13 +125,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathnameMiddlewareRouteImport parentRoute: typeof rootRouteImport } - '/send-context-contract': { - id: '/send-context-contract' - path: '/send-context-contract' - fullPath: '/send-context-contract' - preLoaderRoute: typeof SendContextContractRouteImport - parentRoute: typeof rootRouteImport - } '/simple': { id: '/simple' path: '/simple' @@ -160,7 +140,6 @@ const rootRouteChildren: RootRouteChildren = { ContextCollisionRoute: ContextCollisionRoute, MultipleServerFunctionsRoute: MultipleServerFunctionsRoute, PathnameMiddlewareRoute: PathnameMiddlewareRoute, - SendContextContractRoute: SendContextContractRoute, SimpleRoute: SimpleRoute, } export const routeTree = rootRouteImport diff --git a/e2e/react-start/server-functions-global-middleware/src/routes/send-context-contract.tsx b/e2e/react-start/server-functions-global-middleware/src/routes/send-context-contract.tsx deleted file mode 100644 index af4a22b6fd..0000000000 --- a/e2e/react-start/server-functions-global-middleware/src/routes/send-context-contract.tsx +++ /dev/null @@ -1,181 +0,0 @@ -import { useState } from 'react' -import { createFileRoute } from '@tanstack/react-router' -import { createMiddleware, createServerFn } from '@tanstack/react-start' - -function verifyCopy( - source: object, - actual: unknown, - expected: Record, -) { - if ( - actual === source || - JSON.stringify(actual) !== JSON.stringify(expected) - ) { - throw new Error('sendContext must merge into a fresh object') - } -} - -const absent = createMiddleware({ type: 'function' }) - .client(async ({ sendContext, next }) => { - if (sendContext !== undefined) { - throw new Error('Absent client sendContext must be undefined') - } - const result = await next() - if (result.sendContext !== undefined) { - throw new Error('Absent client result sendContext must be undefined') - } - return result - }) - .server(async ({ next }) => { - const result = await next() - if (result.sendContext !== undefined) { - throw new Error('Absent server result sendContext must be undefined') - } - return result - }) - -const explicitEmpty = createMiddleware({ type: 'function' }) - .client(async ({ next }) => { - const source = Object.freeze({}) - const result = await next({ sendContext: source }) - verifyCopy(source, result.sendContext, {}) - return result - }) - .server(async ({ next }) => { - const source = Object.freeze({}) - const result = await next({ sendContext: source }) - verifyCopy(source, result.sendContext, {}) - return result - }) - -const first = createMiddleware({ type: 'function' }) - .client(async ({ next }) => { - const source = Object.freeze({ first: 'one' }) - const result = await next({ sendContext: source }) - verifyCopy(source, result.sendContext, { first: 'one', second: 'two' }) - return result - }) - .server(async ({ next }) => { - const source = Object.freeze({ first: 'one' }) - const result = await next({ sendContext: source }) - verifyCopy(source, result.sendContext, { first: 'one', second: 'two' }) - return result - }) - -const second = createMiddleware({ type: 'function' }) - .middleware([first]) - .client(async ({ next }) => { - const source = Object.freeze({ second: 'two' }) - const result = await next({ sendContext: source }) - verifyCopy(source, result.sendContext, { first: 'one', second: 'two' }) - return result - }) - .server(async ({ context, next }) => { - if (context.first !== 'one' || context.second !== 'two') { - throw new Error('Client sendContext must reach the server') - } - const source = Object.freeze({ second: 'two' }) - const result = await next({ sendContext: source }) - verifyCopy(source, result.sendContext, { first: 'one', second: 'two' }) - return result - }) - -const absentFn = createServerFn() - .middleware([absent]) - .handler(() => 'absent') - -const emptyFn = createServerFn() - .middleware([explicitEmpty]) - .handler(() => 'empty') - -const nonemptyFn = createServerFn() - .middleware([second]) - .handler(() => 'nonempty') - -const accessors = createMiddleware({ type: 'function' }) - .client(async ({ next }) => { - const source = Object.freeze({ value: 'client' }) - const reads: Array = [] - const result = await next({ - get sendContext() { - reads.push('sendContext') - return source - }, - get headers() { - reads.push('headers') - return { 'x-context-accessor': 'preserved' } - }, - }) - if (reads.join(',') !== 'sendContext,headers,sendContext,headers') { - throw new Error(`Client middleware accessor order changed: ${reads}`) - } - verifyCopy(source, result.sendContext, { value: 'client' }) - if (new Headers(result.headers).get('x-context-accessor') !== 'preserved') { - throw new Error('Client middleware header was not preserved') - } - return result - }) - .server(async ({ next }) => { - const source = Object.freeze({ value: 'server' }) - let reads = 0 - const result = await next({ - get sendContext() { - reads++ - return source - }, - }) - if (reads !== 2) { - throw new Error(`Server middleware accessor read ${reads} times`) - } - verifyCopy(source, result.sendContext, { value: 'server' }) - return result - }) - -const observeServerReply = createMiddleware({ type: 'function' }) - .middleware([accessors]) - .client(async ({ next }) => { - const result = await next() - if (result.context.value !== 'server') { - throw new Error('Server sendContext must reach the client result context') - } - return result - }) - -const accessorFn = createServerFn() - .middleware([observeServerReply]) - .handler(() => 'accessors') - -async function verifyAll() { - return ( - await Promise.all([absentFn(), emptyFn(), nonemptyFn(), accessorFn()]) - ).join(',') -} - -export const Route = createFileRoute('/send-context-contract')({ - loader: verifyAll, - component: SendContextContract, -}) - -function SendContextContract() { - const loaderResult = Route.useLoaderData() - const [result, setResult] = useState('pending') - return ( -
-
{loaderResult}
- -
{result}
-
- ) -} diff --git a/e2e/react-start/server-functions-global-middleware/tests/send-context-contract.spec.ts b/e2e/react-start/server-functions-global-middleware/tests/send-context-contract.spec.ts deleted file mode 100644 index e39927ebab..0000000000 --- a/e2e/react-start/server-functions-global-middleware/tests/send-context-contract.spec.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' - -test('preserves absent and explicit sendContext through SSR and client calls', async ({ - page, -}) => { - await page.goto('/send-context-contract') - await expect(page.getByTestId('send-context-loader')).toHaveText( - 'absent,empty,nonempty,accessors', - ) - await page.getByTestId('invoke-send-context-contract').click() - await expect(page.getByTestId('send-context-client')).toHaveText( - 'absent,empty,nonempty,accessors', - ) -}) diff --git a/e2e/react-start/server-functions/package.json b/e2e/react-start/server-functions/package.json index 63d8661717..390d417423 100644 --- a/e2e/react-start/server-functions/package.json +++ b/e2e/react-start/server-functions/package.json @@ -13,7 +13,7 @@ "build:rsbuild": "rsbuild build && tsc --noEmit", "preview": "vite preview", "start": "node server.js", - "test:e2e": "pnpm build && playwright test --project=chromium && pnpm run test:e2e:rsbuild-cache", + "test:e2e": "rm -rf port*.txt && pnpm build && playwright test --project=chromium && pnpm run test:e2e:rsbuild-cache", "test:e2e:rsbuild-cache": "playwright test -c playwright.rsbuild-cache.config.ts --project=chromium" }, "dependencies": { @@ -31,7 +31,7 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-react": "^2.0.0", "@tailwindcss/postcss": "^4.2.2", "@tailwindcss/vite": "^4.2.2", @@ -42,7 +42,7 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "combinate": "^1.1.11", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/react-start/server-functions/playwright.config.ts b/e2e/react-start/server-functions/playwright.config.ts index 33fe8c0572..d88e582e2f 100644 --- a/e2e/react-start/server-functions/playwright.config.ts +++ b/e2e/react-start/server-functions/playwright.config.ts @@ -1,9 +1,11 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } +const e2ePortKey = process.env.E2E_PORT_KEY ?? packageJson.name const distDir = process.env.E2E_DIST_DIR ?? 'dist' -export const PORT = Number(process.env.E2E_APP_PORT ?? 0) +export const PORT = await getTestServerPort(e2ePortKey) const baseURL = `http://localhost:${PORT}` /** @@ -23,13 +25,14 @@ export default defineConfig({ webServer: { command: `PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { PORT: String(PORT), VITE_SERVER_PORT: String(PORT), E2E_DIST_DIR: distDir, + E2E_PORT_KEY: e2ePortKey, }, }, diff --git a/e2e/react-start/server-functions/tests/server-functions.spec.ts b/e2e/react-start/server-functions/tests/server-functions.spec.ts index f87e699330..5bb458d61c 100644 --- a/e2e/react-start/server-functions/tests/server-functions.spec.ts +++ b/e2e/react-start/server-functions/tests/server-functions.spec.ts @@ -1,9 +1,11 @@ import * as fs from 'node:fs' import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' +import { getTestServerPort, test } from '@tanstack/router-e2e-utils' +import packageJson from '../package.json' with { type: 'json' } import type { Page } from '@playwright/test' -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const e2ePortKey = process.env.E2E_PORT_KEY ?? packageJson.name +const PORT = await getTestServerPort(e2ePortKey) test('Server function URLs correctly include explicit ids', async ({ page, diff --git a/e2e/react-start/server-routes-global-middleware/package.json b/e2e/react-start/server-routes-global-middleware/package.json index ea6ddfb793..6887b19b5f 100644 --- a/e2e/react-start/server-routes-global-middleware/package.json +++ b/e2e/react-start/server-routes-global-middleware/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -25,7 +25,7 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/react-start/server-routes-global-middleware/playwright.config.ts b/e2e/react-start/server-routes-global-middleware/playwright.config.ts index 7b9ac2ceb5..8330e023ee 100644 --- a/e2e/react-start/server-routes-global-middleware/playwright.config.ts +++ b/e2e/react-start/server-routes-global-middleware/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -export const PORT = Number(process.env.E2E_APP_PORT ?? 0) +export const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/server-routes/package.json b/e2e/react-start/server-routes/package.json index 99e9090a16..0e09246ad8 100644 --- a/e2e/react-start/server-routes/package.json +++ b/e2e/react-start/server-routes/package.json @@ -34,7 +34,7 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "combinate": "^1.1.11", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/react-start/server-routes/playwright.config.ts b/e2e/react-start/server-routes/playwright.config.ts index 7b9ac2ceb5..8330e023ee 100644 --- a/e2e/react-start/server-routes/playwright.config.ts +++ b/e2e/react-start/server-routes/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -export const PORT = Number(process.env.E2E_APP_PORT ?? 0) +export const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/server-routes/src/routeTree.gen.ts b/e2e/react-start/server-routes/src/routeTree.gen.ts index 7ae1e4f551..2454c3bb32 100644 --- a/e2e/react-start/server-routes/src/routeTree.gen.ts +++ b/e2e/react-start/server-routes/src/routeTree.gen.ts @@ -20,9 +20,7 @@ import { Route as ApiOnlyAnyRouteImport } from './routes/api/only-any' import { Route as MethodsIndexRouteImport } from './routes/methods/index' import { Route as MethodsOnlyAnyRouteImport } from './routes/methods/only-any' import { Route as ApiParamsFooRouteRouteImport } from './routes/api/params/$foo/route' -import { Route as ApiParsedParamsIdRouteImport } from './routes/api/parsed-params.$id' import { Route as ApiParamsFooBarRouteImport } from './routes/api/params/$foo/$bar' -import { Route as ApiParsedParamsIdChildIdRouteImport } from './routes/api/parsed-params.$id.$childId' const IndexRoute = IndexRouteImport.update({ id: '/', @@ -79,22 +77,11 @@ const ApiParamsFooRouteRoute = ApiParamsFooRouteRouteImport.update({ path: '/api/params/$foo', getParentRoute: () => rootRouteImport, } as any) -const ApiParsedParamsIdRoute = ApiParsedParamsIdRouteImport.update({ - id: '/api/parsed-params/$id', - path: '/api/parsed-params/$id', - getParentRoute: () => rootRouteImport, -} as any) const ApiParamsFooBarRoute = ApiParamsFooBarRouteImport.update({ id: '/$bar', path: '/$bar', getParentRoute: () => ApiParamsFooRouteRoute, } as any) -const ApiParsedParamsIdChildIdRoute = - ApiParsedParamsIdChildIdRouteImport.update({ - id: '/$childId', - path: '/$childId', - getParentRoute: () => ApiParsedParamsIdRoute, - } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -108,9 +95,7 @@ export interface FileRoutesByFullPath { '/methods/only-any': typeof MethodsOnlyAnyRoute '/methods/': typeof MethodsIndexRoute '/api/params/$foo': typeof ApiParamsFooRouteRouteWithChildren - '/api/parsed-params/$id': typeof ApiParsedParamsIdRouteWithChildren '/api/params/$foo/$bar': typeof ApiParamsFooBarRoute - '/api/parsed-params/$id/$childId': typeof ApiParsedParamsIdChildIdRoute } export interface FileRoutesByTo { '/': typeof IndexRoute @@ -123,9 +108,7 @@ export interface FileRoutesByTo { '/methods/only-any': typeof MethodsOnlyAnyRoute '/methods': typeof MethodsIndexRoute '/api/params/$foo': typeof ApiParamsFooRouteRouteWithChildren - '/api/parsed-params/$id': typeof ApiParsedParamsIdRouteWithChildren '/api/params/$foo/$bar': typeof ApiParamsFooBarRoute - '/api/parsed-params/$id/$childId': typeof ApiParsedParamsIdChildIdRoute } export interface FileRoutesById { __root__: typeof rootRouteImport @@ -140,9 +123,7 @@ export interface FileRoutesById { '/methods/only-any': typeof MethodsOnlyAnyRoute '/methods/': typeof MethodsIndexRoute '/api/params/$foo': typeof ApiParamsFooRouteRouteWithChildren - '/api/parsed-params/$id': typeof ApiParsedParamsIdRouteWithChildren '/api/params/$foo/$bar': typeof ApiParamsFooBarRoute - '/api/parsed-params/$id/$childId': typeof ApiParsedParamsIdChildIdRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath @@ -158,9 +139,7 @@ export interface FileRouteTypes { | '/methods/only-any' | '/methods/' | '/api/params/$foo' - | '/api/parsed-params/$id' | '/api/params/$foo/$bar' - | '/api/parsed-params/$id/$childId' fileRoutesByTo: FileRoutesByTo to: | '/' @@ -173,9 +152,7 @@ export interface FileRouteTypes { | '/methods/only-any' | '/methods' | '/api/params/$foo' - | '/api/parsed-params/$id' | '/api/params/$foo/$bar' - | '/api/parsed-params/$id/$childId' id: | '__root__' | '/' @@ -189,9 +166,7 @@ export interface FileRouteTypes { | '/methods/only-any' | '/methods/' | '/api/params/$foo' - | '/api/parsed-params/$id' | '/api/params/$foo/$bar' - | '/api/parsed-params/$id/$childId' fileRoutesById: FileRoutesById } export interface RootRouteChildren { @@ -204,7 +179,6 @@ export interface RootRouteChildren { ApiMiddlewareContextRoute: typeof ApiMiddlewareContextRoute ApiOnlyAnyRoute: typeof ApiOnlyAnyRoute ApiParamsFooRouteRoute: typeof ApiParamsFooRouteRouteWithChildren - ApiParsedParamsIdRoute: typeof ApiParsedParamsIdRouteWithChildren } declare module '@tanstack/react-router' { @@ -286,13 +260,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ApiParamsFooRouteRouteImport parentRoute: typeof rootRouteImport } - '/api/parsed-params/$id': { - id: '/api/parsed-params/$id' - path: '/api/parsed-params/$id' - fullPath: '/api/parsed-params/$id' - preLoaderRoute: typeof ApiParsedParamsIdRouteImport - parentRoute: typeof rootRouteImport - } '/api/params/$foo/$bar': { id: '/api/params/$foo/$bar' path: '/$bar' @@ -300,13 +267,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ApiParamsFooBarRouteImport parentRoute: typeof ApiParamsFooRouteRoute } - '/api/parsed-params/$id/$childId': { - id: '/api/parsed-params/$id/$childId' - path: '/$childId' - fullPath: '/api/parsed-params/$id/$childId' - preLoaderRoute: typeof ApiParsedParamsIdChildIdRouteImport - parentRoute: typeof ApiParsedParamsIdRoute - } } } @@ -335,17 +295,6 @@ const ApiParamsFooRouteRouteChildren: ApiParamsFooRouteRouteChildren = { const ApiParamsFooRouteRouteWithChildren = ApiParamsFooRouteRoute._addFileChildren(ApiParamsFooRouteRouteChildren) -interface ApiParsedParamsIdRouteChildren { - ApiParsedParamsIdChildIdRoute: typeof ApiParsedParamsIdChildIdRoute -} - -const ApiParsedParamsIdRouteChildren: ApiParsedParamsIdRouteChildren = { - ApiParsedParamsIdChildIdRoute: ApiParsedParamsIdChildIdRoute, -} - -const ApiParsedParamsIdRouteWithChildren = - ApiParsedParamsIdRoute._addFileChildren(ApiParsedParamsIdRouteChildren) - const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, MethodsRouteRoute: MethodsRouteRouteWithChildren, @@ -356,7 +305,6 @@ const rootRouteChildren: RootRouteChildren = { ApiMiddlewareContextRoute: ApiMiddlewareContextRoute, ApiOnlyAnyRoute: ApiOnlyAnyRoute, ApiParamsFooRouteRoute: ApiParamsFooRouteRouteWithChildren, - ApiParsedParamsIdRoute: ApiParsedParamsIdRouteWithChildren, } export const routeTree = rootRouteImport ._addFileChildren(rootRouteChildren) diff --git a/e2e/react-start/server-routes/src/routes/api/parsed-params.$id.$childId.tsx b/e2e/react-start/server-routes/src/routes/api/parsed-params.$id.$childId.tsx deleted file mode 100644 index 06697a22cc..0000000000 --- a/e2e/react-start/server-routes/src/routes/api/parsed-params.$id.$childId.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { createMiddleware } from '@tanstack/react-start' - -const handleInvalidParams = createMiddleware().server(async ({ next }) => { - try { - return await next() - } catch (error) { - if (error instanceof Error && error.message === 'Invalid child id') { - return new Response(error.message, { status: 400 }) - } - throw error - } -}) - -export const Route = createFileRoute('/api/parsed-params/$id/$childId')({ - params: { - parse: (params) => { - const childId = Number(params.childId) - if (!Number.isFinite(childId)) { - throw new Error('Invalid child id') - } - return { childId } - }, - stringify: (params) => ({ childId: String(params.childId) }), - }, - server: { - handlers: ({ createHandlers }) => - createHandlers({ - GET: { - middleware: [handleInvalidParams], - handler: ({ params, request, next }) => { - if (new URL(request.url).searchParams.has('render')) { - return next({ context: { handlerParams: params } }) - } - const id: number = params.id - const childId: number = params.childId - return Response.json({ id, childId }) - }, - }, - }), - }, - loader: ({ params, serverContext }) => ({ - loaderParams: params, - handlerParams: serverContext?.handlerParams, - }), - component: () => ( -
-      {JSON.stringify(Route.useLoaderData())}
-    
- ), -}) diff --git a/e2e/react-start/server-routes/src/routes/api/parsed-params.$id.ts b/e2e/react-start/server-routes/src/routes/api/parsed-params.$id.ts deleted file mode 100644 index 0e5f0ab8a9..0000000000 --- a/e2e/react-start/server-routes/src/routes/api/parsed-params.$id.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/api/parsed-params/$id')({ - params: { - parse: (params) => ({ id: Number(params.id) }), - stringify: (params) => ({ id: String(params.id) }), - }, - server: { - handlers: { - GET: ({ params }) => { - const id: number = params.id - return Response.json({ id }) - }, - }, - }, -}) diff --git a/e2e/react-start/server-routes/tests/server-routes.spec.ts b/e2e/react-start/server-routes/tests/server-routes.spec.ts index 0ede9eaac8..97249fd733 100644 --- a/e2e/react-start/server-routes/tests/server-routes.spec.ts +++ b/e2e/react-start/server-routes/tests/server-routes.spec.ts @@ -1,46 +1,6 @@ import { expect } from '@playwright/test' import { test } from '@tanstack/router-e2e-utils' -test('server handlers receive parsed path params (issue #8431)', async ({ - request, -}) => { - const response = await request.get('/api/parsed-params/44') - - expect(response.status()).toBe(200) - expect(await response.json()).toEqual({ id: 44 }) -}) - -test('createHandlers receives parsed parent and child path params', async ({ - request, -}) => { - const response = await request.get('/api/parsed-params/44/2') - - expect(response.status()).toBe(200) - expect(await response.json()).toEqual({ id: 44, childId: 2 }) -}) - -test('handler middleware can catch path parameter parsing errors', async ({ - request, -}) => { - const response = await request.get('/api/parsed-params/44/invalid') - - expect(response.status()).toBe(400) - expect(await response.text()).toBe('Invalid child id') -}) - -test('parsed path params agree when a server handler defers to rendering', async ({ - page, -}) => { - await page.goto('/api/parsed-params/44/2?render') - - const result = page.getByTestId('parsed-params') - await expect(result).toBeVisible() - expect(JSON.parse((await result.textContent())!)).toEqual({ - loaderParams: { id: 44, childId: 2 }, - handlerParams: { id: 44, childId: 2 }, - }) -}) - test('merge-middleware-context', async ({ page }) => { await page.goto('/merge-middleware-context') diff --git a/e2e/react-start/session-handling/.gitignore b/e2e/react-start/session-handling/.gitignore deleted file mode 100644 index 16187ac1de..0000000000 --- a/e2e/react-start/session-handling/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -node_modules -package-lock.json -yarn.lock - -.DS_Store -.cache -.tanstack -.env -.vercel -.output -/build/ -/api/ -/server/build -/public/build - -# Sentry Config File -.env.sentry-build-plugin -/test-results/ -/playwright-report/ -/blob-report/ -/playwright/.cache/ -/dist/ -/dist-*/ -/port-*.txt diff --git a/e2e/react-start/session-handling/.prettierignore b/e2e/react-start/session-handling/.prettierignore deleted file mode 100644 index 40a96e8819..0000000000 --- a/e2e/react-start/session-handling/.prettierignore +++ /dev/null @@ -1,4 +0,0 @@ -**/build -**/public -pnpm-lock.yaml -routeTree.gen.ts diff --git a/e2e/react-start/session-handling/package.json b/e2e/react-start/session-handling/package.json deleted file mode 100644 index 9dda8b2843..0000000000 --- a/e2e/react-start/session-handling/package.json +++ /dev/null @@ -1,66 +0,0 @@ -{ - "name": "tanstack-react-start-e2e-session-handling", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "pnpm dev:vite --port 3000", - "dev:e2e": "pnpm dev:vite", - "dev:vite": "vite dev", - "dev:rsbuild": "rsbuild dev", - "build": "pnpm build:vite", - "build:vite": "vite build && tsc --noEmit", - "build:rsbuild": "rsbuild build && tsc --noEmit", - "preview": "vite preview", - "start": "node server.js", - "test:e2e:local": "pnpm build && playwright test --project=chromium" - }, - "dependencies": { - "@hono/session": "0.2.1", - "@tanstack/react-router": "workspace:*", - "@tanstack/react-start": "workspace:*", - "hono": "4.13.9", - "hono-sessions": "0.8.1", - "iron-session": "9.0.1", - "react": "^19.2.3", - "react-dom": "^19.2.3" - }, - "devDependencies": { - "@playwright/test": "^1.57.0", - "@rsbuild/core": "^2.3.1", - "@rsbuild/plugin-react": "^2.0.0", - "@tanstack/router-e2e-utils": "workspace:^", - "@types/node": "25.0.9", - "@types/react": "^19.2.8", - "@types/react-dom": "^19.2.3", - "@vitejs/plugin-react": "^6.0.1", - "srvx": "^1.0.0", - "typescript": "^6.0.2", - "vite": "^8.0.14" - }, - "nx": { - "targets": { - "test:e2e": { - "parallelism": false - }, - "test:e2e--vite-ssr": { - "parallelism": false - }, - "test:e2e--rsbuild-ssr": { - "parallelism": false - } - }, - "metadata": { - "playwrightModes": [ - { - "toolchain": "vite", - "mode": "ssr" - }, - { - "toolchain": "rsbuild", - "mode": "ssr" - } - ] - } - } -} diff --git a/e2e/react-start/session-handling/playwright.config.ts b/e2e/react-start/session-handling/playwright.config.ts deleted file mode 100644 index 707af45de6..0000000000 --- a/e2e/react-start/session-handling/playwright.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' - -const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' -const distDir = process.env.E2E_DIST_DIR ?? 'dist' - -export const PORT = Number(process.env.E2E_APP_PORT ?? 0) -const baseURL = `http://localhost:${PORT}` - -export default defineConfig({ - testDir: './tests', - workers: 1, - reporter: [['line']], - use: { - baseURL, - }, - webServer: { - command: `pnpm start`, - wait: appServerReady, - reuseExistingServer: false, - stdout: 'pipe', - env: { - PORT: String(PORT), - VITE_SERVER_PORT: String(PORT), - E2E_DIST_DIR: distDir, - E2E_TOOLCHAIN: toolchain, - }, - }, - projects: [ - { - name: 'chromium', - use: { ...devices['Desktop Chrome'] }, - }, - ], -}) diff --git a/e2e/react-start/session-handling/rsbuild.config.ts b/e2e/react-start/session-handling/rsbuild.config.ts deleted file mode 100644 index af8c3df7d2..0000000000 --- a/e2e/react-start/session-handling/rsbuild.config.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { defineConfig } from '@rsbuild/core' -import { pluginReact } from '@rsbuild/plugin-react' -import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' - -const outDir = process.env.E2E_DIST_DIR ?? 'dist' - -export default defineConfig({ - plugins: [pluginReact(), tanstackStart()], - output: { - distPath: { - root: outDir, - }, - }, -}) diff --git a/e2e/react-start/session-handling/server.js b/e2e/react-start/session-handling/server.js deleted file mode 100644 index da874e85c7..0000000000 --- a/e2e/react-start/session-handling/server.js +++ /dev/null @@ -1,51 +0,0 @@ -import fs from 'node:fs' -import path from 'node:path' -import { spawn } from 'node:child_process' -import { pathToFileURL } from 'node:url' - -const distDir = process.env.E2E_DIST_DIR || 'dist' - -function resolveDistClientDir() { - return path.resolve(distDir, 'client') -} - -function resolveDistServerEntryPath() { - const serverJsPath = path.resolve(distDir, 'server', 'server.js') - if (fs.existsSync(serverJsPath)) { - return serverJsPath - } - - const indexJsPath = path.resolve(distDir, 'server', 'index.js') - if (fs.existsSync(indexJsPath)) { - return indexJsPath - } - - return serverJsPath -} - -export function start() { - const child = spawn( - 'srvx', - ['--prod', '-s', resolveDistClientDir(), resolveDistServerEntryPath()], - { - stdio: 'inherit', - shell: process.platform === 'win32', - }, - ) - - child.on('exit', (code, signal) => { - if (signal) { - process.kill(process.pid, signal) - return - } - - process.exit(code ?? 0) - }) -} - -if ( - process.argv[1] && - import.meta.url === pathToFileURL(process.argv[1]).href -) { - start() -} diff --git a/e2e/react-start/session-handling/src/components/DefaultCatchBoundary.tsx b/e2e/react-start/session-handling/src/components/DefaultCatchBoundary.tsx deleted file mode 100644 index f3d691814f..0000000000 --- a/e2e/react-start/session-handling/src/components/DefaultCatchBoundary.tsx +++ /dev/null @@ -1,20 +0,0 @@ -import { ErrorComponent, Link, useRouter } from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' - -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - - return ( -
- - - Home -
- ) -} diff --git a/e2e/react-start/session-handling/src/components/NotFound.tsx b/e2e/react-start/session-handling/src/components/NotFound.tsx deleted file mode 100644 index 0b720f0e37..0000000000 --- a/e2e/react-start/session-handling/src/components/NotFound.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { Link } from '@tanstack/react-router' - -export function NotFound({ children }: { children?: React.ReactNode }) { - return ( -
- {children ||

The page you are looking for does not exist.

} - Start Over -
- ) -} diff --git a/e2e/react-start/session-handling/src/hono-sessions.ts b/e2e/react-start/session-handling/src/hono-sessions.ts deleted file mode 100644 index 63703a487b..0000000000 --- a/e2e/react-start/session-handling/src/hono-sessions.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { useSession as useHonoSession } from '@hono/session' -import { Hono } from 'hono' -import { setCookie } from 'hono/cookie' -import { CookieStore, sessionMiddleware } from 'hono-sessions' -import { sessionPassword } from './session' -import type { SessionEnv } from '@hono/session' -import type { Session } from 'hono-sessions' - -// These are genuine Hono applications. Start forwards the original Fetch -// Request and returns the Response after Hono has finished its middleware. -export const honoSessionApp = new Hono>() - .use( - '*', - useHonoSession({ - secret: new TextEncoder().encode('0123456789abcdef0123456789abcdef'), - duration: { absolute: 3600 }, - }), - ) - .get('/api/session-hono', async (c) => - c.json({ data: (await c.var.session.get()) ?? {} }), - ) - .post('/api/session-hono', async (c) => { - const data = await c.req.json<{ user: string }>() - await c.var.session.update({ user: data.user }) - setCookie(c, 'hono-extra', '1', { - path: '/', - expires: new Date(Date.now() + 24 * 60 * 60 * 1000), - }) - return c.json({ data: c.var.session.data }) - }) - .delete('/api/session-hono', (c) => { - c.var.session.delete() - return c.json({ cleared: true }) - }) - -export const communitySessionApp = new Hono<{ - Variables: { - session: Session<{ user: string }> - session_key_rotation: boolean - } -}>() - .use( - '*', - sessionMiddleware({ - store: new CookieStore(), - encryptionKey: sessionPassword, - expireAfterSeconds: 3600, - sessionCookieName: 'hono-community', - cookieOptions: { - path: '/', - httpOnly: true, - sameSite: 'Lax', - secure: false, - }, - }), - ) - .get('/api/session-hono-community', (c) => - c.json({ data: { user: c.var.session.get('user') } }), - ) - .post('/api/session-hono-community', async (c) => { - const data = await c.req.json<{ user: string }>() - c.var.session.set('user', data.user) - return c.json({ data: { user: c.var.session.get('user') } }) - }) - .delete('/api/session-hono-community', (c) => { - c.var.session.deleteSession() - return c.json({ cleared: true }) - }) diff --git a/e2e/react-start/session-handling/src/routeTree.gen.ts b/e2e/react-start/session-handling/src/routeTree.gen.ts deleted file mode 100644 index 5ecad97ab4..0000000000 --- a/e2e/react-start/session-handling/src/routeTree.gen.ts +++ /dev/null @@ -1,346 +0,0 @@ -/* 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 ServerFunctionsRouteImport } from './routes/server-functions' -import { Route as SsrRouteImport } from './routes/ssr' -import { Route as ApiSessionRouteImport } from './routes/api/session' -import { Route as ApiSessionClearRouteImport } from './routes/api/session-clear' -import { Route as ApiSessionFlashRouteImport } from './routes/api/session-flash' -import { Route as ApiSessionHelperCookieRouteImport } from './routes/api/session-helper-cookie' -import { Route as ApiSessionHonoRouteImport } from './routes/api/session-hono' -import { Route as ApiSessionHonoCommunityRouteImport } from './routes/api/session-hono-community' -import { Route as ApiSessionHonoCookieRouteImport } from './routes/api/session-hono-cookie' -import { Route as ApiSessionIronRouteImport } from './routes/api/session-iron' -import { Route as ApiSessionMiddlewareRouteImport } from './routes/api/session-middleware' -import { Route as ApiSessionNamedRouteImport } from './routes/api/session-named' -import { Route as ApiSessionRedirectRouteImport } from './routes/api/session-redirect' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ServerFunctionsRoute = ServerFunctionsRouteImport.update({ - id: '/server-functions', - path: '/server-functions', - getParentRoute: () => rootRouteImport, -} as any) -const SsrRoute = SsrRouteImport.update({ - id: '/ssr', - path: '/ssr', - getParentRoute: () => rootRouteImport, -} as any) -const ApiSessionRoute = ApiSessionRouteImport.update({ - id: '/api/session', - path: '/api/session', - getParentRoute: () => rootRouteImport, -} as any) -const ApiSessionClearRoute = ApiSessionClearRouteImport.update({ - id: '/api/session-clear', - path: '/api/session-clear', - getParentRoute: () => rootRouteImport, -} as any) -const ApiSessionFlashRoute = ApiSessionFlashRouteImport.update({ - id: '/api/session-flash', - path: '/api/session-flash', - getParentRoute: () => rootRouteImport, -} as any) -const ApiSessionHelperCookieRoute = ApiSessionHelperCookieRouteImport.update({ - id: '/api/session-helper-cookie', - path: '/api/session-helper-cookie', - getParentRoute: () => rootRouteImport, -} as any) -const ApiSessionHonoRoute = ApiSessionHonoRouteImport.update({ - id: '/api/session-hono', - path: '/api/session-hono', - getParentRoute: () => rootRouteImport, -} as any) -const ApiSessionHonoCommunityRoute = ApiSessionHonoCommunityRouteImport.update({ - id: '/api/session-hono-community', - path: '/api/session-hono-community', - getParentRoute: () => rootRouteImport, -} as any) -const ApiSessionHonoCookieRoute = ApiSessionHonoCookieRouteImport.update({ - id: '/api/session-hono-cookie', - path: '/api/session-hono-cookie', - getParentRoute: () => rootRouteImport, -} as any) -const ApiSessionIronRoute = ApiSessionIronRouteImport.update({ - id: '/api/session-iron', - path: '/api/session-iron', - getParentRoute: () => rootRouteImport, -} as any) -const ApiSessionMiddlewareRoute = ApiSessionMiddlewareRouteImport.update({ - id: '/api/session-middleware', - path: '/api/session-middleware', - getParentRoute: () => rootRouteImport, -} as any) -const ApiSessionNamedRoute = ApiSessionNamedRouteImport.update({ - id: '/api/session-named', - path: '/api/session-named', - getParentRoute: () => rootRouteImport, -} as any) -const ApiSessionRedirectRoute = ApiSessionRedirectRouteImport.update({ - id: '/api/session-redirect', - path: '/api/session-redirect', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/server-functions': typeof ServerFunctionsRoute - '/ssr': typeof SsrRoute - '/api/session': typeof ApiSessionRoute - '/api/session-clear': typeof ApiSessionClearRoute - '/api/session-flash': typeof ApiSessionFlashRoute - '/api/session-helper-cookie': typeof ApiSessionHelperCookieRoute - '/api/session-hono': typeof ApiSessionHonoRoute - '/api/session-hono-community': typeof ApiSessionHonoCommunityRoute - '/api/session-hono-cookie': typeof ApiSessionHonoCookieRoute - '/api/session-iron': typeof ApiSessionIronRoute - '/api/session-middleware': typeof ApiSessionMiddlewareRoute - '/api/session-named': typeof ApiSessionNamedRoute - '/api/session-redirect': typeof ApiSessionRedirectRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/server-functions': typeof ServerFunctionsRoute - '/ssr': typeof SsrRoute - '/api/session': typeof ApiSessionRoute - '/api/session-clear': typeof ApiSessionClearRoute - '/api/session-flash': typeof ApiSessionFlashRoute - '/api/session-helper-cookie': typeof ApiSessionHelperCookieRoute - '/api/session-hono': typeof ApiSessionHonoRoute - '/api/session-hono-community': typeof ApiSessionHonoCommunityRoute - '/api/session-hono-cookie': typeof ApiSessionHonoCookieRoute - '/api/session-iron': typeof ApiSessionIronRoute - '/api/session-middleware': typeof ApiSessionMiddlewareRoute - '/api/session-named': typeof ApiSessionNamedRoute - '/api/session-redirect': typeof ApiSessionRedirectRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/server-functions': typeof ServerFunctionsRoute - '/ssr': typeof SsrRoute - '/api/session': typeof ApiSessionRoute - '/api/session-clear': typeof ApiSessionClearRoute - '/api/session-flash': typeof ApiSessionFlashRoute - '/api/session-helper-cookie': typeof ApiSessionHelperCookieRoute - '/api/session-hono': typeof ApiSessionHonoRoute - '/api/session-hono-community': typeof ApiSessionHonoCommunityRoute - '/api/session-hono-cookie': typeof ApiSessionHonoCookieRoute - '/api/session-iron': typeof ApiSessionIronRoute - '/api/session-middleware': typeof ApiSessionMiddlewareRoute - '/api/session-named': typeof ApiSessionNamedRoute - '/api/session-redirect': typeof ApiSessionRedirectRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/server-functions' - | '/ssr' - | '/api/session' - | '/api/session-clear' - | '/api/session-flash' - | '/api/session-helper-cookie' - | '/api/session-hono' - | '/api/session-hono-community' - | '/api/session-hono-cookie' - | '/api/session-iron' - | '/api/session-middleware' - | '/api/session-named' - | '/api/session-redirect' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/server-functions' - | '/ssr' - | '/api/session' - | '/api/session-clear' - | '/api/session-flash' - | '/api/session-helper-cookie' - | '/api/session-hono' - | '/api/session-hono-community' - | '/api/session-hono-cookie' - | '/api/session-iron' - | '/api/session-middleware' - | '/api/session-named' - | '/api/session-redirect' - id: - | '__root__' - | '/' - | '/server-functions' - | '/ssr' - | '/api/session' - | '/api/session-clear' - | '/api/session-flash' - | '/api/session-helper-cookie' - | '/api/session-hono' - | '/api/session-hono-community' - | '/api/session-hono-cookie' - | '/api/session-iron' - | '/api/session-middleware' - | '/api/session-named' - | '/api/session-redirect' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ServerFunctionsRoute: typeof ServerFunctionsRoute - SsrRoute: typeof SsrRoute - ApiSessionRoute: typeof ApiSessionRoute - ApiSessionClearRoute: typeof ApiSessionClearRoute - ApiSessionFlashRoute: typeof ApiSessionFlashRoute - ApiSessionHelperCookieRoute: typeof ApiSessionHelperCookieRoute - ApiSessionHonoRoute: typeof ApiSessionHonoRoute - ApiSessionHonoCommunityRoute: typeof ApiSessionHonoCommunityRoute - ApiSessionHonoCookieRoute: typeof ApiSessionHonoCookieRoute - ApiSessionIronRoute: typeof ApiSessionIronRoute - ApiSessionMiddlewareRoute: typeof ApiSessionMiddlewareRoute - ApiSessionNamedRoute: typeof ApiSessionNamedRoute - ApiSessionRedirectRoute: typeof ApiSessionRedirectRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/server-functions': { - id: '/server-functions' - path: '/server-functions' - fullPath: '/server-functions' - preLoaderRoute: typeof ServerFunctionsRouteImport - parentRoute: typeof rootRouteImport - } - '/ssr': { - id: '/ssr' - path: '/ssr' - fullPath: '/ssr' - preLoaderRoute: typeof SsrRouteImport - parentRoute: typeof rootRouteImport - } - '/api/session': { - id: '/api/session' - path: '/api/session' - fullPath: '/api/session' - preLoaderRoute: typeof ApiSessionRouteImport - parentRoute: typeof rootRouteImport - } - '/api/session-clear': { - id: '/api/session-clear' - path: '/api/session-clear' - fullPath: '/api/session-clear' - preLoaderRoute: typeof ApiSessionClearRouteImport - parentRoute: typeof rootRouteImport - } - '/api/session-flash': { - id: '/api/session-flash' - path: '/api/session-flash' - fullPath: '/api/session-flash' - preLoaderRoute: typeof ApiSessionFlashRouteImport - parentRoute: typeof rootRouteImport - } - '/api/session-helper-cookie': { - id: '/api/session-helper-cookie' - path: '/api/session-helper-cookie' - fullPath: '/api/session-helper-cookie' - preLoaderRoute: typeof ApiSessionHelperCookieRouteImport - parentRoute: typeof rootRouteImport - } - '/api/session-hono': { - id: '/api/session-hono' - path: '/api/session-hono' - fullPath: '/api/session-hono' - preLoaderRoute: typeof ApiSessionHonoRouteImport - parentRoute: typeof rootRouteImport - } - '/api/session-hono-community': { - id: '/api/session-hono-community' - path: '/api/session-hono-community' - fullPath: '/api/session-hono-community' - preLoaderRoute: typeof ApiSessionHonoCommunityRouteImport - parentRoute: typeof rootRouteImport - } - '/api/session-hono-cookie': { - id: '/api/session-hono-cookie' - path: '/api/session-hono-cookie' - fullPath: '/api/session-hono-cookie' - preLoaderRoute: typeof ApiSessionHonoCookieRouteImport - parentRoute: typeof rootRouteImport - } - '/api/session-iron': { - id: '/api/session-iron' - path: '/api/session-iron' - fullPath: '/api/session-iron' - preLoaderRoute: typeof ApiSessionIronRouteImport - parentRoute: typeof rootRouteImport - } - '/api/session-middleware': { - id: '/api/session-middleware' - path: '/api/session-middleware' - fullPath: '/api/session-middleware' - preLoaderRoute: typeof ApiSessionMiddlewareRouteImport - parentRoute: typeof rootRouteImport - } - '/api/session-named': { - id: '/api/session-named' - path: '/api/session-named' - fullPath: '/api/session-named' - preLoaderRoute: typeof ApiSessionNamedRouteImport - parentRoute: typeof rootRouteImport - } - '/api/session-redirect': { - id: '/api/session-redirect' - path: '/api/session-redirect' - fullPath: '/api/session-redirect' - preLoaderRoute: typeof ApiSessionRedirectRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ServerFunctionsRoute: ServerFunctionsRoute, - SsrRoute: SsrRoute, - ApiSessionRoute: ApiSessionRoute, - ApiSessionClearRoute: ApiSessionClearRoute, - ApiSessionFlashRoute: ApiSessionFlashRoute, - ApiSessionHelperCookieRoute: ApiSessionHelperCookieRoute, - ApiSessionHonoRoute: ApiSessionHonoRoute, - ApiSessionHonoCommunityRoute: ApiSessionHonoCommunityRoute, - ApiSessionHonoCookieRoute: ApiSessionHonoCookieRoute, - ApiSessionIronRoute: ApiSessionIronRoute, - ApiSessionMiddlewareRoute: ApiSessionMiddlewareRoute, - ApiSessionNamedRoute: ApiSessionNamedRoute, - ApiSessionRedirectRoute: ApiSessionRedirectRoute, -} -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/session-handling/src/router.tsx b/e2e/react-start/session-handling/src/router.tsx deleted file mode 100644 index c5c2209e5a..0000000000 --- a/e2e/react-start/session-handling/src/router.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' -import { DefaultCatchBoundary } from './components/DefaultCatchBoundary' -import { NotFound } from './components/NotFound' - -export function getRouter() { - return createRouter({ - routeTree, - defaultErrorComponent: DefaultCatchBoundary, - defaultNotFoundComponent: () => , - scrollRestoration: true, - }) -} diff --git a/e2e/react-start/session-handling/src/routes/__root.tsx b/e2e/react-start/session-handling/src/routes/__root.tsx deleted file mode 100644 index e5e5f4cd24..0000000000 --- a/e2e/react-start/session-handling/src/routes/__root.tsx +++ /dev/null @@ -1,59 +0,0 @@ -/// -import * as React from 'react' -import { - HeadContent, - Link, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' -import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary' -import { NotFound } from '~/components/NotFound' -import '~/styles/app.css' - -export const Route = createRootRoute({ - head: () => ({ - meta: [ - { charSet: 'utf-8' }, - { name: 'viewport', content: 'width=device-width, initial-scale=1' }, - ], - }), - errorComponent: (props) => { - return ( - - - - ) - }, - notFoundComponent: () => , - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - ) -} - -function RootDocument({ children }: { children: React.ReactNode }) { - return ( - - - - - - - {children} - - - - ) -} diff --git a/e2e/react-start/session-handling/src/routes/api/session-clear.ts b/e2e/react-start/session-handling/src/routes/api/session-clear.ts deleted file mode 100644 index 44b83e58ac..0000000000 --- a/e2e/react-start/session-handling/src/routes/api/session-clear.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { destroySession } from '~/session' - -export const Route = createFileRoute('/api/session-clear')({ - server: { - handlers: { - POST: async () => { - await destroySession() - return Response.json({ cleared: true }) - }, - }, - }, -}) diff --git a/e2e/react-start/session-handling/src/routes/api/session-flash.ts b/e2e/react-start/session-handling/src/routes/api/session-flash.ts deleted file mode 100644 index 7b494d5050..0000000000 --- a/e2e/react-start/session-handling/src/routes/api/session-flash.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { readSession } from '~/session' - -export const Route = createFileRoute('/api/session-flash')({ - server: { - handlers: { - POST: async () => { - const session = await readSession() - session.notice = 'Saved successfully' - await session.save() - return Response.json({ saved: true }) - }, - GET: async () => { - const session = await readSession() - const notice = session.notice ?? null - delete session.notice - await session.save() - return Response.json({ notice }) - }, - }, - }, -}) diff --git a/e2e/react-start/session-handling/src/routes/api/session-helper-cookie.ts b/e2e/react-start/session-handling/src/routes/api/session-helper-cookie.ts deleted file mode 100644 index 24711e227c..0000000000 --- a/e2e/react-start/session-handling/src/routes/api/session-helper-cookie.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { setCookie } from '@tanstack/react-start/server' -import { readJson, updateSessionData } from '~/session' - -export const Route = createFileRoute('/api/session-helper-cookie')({ - server: { - handlers: { - POST: async ({ request }) => { - const session = await updateSessionData(await readJson(request)) - setCookie('helper-session', '1', { path: '/' }) - const headers = new Headers() - headers.append( - 'Set-Cookie', - 'returned-session=1; Path=/; Expires=Tue, 01 Jan 2030 00:00:00 GMT', - ) - headers.append('Set-Cookie', 'returned-extra=2; Path=/') - return Response.json(session, { headers }) - }, - }, - }, -}) diff --git a/e2e/react-start/session-handling/src/routes/api/session-hono-community.ts b/e2e/react-start/session-handling/src/routes/api/session-hono-community.ts deleted file mode 100644 index deb93ea549..0000000000 --- a/e2e/react-start/session-handling/src/routes/api/session-hono-community.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { setCookie } from '@tanstack/react-start/server' -import { communitySessionApp } from '~/hono-sessions' - -function handle({ request }: { request: Request }) { - setCookie('start-side', 'coexists', { path: '/' }) - return communitySessionApp.fetch(request) -} - -export const Route = createFileRoute('/api/session-hono-community')({ - server: { handlers: { GET: handle, POST: handle, DELETE: handle } }, -}) diff --git a/e2e/react-start/session-handling/src/routes/api/session-hono-cookie.ts b/e2e/react-start/session-handling/src/routes/api/session-hono-cookie.ts deleted file mode 100644 index fb99ce6196..0000000000 --- a/e2e/react-start/session-handling/src/routes/api/session-hono-cookie.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { generateCookie, generateSignedCookie } from 'hono/cookie' -import { parseSigned } from 'hono/utils/cookie' -import { - appendResponseHeader, - getRequestHeader, - setCookie, -} from '@tanstack/react-start/server' -import { sessionPassword } from '~/session' - -// These Hono exports work with strings; they do not require a Hono Context. -// They provide signed cookies, not session storage or server-side expiration. -export const Route = createFileRoute('/api/session-hono-cookie')({ - server: { - handlers: { - GET: async () => { - const values = await parseSigned( - getRequestHeader('cookie') ?? '', - sessionPassword, - 'hono-signed', - ) - return Response.json({ user: values['hono-signed'] || null }) - }, - POST: async ({ request }) => { - const data = await request.json() - appendResponseHeader( - 'set-cookie', - await generateSignedCookie( - 'hono-signed', - data.user, - sessionPassword, - { - httpOnly: true, - sameSite: 'Lax', - path: '/', - maxAge: 3600, - }, - ), - ) - setCookie('start-side', 'coexists', { path: '/' }) - return Response.json({ user: data.user }) - }, - DELETE: () => { - appendResponseHeader( - 'set-cookie', - generateCookie('hono-signed', '', { path: '/', maxAge: 0 }), - ) - return Response.json({ cleared: true }) - }, - }, - }, -}) diff --git a/e2e/react-start/session-handling/src/routes/api/session-hono.ts b/e2e/react-start/session-handling/src/routes/api/session-hono.ts deleted file mode 100644 index fdfd172bf0..0000000000 --- a/e2e/react-start/session-handling/src/routes/api/session-hono.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { setCookie } from '@tanstack/react-start/server' -import { honoSessionApp } from '~/hono-sessions' - -function handle({ request }: { request: Request }) { - setCookie('start-side', 'coexists', { path: '/' }) - return honoSessionApp.fetch(request) -} - -export const Route = createFileRoute('/api/session-hono')({ - server: { handlers: { GET: handle, POST: handle, DELETE: handle } }, -}) diff --git a/e2e/react-start/session-handling/src/routes/api/session-iron.ts b/e2e/react-start/session-handling/src/routes/api/session-iron.ts deleted file mode 100644 index 83337d1dfb..0000000000 --- a/e2e/react-start/session-handling/src/routes/api/session-iron.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { readJson, readSession } from '~/session' - -export const Route = createFileRoute('/api/session-iron')({ - server: { - handlers: { - GET: async () => - Response.json({ data: { ...(await readSession('iron-session')) } }), - POST: async ({ request }) => { - const session = await readSession('iron-session') - const data = await readJson(request) - if (typeof data.user === 'string') { - session.user = data.user - } - if (typeof data.token === 'string') { - session.token = data.token - } - await session.save() - return Response.json({ data: { ...session } }) - }, - DELETE: async () => { - const session = await readSession('iron-session') - session.destroy() - return Response.json({ cleared: true }) - }, - }, - }, -}) diff --git a/e2e/react-start/session-handling/src/routes/api/session-middleware.ts b/e2e/react-start/session-handling/src/routes/api/session-middleware.ts deleted file mode 100644 index 4090262477..0000000000 --- a/e2e/react-start/session-handling/src/routes/api/session-middleware.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { sessionMiddleware } from '~/start' - -export const Route = createFileRoute('/api/session-middleware')({ - server: { - middleware: [sessionMiddleware], - handlers: { - GET: ({ context }) => Response.json({ data: { ...context.session } }), - }, - }, -}) diff --git a/e2e/react-start/session-handling/src/routes/api/session-named.ts b/e2e/react-start/session-handling/src/routes/api/session-named.ts deleted file mode 100644 index 5acb82446c..0000000000 --- a/e2e/react-start/session-handling/src/routes/api/session-named.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { readJson, readSession, updateSessionData } from '~/session' - -function getName(request: Request) { - return new URL(request.url).searchParams.get('name') || 'app-named' -} - -export const Route = createFileRoute('/api/session-named')({ - server: { - handlers: { - GET: async ({ request }) => - Response.json({ - data: { ...(await readSession(getName(request))) }, - }), - POST: async ({ request }) => - Response.json( - await updateSessionData(await readJson(request), getName(request)), - ), - }, - }, -}) diff --git a/e2e/react-start/session-handling/src/routes/api/session-redirect.ts b/e2e/react-start/session-handling/src/routes/api/session-redirect.ts deleted file mode 100644 index 5280d7e6bc..0000000000 --- a/e2e/react-start/session-handling/src/routes/api/session-redirect.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { createFileRoute, redirect } from '@tanstack/react-router' -import { updateSessionData } from '~/session' - -export const Route = createFileRoute('/api/session-redirect')({ - server: { - handlers: { - POST: async () => { - await updateSessionData({ user: 'redirected' }) - throw redirect({ href: '/api/session', statusCode: 303 }) - }, - }, - }, -}) diff --git a/e2e/react-start/session-handling/src/routes/api/session.ts b/e2e/react-start/session-handling/src/routes/api/session.ts deleted file mode 100644 index 4696cf80a4..0000000000 --- a/e2e/react-start/session-handling/src/routes/api/session.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { readJson, readSession, updateSessionData } from '~/session' - -export const Route = createFileRoute('/api/session')({ - server: { - handlers: { - GET: async () => Response.json({ data: { ...(await readSession()) } }), - POST: async ({ request }) => - Response.json(await updateSessionData(await readJson(request))), - }, - }, -}) diff --git a/e2e/react-start/session-handling/src/routes/index.tsx b/e2e/react-start/session-handling/src/routes/index.tsx deleted file mode 100644 index 9dc929d5bb..0000000000 --- a/e2e/react-start/session-handling/src/routes/index.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: Home, -}) - -function Home() { - return ( -
-

Session Handling E2E

-

This app contains HTTP-level session tests.

-
- ) -} diff --git a/e2e/react-start/session-handling/src/routes/server-functions.tsx b/e2e/react-start/session-handling/src/routes/server-functions.tsx deleted file mode 100644 index bce5419c84..0000000000 --- a/e2e/react-start/session-handling/src/routes/server-functions.tsx +++ /dev/null @@ -1,85 +0,0 @@ -import { ClientOnly, createFileRoute, redirect } from '@tanstack/react-router' -import { createServerFn, useServerFn } from '@tanstack/react-start' -import * as React from 'react' -import { destroySession, readSession, updateSessionData } from '~/session' - -const updateSessionFn = createServerFn({ method: 'POST' }).handler(async () => { - const data = { serverFn: 'updated' } - await updateSessionData(data) - return { data } -}) -const readSessionFn = createServerFn().handler(async () => { - const serverFn = (await readSession()).serverFn - return { data: typeof serverFn === 'string' ? { serverFn } : {} } -}) -const clearSessionFn = createServerFn({ method: 'POST' }).handler(async () => { - await destroySession() - return { cleared: true } -}) -const redirectSessionFn = createServerFn({ method: 'POST' }).handler( - async () => { - await updateSessionData({ serverFn: 'redirected' }) - throw redirect({ to: '/ssr' }) - }, -) -const errorSessionFn = createServerFn({ method: 'POST' }).handler(async () => { - await updateSessionData({ serverFn: 'error-persisted' }) - throw new Error('Expected external session error') -}) -const ironSessionFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await readSession('iron-session') - session.user = 'iron-server-function' - await session.save() - return { user: session.user } -}) - -export const Route = createFileRoute('/server-functions')({ - component: ServerFunctions, -}) - -function ServerFunctions() { - return ( -
-

External Session Server Functions

- - - - - - - - -
- ) -} - -function ServerFunctionButton({ - name, - fn, -}: { - name: string - fn: (...args: Array) => Promise -}) { - const serverFn = useServerFn(fn) - const [result, setResult] = React.useState('idle') - return ( -
- - {result} -
- ) -} diff --git a/e2e/react-start/session-handling/src/routes/ssr.tsx b/e2e/react-start/session-handling/src/routes/ssr.tsx deleted file mode 100644 index 0339a4f813..0000000000 --- a/e2e/react-start/session-handling/src/routes/ssr.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { createServerFn } from '@tanstack/react-start' -import { readSession } from '~/session' - -const loadSession = createServerFn().handler(async () => { - const session = await readSession() - const count = Number(session.ssrCount ?? 0) + 1 - session.ssrCount = count - await session.save() - return { count } -}) - -export const Route = createFileRoute('/ssr')({ - loader: () => loadSession(), - component: SsrRoute, -}) - -function SsrRoute() { - const data = Route.useLoaderData() - return ( -
-

External Session SSR

-

{String(data.count)}

-
- ) -} diff --git a/e2e/react-start/session-handling/src/session.ts b/e2e/react-start/session-handling/src/session.ts deleted file mode 100644 index f223c42cbd..0000000000 --- a/e2e/react-start/session-handling/src/session.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { getIronSession } from 'iron-session' -import { getCookie, setCookie } from '@tanstack/react-start/server' - -// Fixed secrets and insecure cookies are only for this local HTTP test fixture. -export const sessionPassword = 'start-external-session-test-only-'.repeat(2) -export type SessionData = { - user?: string - token?: string - serverFn?: string - middleware?: string - notice?: string - ssrCount?: number -} - -export async function updateSessionData(data: SessionData, name?: string) { - const session = await readSession(name) - Object.assign(session, data) - await session.save() - return { data: { ...session } } -} - -export async function destroySession() { - const session = await readSession() - session.destroy() -} - -export function readSession(cookieName = 'app-session') { - return getIronSession( - { read: getCookie, write: setCookie }, - { - cookieName, - password: sessionPassword, - ttl: 3600, - chunk: true, - cookieOptions: { - secure: false, - httpOnly: true, - sameSite: 'lax', - path: '/', - }, - }, - ) -} - -export async function readJson(request: Request): Promise { - return request.json() -} diff --git a/e2e/react-start/session-handling/src/start.ts b/e2e/react-start/session-handling/src/start.ts deleted file mode 100644 index a9571afabb..0000000000 --- a/e2e/react-start/session-handling/src/start.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { createMiddleware, createStart } from '@tanstack/react-start' -import { readSession } from './session' - -export const sessionMiddleware = createMiddleware().server( - async ({ next, request }) => { - const session = await readSession() - const scenario = request.headers.get('x-session-middleware') - if (scenario === 'before') { - session.middleware = 'before' - } - const result = await next({ context: { session } }) - if (scenario === 'after') { - session.middleware = 'after' - } - if (scenario) { - await session.save() - } - return result - }, -) - -export const startInstance = createStart(() => ({})) diff --git a/e2e/react-start/session-handling/src/styles/app.css b/e2e/react-start/session-handling/src/styles/app.css deleted file mode 100644 index a38fb439a6..0000000000 --- a/e2e/react-start/session-handling/src/styles/app.css +++ /dev/null @@ -1,12 +0,0 @@ -html { - color-scheme: light dark; - font-family: system-ui, sans-serif; -} - -body { - margin: 0; -} - -main { - padding: 16px; -} diff --git a/e2e/react-start/session-handling/tests/session-handling.spec.ts b/e2e/react-start/session-handling/tests/session-handling.spec.ts deleted file mode 100644 index aaa975ccef..0000000000 --- a/e2e/react-start/session-handling/tests/session-handling.spec.ts +++ /dev/null @@ -1,334 +0,0 @@ -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' -import type { APIResponse, Page, Response } from '@playwright/test' - -async function setCookieValues(response: APIResponse | Response) { - return (await Promise.resolve(response.headersArray())) - .filter((item) => item.name.toLowerCase() === 'set-cookie') - .map((item) => item.value) -} - -function expectCookie(cookies: Array, name: string) { - expect(cookies.some((cookie) => cookie.startsWith(`${name}=`))).toBe(true) -} - -async function expectResult(page: Page, name: string, value: string) { - await expect( - page.getByTestId(`server-function-${name}-result`), - ).toContainText(value) -} - -async function visitFunctions(page: Page) { - await page.goto('/server-functions') - await expect(page.getByTestId('server-functions-hydrated')).toBeAttached() -} - -test.describe('iron-session in Start', () => { - test('does not write cookies on a read and persists committed mutations', async ({ - request, - }) => { - const initial = await request.get('/api/session') - expect(await initial.json()).toEqual({ data: {} }) - expect(await setCookieValues(initial)).toEqual([]) - - const update = await request.post('/api/session', { - data: { user: 'tanner' }, - }) - const cookies = await setCookieValues(update) - expectCookie(cookies, 'app-session') - expect(cookies[0]).toContain('HttpOnly') - expect(cookies[0]).toContain('SameSite=Lax') - expect(cookies[0]).toContain('Path=/') - - const read = await request.get('/api/session') - expect(await read.json()).toEqual({ data: { user: 'tanner' } }) - expect(await setCookieValues(read)).toEqual([]) - }) - - test('destroy logs out the cookie jar', async ({ request }) => { - await request.post('/api/session', { data: { user: 'clear-me' } }) - const clear = await request.post('/api/session-clear') - const cookies = await setCookieValues(clear) - expectCookie(cookies, 'app-session') - expect(cookies[0]).toContain('Max-Age=0') - expect(await (await request.get('/api/session')).json()).toEqual({ - data: {}, - }) - }) - - test('independent named sessions coexist', async ({ request }) => { - await request.post('/api/session', { data: { user: 'default-user' } }) - await request.post('/api/session-named?name=app-account', { - data: { user: 'account-user' }, - }) - expect(await (await request.get('/api/session')).json()).toEqual({ - data: { user: 'default-user' }, - }) - expect( - await (await request.get('/api/session-named?name=app-account')).json(), - ).toEqual({ data: { user: 'account-user' } }) - }) - - test('invalid input does not become authenticated session data', async ({ - request, - }) => { - const response = await request.get('/api/session', { - headers: { cookie: 'app-session=invalid' }, - }) - expect(await response.json()).toEqual({ data: {} }) - expect(await setCookieValues(response)).toEqual([]) - }) - - test('preserves library, helper, and returned cookies including Expires commas', async ({ - request, - }) => { - const response = await request.post('/api/session-helper-cookie', { - data: { user: 'coexists' }, - }) - const cookies = await setCookieValues(response) - expect(cookies).toHaveLength(4) - for (const name of [ - 'app-session', - 'helper-session', - 'returned-session', - 'returned-extra', - ]) { - expectCookie(cookies, name) - } - expect( - cookies.find((cookie) => cookie.startsWith('returned-session=')), - ).toContain('Expires=Tue, 01 Jan 2030 00:00:00 GMT') - expect(await (await request.get('/api/session')).json()).toEqual({ - data: { user: 'coexists' }, - }) - }) - - test('a notification is consumed once after its deletion is saved', async ({ - request, - }) => { - await request.post('/api/session-flash') - expect(await (await request.get('/api/session-flash')).json()).toEqual({ - notice: 'Saved successfully', - }) - expect(await (await request.get('/api/session-flash')).json()).toEqual({ - notice: null, - }) - }) - - test('session mutations survive a thrown Start redirect', async ({ - request, - }) => { - const response = await request.post('/api/session-redirect', { - maxRedirects: 0, - }) - expect(response.status()).toBe(303) - expect(response.headers().location).toBe('/api/session') - expectCookie(await setCookieValues(response), 'app-session') - expect(await (await request.get('/api/session')).json()).toEqual({ - data: { user: 'redirected' }, - }) - }) - - test('middleware shares the session object and commits changes after next', async ({ - request, - }) => { - const before = await request.get('/api/session-middleware', { - headers: { 'x-session-middleware': 'before' }, - }) - expect(await before.json()).toEqual({ data: { middleware: 'before' } }) - expectCookie(await setCookieValues(before), 'app-session') - const after = await request.get('/api/session-middleware', { - headers: { 'x-session-middleware': 'after' }, - }) - expect(await after.json()).toEqual({ data: { middleware: 'before' } }) - expect(await (await request.get('/api/session')).json()).toEqual({ - data: { middleware: 'after' }, - }) - }) -}) - -test.describe('iron-session cookie jar adapter', () => { - test('saves, reads, and destroys encrypted sessions using Start cookie helpers', async ({ - request, - }) => { - const saved = await request.post('/api/session-iron', { - data: { user: 'iron-user' }, - }) - expectCookie(await setCookieValues(saved), 'iron-session') - expect(await (await request.get('/api/session-iron')).json()).toEqual({ - data: { user: 'iron-user' }, - }) - await request.delete('/api/session-iron') - expect(await (await request.get('/api/session-iron')).json()).toEqual({ - data: {}, - }) - }) - - test('roundtrips chunked cookies and deletes obsolete chunks after shrinking', async ({ - request, - }) => { - const large = await request.post('/api/session-iron', { - data: { token: 'x'.repeat(5000) }, - }) - const cookies = await setCookieValues(large) - expectCookie(cookies, 'iron-session.0') - expectCookie(cookies, 'iron-session.1') - expect( - (await (await request.get('/api/session-iron')).json()).data.token, - ).toHaveLength(5000) - const small = await request.post('/api/session-iron', { - data: { token: 'tiny' }, - }) - const smallCookies = await setCookieValues(small) - expectCookie(smallCookies, 'iron-session') - expect( - smallCookies.some( - (cookie) => - cookie.startsWith('iron-session.1=') && /Max-Age=0/i.test(cookie), - ), - ).toBe(true) - expect( - (await (await request.get('/api/session-iron')).json()).data.token, - ).toBe('tiny') - }) -}) - -test.describe('Hono applications mounted in Start server routes', () => { - for (const [path, cookieName] of [ - ['session-hono', 'sid'], - ['session-hono-community', 'hono-community'], - ]) { - test(`${path} persists and clears sessions after Hono middleware completes`, async ({ - request, - }) => { - const saved = await request.post(`/api/${path}`, { - data: { user: 'hono-user' }, - }) - expect(saved.status()).toBe(200) - const cookies = await setCookieValues(saved) - expectCookie(cookies, cookieName!) - expectCookie(cookies, 'start-side') - if (path === 'session-hono') { - expectCookie(cookies, 'hono-extra') - } - expect((await (await request.get(`/api/${path}`)).json()).data.user).toBe( - 'hono-user', - ) - await request.delete(`/api/${path}`) - expect( - (await (await request.get(`/api/${path}`)).json()).data.user ?? null, - ).toBeNull() - }) - } - - test('Hono context-free signed cookie helpers work directly in Start', async ({ - request, - }) => { - const saved = await request.post('/api/session-hono-cookie', { - data: { user: 'signed-user' }, - }) - expectCookie(await setCookieValues(saved), 'hono-signed') - expectCookie(await setCookieValues(saved), 'start-side') - expect( - await (await request.get('/api/session-hono-cookie')).json(), - ).toEqual({ user: 'signed-user' }) - await request.delete('/api/session-hono-cookie') - expect( - await (await request.get('/api/session-hono-cookie')).json(), - ).toEqual({ user: null }) - }) -}) - -test.describe('document and server function sessions', () => { - test('SSR loader commits persist across browser reloads', async ({ - page, - }) => { - await page.goto('/ssr') - await expect(page.getByTestId('ssr-session-count')).toHaveText('1') - await page.reload() - await expect(page.getByTestId('ssr-session-count')).toHaveText('2') - }) - - test('server functions update, read, and clear the browser session', async ({ - page, - }) => { - await visitFunctions(page) - const responsePromise = page.waitForResponse((response) => - response.url().includes('/_serverFn/'), - ) - await page.getByTestId('server-function-update').click() - expectCookie(await setCookieValues(await responsePromise), 'app-session') - await expectResult(page, 'update', '"serverFn":"updated"') - await page.getByTestId('server-function-read').click() - await expectResult(page, 'read', '"serverFn":"updated"') - await page.getByTestId('server-function-clear').click() - await expectResult(page, 'clear', '"cleared":true') - await page.getByTestId('server-function-read').click() - await expectResult(page, 'read', '"data":{}') - }) - - test('server function redirects retain committed session data', async ({ - page, - }) => { - await visitFunctions(page) - await page.getByTestId('server-function-redirect').click() - await expect(page).toHaveURL(/\/ssr$/) - await expect(page.getByTestId('ssr-session-count')).toHaveText('1') - expect( - (await (await page.request.get('/api/session')).json()).data.serverFn, - ).toBe('redirected') - }) - - test.describe('expected server function error', () => { - test.use({ - whitelistErrors: [ - /Failed to load resource: the server responded with a status of 500/, - ], - }) - test('server function errors retain committed session data', async ({ - page, - }) => { - await visitFunctions(page) - await page.getByTestId('server-function-error').click() - await expectResult(page, 'error', 'Expected external session error') - expect( - (await (await page.request.get('/api/session')).json()).data.serverFn, - ).toBe('error-persisted') - }) - }) - - test('iron-session cookie jar works in browser-invoked server functions', async ({ - page, - }) => { - await visitFunctions(page) - await page.getByTestId('server-function-iron').click() - await expectResult(page, 'iron', 'iron-server-function') - expect( - (await (await page.request.get('/api/session-iron')).json()).data.user, - ).toBe('iron-server-function') - }) - - test('separate browser contexts retain independent sessions', async ({ - browser, - baseURL, - }) => { - const first = await browser.newContext({ baseURL }) - const second = await browser.newContext({ baseURL }) - try { - const firstPage = await first.newPage() - const secondPage = await second.newPage() - const [firstResponse, secondResponse] = await Promise.all([ - firstPage.goto('/ssr'), - secondPage.goto('/ssr'), - ]) - expect(firstResponse?.ok()).toBe(true) - expect(secondResponse?.ok()).toBe(true) - await firstPage.reload() - await expect(firstPage.getByTestId('ssr-session-count')).toHaveText('2') - await expect(secondPage.getByTestId('ssr-session-count')).toHaveText('1') - } finally { - await first.close() - await second.close() - } - }) -}) diff --git a/e2e/react-start/session-handling/tsconfig.json b/e2e/react-start/session-handling/tsconfig.json deleted file mode 100644 index c7a0597e4b..0000000000 --- a/e2e/react-start/session-handling/tsconfig.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "include": ["**/*.ts", "**/*.tsx"], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "react-jsx", - "module": "ESNext", - "moduleResolution": "Bundler", - "lib": ["DOM", "DOM.Iterable", "ES2022"], - "isolatedModules": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "target": "ES2022", - "allowJs": true, - "forceConsistentCasingInFileNames": true, - "paths": { - "~/*": ["./src/*"] - }, - "noEmit": true, - "types": ["vite/client"] - } -} diff --git a/e2e/react-start/session-handling/vite.config.ts b/e2e/react-start/session-handling/vite.config.ts deleted file mode 100644 index ef9695579b..0000000000 --- a/e2e/react-start/session-handling/vite.config.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { defineConfig } from 'vite' -import { tanstackStart } from '@tanstack/react-start/plugin/vite' -import viteReact from '@vitejs/plugin-react' - -const outDir = process.env.E2E_DIST_DIR ?? 'dist' - -export default defineConfig({ - resolve: { tsconfigPaths: true }, - build: { - outDir, - }, - plugins: [tanstackStart(), viteReact()], -}) diff --git a/e2e/react-start/spa-mode/package.json b/e2e/react-start/spa-mode/package.json index 5281364692..1810493b1a 100644 --- a/e2e/react-start/spa-mode/package.json +++ b/e2e/react-start/spa-mode/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "npx serve dist/client", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", diff --git a/e2e/react-start/spa-mode/playwright.config.ts b/e2e/react-start/spa-mode/playwright.config.ts index 630989e41f..badd6db0eb 100644 --- a/e2e/react-start/spa-mode/playwright.config.ts +++ b/e2e/react-start/spa-mode/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/split-base-and-basepath/package.json b/e2e/react-start/split-base-and-basepath/package.json index 7f0e62766c..c0066b7aaf 100644 --- a/e2e/react-start/split-base-and-basepath/package.json +++ b/e2e/react-start/split-base-and-basepath/package.json @@ -10,7 +10,7 @@ "start": "node prod-server.js", "test:e2e:dev": "MODE=dev playwright test --project=chromium", "test:e2e:prod": "playwright test --project=chromium", - "test:e2e": "pnpm run test:e2e:dev && pnpm run test:e2e:prod" + "test:e2e": "rm -rf port*.txt; pnpm run test:e2e:dev && pnpm run test:e2e:prod" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -26,7 +26,7 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" diff --git a/e2e/react-start/split-base-and-basepath/playwright.config.ts b/e2e/react-start/split-base-and-basepath/playwright.config.ts index f0e25bb95a..3596ccd106 100644 --- a/e2e/react-start/split-base-and-basepath/playwright.config.ts +++ b/e2e/react-start/split-base-and-basepath/playwright.config.ts @@ -1,10 +1,11 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } const mode = process.env.MODE ?? 'prod' const isDev = mode === 'dev' -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -13,17 +14,16 @@ export default defineConfig({ reporter: [['line']], globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', use: { baseURL, }, webServer: { - command: isDev - ? `pnpm dev:e2e --port 0` - : `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: isDev ? `pnpm dev:e2e` : `pnpm build && PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { PORT: String(PORT), diff --git a/e2e/react-start/split-base-and-basepath/prod-server.js b/e2e/react-start/split-base-and-basepath/prod-server.js index 58421125cf..72114a1d40 100644 --- a/e2e/react-start/split-base-and-basepath/prod-server.js +++ b/e2e/react-start/split-base-and-basepath/prod-server.js @@ -20,9 +20,7 @@ app.use(async (req, res, next) => { } }) -const httpServer = app.listen(PORT, (error) => { - if (error) { - throw error - } - console.log(`E2E app: http://localhost:${httpServer.address().port}`) +app.listen(PORT, (error) => { + if (error) throw error + console.log(`Server is running on http://localhost:${PORT}`) }) diff --git a/e2e/react-start/split-base-and-basepath/tests/setup/global.setup.ts b/e2e/react-start/split-base-and-basepath/tests/setup/global.setup.ts index 9fc3ddc286..41ad16a44f 100644 --- a/e2e/react-start/split-base-and-basepath/tests/setup/global.setup.ts +++ b/e2e/react-start/split-base-and-basepath/tests/setup/global.setup.ts @@ -1,9 +1,17 @@ -import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' +import { + e2eStartDummyServer, + getTestServerPort, + preOptimizeDevServer, + waitForServer, +} from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } export default async function setup() { + await e2eStartDummyServer(packageJson.name) + if (process.env.MODE !== 'dev') return - const port = Number(process.env.E2E_APP_PORT ?? 0) + const port = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${port}` await waitForServer(baseURL) diff --git a/e2e/react-start/split-base-and-basepath/tests/setup/global.teardown.ts b/e2e/react-start/split-base-and-basepath/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-start/split-base-and-basepath/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-start/start-manifest/package.json b/e2e/react-start/start-manifest/package.json index d5367558e8..939882a346 100644 --- a/e2e/react-start/start-manifest/package.json +++ b/e2e/react-start/start-manifest/package.json @@ -21,7 +21,7 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "nitro": "^3.0.260903-beta", + "nitro": "^3.0.260311-beta", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" @@ -29,11 +29,7 @@ "nx": { "targets": { "test:e2e": { - "parallelism": false, - "outputs": [ - "...", - "{projectRoot}/.output" - ] + "parallelism": false } } } diff --git a/e2e/react-start/start-manifest/playwright.config.ts b/e2e/react-start/start-manifest/playwright.config.ts index 333ada654d..9e72f6160b 100644 --- a/e2e/react-start/start-manifest/playwright.config.ts +++ b/e2e/react-start/start-manifest/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -15,8 +16,8 @@ export default defineConfig({ webServer: { command: `PORT=${PORT} pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/start-manifest/tests/start-manifest.spec.ts b/e2e/react-start/start-manifest/tests/start-manifest.spec.ts index bd7bd20e98..7dfa390997 100644 --- a/e2e/react-start/start-manifest/tests/start-manifest.spec.ts +++ b/e2e/react-start/start-manifest/tests/start-manifest.spec.ts @@ -27,6 +27,12 @@ async function getBackgroundColor(testId: string, page: Page) { .evaluate((element) => getComputedStyle(element).backgroundColor) } +async function getBorderTopColor(testId: string, page: Page) { + return page + .getByTestId(testId) + .evaluate((element) => getComputedStyle(element).borderTopColor) +} + function getStylesheetHrefsFromHtml(html: string) { return Array.from( html.matchAll(/]+rel="stylesheet"[^>]+href="([^"]+)"/g), @@ -356,19 +362,24 @@ test('shared widget CSS stays applied when navigating from static to lazy route' const widget = page.getByTestId('shared-widget') await expect(widget).toBeVisible() - await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) + expect(await getBackgroundColor('shared-widget', page)).toBe(SHARED_WIDGET_BG) + await expect + .poll(() => getBorderTopColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BORDER) await expect(page.getByTestId('lazy-css-static-hydrated')).toBeVisible() await page.getByTestId('nav-/lazy-css-lazy').click() await page.waitForURL('**/lazy-css-lazy') - // Both routes render `shared-widget`: wait for the destination route before - // asserting on it, so the assertions cannot match the departing widget. await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() - await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) }) test('shared widget CSS stays applied when navigating from lazy to static route', async ({ @@ -378,19 +389,28 @@ test('shared widget CSS stays applied when navigating from lazy to static route' await page.goto(buildUrl(baseURL!, '/lazy-css-lazy')) await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() - const widget = page.getByTestId('shared-widget') - await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) await page.getByTestId('nav-/lazy-css-static').click() await page.waitForURL('**/lazy-css-static') - // The URL updates before the lazy route unmounts, and both routes render - // `shared-widget`: wait for a marker only the static route renders. await expect(page.getByTestId('lazy-css-static-hydrated')).toBeVisible() + const widget = page.getByTestId('shared-widget') await expect(widget).toBeVisible() - await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) + await expect + .poll(() => getBorderTopColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BORDER) }) test('shared widget CSS is applied on direct navigation to lazy route', async ({ @@ -402,8 +422,17 @@ test('shared widget CSS is applied on direct navigation to lazy route', async ({ const widget = page.getByTestId('shared-widget') await expect(widget).toBeVisible() - await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) + + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) + await expect + .poll(() => getBorderTopColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BORDER) }) test('shared widget CSS persists after navigating away from lazy and back', async ({ @@ -413,21 +442,19 @@ test('shared widget CSS persists after navigating away from lazy and back', asyn await page.goto(buildUrl(baseURL!, '/lazy-css-static')) await expect(page.getByTestId('lazy-css-static-hydrated')).toBeVisible() - const widget = page.getByTestId('shared-widget') - await page.getByTestId('nav-/lazy-css-lazy').click() await page.waitForURL('**/lazy-css-lazy') - await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() - await expect(widget).toBeVisible() + await expect(page.getByTestId('shared-widget')).toBeVisible() await page.getByTestId('nav-home').click() await page.waitForURL((url) => url.pathname === '/') - await expect(page.getByTestId('home-copy')).toBeVisible() await page.getByTestId('nav-/lazy-css-lazy').click() await page.waitForURL('**/lazy-css-lazy') - await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() - await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) }) diff --git a/e2e/react-start/static-server-functions/package.json b/e2e/react-start/static-server-functions/package.json index 85f08d19c9..6aa146fc59 100644 --- a/e2e/react-start/static-server-functions/package.json +++ b/e2e/react-start/static-server-functions/package.json @@ -9,13 +9,13 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "node .output/server/index.mjs", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:*", "@tanstack/react-start": "workspace:*", "@tanstack/start-static-server-functions": "workspace:*", - "nitro": "^3.0.260903-beta", + "nitro": "^3.0.1-alpha.2", "react": "^19.0.0", "react-dom": "^19.0.0" }, @@ -29,14 +29,5 @@ "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" - }, - "nx": { - "targets": { - "test:e2e": { - "dependsOn": [ - "build" - ] - } - } } } diff --git a/e2e/react-start/static-server-functions/playwright.config.ts b/e2e/react-start/static-server-functions/playwright.config.ts index 08416e4d53..b9f835c16a 100644 --- a/e2e/react-start/static-server-functions/playwright.config.ts +++ b/e2e/react-start/static-server-functions/playwright.config.ts @@ -1,6 +1,8 @@ import { defineConfig, devices } from '@playwright/test' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = 3000 +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -13,9 +15,9 @@ export default defineConfig({ }, webServer: { - command: `PORT=${PORT} pnpm start`, + command: `pnpm build && PORT=${PORT} pnpm start`, url: baseURL, - reuseExistingServer: false, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/static-server-functions/src/routeTree.gen.ts b/e2e/react-start/static-server-functions/src/routeTree.gen.ts index 558b1ab4d9..ea6a6a3806 100644 --- a/e2e/react-start/static-server-functions/src/routeTree.gen.ts +++ b/e2e/react-start/static-server-functions/src/routeTree.gen.ts @@ -11,7 +11,6 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' import { Route as PostsRouteImport } from './routes/posts' -import { Route as RawStreamRouteImport } from './routes/raw-stream' import { Route as PostsIndexRouteImport } from './routes/posts.index' const IndexRoute = IndexRouteImport.update({ @@ -24,11 +23,6 @@ const PostsRoute = PostsRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const RawStreamRoute = RawStreamRouteImport.update({ - id: '/raw-stream', - path: '/raw-stream', - getParentRoute: () => rootRouteImport, -} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -38,33 +32,29 @@ const PostsIndexRoute = PostsIndexRouteImport.update({ export interface FileRoutesByFullPath { '/': typeof IndexRoute '/posts': typeof PostsRouteWithChildren - '/raw-stream': typeof RawStreamRoute '/posts/': typeof PostsIndexRoute } export interface FileRoutesByTo { '/': typeof IndexRoute - '/raw-stream': typeof RawStreamRoute '/posts': typeof PostsIndexRoute } export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute '/posts': typeof PostsRouteWithChildren - '/raw-stream': typeof RawStreamRoute '/posts/': typeof PostsIndexRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/posts' | '/raw-stream' | '/posts/' + fullPaths: '/' | '/posts' | '/posts/' fileRoutesByTo: FileRoutesByTo - to: '/' | '/raw-stream' | '/posts' - id: '__root__' | '/' | '/posts' | '/raw-stream' | '/posts/' + to: '/' | '/posts' + id: '__root__' | '/' | '/posts' | '/posts/' fileRoutesById: FileRoutesById } export interface RootRouteChildren { IndexRoute: typeof IndexRoute PostsRoute: typeof PostsRouteWithChildren - RawStreamRoute: typeof RawStreamRoute } declare module '@tanstack/react-router' { @@ -83,13 +73,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } - '/raw-stream': { - id: '/raw-stream' - path: '/raw-stream' - fullPath: '/raw-stream' - preLoaderRoute: typeof RawStreamRouteImport - parentRoute: typeof rootRouteImport - } '/posts/': { id: '/posts/' path: '/' @@ -113,7 +96,6 @@ const PostsRouteWithChildren = PostsRoute._addFileChildren(PostsRouteChildren) const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, PostsRoute: PostsRouteWithChildren, - RawStreamRoute: RawStreamRoute, } export const routeTree = rootRouteImport ._addFileChildren(rootRouteChildren) diff --git a/e2e/react-start/static-server-functions/src/routes/__root.tsx b/e2e/react-start/static-server-functions/src/routes/__root.tsx index a300613fa8..b768e8b9a1 100644 --- a/e2e/react-start/static-server-functions/src/routes/__root.tsx +++ b/e2e/react-start/static-server-functions/src/routes/__root.tsx @@ -30,9 +30,6 @@ function RootComponent() { Posts - - Raw Stream -

diff --git a/e2e/react-start/static-server-functions/src/routes/raw-stream.tsx b/e2e/react-start/static-server-functions/src/routes/raw-stream.tsx deleted file mode 100644 index df898d2907..0000000000 --- a/e2e/react-start/static-server-functions/src/routes/raw-stream.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { RawStream, createServerFn } from '@tanstack/react-start' -import { staticFunctionMiddleware } from '@tanstack/start-static-server-functions' - -const fetchRawStream = createServerFn({ method: 'GET' }) - .middleware([staticFunctionMiddleware]) - .handler(async () => { - return new RawStream(new Response('Static cache stream').body!, { - hint: 'text', - }) - }) - -export const Route = createFileRoute('/raw-stream')({ - loader: async () => { - const result = await fetchRawStream() - if (typeof document === 'undefined') { - return '' - } - const stream = result as RawStream | ReadableStream - return new Response( - stream instanceof RawStream ? stream.stream : stream, - ).text() - }, - component: RawStreamComponent, -}) - -function RawStreamComponent() { - return

{Route.useLoaderData()}

-} diff --git a/e2e/react-start/static-server-functions/tests/app.spec.ts b/e2e/react-start/static-server-functions/tests/app.spec.ts index d86fd61a75..895566aa35 100644 --- a/e2e/react-start/static-server-functions/tests/app.spec.ts +++ b/e2e/react-start/static-server-functions/tests/app.spec.ts @@ -59,32 +59,5 @@ test.describe('Static Server Functions with Nitro', () => { await expect(page.getByTestId('post-2')).toHaveText('Second Post') await expect(page.getByTestId('post-3')).toHaveText('Third Post') }) - - test('should decode a cached RawStream during client navigation', async ({ - page, - }) => { - await page.goto('/') - // Nitro snapshots public assets before Start prerenders (see #6787). - // Serve the generated file as a static host would to isolate decoding. - await page.route('**/__tsr/staticServerFnCache/*.json', (route) => - route.fulfill({ - path: join( - process.cwd(), - '.output', - 'public', - new URL(route.request().url()).pathname, - ), - }), - ) - const cacheResponse = page.waitForResponse((response) => - response.url().includes('/__tsr/staticServerFnCache/'), - ) - await page.getByTestId('link-raw-stream').click() - const response = await cacheResponse - expect(response.status(), response.url()).toBe(200) - await expect(page.getByTestId('raw-stream')).toHaveText( - 'Static cache stream', - ) - }) }) }) diff --git a/e2e/react-start/streaming-ssr/package.json b/e2e/react-start/streaming-ssr/package.json index 1d08a07622..fcf78262d5 100644 --- a/e2e/react-start/streaming-ssr/package.json +++ b/e2e/react-start/streaming-ssr/package.json @@ -9,9 +9,8 @@ "build": "vite build && tsc --noEmit", "start": "pnpx srvx --prod -s ../client dist/server/server.js", "preview": "vite preview", - "test:e2e": "playwright test --project=chromium", - "test:e2e:preview": "MODE=preview playwright test preview-streaming.spec.ts --project=chromium", - "test:e2e:buffer-repro": "RUN_SSR_ROUTER_HTML_BUFFER_REPRO=true playwright test router-html-buffer.spec.ts --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium", + "test:e2e:preview": "rm -rf port*.txt; MODE=preview playwright test preview-streaming.spec.ts --project=chromium" }, "dependencies": { "@tanstack/react-query": "^5.80.7", @@ -27,45 +26,9 @@ "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" - }, - "nx": { - "targets": { - "build": { - "inputs": [ - "buildProduction", - "^buildProduction", - "dependentTaskOutputs", - "streamingSsrTests" - ] - }, - "test:e2e": { - "inputs": [ - "default", - "^production", - "dependentTaskOutputs", - "streamingSsrTests" - ] - }, - "test:e2e:preview": { - "inputs": [ - "default", - "^production", - "streamingSsrTests" - ] - }, - "test:e2e:buffer-repro": { - "inputs": [ - "default", - "^production", - "dependentTaskOutputs", - "streamingSsrTests" - ] - } - } } } diff --git a/e2e/react-start/streaming-ssr/playwright.config.ts b/e2e/react-start/streaming-ssr/playwright.config.ts index c2f3b67a0c..052ebe879d 100644 --- a/e2e/react-start/streaming-ssr/playwright.config.ts +++ b/e2e/react-start/streaming-ssr/playwright.config.ts @@ -1,9 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } const isPreview = process.env.MODE === 'preview' -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort( + `${packageJson.name}${isPreview ? '_preview' : ''}`, +) const baseURL = `http://localhost:${PORT}` const ssrCommand = `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start` @@ -25,8 +28,8 @@ export default defineConfig({ webServer: { command: isPreview ? previewCommand : ssrCommand, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/streaming-ssr/src/routeTree.gen.ts b/e2e/react-start/streaming-ssr/src/routeTree.gen.ts index 169121003d..c1a51b62f8 100644 --- a/e2e/react-start/streaming-ssr/src/routeTree.gen.ts +++ b/e2e/react-start/streaming-ssr/src/routeTree.gen.ts @@ -17,7 +17,6 @@ import { Route as FastSerialRouteImport } from './routes/fast-serial' import { Route as ManyPromisesRouteImport } from './routes/many-promises' import { Route as NestedDeferredRouteImport } from './routes/nested-deferred' import { Route as QueryHeavyRouteImport } from './routes/query-heavy' -import { Route as RouterHtmlBufferRouteImport } from './routes/router-html-buffer' import { Route as SlowRenderRouteImport } from './routes/slow-render' import { Route as StreamRouteImport } from './routes/stream' import { Route as SyncOnlyRouteImport } from './routes/sync-only' @@ -62,11 +61,6 @@ const QueryHeavyRoute = QueryHeavyRouteImport.update({ path: '/query-heavy', getParentRoute: () => rootRouteImport, } as any) -const RouterHtmlBufferRoute = RouterHtmlBufferRouteImport.update({ - id: '/router-html-buffer', - path: '/router-html-buffer', - getParentRoute: () => rootRouteImport, -} as any) const SlowRenderRoute = SlowRenderRouteImport.update({ id: '/slow-render', path: '/slow-render', @@ -92,7 +86,6 @@ export interface FileRoutesByFullPath { '/many-promises': typeof ManyPromisesRoute '/nested-deferred': typeof NestedDeferredRoute '/query-heavy': typeof QueryHeavyRoute - '/router-html-buffer': typeof RouterHtmlBufferRoute '/slow-render': typeof SlowRenderRoute '/stream': typeof StreamRoute '/sync-only': typeof SyncOnlyRoute @@ -106,7 +99,6 @@ export interface FileRoutesByTo { '/many-promises': typeof ManyPromisesRoute '/nested-deferred': typeof NestedDeferredRoute '/query-heavy': typeof QueryHeavyRoute - '/router-html-buffer': typeof RouterHtmlBufferRoute '/slow-render': typeof SlowRenderRoute '/stream': typeof StreamRoute '/sync-only': typeof SyncOnlyRoute @@ -121,7 +113,6 @@ export interface FileRoutesById { '/many-promises': typeof ManyPromisesRoute '/nested-deferred': typeof NestedDeferredRoute '/query-heavy': typeof QueryHeavyRoute - '/router-html-buffer': typeof RouterHtmlBufferRoute '/slow-render': typeof SlowRenderRoute '/stream': typeof StreamRoute '/sync-only': typeof SyncOnlyRoute @@ -137,7 +128,6 @@ export interface FileRouteTypes { | '/many-promises' | '/nested-deferred' | '/query-heavy' - | '/router-html-buffer' | '/slow-render' | '/stream' | '/sync-only' @@ -151,7 +141,6 @@ export interface FileRouteTypes { | '/many-promises' | '/nested-deferred' | '/query-heavy' - | '/router-html-buffer' | '/slow-render' | '/stream' | '/sync-only' @@ -165,7 +154,6 @@ export interface FileRouteTypes { | '/many-promises' | '/nested-deferred' | '/query-heavy' - | '/router-html-buffer' | '/slow-render' | '/stream' | '/sync-only' @@ -180,7 +168,6 @@ export interface RootRouteChildren { ManyPromisesRoute: typeof ManyPromisesRoute NestedDeferredRoute: typeof NestedDeferredRoute QueryHeavyRoute: typeof QueryHeavyRoute - RouterHtmlBufferRoute: typeof RouterHtmlBufferRoute SlowRenderRoute: typeof SlowRenderRoute StreamRoute: typeof StreamRoute SyncOnlyRoute: typeof SyncOnlyRoute @@ -244,13 +231,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof QueryHeavyRouteImport parentRoute: typeof rootRouteImport } - '/router-html-buffer': { - id: '/router-html-buffer' - path: '/router-html-buffer' - fullPath: '/router-html-buffer' - preLoaderRoute: typeof RouterHtmlBufferRouteImport - parentRoute: typeof rootRouteImport - } '/slow-render': { id: '/slow-render' path: '/slow-render' @@ -284,7 +264,6 @@ const rootRouteChildren: RootRouteChildren = { ManyPromisesRoute: ManyPromisesRoute, NestedDeferredRoute: NestedDeferredRoute, QueryHeavyRoute: QueryHeavyRoute, - RouterHtmlBufferRoute: RouterHtmlBufferRoute, SlowRenderRoute: SlowRenderRoute, StreamRoute: StreamRoute, SyncOnlyRoute: SyncOnlyRoute, diff --git a/e2e/react-start/streaming-ssr/src/routes/concurrent.tsx b/e2e/react-start/streaming-ssr/src/routes/concurrent.tsx index c04155aa59..a1bed0fe07 100644 --- a/e2e/react-start/streaming-ssr/src/routes/concurrent.tsx +++ b/e2e/react-start/streaming-ssr/src/routes/concurrent.tsx @@ -1,9 +1,54 @@ import { Await, createFileRoute } from '@tanstack/react-router' import { Suspense } from 'react' -import { createConcurrentLoaderData } from '../../../../streaming-ssr-fixtures' + +/** + * Tests concurrent promise resolution - multiple promises resolving at the exact same time. + * This can stress the serialization system and reveal race conditions. + */ + +// Shared delay function that resolves multiple promises at the same instant +function createConcurrentPromises( + count: number, + delayMs: number, +): Array> { + const sharedPromise = new Promise((resolve) => + setTimeout(resolve, delayMs), + ) + return Array.from({ length: count }, (_, i) => + sharedPromise.then(() => `concurrent-${i + 1}`), + ) +} export const Route = createFileRoute('/concurrent')({ - loader: async () => createConcurrentLoaderData(), + loader: async () => { + // Create fresh batches of concurrent promises for each request + const batch1 = createConcurrentPromises(5, 100) // 5 promises resolving at 100ms + const batch2 = createConcurrentPromises(5, 200) // 5 promises resolving at 200ms + const batch3 = createConcurrentPromises(5, 300) // 5 promises resolving at 300ms + + return { + // Batch 1: 5 promises resolving at exactly the same time (100ms) + concurrent1_1: batch1[0], + concurrent1_2: batch1[1], + concurrent1_3: batch1[2], + concurrent1_4: batch1[3], + concurrent1_5: batch1[4], + + // Batch 2: 5 promises resolving at exactly the same time (200ms) + concurrent2_1: batch2[0], + concurrent2_2: batch2[1], + concurrent2_3: batch2[2], + concurrent2_4: batch2[3], + concurrent2_5: batch2[4], + + // Batch 3: 5 promises resolving at exactly the same time (300ms) + concurrent3_1: batch3[0], + concurrent3_2: batch3[1], + concurrent3_3: batch3[2], + concurrent3_4: batch3[3], + concurrent3_5: batch3[4], + } + }, component: Concurrent, }) @@ -41,6 +86,7 @@ function Concurrent() { gap: '20px', }} > + {/* Batch 1: 100ms */}

Batch 1 (100ms)

@@ -50,6 +96,7 @@ function Concurrent() {
+ {/* Batch 2: 200ms */}

Batch 2 (200ms)

@@ -59,6 +106,7 @@ function Concurrent() {
+ {/* Batch 3: 300ms */}

Batch 3 (300ms)

diff --git a/e2e/react-start/streaming-ssr/src/routes/deferred-rejection.tsx b/e2e/react-start/streaming-ssr/src/routes/deferred-rejection.tsx index 3ac1e7fc2d..d9b5305480 100644 --- a/e2e/react-start/streaming-ssr/src/routes/deferred-rejection.tsx +++ b/e2e/react-start/streaming-ssr/src/routes/deferred-rejection.tsx @@ -1,9 +1,7 @@ import { Await, createFileRoute } from '@tanstack/react-router' import { Suspense } from 'react' -import { - deferredDataDelay, - deferredErrorMessage, -} from '../../../../streaming-ssr-fixtures' + +const deferredErrorMessage = 'Error in deferred object' export const Route = createFileRoute('/deferred-rejection')({ loader: async () => { @@ -11,7 +9,7 @@ export const Route = createFileRoute('/deferred-rejection')({ deferredData: new Promise((_resolve, reject) => { setTimeout(() => { reject(new Error(deferredErrorMessage)) - }, deferredDataDelay) + }, 1000) }), } }, diff --git a/e2e/react-start/streaming-ssr/src/routes/deferred.tsx b/e2e/react-start/streaming-ssr/src/routes/deferred.tsx index 9f91c0f2d4..506efbd345 100644 --- a/e2e/react-start/streaming-ssr/src/routes/deferred.tsx +++ b/e2e/react-start/streaming-ssr/src/routes/deferred.tsx @@ -1,40 +1,55 @@ import { Await, createFileRoute } from '@tanstack/react-router' import { createServerFn } from '@tanstack/react-start' import { Suspense } from 'react' -import { - deferredDataDelay, - deferredDataMessage, - deferredImmediateName, - deferredServerDelay, - deferredSlowName, - delay, - makeDeferredMessage, - makeServerData, - sourceMarker, -} from '../../../../streaming-ssr-fixtures' +// Server function that returns immediately const getImmediateData = createServerFn({ method: 'GET' }) .validator((data: { name: string }) => data) - .handler(({ data }) => makeServerData(data.name)) + .handler(({ data }) => { + return { + name: data.name, + timestamp: Date.now(), + // Track where this data came from - should always be 'server' if SSR works + source: 'server' as const, + } + }) +// Server function that takes time to complete const getSlowData = createServerFn({ method: 'GET' }) .validator((data: { name: string; delay: number }) => data) .handler(async ({ data }) => { - await delay(data.delay) - return makeServerData(data.name) + await new Promise((r) => setTimeout(r, data.delay)) + return { + name: data.name, + timestamp: Date.now(), + // Track where this data came from - should always be 'server' if SSR works + source: 'server' as const, + } }) export const Route = createFileRoute('/deferred')({ loader: async () => { return { - deferredData: makeDeferredMessage(deferredDataMessage, deferredDataDelay), + // Deferred promise that resolves after 1 second + deferredData: new Promise<{ message: string; source: string }>((r) => + setTimeout( + () => + r({ + message: 'Deferred data loaded!', + // Track where this data came from - should always be 'server' if SSR works + source: typeof window === 'undefined' ? 'server' : 'client', + }), + 1000, + ), + ), + // Deferred server function call deferredServerData: getSlowData({ - data: { name: deferredSlowName, delay: deferredServerDelay }, + data: { name: 'Slow User', delay: 800 }, }), - immediateData: await getImmediateData({ - data: { name: deferredImmediateName }, - }), - loaderSource: sourceMarker(), + // Immediate data (awaited) + immediateData: await getImmediateData({ data: { name: 'Fast User' } }), + // Track where loader ran - should always be 'server' if SSR works + loaderSource: typeof window === 'undefined' ? 'server' : 'client', } }, component: Deferred, @@ -48,6 +63,7 @@ function Deferred() {

Deferred Data Test

+ {/* Immediate data should be available right away */}
Immediate: {immediateData.name} @ {immediateData.timestamp}
@@ -58,6 +74,7 @@ function Deferred() {
Loader source: {loaderSource}
+ {/* Deferred promise */} Loading deferred...
} > @@ -71,6 +88,7 @@ function Deferred() { /> + {/* Deferred server function */} Loading server data...
diff --git a/e2e/react-start/streaming-ssr/src/routes/fast-serial.tsx b/e2e/react-start/streaming-ssr/src/routes/fast-serial.tsx index cc3f0c2b5c..61a47469f4 100644 --- a/e2e/react-start/streaming-ssr/src/routes/fast-serial.tsx +++ b/e2e/react-start/streaming-ssr/src/routes/fast-serial.tsx @@ -1,23 +1,26 @@ import { createFileRoute } from '@tanstack/react-router' import { createServerFn } from '@tanstack/react-start' -import { - fastSerialStaticData, - makeFastSerialSmallData, - sourceMarker, -} from '../../../../streaming-ssr-fixtures' -const getSmallData = createServerFn({ method: 'GET' }).handler(() => - makeFastSerialSmallData(), -) +// Server function that returns immediately with minimal data +const getSmallData = createServerFn({ method: 'GET' }).handler(() => { + return { + value: 'small-data', + timestamp: Date.now(), + // Track where this data came from - should always be 'server' if SSR works + source: 'server' as const, + } +}) export const Route = createFileRoute('/fast-serial')({ loader: async () => { + // All data is awaited immediately - serialization should complete quickly const data = await getSmallData() return { serverData: data, - staticData: fastSerialStaticData, + staticData: 'This is static data', timestamp: Date.now(), - loaderSource: sourceMarker(), + // Track where loader ran - should always be 'server' if SSR works + loaderSource: typeof window === 'undefined' ? 'server' : 'client', } }, component: FastSerial, diff --git a/e2e/react-start/streaming-ssr/src/routes/many-promises.tsx b/e2e/react-start/streaming-ssr/src/routes/many-promises.tsx index 25cb6511c7..a6d0374972 100644 --- a/e2e/react-start/streaming-ssr/src/routes/many-promises.tsx +++ b/e2e/react-start/streaming-ssr/src/routes/many-promises.tsx @@ -1,9 +1,47 @@ import { Await, createFileRoute } from '@tanstack/react-router' import { Suspense } from 'react' -import { createManyPromises } from '../../../../streaming-ssr-fixtures' + +/** + * Tests streaming with many (15+) deferred promises resolving in various orders. + * This stresses the serialization system with concurrent promise resolutions. + */ + +// Helper to create a promise with a specific delay and value +function createDelayedPromise(value: T, delayMs: number): Promise { + return new Promise((resolve) => setTimeout(() => resolve(value), delayMs)) +} export const Route = createFileRoute('/many-promises')({ - loader: async () => createManyPromises(), + loader: async () => { + // Create 15 promises with varying delays to test ordering + // Some resolve quickly, some slowly, some at similar times + return { + // Immediate/very fast (0-50ms) + immediate1: createDelayedPromise('immediate-1', 0), + immediate2: createDelayedPromise('immediate-2', 10), + immediate3: createDelayedPromise('immediate-3', 20), + + // Fast (50-150ms) + fast1: createDelayedPromise('fast-1', 50), + fast2: createDelayedPromise('fast-2', 75), + fast3: createDelayedPromise('fast-3', 100), + fast4: createDelayedPromise('fast-4', 125), + + // Medium (150-300ms) + medium1: createDelayedPromise('medium-1', 150), + medium2: createDelayedPromise('medium-2', 200), + medium3: createDelayedPromise('medium-3', 250), + + // Slow (300-600ms) + slow1: createDelayedPromise('slow-1', 300), + slow2: createDelayedPromise('slow-2', 400), + slow3: createDelayedPromise('slow-3', 500), + + // Very slow (600ms+) + verySlow1: createDelayedPromise('very-slow-1', 600), + verySlow2: createDelayedPromise('very-slow-2', 800), + } + }, component: ManyPromises, }) @@ -47,6 +85,7 @@ function ManyPromises() { gap: '10px', }} > + {/* Immediate group */}

Immediate (0-20ms)

+ {/* Fast group */}

Fast (50-125ms)

@@ -74,6 +114,7 @@ function ManyPromises() {
+ {/* Medium group */}

Medium (150-250ms)

+ {/* Slow group */}

Slow (300-500ms)

@@ -100,6 +142,7 @@ function ManyPromises() {
+ {/* Very slow group */}

Very Slow (600-800ms)

{ - await delay(nestedLevelDelays[0]) - return makeLevelData(1) + await new Promise((r) => setTimeout(r, 200)) + return { level: 1, timestamp: Date.now() } }) const getLevel2Data = createServerFn({ method: 'GET' }).handler(async () => { - await delay(nestedLevelDelays[1]) - return makeLevelData(2) + await new Promise((r) => setTimeout(r, 400)) + return { level: 2, timestamp: Date.now() } }) const getLevel3Data = createServerFn({ method: 'GET' }).handler(async () => { - await delay(nestedLevelDelays[2]) - return makeLevelData(3) + await new Promise((r) => setTimeout(r, 600)) + return { level: 3, timestamp: Date.now() } }) export const Route = createFileRoute('/nested-deferred')({ loader: async () => { return { + // Multiple deferred promises that resolve at different times level1: getLevel1Data(), level2: getLevel2Data(), level3: getLevel3Data(), - plainDeferred: makeDeferred(nestedPlainMessage, nestedPlainDelay), + // Also a plain deferred promise + plainDeferred: new Promise((r) => + setTimeout(() => r('Plain deferred resolved!'), 300), + ), } }, component: NestedDeferred, }) +// Nested component that renders more Await components function Level1Content({ level2, level3, @@ -108,6 +106,7 @@ function NestedDeferred() { Tests multiple nested deferred promises resolving at different times.

+ {/* Plain deferred */} Loading plain...
} > @@ -117,6 +116,7 @@ function NestedDeferred() { /> + {/* Nested structure */}
Loading level 1...
} diff --git a/e2e/react-start/streaming-ssr/src/routes/query-heavy.tsx b/e2e/react-start/streaming-ssr/src/routes/query-heavy.tsx index 115ae9f10f..b20921323c 100644 --- a/e2e/react-start/streaming-ssr/src/routes/query-heavy.tsx +++ b/e2e/react-start/streaming-ssr/src/routes/query-heavy.tsx @@ -1,48 +1,167 @@ import { queryOptions, useSuspenseQuery } from '@tanstack/react-query' import { createFileRoute } from '@tanstack/react-router' import { Suspense } from 'react' -import { - delay, - makeQueryData, - queryHeavyItems, -} from '../../../../streaming-ssr-fixtures' -import type { QueryData } from '../../../../streaming-ssr-fixtures' -function makeQueryOptions(item: (typeof queryHeavyItems)[number]) { - return queryOptions({ - queryKey: ['streaming-ssr-query-heavy', item.type, item.id], - queryFn: (): QueryData | Promise => { - if (item.delayMs > 0) { - return delay(item.delayMs).then(() => makeQueryData(item)) - } +/** + * Tests multiple useSuspenseQuery calls on a single route. + * Some queries have synchronous queryFn (return immediately), + * some have async queryFn with various delays. + * + * This stresses the SSR query streaming integration. + */ - return makeQueryData(item) - }, - staleTime: Infinity, - }) -} +// Synchronous query - returns immediately (no await) +const syncQuery1 = queryOptions({ + queryKey: ['sync', 1], + queryFn: () => { + // Synchronous return - no Promise delay + return { + type: 'sync', + id: 1, + value: 'sync-value-1', + source: typeof window === 'undefined' ? 'server' : 'client', + } + }, + staleTime: Infinity, +}) -const syncQuery1 = makeQueryOptions(queryHeavyItems[0]) -const syncQuery2 = makeQueryOptions(queryHeavyItems[1]) -const syncQuery3 = makeQueryOptions(queryHeavyItems[2]) -const fastAsyncQuery1 = makeQueryOptions(queryHeavyItems[3]) -const fastAsyncQuery2 = makeQueryOptions(queryHeavyItems[4]) -const fastAsyncQuery3 = makeQueryOptions(queryHeavyItems[5]) -const slowAsyncQuery1 = makeQueryOptions(queryHeavyItems[6]) -const slowAsyncQuery2 = makeQueryOptions(queryHeavyItems[7]) -const slowAsyncQuery3 = makeQueryOptions(queryHeavyItems[8]) +const syncQuery2 = queryOptions({ + queryKey: ['sync', 2], + queryFn: () => { + return { + type: 'sync', + id: 2, + value: 'sync-value-2', + source: typeof window === 'undefined' ? 'server' : 'client', + } + }, + staleTime: Infinity, +}) -type QueryOptions = ReturnType +const syncQuery3 = queryOptions({ + queryKey: ['sync', 3], + queryFn: () => { + return { + type: 'sync', + id: 3, + value: 'sync-value-3', + source: typeof window === 'undefined' ? 'server' : 'client', + } + }, + staleTime: Infinity, +}) + +// Fast async queries (50-100ms) +const fastAsyncQuery1 = queryOptions({ + queryKey: ['fast-async', 1], + queryFn: async () => { + await new Promise((r) => setTimeout(r, 50)) + return { + type: 'fast-async', + id: 1, + value: 'fast-async-1', + source: typeof window === 'undefined' ? 'server' : 'client', + } + }, + staleTime: Infinity, +}) + +const fastAsyncQuery2 = queryOptions({ + queryKey: ['fast-async', 2], + queryFn: async () => { + await new Promise((r) => setTimeout(r, 75)) + return { + type: 'fast-async', + id: 2, + value: 'fast-async-2', + source: typeof window === 'undefined' ? 'server' : 'client', + } + }, + staleTime: Infinity, +}) + +const fastAsyncQuery3 = queryOptions({ + queryKey: ['fast-async', 3], + queryFn: async () => { + await new Promise((r) => setTimeout(r, 100)) + return { + type: 'fast-async', + id: 3, + value: 'fast-async-3', + source: typeof window === 'undefined' ? 'server' : 'client', + } + }, + staleTime: Infinity, +}) + +// Slow async queries (200-400ms) +const slowAsyncQuery1 = queryOptions({ + queryKey: ['slow-async', 1], + queryFn: async () => { + await new Promise((r) => setTimeout(r, 200)) + return { + type: 'slow-async', + id: 1, + value: 'slow-async-1', + source: typeof window === 'undefined' ? 'server' : 'client', + } + }, + staleTime: Infinity, +}) + +const slowAsyncQuery2 = queryOptions({ + queryKey: ['slow-async', 2], + queryFn: async () => { + await new Promise((r) => setTimeout(r, 300)) + return { + type: 'slow-async', + id: 2, + value: 'slow-async-2', + source: typeof window === 'undefined' ? 'server' : 'client', + } + }, + staleTime: Infinity, +}) + +const slowAsyncQuery3 = queryOptions({ + queryKey: ['slow-async', 3], + queryFn: async () => { + await new Promise((r) => setTimeout(r, 400)) + return { + type: 'slow-async', + id: 3, + value: 'slow-async-3', + source: typeof window === 'undefined' ? 'server' : 'client', + } + }, + staleTime: Infinity, +}) export const Route = createFileRoute('/query-heavy')({ component: QueryHeavy, }) -function QueryDisplay({ +// Individual query components to test Suspense boundaries +function SyncQueryDisplay({ queryOpts, testId, }: { - queryOpts: QueryOptions + queryOpts: typeof syncQuery1 + testId: string +}) { + const { data } = useSuspenseQuery(queryOpts) + return ( +
+ {data.value} (source: {data.source}) +
+ ) +} + +function AsyncQueryDisplay({ + queryOpts, + testId, +}: { + queryOpts: typeof fastAsyncQuery1 testId: string }) { const { data } = useSuspenseQuery(queryOpts) @@ -71,25 +190,27 @@ function QueryHeavy() { marginTop: '20px', }} > + {/* Sync queries - should resolve immediately */}

Sync Queries (immediate)

Loading sync 1...
} > - + Loading sync 2...} > - + Loading sync 3...} > - + + {/* Fast async queries */}

Fast Async Queries (50-100ms)

Loading fast 1...
} > - @@ -107,7 +228,7 @@ function QueryHeavy() {
Loading fast 2...
} > - @@ -117,13 +238,14 @@ function QueryHeavy() {
Loading fast 3...
} > - + {/* Slow async queries */}

Slow Async Queries (200-400ms)

Loading slow 1...
} > - @@ -141,7 +263,7 @@ function QueryHeavy() {
Loading slow 2...
} > - @@ -151,7 +273,7 @@ function QueryHeavy() {
Loading slow 3...
} > - diff --git a/e2e/react-start/streaming-ssr/src/routes/router-html-buffer.tsx b/e2e/react-start/streaming-ssr/src/routes/router-html-buffer.tsx deleted file mode 100644 index 6fb7bde27b..0000000000 --- a/e2e/react-start/streaming-ssr/src/routes/router-html-buffer.tsx +++ /dev/null @@ -1,58 +0,0 @@ -import { Suspense, useState } from 'react' -import { Await, createFileRoute } from '@tanstack/react-router' -import { createRouterHtmlPayload } from '../../../../streaming-ssr-fixtures' - -export const Route = createFileRoute('/router-html-buffer')({ - loader: () => { - return { - payload: createRouterHtmlPayload(), - } - }, - component: RouterHtmlBufferRoute, -}) - -function RouterHtmlBufferRoute() { - const { payload } = Route.useLoaderData() - - return ( -
-

Router HTML Buffer Reproduction

- Waiting for the deferred payload...

}> - ( - - )} - /> -
-
- ) -} - -function HydratedPayload({ - payload, - source, -}: { - payload: string - source: 'server' | 'client' -}) { - const [hydrationResult, setHydrationResult] = useState('not checked') - - return ( - <> -

{payload.length}

- -

{hydrationResult}

- - ) -} diff --git a/e2e/react-start/streaming-ssr/src/routes/slow-render.tsx b/e2e/react-start/streaming-ssr/src/routes/slow-render.tsx index a897c519c1..5dd9772604 100644 --- a/e2e/react-start/streaming-ssr/src/routes/slow-render.tsx +++ b/e2e/react-start/streaming-ssr/src/routes/slow-render.tsx @@ -1,36 +1,47 @@ import { Await, createFileRoute } from '@tanstack/react-router' import { createServerFn } from '@tanstack/react-start' import { Suspense } from 'react' -import { - makeDeferredMessage, - makeServerData, - slowRenderComponents, - slowRenderDeferredDelay, - slowRenderDeferredMessage, - slowRenderQuickName, - sourceMarker, -} from '../../../../streaming-ssr-fixtures' -const getQuickData = createServerFn({ method: 'GET' }).handler(() => - makeServerData(slowRenderQuickName), -) +// Server function that completes quickly +const getQuickData = createServerFn({ method: 'GET' }).handler(() => { + return { + name: 'Quick data', + timestamp: Date.now(), + // Track where this data came from - should always be 'server' if SSR works + source: 'server' as const, + } +}) +// Simulate a slow component render by doing work during render function SlowComponent({ data, index }: { data: string; index: number }) { + // This simulates a component that takes time to render const startTime = Date.now() - while (Date.now() - startTime < 100) {} + while (Date.now() - startTime < 100) { + // Blocking loop to simulate slow render + } return
{data}
} export const Route = createFileRoute('/slow-render')({ loader: async () => { + // All data loads quickly const quickData = await getQuickData() return { quickData, - deferredData: makeDeferredMessage( - slowRenderDeferredMessage, - slowRenderDeferredDelay, + // Deferred data that resolves before render might complete + deferredData: new Promise<{ message: string; source: string }>((r) => + setTimeout( + () => + r({ + message: 'Deferred resolved!', + // Track where this data came from - should always be 'server' if SSR works + source: typeof window === 'undefined' ? 'server' : 'client', + }), + 50, + ), ), - loaderSource: sourceMarker(), + // Track where loader ran - should always be 'server' if SSR works + loaderSource: typeof window === 'undefined' ? 'server' : 'client', } }, component: SlowRender, @@ -65,9 +76,10 @@ function SlowRender() { /> - {slowRenderComponents.map((data, index) => ( - - ))} + {/* Multiple slow components to extend render time */} + + + ) } diff --git a/e2e/react-start/streaming-ssr/src/routes/stream.tsx b/e2e/react-start/streaming-ssr/src/routes/stream.tsx index 458be61366..c1629204c7 100644 --- a/e2e/react-start/streaming-ssr/src/routes/stream.tsx +++ b/e2e/react-start/streaming-ssr/src/routes/stream.tsx @@ -1,16 +1,24 @@ import { Await, createFileRoute } from '@tanstack/react-router' import { Suspense, useEffect, useRef, useState } from 'react' -import { - createChunkStream, - createStreamPromise, -} from '../../../../streaming-ssr-fixtures' export const Route = createFileRoute('/stream')({ component: StreamRoute, loader() { return { - promise: createStreamPromise(), - stream: createChunkStream(), + // A promise that resolves after a short delay + promise: new Promise((resolve) => + setTimeout(() => resolve('promise-resolved'), 150), + ), + // A ReadableStream that emits chunks over time + stream: new ReadableStream({ + async start(controller) { + for (let i = 0; i < 5; i++) { + await new Promise((resolve) => setTimeout(resolve, 200)) + controller.enqueue(`chunk-${i}`) + } + controller.close() + }, + }), } }, }) @@ -25,16 +33,19 @@ function StreamRoute() { const streamRef = useRef(null) useEffect(() => { + // If we're already reading this exact stream, don't start again if (streamRef.current === stream && readerRef.current) { return } + // Reset state for a new stream if (streamRef.current !== stream) { setStreamData([]) setStreamComplete(false) streamRef.current = stream } + // Check if stream is already locked (from a previous render) if (stream.locked) { return } @@ -54,6 +65,7 @@ function StreamRoute() { } setStreamComplete(true) } catch (e) { + // Stream was cancelled or errored, ignore if (!(e instanceof TypeError && String(e).includes('cancelled'))) { console.error('Stream error:', e) } @@ -63,6 +75,7 @@ function StreamRoute() { fetchStream() return () => { + // Cancel the reader on cleanup if (readerRef.current) { readerRef.current.cancel().catch(() => {}) readerRef.current = null @@ -74,6 +87,7 @@ function StreamRoute() {

ReadableStream Test

+ {/* Promise data */} Loading promise...
} > @@ -83,6 +97,7 @@ function StreamRoute() { /> + {/* Stream data */}

Stream chunks:

diff --git a/e2e/react-start/streaming-ssr/src/routes/sync-only.tsx b/e2e/react-start/streaming-ssr/src/routes/sync-only.tsx index 67a77a3e9f..c95a1d467f 100644 --- a/e2e/react-start/streaming-ssr/src/routes/sync-only.tsx +++ b/e2e/react-start/streaming-ssr/src/routes/sync-only.tsx @@ -1,8 +1,22 @@ import { createFileRoute } from '@tanstack/react-router' -import { makeSyncOnlyData } from '../../../../streaming-ssr-fixtures' +/** + * This route tests synchronous serialization - no deferred data, no streaming. + * The loader returns data synchronously (awaited), so crossSerializeStream + * completes immediately and all bootstrap scripts should be in the initial HTML. + */ export const Route = createFileRoute('/sync-only')({ - loader: async () => makeSyncOnlyData(), + loader: async () => { + // Simulate a fast synchronous data fetch + // This data is awaited, not deferred, so serialization completes synchronously + return { + message: 'Hello from sync loader!', + timestamp: Date.now(), + items: ['item-1', 'item-2', 'item-3'], + // Track where this data came from - should always be 'server' if SSR works + source: typeof window === 'undefined' ? 'server' : 'client', + } + }, component: SyncOnly, }) diff --git a/e2e/react-start/streaming-ssr/tests/client-navigation.spec.ts b/e2e/react-start/streaming-ssr/tests/client-navigation.spec.ts index 8b9b3a8dcc..91138987ad 100644 --- a/e2e/react-start/streaming-ssr/tests/client-navigation.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/client-navigation.spec.ts @@ -1 +1,372 @@ -import '../../../streaming-ssr-specs/client-navigation' +import { expect, test, testWithHydration } from './fixtures' + +test.describe('Client-side navigation between all routes', () => { + test.beforeEach(async ({ page }) => { + // Start from home page + await page.goto('/') + await page.waitForLoadState('networkidle') + }) + + test('home -> sync-only -> home works', async ({ page }) => { + // Navigate to sync-only + await page + .getByRole('navigation') + .getByRole('link', { name: 'Sync Only' }) + .click() + await expect(page).toHaveURL('/sync-only') + await expect(page.getByTestId('sync-message')).toBeVisible() + + // Navigate back to home + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + await expect(page.getByTestId('index-title')).toBeVisible() + }) + + test('home -> deferred -> home works', async ({ page }) => { + // Navigate to deferred (use exact: true to avoid matching "Nested Deferred") + await page + .getByRole('navigation') + .getByRole('link', { name: 'Deferred', exact: true }) + .click() + await expect(page).toHaveURL('/deferred') + await expect(page.getByTestId('immediate-data')).toBeVisible() + + // Wait for deferred data + await expect(page.getByTestId('deferred-data')).toBeVisible({ + timeout: 5000, + }) + + // Navigate back to home + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + }) + + test('home -> stream -> home works (no stream locking error)', async ({ + page, + }) => { + // This test specifically validates the ReadableStream locking fix + // Console errors are monitored by the fixture automatically + + // Navigate to stream + await page + .getByRole('navigation') + .getByRole('link', { name: 'Stream' }) + .click() + await expect(page).toHaveURL('/stream') + + // Wait for stream to start (at least one chunk or promise resolved) + await expect(page.getByTestId('promise-data')).toBeVisible({ + timeout: 5000, + }) + + // Navigate back to home before stream completes + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + }) + + test('home -> stream -> wait for completion -> home works', async ({ + page, + }) => { + // Navigate to stream + await page + .getByRole('navigation') + .getByRole('link', { name: 'Stream' }) + .click() + await expect(page).toHaveURL('/stream') + + // Wait for stream to complete + await expect(page.getByTestId('stream-complete')).toBeVisible({ + timeout: 10000, + }) + + // Navigate back to home + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + await expect(page.getByTestId('index-title')).toBeVisible() + }) + + test('home -> stream -> home -> stream again works (fresh stream each time)', async ({ + page, + }) => { + // Console errors are monitored by the fixture automatically + + // First navigation to stream + await page + .getByRole('navigation') + .getByRole('link', { name: 'Stream' }) + .click() + await expect(page).toHaveURL('/stream') + await expect(page.getByTestId('promise-data')).toBeVisible({ + timeout: 5000, + }) + + // Navigate back to home + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + + // Second navigation to stream - should get fresh stream without errors + await page + .getByRole('navigation') + .getByRole('link', { name: 'Stream' }) + .click() + await expect(page).toHaveURL('/stream') + + // Wait for stream to complete + await expect(page.getByTestId('stream-complete')).toBeVisible({ + timeout: 10000, + }) + + // Verify all chunks are present + await expect(page.getByTestId('stream-chunk-0')).toBeVisible() + await expect(page.getByTestId('stream-chunk-4')).toBeVisible() + }) + + test('home -> fast-serial -> home works', async ({ page }) => { + await page + .getByRole('navigation') + .getByRole('link', { name: 'Fast Serial' }) + .click() + await expect(page).toHaveURL('/fast-serial') + await expect(page.getByTestId('server-data')).toBeVisible() + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + }) + + test('home -> slow-render -> home works', async ({ page }) => { + await page + .getByRole('navigation') + .getByRole('link', { name: 'Slow Render' }) + .click() + await expect(page).toHaveURL('/slow-render') + await expect(page.getByTestId('quick-data')).toBeVisible() + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + }) + + test('home -> nested-deferred -> home works', async ({ page }) => { + await page + .getByRole('navigation') + .getByRole('link', { name: 'Nested Deferred' }) + .click() + await expect(page).toHaveURL('/nested-deferred') + + // Wait for all levels to load + await expect(page.getByTestId('level3-data')).toBeVisible({ timeout: 5000 }) + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + }) + + test('rapid navigation between routes works', async ({ page }) => { + // Console errors are monitored by the fixture automatically + + // Rapid navigation sequence + await page + .getByRole('navigation') + .getByRole('link', { name: 'Sync Only' }) + .click() + await expect(page).toHaveURL('/sync-only') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Deferred', exact: true }) + .click() + await expect(page).toHaveURL('/deferred') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Stream' }) + .click() + await expect(page).toHaveURL('/stream') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Fast Serial' }) + .click() + await expect(page).toHaveURL('/fast-serial') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Slow Render' }) + .click() + await expect(page).toHaveURL('/slow-render') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Nested Deferred' }) + .click() + await expect(page).toHaveURL('/nested-deferred') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + }) +}) + +test.describe('Direct navigation followed by client navigation', () => { + test('direct to stream -> client nav to deferred works', async ({ page }) => { + // Direct navigation to stream + await page.goto('/stream') + await expect(page.getByTestId('promise-data')).toBeVisible({ + timeout: 5000, + }) + + // Client navigation to deferred (use exact: true) + await page + .getByRole('navigation') + .getByRole('link', { name: 'Deferred', exact: true }) + .click() + await expect(page).toHaveURL('/deferred') + await expect(page.getByTestId('immediate-data')).toBeVisible() + }) + + test('direct to deferred -> client nav to stream works', async ({ page }) => { + // Console errors are monitored by the fixture automatically + + // Direct navigation to deferred + await page.goto('/deferred') + await expect(page.getByTestId('immediate-data')).toBeVisible() + + // Client navigation to stream + await page + .getByRole('navigation') + .getByRole('link', { name: 'Stream' }) + .click() + await expect(page).toHaveURL('/stream') + await expect(page.getByTestId('stream-complete')).toBeVisible({ + timeout: 10000, + }) + }) + + test('direct to sync-only -> client nav to all routes works', async ({ + page, + }) => { + await page.goto('/sync-only') + await expect(page.getByTestId('sync-message')).toBeVisible() + + // Navigate through all routes + await page + .getByRole('navigation') + .getByRole('link', { name: 'Deferred', exact: true }) + .click() + await expect(page).toHaveURL('/deferred') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Stream' }) + .click() + await expect(page).toHaveURL('/stream') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Fast Serial' }) + .click() + await expect(page).toHaveURL('/fast-serial') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + }) +}) + +testWithHydration.describe('Hydration after client navigation', () => { + testWithHydration( + 'interactive elements work after navigating to deferred', + async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Deferred', exact: true }) + .click() + await expect(page).toHaveURL('/deferred') + + // Wait for the page to be fully loaded + await expect(page.getByTestId('immediate-data')).toBeVisible() + }, + ) + + testWithHydration( + 'interactive elements work after navigating to fast-serial', + async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Fast Serial' }) + .click() + await expect(page).toHaveURL('/fast-serial') + + // Wait for page to load + await expect(page.getByTestId('server-data')).toBeVisible() + }, + ) + + testWithHydration( + 'interactive elements work after navigating to nested-deferred', + async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Nested Deferred' }) + .click() + await expect(page).toHaveURL('/nested-deferred') + + // Wait for page to load + await expect(page.getByTestId('plain-deferred')).toBeVisible({ + timeout: 5000, + }) + }, + ) + + testWithHydration( + 'interactive elements work after navigating to slow-render', + async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Slow Render' }) + .click() + await expect(page).toHaveURL('/slow-render') + + // Wait for page to load (slow-render has blocking loops) + await expect(page.getByTestId('quick-data')).toBeVisible() + }, + ) +}) diff --git a/e2e/react-start/streaming-ssr/tests/concurrent.spec.ts b/e2e/react-start/streaming-ssr/tests/concurrent.spec.ts index 8625473a58..10e32c6809 100644 --- a/e2e/react-start/streaming-ssr/tests/concurrent.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/concurrent.spec.ts @@ -1 +1,100 @@ -import '../../../streaming-ssr-specs/concurrent' +import { expect, test, testWithHydration } from './fixtures' + +test.describe('Concurrent promise resolution (15 promises in 3 batches)', () => { + test('all concurrent promises resolve correctly', async ({ page }) => { + await page.goto('/concurrent') + + // Batch 1 (5 promises at 100ms) + await expect(page.getByTestId('concurrent-1-1')).toContainText( + 'concurrent-1', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-1-2')).toContainText( + 'concurrent-2', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-1-3')).toContainText( + 'concurrent-3', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-1-4')).toContainText( + 'concurrent-4', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-1-5')).toContainText( + 'concurrent-5', + { timeout: 5000 }, + ) + + // Batch 2 (5 promises at 200ms) + await expect(page.getByTestId('concurrent-2-1')).toContainText( + 'concurrent-1', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-2-2')).toContainText( + 'concurrent-2', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-2-3')).toContainText( + 'concurrent-3', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-2-4')).toContainText( + 'concurrent-4', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-2-5')).toContainText( + 'concurrent-5', + { timeout: 5000 }, + ) + + // Batch 3 (5 promises at 300ms) + await expect(page.getByTestId('concurrent-3-1')).toContainText( + 'concurrent-1', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-3-2')).toContainText( + 'concurrent-2', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-3-3')).toContainText( + 'concurrent-3', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-3-4')).toContainText( + 'concurrent-4', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-3-5')).toContainText( + 'concurrent-5', + { timeout: 5000 }, + ) + }) + + test('batch 1 resolves before batch 3', async ({ page }) => { + await page.goto('/concurrent', { waitUntil: 'commit' }) + + // Batch 1 should be visible before batch 3 + await expect(page.getByTestId('concurrent-1-1')).toBeVisible({ + timeout: 3000, + }) + + // Eventually batch 3 should also be visible + await expect(page.getByTestId('concurrent-3-5')).toBeVisible({ + timeout: 5000, + }) + }) + + testWithHydration( + 'hydration works with concurrent resolutions', + async ({ page }) => { + await page.goto('/concurrent') + await page.waitForLoadState('networkidle') + + // Wait for all batches + await expect(page.getByTestId('concurrent-3-5')).toBeVisible({ + timeout: 5000, + }) + }, + ) +}) diff --git a/e2e/react-start/streaming-ssr/tests/deferred-rejection.spec.ts b/e2e/react-start/streaming-ssr/tests/deferred-rejection.spec.ts index 355b5019bc..3b8144072c 100644 --- a/e2e/react-start/streaming-ssr/tests/deferred-rejection.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/deferred-rejection.spec.ts @@ -1 +1,21 @@ -import '../../../streaming-ssr-specs/deferred-rejection' +import { expect, test } from './fixtures' + +test.use({ + whitelistErrors: ['Error in deferred object'], +}) + +test('rejected deferred Await renders the route error boundary without killing SSR', async ({ + page, +}) => { + await page.goto('/deferred-rejection') + + await expect(page.getByTestId('deferred-error-boundary')).toContainText( + 'Error in deferred object', + { timeout: 5000 }, + ) + + await page.goto('/sync-only') + await expect(page.getByTestId('sync-message')).toContainText( + 'Hello from sync loader!', + ) +}) diff --git a/e2e/react-start/streaming-ssr/tests/deferred.spec.ts b/e2e/react-start/streaming-ssr/tests/deferred.spec.ts index 3145897d7b..90ee16edc0 100644 --- a/e2e/react-start/streaming-ssr/tests/deferred.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/deferred.spec.ts @@ -1 +1,120 @@ -import '../../../streaming-ssr-specs/deferred' +import { expect, test, testWithHydration } from './fixtures' + +test.describe('Deferred data streaming', () => { + test('shows immediate data right away and deferred data after loading', async ({ + page, + }) => { + await page.goto('/deferred') + + // Immediate data should be available right away + await expect(page.getByTestId('immediate-data')).toBeVisible() + await expect(page.getByTestId('immediate-data')).toContainText( + 'Immediate: Fast User', + ) + + // Verify immediate data came from server + await expect(page.getByTestId('immediate-source')).toContainText( + 'Immediate source: server', + ) + await expect(page.getByTestId('loader-source')).toContainText( + 'Loader source: server', + ) + + // Deferred data should eventually appear with server source + await expect(page.getByTestId('deferred-data')).toContainText( + 'Deferred data loaded!', + { timeout: 5000 }, + ) + await expect(page.getByTestId('deferred-data')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + await expect(page.getByTestId('deferred-server-data')).toContainText( + 'Server: Slow User', + { timeout: 5000 }, + ) + await expect(page.getByTestId('deferred-server-data')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + }) + + test('shows loading states for deferred content', async ({ page }) => { + // Navigate with cache disabled to ensure fresh load + await page.goto('/deferred', { waitUntil: 'commit' }) + + // Should see loading states initially (may be very brief) + // We check that deferred content eventually shows + await expect(page.getByTestId('deferred-data')).toBeVisible({ + timeout: 5000, + }) + await expect(page.getByTestId('deferred-server-data')).toBeVisible({ + timeout: 5000, + }) + }) + + testWithHydration( + 'hydration works - interactive elements respond', + async ({ page }) => { + await page.goto('/deferred') + await page.waitForLoadState('networkidle') + + // Wait for all deferred content to load + await expect(page.getByTestId('deferred-data')).toBeVisible({ + timeout: 5000, + }) + + // Verify all data came from server after hydration + await expect(page.getByTestId('loader-source')).toContainText( + 'Loader source: server', + ) + await expect(page.getByTestId('deferred-data')).toContainText( + 'source: server', + ) + }, + ) + + test('client-side navigation to deferred route works', async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Navigate via client-side routing using nav link + await page.getByRole('link', { name: 'Deferred' }).first().click() + await expect(page).toHaveURL('/deferred') + + // Data should load + await expect(page.getByTestId('immediate-data')).toContainText('Fast User') + await expect(page.getByTestId('deferred-data')).toContainText( + 'Deferred data loaded!', + { timeout: 5000 }, + ) + }) + + test('all data sources are server - proves SSR streaming works', async ({ + page, + }) => { + await page.goto('/deferred') + + // Wait for all deferred content + await expect(page.getByTestId('deferred-data')).toBeVisible({ + timeout: 5000, + }) + await expect(page.getByTestId('deferred-server-data')).toBeVisible({ + timeout: 5000, + }) + + // Count all elements showing 'server' source - should be 4: + // 1. immediate-source + // 2. loader-source + // 3. deferred-data (contains "source: server") + // 4. deferred-server-data (contains "source: server") + await expect(page.getByTestId('immediate-source')).toContainText('server') + await expect(page.getByTestId('loader-source')).toContainText('server') + await expect(page.getByTestId('deferred-data')).toContainText( + 'source: server', + ) + await expect(page.getByTestId('deferred-server-data')).toContainText( + 'source: server', + ) + }) +}) diff --git a/e2e/react-start/streaming-ssr/tests/fast-serial.spec.ts b/e2e/react-start/streaming-ssr/tests/fast-serial.spec.ts index 95df0555e2..339d6408ea 100644 --- a/e2e/react-start/streaming-ssr/tests/fast-serial.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/fast-serial.spec.ts @@ -1 +1,72 @@ -import '../../../streaming-ssr-specs/fast-serial' +import { expect, test, testWithHydration } from './fixtures' + +test.describe('Fast serialization (serialization completes before render)', () => { + test('initial HTML contains router bootstrap + barrier', async ({ page }) => { + let responseHtml = '' + await page.route('/fast-serial', async (route) => { + const response = await route.fetch() + responseHtml = await response.text() + await route.fulfill({ response }) + }) + + await page.goto('/fast-serial') + await expect(page.getByTestId('server-data')).toBeVisible() + + expect(responseHtml).toContain('$_TSR') + expect(responseHtml).toContain('$_TSR.router') + expect(responseHtml).toContain('$_TSR.e()') + expect(responseHtml).toContain('$tsr-stream-barrier') + }) + + test('all data is available immediately', async ({ page }) => { + await page.goto('/fast-serial') + await page.waitForLoadState('networkidle') + + // All data should be visible + await expect(page.getByTestId('server-data')).toContainText('small-data') + await expect(page.getByTestId('static-data')).toContainText( + 'This is static data', + ) + await expect(page.getByTestId('loader-timestamp')).toBeVisible() + + // Verify data came from server (proves SSR streaming worked) + await expect(page.getByTestId('loader-source')).toContainText( + 'Loader source: server', + ) + await expect(page.getByTestId('server-fn-source')).toContainText( + 'Server function source: server', + ) + }) + + testWithHydration('hydration works correctly', async ({ page }) => { + await page.goto('/fast-serial') + await page.waitForLoadState('networkidle') + + // Verify data came from server after hydration + await expect(page.getByTestId('loader-source')).toContainText( + 'Loader source: server', + ) + }) + + test('direct navigation renders correctly', async ({ page }) => { + // Direct navigation (SSR) + await page.goto('/fast-serial') + + // Should render without errors and show server source + await expect(page.getByTestId('server-data')).toBeVisible() + await expect(page.getByTestId('loader-source')).toContainText( + 'Loader source: server', + ) + }) + + test('client-side navigation works', async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Navigate via nav link + await page.getByRole('link', { name: 'Fast Serial' }).first().click() + await expect(page).toHaveURL('/fast-serial') + + await expect(page.getByTestId('server-data')).toContainText('small-data') + }) +}) diff --git a/e2e/react-start/streaming-ssr/tests/fixtures.ts b/e2e/react-start/streaming-ssr/tests/fixtures.ts new file mode 100644 index 0000000000..71c564aebe --- /dev/null +++ b/e2e/react-start/streaming-ssr/tests/fixtures.ts @@ -0,0 +1,90 @@ +import { test as base, expect, type Page } from '@playwright/test' + +/** + * Verifies that React hydration has completed by clicking the global + * hydration check button and verifying the status changes. + * + * This is the canonical way to verify hydration in streaming-ssr tests. + * The HydrationCheck component is rendered in the root layout (__root.tsx). + * + * The function retries clicking until the status changes to 'hydrated', + * which handles the case where the button is visible from SSR before + * React has finished hydrating. + */ +async function verifyHydration( + page: Page, + options: { timeout?: number } = {}, +): Promise { + const timeout = options.timeout ?? 10000 + const button = page.getByTestId('hydration-check-btn') + const status = page.getByTestId('hydration-status') + + // Ensure the button is visible + await expect(button).toBeVisible() + + // Retry clicking until hydration succeeds + // This handles the case where SSR renders the button before React hydrates + await expect(async () => { + // Click the button to trigger hydration verification + await button.click() + + // Check if the status changed to 'hydrated' + await expect(status).toHaveText('hydrated', { timeout: 100 }) + }).toPass({ timeout }) +} + +export interface StreamingSsrOptions { + /** + * List of error message patterns to ignore in console output. + */ + whitelistErrors: Array +} + +/** + * Base test fixture for streaming-ssr e2e tests. + * Provides console error monitoring. + */ +export const test = base.extend({ + whitelistErrors: [[], { option: true }], + + page: async ({ page, whitelistErrors }, use) => { + const errorMessages: Array = [] + + page.on('console', (m) => { + if (m.type() === 'error') { + const text = m.text() + for (const whitelistError of whitelistErrors) { + if ( + (typeof whitelistError === 'string' && + text.includes(whitelistError)) || + (whitelistError instanceof RegExp && whitelistError.test(text)) + ) { + return + } + } + errorMessages.push(text) + } + }) + + await use(page) + + // Assert no unexpected console errors + expect(errorMessages).toEqual([]) + }, +}) + +/** + * Extended test fixture that automatically verifies hydration at the end. + * Use this for tests where you want to confirm React hydration succeeded. + */ +export const testWithHydration = test.extend({ + page: async ({ page }, use) => { + await use(page) + + // Automatically verify hydration at the end of the test + await verifyHydration(page) + }, +}) + +// Re-export expect for convenience +export { expect } diff --git a/e2e/react-start/streaming-ssr/tests/home.spec.ts b/e2e/react-start/streaming-ssr/tests/home.spec.ts index 5d49d34a56..e231d007fb 100644 --- a/e2e/react-start/streaming-ssr/tests/home.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/home.spec.ts @@ -1 +1,34 @@ -import '../../../streaming-ssr-specs/home' +import { expect, test, testWithHydration } from './fixtures' + +test.describe('Home page', () => { + testWithHydration( + 'renders index page with all navigation links', + async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + await expect(page.getByTestId('index-title')).toContainText( + 'Streaming SSR Test Scenarios', + ) + // Check links exist (they're in the nav and the body) + await expect( + page.getByRole('link', { name: 'Deferred' }).first(), + ).toBeVisible() + await expect( + page.getByRole('link', { name: 'Stream' }).first(), + ).toBeVisible() + }, + ) + + testWithHydration( + 'navigation from home to routes works', + async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Use the link in the content (not nav) + await page.getByTestId('link-deferred').click() + await expect(page).toHaveURL('/deferred') + }, + ) +}) diff --git a/e2e/react-start/streaming-ssr/tests/many-promises.spec.ts b/e2e/react-start/streaming-ssr/tests/many-promises.spec.ts index b747bd7d0a..034ab74220 100644 --- a/e2e/react-start/streaming-ssr/tests/many-promises.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/many-promises.spec.ts @@ -1 +1,93 @@ -import '../../../streaming-ssr-specs/many-promises' +import { expect, test, testWithHydration } from './fixtures' + +test.describe('Many promises streaming (15 deferred)', () => { + test('all 15 promises eventually resolve', async ({ page }) => { + await page.goto('/many-promises') + + // Immediate group (0-20ms) + await expect(page.getByTestId('immediate-1')).toContainText('immediate-1', { + timeout: 5000, + }) + await expect(page.getByTestId('immediate-2')).toContainText('immediate-2', { + timeout: 5000, + }) + await expect(page.getByTestId('immediate-3')).toContainText('immediate-3', { + timeout: 5000, + }) + + // Fast group (50-125ms) + await expect(page.getByTestId('fast-1')).toContainText('fast-1', { + timeout: 5000, + }) + await expect(page.getByTestId('fast-2')).toContainText('fast-2', { + timeout: 5000, + }) + await expect(page.getByTestId('fast-3')).toContainText('fast-3', { + timeout: 5000, + }) + await expect(page.getByTestId('fast-4')).toContainText('fast-4', { + timeout: 5000, + }) + + // Medium group (150-250ms) + await expect(page.getByTestId('medium-1')).toContainText('medium-1', { + timeout: 5000, + }) + await expect(page.getByTestId('medium-2')).toContainText('medium-2', { + timeout: 5000, + }) + await expect(page.getByTestId('medium-3')).toContainText('medium-3', { + timeout: 5000, + }) + + // Slow group (300-500ms) + await expect(page.getByTestId('slow-1')).toContainText('slow-1', { + timeout: 5000, + }) + await expect(page.getByTestId('slow-2')).toContainText('slow-2', { + timeout: 5000, + }) + await expect(page.getByTestId('slow-3')).toContainText('slow-3', { + timeout: 5000, + }) + + // Very slow group (600-800ms) + await expect(page.getByTestId('very-slow-1')).toContainText('very-slow-1', { + timeout: 5000, + }) + await expect(page.getByTestId('very-slow-2')).toContainText('very-slow-2', { + timeout: 5000, + }) + }) + + testWithHydration('hydration works with many promises', async ({ page }) => { + await page.goto('/many-promises') + await page.waitForLoadState('networkidle') + + // Wait for all promises to resolve + await expect(page.getByTestId('very-slow-2')).toBeVisible({ timeout: 5000 }) + }) + + test('client-side navigation works', async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Navigate via nav link + await page.getByRole('link', { name: 'Many Promises' }).click() + await expect(page).toHaveURL('/many-promises') + + // All promises should eventually resolve + await expect(page.getByTestId('very-slow-2')).toBeVisible({ timeout: 5000 }) + }) + + test('fast promises resolve before slow ones', async ({ page }) => { + // Navigate and check ordering - faster promises should be visible first + await page.goto('/many-promises', { waitUntil: 'commit' }) + + // Immediate promises should appear first + await expect(page.getByTestId('immediate-1')).toBeVisible({ timeout: 2000 }) + + // By the time we check very-slow, all should be visible + await expect(page.getByTestId('very-slow-2')).toBeVisible({ timeout: 5000 }) + }) +}) diff --git a/e2e/react-start/streaming-ssr/tests/nested-deferred.spec.ts b/e2e/react-start/streaming-ssr/tests/nested-deferred.spec.ts index 8df20a8a95..dbf6df4265 100644 --- a/e2e/react-start/streaming-ssr/tests/nested-deferred.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/nested-deferred.spec.ts @@ -1 +1,77 @@ -import '../../../streaming-ssr-specs/nested-deferred' +import { expect, test, testWithHydration } from './fixtures' + +test.describe('Nested deferred (multiple levels of deferred data)', () => { + test('all levels of deferred data eventually resolve', async ({ page }) => { + await page.goto('/nested-deferred') + + // Plain deferred should resolve first (300ms) + await expect(page.getByTestId('plain-deferred')).toContainText( + 'Plain deferred resolved!', + { timeout: 5000 }, + ) + + // Level 1 should resolve (200ms) + await expect(page.getByTestId('level1-data')).toContainText('Level 1:', { + timeout: 5000, + }) + + // Level 2 should resolve (400ms) + await expect(page.getByTestId('level2-data')).toContainText('Level 2:', { + timeout: 5000, + }) + + // Level 3 should resolve (600ms) + await expect(page.getByTestId('level3-data')).toContainText('Level 3:', { + timeout: 5000, + }) + }) + + test('shows loading states while data is loading', async ({ page }) => { + // Use fast navigation to catch loading states + await page.goto('/nested-deferred', { waitUntil: 'commit' }) + + // Eventually all data should be visible + await expect(page.getByTestId('level3-data')).toBeVisible({ + timeout: 10000, + }) + }) + + testWithHydration( + 'hydration works with nested deferred', + async ({ page }) => { + await page.goto('/nested-deferred') + await page.waitForLoadState('networkidle') + + // Wait for all data + await expect(page.getByTestId('level3-data')).toBeVisible({ + timeout: 10000, + }) + }, + ) + + test('client-side navigation works', async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Navigate via nav link + await page.getByRole('link', { name: 'Nested Deferred' }).first().click() + await expect(page).toHaveURL('/nested-deferred') + + // All levels should eventually render + await expect(page.getByTestId('level3-data')).toBeVisible({ + timeout: 10000, + }) + }) + + test('data resolves in expected order (fastest first)', async ({ page }) => { + await page.goto('/nested-deferred') + + // Wait for all to be visible + await expect(page.getByTestId('level1-data')).toBeVisible({ timeout: 5000 }) + await expect(page.getByTestId('level2-data')).toBeVisible({ timeout: 5000 }) + await expect(page.getByTestId('level3-data')).toBeVisible({ timeout: 5000 }) + await expect(page.getByTestId('plain-deferred')).toBeVisible({ + timeout: 5000, + }) + }) +}) diff --git a/e2e/react-start/streaming-ssr/tests/preview-streaming.spec.ts b/e2e/react-start/streaming-ssr/tests/preview-streaming.spec.ts index 34241cfbaa..319219c519 100644 --- a/e2e/react-start/streaming-ssr/tests/preview-streaming.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/preview-streaming.spec.ts @@ -1 +1,21 @@ -import '../../../streaming-ssr-specs/preview-streaming' +import { expect, test } from './fixtures' + +test('vite preview streams HTML incrementally', async ({ page }) => { + // /deferred has immediate data + deferred data with a ~1s delay. + // Without streaming, compression buffers the entire response. + await page.goto('/deferred', { waitUntil: 'commit' }) + + // Immediate data should arrive in the first chunk + await expect(page.getByTestId('immediate-data')).toBeVisible({ + timeout: 3000, + }) + + // Deferred data (1s delay) should still be loading at this point + await expect(page.getByTestId('deferred-loading')).toBeVisible() + + // Wait for it to resolve + await expect(page.getByTestId('deferred-data')).toContainText( + 'Deferred data loaded!', + { timeout: 5000 }, + ) +}) diff --git a/e2e/react-start/streaming-ssr/tests/query-heavy.spec.ts b/e2e/react-start/streaming-ssr/tests/query-heavy.spec.ts index e0d617106c..8e735040c2 100644 --- a/e2e/react-start/streaming-ssr/tests/query-heavy.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/query-heavy.spec.ts @@ -1,18 +1,168 @@ -import '../../../streaming-ssr-specs/query-heavy' -import { expect, test } from '../../../streaming-ssr-assertions' +import { expect, test, testWithHydration } from './fixtures' -test('batches same-turn queries into one stream chunk', async ({ request }) => { - const response = await request.get('/query-heavy') - const html = await response.text() - const scripts = Array.from( - html.matchAll(/]*>([\s\S]*?)<\/script>/g), - (match) => match[1]!, - ) - const syncQueryChunk = scripts.find((script) => - script.includes('sync-value-1'), - ) +test.describe('Query heavy route (9 useSuspenseQuery)', () => { + test('all queries resolve with server data', async ({ page }) => { + await page.goto('/query-heavy') - expect(syncQueryChunk).toBeDefined() - expect(syncQueryChunk).toContain('sync-value-2') - expect(syncQueryChunk).toContain('sync-value-3') + // Sync queries should show server source + await expect(page.getByTestId('sync-query-1')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + await expect(page.getByTestId('sync-query-2')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + await expect(page.getByTestId('sync-query-3')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + + // Fast async queries should show server source + await expect(page.getByTestId('fast-async-query-1')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + await expect(page.getByTestId('fast-async-query-2')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + await expect(page.getByTestId('fast-async-query-3')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + + // Slow async queries should show server source + await expect(page.getByTestId('slow-async-query-1')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + await expect(page.getByTestId('slow-async-query-2')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + await expect(page.getByTestId('slow-async-query-3')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + }) + + test('sync queries have correct values', async ({ page }) => { + await page.goto('/query-heavy') + + await expect(page.getByTestId('sync-query-1')).toContainText('sync-value-1') + await expect(page.getByTestId('sync-query-2')).toContainText('sync-value-2') + await expect(page.getByTestId('sync-query-3')).toContainText('sync-value-3') + }) + + test('async queries have correct values', async ({ page }) => { + await page.goto('/query-heavy') + + await expect(page.getByTestId('fast-async-query-1')).toContainText( + 'fast-async-1', + { timeout: 5000 }, + ) + await expect(page.getByTestId('fast-async-query-2')).toContainText( + 'fast-async-2', + { timeout: 5000 }, + ) + await expect(page.getByTestId('fast-async-query-3')).toContainText( + 'fast-async-3', + { timeout: 5000 }, + ) + + await expect(page.getByTestId('slow-async-query-1')).toContainText( + 'slow-async-1', + { timeout: 5000 }, + ) + await expect(page.getByTestId('slow-async-query-2')).toContainText( + 'slow-async-2', + { timeout: 5000 }, + ) + await expect(page.getByTestId('slow-async-query-3')).toContainText( + 'slow-async-3', + { timeout: 5000 }, + ) + }) + + testWithHydration('hydration works with many queries', async ({ page }) => { + await page.goto('/query-heavy') + await page.waitForLoadState('networkidle') + + // Wait for all queries to resolve + await expect(page.getByTestId('slow-async-query-3')).toBeVisible({ + timeout: 5000, + }) + }) + + test('client-side navigation works', async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Navigate via nav link + await page.getByRole('link', { name: 'Query Heavy' }).click() + await expect(page).toHaveURL('/query-heavy') + + // All queries should eventually resolve (on client) + await expect(page.getByTestId('slow-async-query-3')).toBeVisible({ + timeout: 5000, + }) + }) + + test('no hydration mismatch - queries streamed from server', async ({ + page, + }) => { + // This test verifies that query data is streamed from server + // If it wasn't, the queries would re-execute on client and show 'client' as source + await page.goto('/query-heavy') + + // Wait for all queries + await expect(page.getByTestId('slow-async-query-3')).toBeVisible({ + timeout: 5000, + }) + + // Verify all show 'server' - this proves data was streamed, not re-fetched + const serverSourceCount = await page + .locator('[data-testid*="query-"]') + .filter({ hasText: 'source: server' }) + .count() + expect(serverSourceCount).toBe(9) + }) + + test('emits query stream data before stream end marker', async ({ + request, + }) => { + const response = await request.get('/query-heavy') + const html = await response.text() + const endMarker = '$_TSR.e()' + const endIndex = html.indexOf(endMarker) + const slowAsyncPayloadIndex = html.indexOf('"slow-async-3"') + const lastScriptOpen = html.lastIndexOf('', endIndex) + + expect(endIndex).toBeGreaterThan(-1) + expect(lastScriptOpen).toBeGreaterThan(lastScriptClose) + expect(slowAsyncPayloadIndex).toBeGreaterThan(-1) + expect(slowAsyncPayloadIndex).toBeLessThan(endIndex) + expect(html.slice(lastScriptOpen, endIndex)).toContain('.return(void 0)') + expect(endIndex).toBeLessThan(html.indexOf('')) + }) + + test('batches same-turn queries into one stream chunk', async ({ + request, + }) => { + const response = await request.get('/query-heavy') + const html = await response.text() + const scripts = Array.from( + html.matchAll(/]*>([\s\S]*?)<\/script>/g), + (match) => match[1]!, + ) + const syncQueryChunk = scripts.find( + (script) => script.includes('.next(') && script.includes('sync-value-1'), + ) + + expect(syncQueryChunk).toBeDefined() + expect(syncQueryChunk).toContain('sync-value-2') + expect(syncQueryChunk).toContain('sync-value-3') + }) }) diff --git a/e2e/react-start/streaming-ssr/tests/router-html-buffer.spec.ts b/e2e/react-start/streaming-ssr/tests/router-html-buffer.spec.ts deleted file mode 100644 index a9cf8a8142..0000000000 --- a/e2e/react-start/streaming-ssr/tests/router-html-buffer.spec.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { - STREAM_PART_SELECTOR, - expect, - test, - testWithHydration, -} from '../../../streaming-ssr-assertions' - -const runBufferReproduction = - process.env.RUN_SSR_ROUTER_HTML_BUFFER_REPRO === 'true' - -test.describe('SSR router HTML buffer', () => { - test.skip( - !runBufferReproduction, - 'The 17 MiB ASCII reproduction is intentionally opt-in: pnpm test:e2e:buffer-repro', - ) - - testWithHydration( - 'hydrates a large deferred loader payload from server state', - async ({ page }) => { - const response = await page.goto('/router-html-buffer') - - expect(response?.ok()).toBe(true) - await expect(page.getByTestId('router-html-payload-length')).toHaveText( - '17825792', - ) - await expect(page.locator(STREAM_PART_SELECTOR)).toHaveCount(0) - - await page.getByTestId('router-html-payload-check').click() - await expect(page.getByTestId('router-html-payload-result')).toHaveText( - 'server:17825792:x', - ) - }, - ) -}) diff --git a/e2e/react-start/streaming-ssr/tests/slow-render.spec.ts b/e2e/react-start/streaming-ssr/tests/slow-render.spec.ts index 0d5a87363f..c3631a7fc0 100644 --- a/e2e/react-start/streaming-ssr/tests/slow-render.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/slow-render.spec.ts @@ -1 +1,73 @@ -import '../../../streaming-ssr-specs/slow-render' +import { expect, test, testWithHydration } from './fixtures' + +test.describe('Slow render (render takes longer than serialization)', () => { + test('all data eventually renders with server source', async ({ page }) => { + await page.goto('/slow-render') + await page.waitForLoadState('networkidle') + + // Quick data should be available with server source + await expect(page.getByTestId('quick-data')).toContainText('Quick:') + await expect(page.getByTestId('quick-source')).toContainText( + 'Quick data source: server', + ) + await expect(page.getByTestId('loader-source')).toContainText( + 'Loader source: server', + ) + + // Deferred data should resolve with server source + await expect(page.getByTestId('deferred-resolved')).toContainText( + 'Deferred resolved!', + { timeout: 5000 }, + ) + await expect(page.getByTestId('deferred-resolved')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + + // Slow components should have rendered + await expect(page.getByTestId('slow-component-1')).toBeVisible() + await expect(page.getByTestId('slow-component-2')).toBeVisible() + await expect(page.getByTestId('slow-component-3')).toBeVisible() + }) + + testWithHydration('hydration works after slow render', async ({ page }) => { + await page.goto('/slow-render') + await page.waitForLoadState('networkidle') + + // Wait for content and verify server source + await expect(page.getByTestId('slow-component-1')).toBeVisible() + await expect(page.getByTestId('loader-source')).toContainText( + 'Loader source: server', + ) + }) + + test('client-side navigation works', async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Navigate via nav link + await page.getByRole('link', { name: 'Slow Render' }).first().click() + await expect(page).toHaveURL('/slow-render') + + await expect(page.getByTestId('quick-data')).toBeVisible({ timeout: 10000 }) + }) + + test('all data sources are server - proves SSR streaming works', async ({ + page, + }) => { + await page.goto('/slow-render') + await page.waitForLoadState('networkidle') + + // Wait for deferred content + await expect(page.getByTestId('deferred-resolved')).toBeVisible({ + timeout: 5000, + }) + + // Verify all sources are server + await expect(page.getByTestId('quick-source')).toContainText('server') + await expect(page.getByTestId('loader-source')).toContainText('server') + await expect(page.getByTestId('deferred-resolved')).toContainText( + 'source: server', + ) + }) +}) diff --git a/e2e/react-start/streaming-ssr/tests/stream.spec.ts b/e2e/react-start/streaming-ssr/tests/stream.spec.ts index a51614f09a..5e4c134f82 100644 --- a/e2e/react-start/streaming-ssr/tests/stream.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/stream.spec.ts @@ -1 +1,46 @@ -import '../../../streaming-ssr-specs/stream' +import { expect, test, testWithHydration } from './fixtures' + +test.describe('ReadableStream streaming', () => { + testWithHydration('promise data resolves correctly', async ({ page }) => { + await page.goto('/stream') + + // Promise should resolve + await expect(page.getByTestId('promise-data')).toContainText( + 'promise-resolved', + { timeout: 5000 }, + ) + }) + + testWithHydration('stream chunks arrive incrementally', async ({ page }) => { + await page.goto('/stream') + + // Wait for stream to complete + await expect(page.getByTestId('stream-complete')).toBeVisible({ + timeout: 10000, + }) + + // All chunks should be present + await expect(page.getByTestId('stream-chunk-0')).toContainText('chunk-0') + await expect(page.getByTestId('stream-chunk-1')).toContainText('chunk-1') + await expect(page.getByTestId('stream-chunk-2')).toContainText('chunk-2') + await expect(page.getByTestId('stream-chunk-3')).toContainText('chunk-3') + await expect(page.getByTestId('stream-chunk-4')).toContainText('chunk-4') + }) + + testWithHydration( + 'client-side navigation to stream route works', + async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Navigate via nav link + await page.getByRole('link', { name: 'Stream' }).first().click() + await expect(page).toHaveURL('/stream') + + // Wait for stream to complete + await expect(page.getByTestId('stream-complete')).toBeVisible({ + timeout: 10000, + }) + }, + ) +}) diff --git a/e2e/react-start/streaming-ssr/tests/sync-only.spec.ts b/e2e/react-start/streaming-ssr/tests/sync-only.spec.ts index 0e9278d3f2..a0060a07ee 100644 --- a/e2e/react-start/streaming-ssr/tests/sync-only.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/sync-only.spec.ts @@ -1 +1,84 @@ -import '../../../streaming-ssr-specs/sync-only' +import { expect } from '@playwright/test' +import { test, testWithHydration } from './fixtures' + +/** + * Tests for synchronous serialization - no deferred data, no streaming. + * This is the most common case where all loader data is immediately available. + * The hydration scripts should be included in the initial HTML response. + */ + +test('Sync-only route renders with loader data', async ({ page }) => { + await page.goto('/sync-only') + + // Verify the page content is rendered + await expect(page.getByTestId('sync-title')).toContainText( + 'Synchronous Serialization Test', + ) + await expect(page.getByTestId('sync-message')).toContainText( + 'Hello from sync loader!', + ) + + // Verify loader data items are rendered + await expect(page.getByTestId('sync-item-item-1')).toBeVisible() + await expect(page.getByTestId('sync-item-item-2')).toBeVisible() + await expect(page.getByTestId('sync-item-item-3')).toBeVisible() + + // Verify data came from server (proves SSR streaming worked) + await expect(page.getByTestId('sync-source')).toContainText('Source: server') +}) + +testWithHydration('Sync-only route hydrates correctly', async ({ page }) => { + await page.goto('/sync-only') + + // Verify client-side navigation works (proves hydration succeeded) + await page.getByRole('navigation').getByRole('link', { name: 'Home' }).click() + await expect(page.getByTestId('index-title')).toBeVisible() + + // Navigate back to sync-only via client-side navigation (use nav link to be specific) + await page + .getByRole('navigation') + .getByRole('link', { name: 'Sync Only' }) + .click() + await expect(page.getByTestId('sync-title')).toBeVisible() +}) + +test('Sync-only route has bootstrap scripts in initial HTML', async ({ + page, +}) => { + // Intercept the response to check the raw HTML + let responseHtml = '' + await page.route('/sync-only', async (route) => { + const response = await route.fetch() + responseHtml = await response.text() + await route.fulfill({ response }) + }) + + await page.goto('/sync-only') + + // Wait for page to load + await expect(page.getByTestId('sync-title')).toBeVisible() + + // The HTML should contain the bootstrap scripts + // $_TSR.router should be present (the dehydrated router state) + expect(responseHtml).toContain('$_TSR') + expect(responseHtml).toContain('$_TSR.router') + // The serialization end marker should be present + expect(responseHtml).toContain('$_TSR.e()') + + // SSR should include the barrier script tag in the HTML (rendered by ) + // This is the critical marker transformStreamWithRouter can scan for. + expect(responseHtml).toContain('$tsr-stream-barrier') +}) + +test('Navigating to sync-only from home page', async ({ page }) => { + await page.goto('/') + + await page.getByTestId('link-sync-only').click() + + await expect(page.getByTestId('sync-title')).toContainText( + 'Synchronous Serialization Test', + ) + await expect(page.getByTestId('sync-message')).toContainText( + 'Hello from sync loader!', + ) +}) diff --git a/e2e/react-start/streaming-ssr/vite.config.ts b/e2e/react-start/streaming-ssr/vite.config.ts index 0590c197a5..275bfacde2 100644 --- a/e2e/react-start/streaming-ssr/vite.config.ts +++ b/e2e/react-start/streaming-ssr/vite.config.ts @@ -1,10 +1,9 @@ import { defineConfig } from 'vite' import { tanstackStart } from '@tanstack/react-start/plugin/vite' -import viteReact from '@vitejs/plugin-react' export default defineConfig({ server: { port: 3000, }, - plugins: [tanstackStart(), viteReact()], + plugins: [tanstackStart()], }) diff --git a/e2e/react-start/transform-asset-urls/package.json b/e2e/react-start/transform-asset-urls/package.json index e0a5ffec59..95e39e459b 100644 --- a/e2e/react-start/transform-asset-urls/package.json +++ b/e2e/react-start/transform-asset-urls/package.json @@ -16,19 +16,19 @@ "manual:both:options": "TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=createTransform pnpm manual:both", "manual:both:options:transform": "TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=transform pnpm manual:both", "manual:both:options:createTransform": "TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=createTransform pnpm manual:both", - "test:e2e:string": "rm -rf dist; TRANSFORM_ASSETS_MODE=string playwright test --project=chromium", - "test:e2e:function": "rm -rf dist; TRANSFORM_ASSETS_MODE=function playwright test --project=chromium", - "test:e2e:options": "rm -rf dist; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=transform playwright test --project=chromium", - "test:e2e:options:transform": "rm -rf dist; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=transform playwright test --project=chromium", - "test:e2e:options:createTransform": "rm -rf dist; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=createTransform playwright test --project=chromium", - "test:e2e:options:transform:cache-true:warmup-true": "rm -rf dist; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=transform TRANSFORM_ASSETS_OPTIONS_CACHE=true TRANSFORM_ASSETS_OPTIONS_WARMUP=true playwright test --project=chromium", - "test:e2e:options:transform:cache-true:warmup-false": "rm -rf dist; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=transform TRANSFORM_ASSETS_OPTIONS_CACHE=true TRANSFORM_ASSETS_OPTIONS_WARMUP=false playwright test --project=chromium", - "test:e2e:options:transform:cache-false:warmup-true": "rm -rf dist; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=transform TRANSFORM_ASSETS_OPTIONS_CACHE=false TRANSFORM_ASSETS_OPTIONS_WARMUP=true playwright test --project=chromium", - "test:e2e:options:transform:cache-false:warmup-false": "rm -rf dist; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=transform TRANSFORM_ASSETS_OPTIONS_CACHE=false TRANSFORM_ASSETS_OPTIONS_WARMUP=false playwright test --project=chromium", - "test:e2e:options:createTransform:cache-true:warmup-true": "rm -rf dist; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=createTransform TRANSFORM_ASSETS_OPTIONS_CACHE=true TRANSFORM_ASSETS_OPTIONS_WARMUP=true playwright test --project=chromium", - "test:e2e:options:createTransform:cache-true:warmup-false": "rm -rf dist; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=createTransform TRANSFORM_ASSETS_OPTIONS_CACHE=true TRANSFORM_ASSETS_OPTIONS_WARMUP=false playwright test --project=chromium", - "test:e2e:options:createTransform:cache-false:warmup-true": "rm -rf dist; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=createTransform TRANSFORM_ASSETS_OPTIONS_CACHE=false TRANSFORM_ASSETS_OPTIONS_WARMUP=true playwright test --project=chromium", - "test:e2e:options:createTransform:cache-false:warmup-false": "rm -rf dist; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=createTransform TRANSFORM_ASSETS_OPTIONS_CACHE=false TRANSFORM_ASSETS_OPTIONS_WARMUP=false playwright test --project=chromium", + "test:e2e:string": "rm -rf dist; rm -rf port*.txt; TRANSFORM_ASSETS_MODE=string playwright test --project=chromium", + "test:e2e:function": "rm -rf dist; rm -rf port*.txt; TRANSFORM_ASSETS_MODE=function playwright test --project=chromium", + "test:e2e:options": "rm -rf dist; rm -rf port*.txt; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=transform playwright test --project=chromium", + "test:e2e:options:transform": "rm -rf dist; rm -rf port*.txt; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=transform playwright test --project=chromium", + "test:e2e:options:createTransform": "rm -rf dist; rm -rf port*.txt; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=createTransform playwright test --project=chromium", + "test:e2e:options:transform:cache-true:warmup-true": "rm -rf dist; rm -rf port*.txt; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=transform TRANSFORM_ASSETS_OPTIONS_CACHE=true TRANSFORM_ASSETS_OPTIONS_WARMUP=true playwright test --project=chromium", + "test:e2e:options:transform:cache-true:warmup-false": "rm -rf dist; rm -rf port*.txt; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=transform TRANSFORM_ASSETS_OPTIONS_CACHE=true TRANSFORM_ASSETS_OPTIONS_WARMUP=false playwright test --project=chromium", + "test:e2e:options:transform:cache-false:warmup-true": "rm -rf dist; rm -rf port*.txt; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=transform TRANSFORM_ASSETS_OPTIONS_CACHE=false TRANSFORM_ASSETS_OPTIONS_WARMUP=true playwright test --project=chromium", + "test:e2e:options:transform:cache-false:warmup-false": "rm -rf dist; rm -rf port*.txt; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=transform TRANSFORM_ASSETS_OPTIONS_CACHE=false TRANSFORM_ASSETS_OPTIONS_WARMUP=false playwright test --project=chromium", + "test:e2e:options:createTransform:cache-true:warmup-true": "rm -rf dist; rm -rf port*.txt; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=createTransform TRANSFORM_ASSETS_OPTIONS_CACHE=true TRANSFORM_ASSETS_OPTIONS_WARMUP=true playwright test --project=chromium", + "test:e2e:options:createTransform:cache-true:warmup-false": "rm -rf dist; rm -rf port*.txt; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=createTransform TRANSFORM_ASSETS_OPTIONS_CACHE=true TRANSFORM_ASSETS_OPTIONS_WARMUP=false playwright test --project=chromium", + "test:e2e:options:createTransform:cache-false:warmup-true": "rm -rf dist; rm -rf port*.txt; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=createTransform TRANSFORM_ASSETS_OPTIONS_CACHE=false TRANSFORM_ASSETS_OPTIONS_WARMUP=true playwright test --project=chromium", + "test:e2e:options:createTransform:cache-false:warmup-false": "rm -rf dist; rm -rf port*.txt; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=createTransform TRANSFORM_ASSETS_OPTIONS_CACHE=false TRANSFORM_ASSETS_OPTIONS_WARMUP=false playwright test --project=chromium", "test:e2e:options:matrix": "pnpm test:e2e:options:transform:cache-true:warmup-true && pnpm test:e2e:options:transform:cache-true:warmup-false && pnpm test:e2e:options:transform:cache-false:warmup-true && pnpm test:e2e:options:transform:cache-false:warmup-false && pnpm test:e2e:options:createTransform:cache-true:warmup-true && pnpm test:e2e:options:createTransform:cache-true:warmup-false && pnpm test:e2e:options:createTransform:cache-false:warmup-true && pnpm test:e2e:options:createTransform:cache-false:warmup-false", "test:e2e": "pnpm test:e2e:string && pnpm test:e2e:function && pnpm test:e2e:options:matrix" }, @@ -46,7 +46,7 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" diff --git a/e2e/react-start/transform-asset-urls/playwright.config.ts b/e2e/react-start/transform-asset-urls/playwright.config.ts index 209a7e0596..bbef6838fe 100644 --- a/e2e/react-start/transform-asset-urls/playwright.config.ts +++ b/e2e/react-start/transform-asset-urls/playwright.config.ts @@ -1,10 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const APP_PORT = Number(process.env.E2E_APP_PORT ?? 0) -const CDN_PORT = Number(process.env.E2E_CDN_PORT ?? 0) +const APP_PORT = await getTestServerPort(packageJson.name) +const CDN_PORT = await getTestServerPort(`${packageJson.name}_cdn`) const baseURL = `http://localhost:${APP_PORT}` +const cdnOrigin = `http://localhost:${CDN_PORT}` const transformMode = process.env.TRANSFORM_ASSETS_MODE || 'string' const optionsKind = process.env.TRANSFORM_ASSETS_OPTIONS_KIND || 'createTransform' @@ -24,11 +26,8 @@ export default defineConfig({ { // CDN server — serves built client assets on a separate port with CORS command: `node tests/cdn-server.mjs`, - wait: { - stdout: - /CDN Server: (?http:\/\/localhost:(?\d+))/, - }, - reuseExistingServer: false, + url: `http://localhost:${CDN_PORT}/health`, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { CDN_PORT: String(CDN_PORT), @@ -38,11 +37,12 @@ export default defineConfig({ // App server — builds the project then starts the srvx server // with CDN_ORIGIN so that transformAssets rewrites manifest URLs command: `pnpm build && pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { PORT: String(APP_PORT), + CDN_ORIGIN: cdnOrigin, TRANSFORM_ASSETS_MODE: transformMode, TRANSFORM_ASSETS_OPTIONS_KIND: optionsKind, TRANSFORM_ASSETS_OPTIONS_CACHE: optionsCache, diff --git a/e2e/react-start/transform-asset-urls/src/server.ts b/e2e/react-start/transform-asset-urls/src/server.ts index a51f29ad66..241fc2fe51 100644 --- a/e2e/react-start/transform-asset-urls/src/server.ts +++ b/e2e/react-start/transform-asset-urls/src/server.ts @@ -83,18 +83,4 @@ const handler = createStartHandler( : defaultStreamHandler, ) -export default createServerEntry({ - fetch(request, options) { - const scriptUrl = request.headers.get('x-test-script-url') - if (scriptUrl) { - return createStartHandler({ - handler: defaultStreamHandler, - transformAssets: ({ kind, url }) => ({ - href: kind === 'script' ? scriptUrl : url, - }), - })(request, options) - } - - return handler(request, options) - }, -}) +export default createServerEntry({ fetch: handler }) diff --git a/e2e/react-start/transform-asset-urls/tests/cdn-server.mjs b/e2e/react-start/transform-asset-urls/tests/cdn-server.mjs index 280c626867..ea9bf62cd0 100644 --- a/e2e/react-start/transform-asset-urls/tests/cdn-server.mjs +++ b/e2e/react-start/transform-asset-urls/tests/cdn-server.mjs @@ -3,7 +3,7 @@ import path from 'node:path' import { fileURLToPath } from 'node:url' const __dirname = path.dirname(fileURLToPath(import.meta.url)) -const port = Number(process.env.CDN_PORT ?? 0) +const port = process.env.CDN_PORT || 3002 const app = express() @@ -36,7 +36,7 @@ app.use((req, res, next) => { app.use(express.static(path.resolve(__dirname, '..', 'dist', 'client'))) -const server = app.listen(port, (error) => { +app.listen(port, (error) => { if (error) throw error - console.info(`CDN Server: http://localhost:${server.address().port}`) + console.info(`CDN Server: http://localhost:${port}`) }) diff --git a/e2e/react-start/transform-asset-urls/tests/script-url-escaping.spec.ts b/e2e/react-start/transform-asset-urls/tests/script-url-escaping.spec.ts deleted file mode 100644 index 22251df671..0000000000 --- a/e2e/react-start/transform-asset-urls/tests/script-url-escaping.spec.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { expect, test } from '@playwright/test' - -for (const [name, scriptUrl] of [ - [ - 'closing script tag', - '', endIndex) - const scriptCloseIndex = html.indexOf('', endIndex) - const bodyCloseIndex = html.indexOf('', scriptCloseIndex) - const htmlCloseIndex = html.indexOf('', bodyCloseIndex) - - expect(endIndex).toBeGreaterThan(-1) - expect(scriptOpenIndex).toBeGreaterThan(previousScriptCloseIndex) - expect(scriptCloseIndex).toBeGreaterThan(endIndex) - expect(payloadIndex).toBeGreaterThan(-1) - expect(payloadIndex).toBeLessThan(endIndex) - expect(html.slice(endIndex, scriptCloseIndex)).toContain(LATE_RECORD_CLOSE) - expect(scriptCloseIndex).toBeLessThan(bodyCloseIndex) - expect(bodyCloseIndex).toBeLessThan(htmlCloseIndex) -} - -async function verifyHydration( - page: Page, - { timeout = 10_000 }: { timeout?: number } = {}, -) { - const button = page.getByTestId('hydration-check-btn') - const status = page.getByTestId('hydration-status') - - await expect(button).toBeVisible() - await expect(async () => { - await button.click() - await expect(status).toHaveText('hydrated', { timeout: 100 }) - }).toPass({ timeout }) - - await expect(page.locator(STREAM_PART_SELECTOR)).toHaveCount(0) - await expect( - page.locator('script').filter({ hasText: STREAM_BOUNDARY_MARKER }), - ).toHaveCount(0) -} - -export { test } - -export const testWithHydration = test.extend({ - page: async ({ page }, use) => { - await use(page) - await verifyHydration(page) - }, -}) - -export { expect } diff --git a/e2e/streaming-ssr-fixtures/index.ts b/e2e/streaming-ssr-fixtures/index.ts deleted file mode 100644 index a70ef94459..0000000000 --- a/e2e/streaming-ssr-fixtures/index.ts +++ /dev/null @@ -1,381 +0,0 @@ -export type SourceMarker = 'server' | 'client' - -export type ServerData = { - name: string - timestamp: number - source: 'server' -} - -export type DeferredMessage = { - message: string - source: SourceMarker -} - -export type QueryType = 'sync' | 'fast-async' | 'slow-async' - -export type QueryData = { - type: QueryType - id: number - value: string - source: SourceMarker -} - -export const deferredDataMessage = 'Deferred data loaded!' -export const deferredDataDelay = 1000 -export const deferredServerDelay = 800 -export const deferredImmediateName = 'Fast User' -export const deferredSlowName = 'Slow User' -export const deferredErrorMessage = 'Error in deferred object' - -export const fastSerialStaticData = 'This is static data' -export const fastSerialSmallValue = 'small-data' - -export const syncOnlyMessage = 'Hello from sync loader!' -export const syncOnlyItems = ['item-1', 'item-2', 'item-3'] as const - -export const slowRenderDeferredMessage = 'Deferred resolved!' -export const slowRenderDeferredDelay = 50 -export const slowRenderQuickName = 'Quick data' -export const slowRenderComponents = [ - 'Slow component 1', - 'Slow component 2', - 'Slow component 3', -] as const - -export const nestedLevelDelays = [200, 400, 600] as const -export const nestedPlainDelay = 300 -export const nestedPlainMessage = 'Plain deferred resolved!' - -export const streamPromiseValue = 'promise-resolved' -export const streamPromiseDelay = 150 -export const streamChunkDelay = 200 -export const streamChunks = Array.from({ length: 5 }, (_, i) => `chunk-${i}`) - -export const routerHtmlPayloadChars = 17 * 1024 * 1024 -export const routerHtmlPayloadChar = 'x' -export const routerHtmlPayloadDelay = 100 - -export const manyPromiseItems = [ - { - key: 'immediate1', - testId: 'immediate-1', - label: 'Immediate 1', - value: 'immediate-1', - delayMs: 0, - }, - { - key: 'immediate2', - testId: 'immediate-2', - label: 'Immediate 2', - value: 'immediate-2', - delayMs: 10, - }, - { - key: 'immediate3', - testId: 'immediate-3', - label: 'Immediate 3', - value: 'immediate-3', - delayMs: 20, - }, - { - key: 'fast1', - testId: 'fast-1', - label: 'Fast 1', - value: 'fast-1', - delayMs: 50, - }, - { - key: 'fast2', - testId: 'fast-2', - label: 'Fast 2', - value: 'fast-2', - delayMs: 75, - }, - { - key: 'fast3', - testId: 'fast-3', - label: 'Fast 3', - value: 'fast-3', - delayMs: 100, - }, - { - key: 'fast4', - testId: 'fast-4', - label: 'Fast 4', - value: 'fast-4', - delayMs: 125, - }, - { - key: 'medium1', - testId: 'medium-1', - label: 'Medium 1', - value: 'medium-1', - delayMs: 150, - }, - { - key: 'medium2', - testId: 'medium-2', - label: 'Medium 2', - value: 'medium-2', - delayMs: 200, - }, - { - key: 'medium3', - testId: 'medium-3', - label: 'Medium 3', - value: 'medium-3', - delayMs: 250, - }, - { - key: 'slow1', - testId: 'slow-1', - label: 'Slow 1', - value: 'slow-1', - delayMs: 300, - }, - { - key: 'slow2', - testId: 'slow-2', - label: 'Slow 2', - value: 'slow-2', - delayMs: 400, - }, - { - key: 'slow3', - testId: 'slow-3', - label: 'Slow 3', - value: 'slow-3', - delayMs: 500, - }, - { - key: 'verySlow1', - testId: 'very-slow-1', - label: 'Very Slow 1', - value: 'very-slow-1', - delayMs: 600, - }, - { - key: 'verySlow2', - testId: 'very-slow-2', - label: 'Very Slow 2', - value: 'very-slow-2', - delayMs: 800, - }, -] as const - -export const concurrentBatchCount = 5 -export const concurrentBatchDelays = [100, 200, 300] as const - -export const queryHeavyItems = [ - { - type: 'sync', - id: 1, - value: 'sync-value-1', - delayMs: 0, - testId: 'sync-query-1', - fallback: 'Loading sync 1...', - }, - { - type: 'sync', - id: 2, - value: 'sync-value-2', - delayMs: 0, - testId: 'sync-query-2', - fallback: 'Loading sync 2...', - }, - { - type: 'sync', - id: 3, - value: 'sync-value-3', - delayMs: 0, - testId: 'sync-query-3', - fallback: 'Loading sync 3...', - }, - { - type: 'fast-async', - id: 1, - value: 'fast-async-1', - delayMs: 50, - testId: 'fast-async-query-1', - fallback: 'Loading fast 1...', - }, - { - type: 'fast-async', - id: 2, - value: 'fast-async-2', - delayMs: 75, - testId: 'fast-async-query-2', - fallback: 'Loading fast 2...', - }, - { - type: 'fast-async', - id: 3, - value: 'fast-async-3', - delayMs: 100, - testId: 'fast-async-query-3', - fallback: 'Loading fast 3...', - }, - { - type: 'slow-async', - id: 1, - value: 'slow-async-1', - delayMs: 200, - testId: 'slow-async-query-1', - fallback: 'Loading slow 1...', - }, - { - type: 'slow-async', - id: 2, - value: 'slow-async-2', - delayMs: 300, - testId: 'slow-async-query-2', - fallback: 'Loading slow 2...', - }, - { - type: 'slow-async', - id: 3, - value: 'slow-async-3', - delayMs: 400, - testId: 'slow-async-query-3', - fallback: 'Loading slow 3...', - }, -] as const - -export function sourceMarker(): SourceMarker { - return typeof window === 'undefined' ? 'server' : 'client' -} - -export function delay(ms: number): Promise { - return new Promise((resolve) => setTimeout(resolve, ms)) -} - -export function makeServerData(name: string): ServerData { - return { - name, - timestamp: Date.now(), - source: 'server', - } -} - -export function makeDeferred(value: T, delayMs: number): Promise { - return new Promise((resolve) => setTimeout(() => resolve(value), delayMs)) -} - -export function makeDeferredMessage( - message: string, - delayMs: number, -): Promise { - return makeDeferred({ message, source: sourceMarker() }, delayMs) -} - -export function makeFastSerialSmallData() { - return { - value: fastSerialSmallValue, - timestamp: Date.now(), - source: 'server' as const, - } -} - -export function makeSyncOnlyData() { - return { - message: syncOnlyMessage, - timestamp: Date.now(), - items: syncOnlyItems, - source: sourceMarker(), - } -} - -export function makeLevelData(level: number) { - return { level, timestamp: Date.now() } -} - -export function makeQueryData(item: { - type: QueryType - id: number - value: string -}): QueryData { - return { - type: item.type, - id: item.id, - value: item.value, - source: sourceMarker(), - } -} - -export function createManyPromises() { - return Object.fromEntries( - manyPromiseItems.map((item) => [ - item.key, - makeDeferred(item.value, item.delayMs), - ]), - ) as Record<(typeof manyPromiseItems)[number]['key'], Promise> -} - -export function createConcurrentPromises( - count: number, - delayMs: number, -): Array> { - const sharedPromise = delay(delayMs) - return Array.from({ length: count }, (_, i) => - sharedPromise.then(() => `concurrent-${i + 1}`), - ) -} - -export function createConcurrentLoaderData() { - const batch1 = createConcurrentPromises( - concurrentBatchCount, - concurrentBatchDelays[0], - ) - const batch2 = createConcurrentPromises( - concurrentBatchCount, - concurrentBatchDelays[1], - ) - const batch3 = createConcurrentPromises( - concurrentBatchCount, - concurrentBatchDelays[2], - ) - - return { - concurrent1_1: batch1[0], - concurrent1_2: batch1[1], - concurrent1_3: batch1[2], - concurrent1_4: batch1[3], - concurrent1_5: batch1[4], - concurrent2_1: batch2[0], - concurrent2_2: batch2[1], - concurrent2_3: batch2[2], - concurrent2_4: batch2[3], - concurrent2_5: batch2[4], - concurrent3_1: batch3[0], - concurrent3_2: batch3[1], - concurrent3_3: batch3[2], - concurrent3_4: batch3[3], - concurrent3_5: batch3[4], - } -} - -export function createStreamPromise(): Promise { - return makeDeferred(streamPromiseValue, streamPromiseDelay) -} - -export function createChunkStream(): ReadableStream { - return new ReadableStream({ - async start(controller) { - for (const chunk of streamChunks) { - await delay(streamChunkDelay) - controller.enqueue(chunk) - } - controller.close() - }, - }) -} - -export function createRouterHtmlPayload() { - return makeDeferred( - { - value: routerHtmlPayloadChar.repeat(routerHtmlPayloadChars), - source: sourceMarker(), - }, - routerHtmlPayloadDelay, - ) -} diff --git a/e2e/streaming-ssr-specs/client-navigation.ts b/e2e/streaming-ssr-specs/client-navigation.ts deleted file mode 100644 index 759f8e0282..0000000000 --- a/e2e/streaming-ssr-specs/client-navigation.ts +++ /dev/null @@ -1,372 +0,0 @@ -import { expect, test, testWithHydration } from '../streaming-ssr-assertions' - -test.describe('Client-side navigation between all routes', () => { - test.beforeEach(async ({ page }) => { - // Start from home page - await page.goto('/') - await page.waitForLoadState('networkidle') - }) - - test('home -> sync-only -> home works', async ({ page }) => { - // Navigate to sync-only - await page - .getByRole('navigation') - .getByRole('link', { name: 'Sync Only' }) - .click() - await expect(page).toHaveURL('/sync-only') - await expect(page.getByTestId('sync-message')).toBeVisible() - - // Navigate back to home - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - await expect(page.getByTestId('index-title')).toBeVisible() - }) - - test('home -> deferred -> home works', async ({ page }) => { - // Navigate to deferred (use exact: true to avoid matching "Nested Deferred") - await page - .getByRole('navigation') - .getByRole('link', { name: 'Deferred', exact: true }) - .click() - await expect(page).toHaveURL('/deferred') - await expect(page.getByTestId('immediate-data')).toBeVisible() - - // Wait for deferred data - await expect(page.getByTestId('deferred-data')).toBeVisible({ - timeout: 5000, - }) - - // Navigate back to home - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - }) - - test('home -> stream -> home works (no stream locking error)', async ({ - page, - }) => { - // This test specifically validates the ReadableStream locking fix - // Console errors are monitored by the fixture automatically - - // Navigate to stream - await page - .getByRole('navigation') - .getByRole('link', { name: 'Stream' }) - .click() - await expect(page).toHaveURL('/stream') - - // Wait for stream to start (at least one chunk or promise resolved) - await expect(page.getByTestId('promise-data')).toBeVisible({ - timeout: 5000, - }) - - // Navigate back without waiting for stream completion. - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - }) - - test('home -> stream -> wait for completion -> home works', async ({ - page, - }) => { - // Navigate to stream - await page - .getByRole('navigation') - .getByRole('link', { name: 'Stream' }) - .click() - await expect(page).toHaveURL('/stream') - - // Wait for stream to complete - await expect(page.getByTestId('stream-complete')).toBeVisible({ - timeout: 10000, - }) - - // Navigate back to home - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - await expect(page.getByTestId('index-title')).toBeVisible() - }) - - test('home -> stream -> home -> stream again works (fresh stream each time)', async ({ - page, - }) => { - // Console errors are monitored by the fixture automatically - - // First navigation to stream - await page - .getByRole('navigation') - .getByRole('link', { name: 'Stream' }) - .click() - await expect(page).toHaveURL('/stream') - await expect(page.getByTestId('promise-data')).toBeVisible({ - timeout: 5000, - }) - - // Navigate back to home - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - - // Second navigation to stream - should get fresh stream without errors - await page - .getByRole('navigation') - .getByRole('link', { name: 'Stream' }) - .click() - await expect(page).toHaveURL('/stream') - - // Wait for stream to complete - await expect(page.getByTestId('stream-complete')).toBeVisible({ - timeout: 10000, - }) - - // Verify all chunks are present - await expect(page.getByTestId('stream-chunk-0')).toBeVisible() - await expect(page.getByTestId('stream-chunk-4')).toBeVisible() - }) - - test('home -> fast-serial -> home works', async ({ page }) => { - await page - .getByRole('navigation') - .getByRole('link', { name: 'Fast Serial' }) - .click() - await expect(page).toHaveURL('/fast-serial') - await expect(page.getByTestId('server-data')).toBeVisible() - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - }) - - test('home -> slow-render -> home works', async ({ page }) => { - await page - .getByRole('navigation') - .getByRole('link', { name: 'Slow Render' }) - .click() - await expect(page).toHaveURL('/slow-render') - await expect(page.getByTestId('quick-data')).toBeVisible() - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - }) - - test('home -> nested-deferred -> home works', async ({ page }) => { - await page - .getByRole('navigation') - .getByRole('link', { name: 'Nested Deferred' }) - .click() - await expect(page).toHaveURL('/nested-deferred') - - // Wait for all levels to load - await expect(page.getByTestId('level3-data')).toBeVisible({ timeout: 5000 }) - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - }) - - test('navigation without waiting for route data works', async ({ page }) => { - // Console errors are monitored by the fixture automatically - - // Change routes as soon as each URL updates, without waiting for route data. - await page - .getByRole('navigation') - .getByRole('link', { name: 'Sync Only' }) - .click() - await expect(page).toHaveURL('/sync-only') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Deferred', exact: true }) - .click() - await expect(page).toHaveURL('/deferred') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Stream' }) - .click() - await expect(page).toHaveURL('/stream') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Fast Serial' }) - .click() - await expect(page).toHaveURL('/fast-serial') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Slow Render' }) - .click() - await expect(page).toHaveURL('/slow-render') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Nested Deferred' }) - .click() - await expect(page).toHaveURL('/nested-deferred') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - }) -}) - -test.describe('Direct navigation followed by client navigation', () => { - test('direct to stream -> client nav to deferred works', async ({ page }) => { - // Direct navigation to stream - await page.goto('/stream') - await expect(page.getByTestId('promise-data')).toBeVisible({ - timeout: 5000, - }) - - // Client navigation to deferred (use exact: true) - await page - .getByRole('navigation') - .getByRole('link', { name: 'Deferred', exact: true }) - .click() - await expect(page).toHaveURL('/deferred') - await expect(page.getByTestId('immediate-data')).toBeVisible() - }) - - test('direct to deferred -> client nav to stream works', async ({ page }) => { - // Console errors are monitored by the fixture automatically - - // Direct navigation to deferred - await page.goto('/deferred') - await expect(page.getByTestId('immediate-data')).toBeVisible() - - // Client navigation to stream - await page - .getByRole('navigation') - .getByRole('link', { name: 'Stream' }) - .click() - await expect(page).toHaveURL('/stream') - await expect(page.getByTestId('stream-complete')).toBeVisible({ - timeout: 10000, - }) - }) - - test('direct to sync-only -> client nav to all routes works', async ({ - page, - }) => { - await page.goto('/sync-only') - await expect(page.getByTestId('sync-message')).toBeVisible() - - // Navigate through all routes - await page - .getByRole('navigation') - .getByRole('link', { name: 'Deferred', exact: true }) - .click() - await expect(page).toHaveURL('/deferred') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Stream' }) - .click() - await expect(page).toHaveURL('/stream') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Fast Serial' }) - .click() - await expect(page).toHaveURL('/fast-serial') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - }) -}) - -testWithHydration.describe('Hydration after client navigation', () => { - testWithHydration( - 'interactive elements work after navigating to deferred', - async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Deferred', exact: true }) - .click() - await expect(page).toHaveURL('/deferred') - - // Wait for the page to be fully loaded - await expect(page.getByTestId('immediate-data')).toBeVisible() - }, - ) - - testWithHydration( - 'interactive elements work after navigating to fast-serial', - async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Fast Serial' }) - .click() - await expect(page).toHaveURL('/fast-serial') - - // Wait for page to load - await expect(page.getByTestId('server-data')).toBeVisible() - }, - ) - - testWithHydration( - 'interactive elements work after navigating to nested-deferred', - async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Nested Deferred' }) - .click() - await expect(page).toHaveURL('/nested-deferred') - - // Wait for page to load - await expect(page.getByTestId('plain-deferred')).toBeVisible({ - timeout: 5000, - }) - }, - ) - - testWithHydration( - 'interactive elements work after navigating to slow-render', - async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Slow Render' }) - .click() - await expect(page).toHaveURL('/slow-render') - - // Wait for page to load (slow-render has blocking loops) - await expect(page.getByTestId('quick-data')).toBeVisible() - }, - ) -}) diff --git a/e2e/streaming-ssr-specs/concurrent.ts b/e2e/streaming-ssr-specs/concurrent.ts deleted file mode 100644 index ef14f80367..0000000000 --- a/e2e/streaming-ssr-specs/concurrent.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { expect, test, testWithHydration } from '../streaming-ssr-assertions' - -test.describe('Concurrent promise resolution (15 promises in 3 batches)', () => { - test('all concurrent promises resolve correctly', async ({ page }) => { - await page.goto('/concurrent') - - // Batch 1 (5 promises at 100ms) - await expect(page.getByTestId('concurrent-1-1')).toContainText( - 'concurrent-1', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-1-2')).toContainText( - 'concurrent-2', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-1-3')).toContainText( - 'concurrent-3', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-1-4')).toContainText( - 'concurrent-4', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-1-5')).toContainText( - 'concurrent-5', - { timeout: 5000 }, - ) - - // Batch 2 (5 promises at 200ms) - await expect(page.getByTestId('concurrent-2-1')).toContainText( - 'concurrent-1', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-2-2')).toContainText( - 'concurrent-2', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-2-3')).toContainText( - 'concurrent-3', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-2-4')).toContainText( - 'concurrent-4', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-2-5')).toContainText( - 'concurrent-5', - { timeout: 5000 }, - ) - - // Batch 3 (5 promises at 300ms) - await expect(page.getByTestId('concurrent-3-1')).toContainText( - 'concurrent-1', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-3-2')).toContainText( - 'concurrent-2', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-3-3')).toContainText( - 'concurrent-3', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-3-4')).toContainText( - 'concurrent-4', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-3-5')).toContainText( - 'concurrent-5', - { timeout: 5000 }, - ) - }) - - testWithHydration( - 'hydration works with concurrent resolutions', - async ({ page }) => { - await page.goto('/concurrent') - await page.waitForLoadState('networkidle') - - // Wait for all batches - await expect(page.getByTestId('concurrent-3-5')).toBeVisible({ - timeout: 5000, - }) - }, - ) -}) diff --git a/e2e/streaming-ssr-specs/deferred-rejection.ts b/e2e/streaming-ssr-specs/deferred-rejection.ts deleted file mode 100644 index 3e944b1c0c..0000000000 --- a/e2e/streaming-ssr-specs/deferred-rejection.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { expect, test } from '../streaming-ssr-assertions' - -test.use({ - whitelistErrors: ['Error in deferred object'], -}) - -test('rejected deferred Await renders the route error boundary without killing SSR', async ({ - page, -}) => { - await page.goto('/deferred-rejection') - - await expect(page.getByTestId('deferred-error-boundary')).toContainText( - 'Error in deferred object', - { timeout: 5000 }, - ) - - await page.goto('/sync-only') - await expect(page.getByTestId('sync-message')).toContainText( - 'Hello from sync loader!', - ) -}) diff --git a/e2e/streaming-ssr-specs/deferred.ts b/e2e/streaming-ssr-specs/deferred.ts deleted file mode 100644 index abece0b43e..0000000000 --- a/e2e/streaming-ssr-specs/deferred.ts +++ /dev/null @@ -1,113 +0,0 @@ -import { - expect, - expectDeferredRouteResponseOrder, - test, - testWithHydration, -} from '../streaming-ssr-assertions' - -test.describe('Deferred data streaming', () => { - test('finishes the router stream after renderer output', async ({ - baseURL, - }) => { - await expectDeferredRouteResponseOrder(baseURL) - }) - - test('renders immediate and deferred server data', async ({ page }) => { - await page.goto('/deferred') - - // Immediate loader data is rendered. - await expect(page.getByTestId('immediate-data')).toBeVisible() - await expect(page.getByTestId('immediate-data')).toContainText( - 'Immediate: Fast User', - ) - - // Verify immediate data came from server - await expect(page.getByTestId('immediate-source')).toContainText( - 'Immediate source: server', - ) - await expect(page.getByTestId('loader-source')).toContainText( - 'Loader source: server', - ) - - // Deferred data should eventually appear with server source - await expect(page.getByTestId('deferred-data')).toContainText( - 'Deferred data loaded!', - { timeout: 5000 }, - ) - await expect(page.getByTestId('deferred-data')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - await expect(page.getByTestId('deferred-server-data')).toContainText( - 'Server: Slow User', - { timeout: 5000 }, - ) - await expect(page.getByTestId('deferred-server-data')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - }) - - testWithHydration( - 'hydration works - interactive elements respond', - async ({ page }) => { - await page.goto('/deferred') - await page.waitForLoadState('networkidle') - - // Wait for all deferred content to load - await expect(page.getByTestId('deferred-data')).toBeVisible({ - timeout: 5000, - }) - - // Verify all data came from server after hydration - await expect(page.getByTestId('loader-source')).toContainText( - 'Loader source: server', - ) - await expect(page.getByTestId('deferred-data')).toContainText( - 'source: server', - ) - }, - ) - - test('client-side navigation to deferred route works', async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - // Navigate via client-side routing using nav link - await page.getByRole('link', { name: 'Deferred' }).first().click() - await expect(page).toHaveURL('/deferred') - - // Data should load - await expect(page.getByTestId('immediate-data')).toContainText('Fast User') - await expect(page.getByTestId('deferred-data')).toContainText( - 'Deferred data loaded!', - { timeout: 5000 }, - ) - }) - - test('all data sources are server', async ({ page }) => { - await page.goto('/deferred') - - // Wait for all deferred content - await expect(page.getByTestId('deferred-data')).toBeVisible({ - timeout: 5000, - }) - await expect(page.getByTestId('deferred-server-data')).toBeVisible({ - timeout: 5000, - }) - - // Count all elements showing 'server' source - should be 4: - // 1. immediate-source - // 2. loader-source - // 3. deferred-data (contains "source: server") - // 4. deferred-server-data (contains "source: server") - await expect(page.getByTestId('immediate-source')).toContainText('server') - await expect(page.getByTestId('loader-source')).toContainText('server') - await expect(page.getByTestId('deferred-data')).toContainText( - 'source: server', - ) - await expect(page.getByTestId('deferred-server-data')).toContainText( - 'source: server', - ) - }) -}) diff --git a/e2e/streaming-ssr-specs/fast-serial.ts b/e2e/streaming-ssr-specs/fast-serial.ts deleted file mode 100644 index 03201f0a55..0000000000 --- a/e2e/streaming-ssr-specs/fast-serial.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { - expect, - expectRouterHydrationMarkers, - test, - testWithHydration, -} from '../streaming-ssr-assertions' - -test.describe('Fast serialization (serialization completes before render)', () => { - test('initial HTML contains router bootstrap + barrier', async ({ page }) => { - let responseHtml = '' - await page.route('/fast-serial', async (route) => { - const response = await route.fetch() - responseHtml = await response.text() - await route.fulfill({ response }) - }) - - await page.goto('/fast-serial') - await expect(page.getByTestId('server-data')).toBeVisible() - - expectRouterHydrationMarkers(responseHtml) - }) - - test('renders all server data', async ({ page }) => { - await page.goto('/fast-serial') - await page.waitForLoadState('networkidle') - - // All data should be visible - await expect(page.getByTestId('server-data')).toContainText('small-data') - await expect(page.getByTestId('static-data')).toContainText( - 'This is static data', - ) - await expect(page.getByTestId('loader-timestamp')).toBeVisible() - - // Verify the loader and server function ran during SSR. - await expect(page.getByTestId('loader-source')).toContainText( - 'Loader source: server', - ) - await expect(page.getByTestId('server-fn-source')).toContainText( - 'Server function source: server', - ) - }) - - testWithHydration('hydration works correctly', async ({ page }) => { - await page.goto('/fast-serial') - await page.waitForLoadState('networkidle') - - // Verify data came from server after hydration - await expect(page.getByTestId('loader-source')).toContainText( - 'Loader source: server', - ) - }) - - test('direct navigation renders correctly', async ({ page }) => { - // Direct navigation (SSR) - await page.goto('/fast-serial') - - // Should render without errors and show server source - await expect(page.getByTestId('server-data')).toBeVisible() - await expect(page.getByTestId('loader-source')).toContainText( - 'Loader source: server', - ) - }) - - test('client-side navigation works', async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - // Navigate via nav link - await page.getByRole('link', { name: 'Fast Serial' }).first().click() - await expect(page).toHaveURL('/fast-serial') - - await expect(page.getByTestId('server-data')).toContainText('small-data') - }) -}) diff --git a/e2e/streaming-ssr-specs/home.ts b/e2e/streaming-ssr-specs/home.ts deleted file mode 100644 index d85e19bfa7..0000000000 --- a/e2e/streaming-ssr-specs/home.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { expect, test, testWithHydration } from '../streaming-ssr-assertions' - -test.describe('Home page', () => { - testWithHydration( - 'renders index page with all navigation links', - async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - await expect(page.getByTestId('index-title')).toContainText( - 'Streaming SSR Test Scenarios', - ) - // Check links exist (they're in the nav and the body) - await expect( - page.getByRole('link', { name: 'Deferred' }).first(), - ).toBeVisible() - await expect( - page.getByRole('link', { name: 'Stream' }).first(), - ).toBeVisible() - }, - ) - - testWithHydration( - 'navigation from home to routes works', - async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - // Use the link in the content (not nav) - await page.getByTestId('link-deferred').click() - await expect(page).toHaveURL('/deferred') - }, - ) -}) diff --git a/e2e/streaming-ssr-specs/many-promises.ts b/e2e/streaming-ssr-specs/many-promises.ts deleted file mode 100644 index 768859c7e4..0000000000 --- a/e2e/streaming-ssr-specs/many-promises.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { expect, test, testWithHydration } from '../streaming-ssr-assertions' - -test.describe('Many promises streaming (15 deferred)', () => { - test('all 15 promises eventually resolve', async ({ page }) => { - await page.goto('/many-promises') - - // Immediate group (0-20ms) - await expect(page.getByTestId('immediate-1')).toContainText('immediate-1', { - timeout: 5000, - }) - await expect(page.getByTestId('immediate-2')).toContainText('immediate-2', { - timeout: 5000, - }) - await expect(page.getByTestId('immediate-3')).toContainText('immediate-3', { - timeout: 5000, - }) - - // Fast group (50-125ms) - await expect(page.getByTestId('fast-1')).toContainText('fast-1', { - timeout: 5000, - }) - await expect(page.getByTestId('fast-2')).toContainText('fast-2', { - timeout: 5000, - }) - await expect(page.getByTestId('fast-3')).toContainText('fast-3', { - timeout: 5000, - }) - await expect(page.getByTestId('fast-4')).toContainText('fast-4', { - timeout: 5000, - }) - - // Medium group (150-250ms) - await expect(page.getByTestId('medium-1')).toContainText('medium-1', { - timeout: 5000, - }) - await expect(page.getByTestId('medium-2')).toContainText('medium-2', { - timeout: 5000, - }) - await expect(page.getByTestId('medium-3')).toContainText('medium-3', { - timeout: 5000, - }) - - // Slow group (300-500ms) - await expect(page.getByTestId('slow-1')).toContainText('slow-1', { - timeout: 5000, - }) - await expect(page.getByTestId('slow-2')).toContainText('slow-2', { - timeout: 5000, - }) - await expect(page.getByTestId('slow-3')).toContainText('slow-3', { - timeout: 5000, - }) - - // Very slow group (600-800ms) - await expect(page.getByTestId('very-slow-1')).toContainText('very-slow-1', { - timeout: 5000, - }) - await expect(page.getByTestId('very-slow-2')).toContainText('very-slow-2', { - timeout: 5000, - }) - }) - - testWithHydration('hydration works with many promises', async ({ page }) => { - await page.goto('/many-promises') - await page.waitForLoadState('networkidle') - - // Wait for all promises to resolve - await expect(page.getByTestId('very-slow-2')).toBeVisible({ timeout: 5000 }) - }) - - test('client-side navigation works', async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - // Navigate via nav link - await page.getByRole('link', { name: 'Many Promises' }).click() - await expect(page).toHaveURL('/many-promises') - - // All promises should eventually resolve - await expect(page.getByTestId('very-slow-2')).toBeVisible({ timeout: 5000 }) - }) -}) diff --git a/e2e/streaming-ssr-specs/nested-deferred.ts b/e2e/streaming-ssr-specs/nested-deferred.ts deleted file mode 100644 index 0146a23162..0000000000 --- a/e2e/streaming-ssr-specs/nested-deferred.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { expect, test, testWithHydration } from '../streaming-ssr-assertions' - -test.describe('Nested deferred (multiple levels of deferred data)', () => { - test('all levels of deferred data eventually resolve', async ({ page }) => { - await page.goto('/nested-deferred') - - // All deferred values should eventually resolve. - await expect(page.getByTestId('plain-deferred')).toContainText( - 'Plain deferred resolved!', - { timeout: 5000 }, - ) - - await expect(page.getByTestId('level1-data')).toContainText('Level 1:', { - timeout: 5000, - }) - - await expect(page.getByTestId('level2-data')).toContainText('Level 2:', { - timeout: 5000, - }) - - await expect(page.getByTestId('level3-data')).toContainText('Level 3:', { - timeout: 5000, - }) - }) - - testWithHydration( - 'hydration works with nested deferred', - async ({ page }) => { - await page.goto('/nested-deferred') - await page.waitForLoadState('networkidle') - - // Wait for all data - await expect(page.getByTestId('level3-data')).toBeVisible({ - timeout: 10000, - }) - }, - ) - - test('client-side navigation works', async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - // Navigate via nav link - await page.getByRole('link', { name: 'Nested Deferred' }).first().click() - await expect(page).toHaveURL('/nested-deferred') - - // All levels should eventually render - await expect(page.getByTestId('level3-data')).toBeVisible({ - timeout: 10000, - }) - }) -}) diff --git a/e2e/streaming-ssr-specs/preview-streaming.ts b/e2e/streaming-ssr-specs/preview-streaming.ts deleted file mode 100644 index 5087dff730..0000000000 --- a/e2e/streaming-ssr-specs/preview-streaming.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { - expectDeferredRouteResponseOrder, - test, -} from '../streaming-ssr-assertions' - -test.skip( - process.env.MODE !== 'preview', - 'Only runs against vite preview: pnpm test:e2e:preview', -) - -test('vite preview preserves deferred HTML order', async ({ baseURL }) => { - await expectDeferredRouteResponseOrder(baseURL) -}) diff --git a/e2e/streaming-ssr-specs/query-heavy.ts b/e2e/streaming-ssr-specs/query-heavy.ts deleted file mode 100644 index b33a64f366..0000000000 --- a/e2e/streaming-ssr-specs/query-heavy.ts +++ /dev/null @@ -1,142 +0,0 @@ -import { - expect, - expectQueryHeavyRouteStreamOrder, - test, - testWithHydration, -} from '../streaming-ssr-assertions' - -test.describe('Query heavy route (9 queries)', () => { - test('emits the complete router stream before document closes', async ({ - baseURL, - }) => { - await expectQueryHeavyRouteStreamOrder(baseURL) - }) - - test('all queries resolve with server data', async ({ page }) => { - await page.goto('/query-heavy') - - // Sync queries should show server source - await expect(page.getByTestId('sync-query-1')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - await expect(page.getByTestId('sync-query-2')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - await expect(page.getByTestId('sync-query-3')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - - // Fast async queries should show server source - await expect(page.getByTestId('fast-async-query-1')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - await expect(page.getByTestId('fast-async-query-2')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - await expect(page.getByTestId('fast-async-query-3')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - - // Slow async queries should show server source - await expect(page.getByTestId('slow-async-query-1')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - await expect(page.getByTestId('slow-async-query-2')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - await expect(page.getByTestId('slow-async-query-3')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - }) - - test('sync queries have correct values', async ({ page }) => { - await page.goto('/query-heavy') - - await expect(page.getByTestId('sync-query-1')).toContainText('sync-value-1') - await expect(page.getByTestId('sync-query-2')).toContainText('sync-value-2') - await expect(page.getByTestId('sync-query-3')).toContainText('sync-value-3') - }) - - test('async queries have correct values', async ({ page }) => { - await page.goto('/query-heavy') - - await expect(page.getByTestId('fast-async-query-1')).toContainText( - 'fast-async-1', - { timeout: 5000 }, - ) - await expect(page.getByTestId('fast-async-query-2')).toContainText( - 'fast-async-2', - { timeout: 5000 }, - ) - await expect(page.getByTestId('fast-async-query-3')).toContainText( - 'fast-async-3', - { timeout: 5000 }, - ) - - await expect(page.getByTestId('slow-async-query-1')).toContainText( - 'slow-async-1', - { timeout: 5000 }, - ) - await expect(page.getByTestId('slow-async-query-2')).toContainText( - 'slow-async-2', - { timeout: 5000 }, - ) - await expect(page.getByTestId('slow-async-query-3')).toContainText( - 'slow-async-3', - { timeout: 5000 }, - ) - }) - - testWithHydration('hydration works with many queries', async ({ page }) => { - await page.goto('/query-heavy') - await page.waitForLoadState('networkidle') - - // Wait for all queries to resolve - await expect(page.getByTestId('slow-async-query-3')).toBeVisible({ - timeout: 5000, - }) - }) - - test('client-side navigation works', async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - // Navigate via nav link - await page.getByRole('link', { name: 'Query Heavy' }).click() - await expect(page).toHaveURL('/query-heavy') - - // All queries should eventually resolve (on client) - await expect(page.getByTestId('slow-async-query-3')).toBeVisible({ - timeout: 5000, - }) - }) - - test('server query data hydrates without client refetch', async ({ - page, - }) => { - // If hydration missed the server data, these queries would re-execute on - // the client and show "client" as their source. - await page.goto('/query-heavy') - - // Wait for all queries - await expect(page.getByTestId('slow-async-query-3')).toBeVisible({ - timeout: 5000, - }) - - // Verify that all server results hydrated without a client refetch. - const serverSourceCount = await page - .locator('[data-testid*="query-"]') - .filter({ hasText: 'source: server' }) - .count() - expect(serverSourceCount).toBe(9) - }) -}) diff --git a/e2e/streaming-ssr-specs/slow-render.ts b/e2e/streaming-ssr-specs/slow-render.ts deleted file mode 100644 index 117559701e..0000000000 --- a/e2e/streaming-ssr-specs/slow-render.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { expect, test, testWithHydration } from '../streaming-ssr-assertions' - -test.describe('Slow render (render takes longer than serialization)', () => { - test('all data eventually renders with server source', async ({ page }) => { - await page.goto('/slow-render') - await page.waitForLoadState('networkidle') - - // Quick data should be available with server source - await expect(page.getByTestId('quick-data')).toContainText('Quick:') - await expect(page.getByTestId('quick-source')).toContainText( - 'Quick data source: server', - ) - await expect(page.getByTestId('loader-source')).toContainText( - 'Loader source: server', - ) - - // Deferred data should resolve with server source - await expect(page.getByTestId('deferred-resolved')).toContainText( - 'Deferred resolved!', - { timeout: 5000 }, - ) - await expect(page.getByTestId('deferred-resolved')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - - // Slow components should have rendered - await expect(page.getByTestId('slow-component-1')).toBeVisible() - await expect(page.getByTestId('slow-component-2')).toBeVisible() - await expect(page.getByTestId('slow-component-3')).toBeVisible() - }) - - testWithHydration('hydration works after slow render', async ({ page }) => { - await page.goto('/slow-render') - await page.waitForLoadState('networkidle') - - // Wait for content and verify server source - await expect(page.getByTestId('slow-component-1')).toBeVisible() - await expect(page.getByTestId('loader-source')).toContainText( - 'Loader source: server', - ) - }) - - test('client-side navigation works', async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - // Navigate via nav link - await page.getByRole('link', { name: 'Slow Render' }).first().click() - await expect(page).toHaveURL('/slow-render') - - await expect(page.getByTestId('quick-data')).toBeVisible({ timeout: 10000 }) - }) - - test('all data sources are server', async ({ page }) => { - await page.goto('/slow-render') - await page.waitForLoadState('networkidle') - - // Wait for deferred content - await expect(page.getByTestId('deferred-resolved')).toBeVisible({ - timeout: 5000, - }) - - // Verify all sources are server - await expect(page.getByTestId('quick-source')).toContainText('server') - await expect(page.getByTestId('loader-source')).toContainText('server') - await expect(page.getByTestId('deferred-resolved')).toContainText( - 'source: server', - ) - }) -}) diff --git a/e2e/streaming-ssr-specs/stream.ts b/e2e/streaming-ssr-specs/stream.ts deleted file mode 100644 index ee61f170de..0000000000 --- a/e2e/streaming-ssr-specs/stream.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { expect, test, testWithHydration } from '../streaming-ssr-assertions' - -const expectedStreamChunks = [ - 'chunk-0', - 'chunk-1', - 'chunk-2', - 'chunk-3', - 'chunk-4', -] - -test.describe('ReadableStream deserialization', () => { - testWithHydration('promise data deserializes correctly', async ({ page }) => { - await page.goto('/stream') - - await expect(page.getByTestId('promise-data')).toContainText( - 'promise-resolved', - { timeout: 5000 }, - ) - }) - - testWithHydration( - 'stream chunks deserialize in source order', - async ({ page }) => { - await page.goto('/stream') - - await expect(page.getByTestId('stream-complete')).toBeVisible({ - timeout: 10000, - }) - - const chunks = page - .getByTestId('stream-data') - .locator('[data-testid^="stream-chunk-"]') - await expect(chunks).toHaveText(expectedStreamChunks) - - // This browser assertion covers deserialization and source order. The - // raw `/deferred` assertion covers server-response and router ordering. - }, - ) - - testWithHydration( - 'client-side navigation to stream route works', - async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - // Navigate via nav link - await page.getByRole('link', { name: 'Stream' }).first().click() - await expect(page).toHaveURL('/stream') - - await expect(page.getByTestId('stream-complete')).toBeVisible({ - timeout: 10000, - }) - }, - ) -}) diff --git a/e2e/streaming-ssr-specs/sync-only.ts b/e2e/streaming-ssr-specs/sync-only.ts deleted file mode 100644 index 9850265109..0000000000 --- a/e2e/streaming-ssr-specs/sync-only.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { - expect, - expectRouterHydrationMarkers, - test, - testWithHydration, -} from '../streaming-ssr-assertions' - -/** - * Tests for synchronous serialization - no deferred data, no streaming. - * This is the most common case where all loader data is immediately available. - * The hydration scripts should be included in the initial HTML response. - */ - -test('Sync-only route renders with loader data', async ({ page }) => { - await page.goto('/sync-only') - - // Verify the page content is rendered - await expect(page.getByTestId('sync-title')).toContainText( - 'Synchronous Serialization Test', - ) - await expect(page.getByTestId('sync-message')).toContainText( - 'Hello from sync loader!', - ) - - // Verify loader data items are rendered - await expect(page.getByTestId('sync-item-item-1')).toBeVisible() - await expect(page.getByTestId('sync-item-item-2')).toBeVisible() - await expect(page.getByTestId('sync-item-item-3')).toBeVisible() - - // Verify the loader ran during SSR. - await expect(page.getByTestId('sync-source')).toContainText('Source: server') -}) - -testWithHydration('Sync-only route hydrates correctly', async ({ page }) => { - await page.goto('/sync-only') - - // Verify client-side navigation works (proves hydration succeeded) - await page.getByRole('navigation').getByRole('link', { name: 'Home' }).click() - await expect(page.getByTestId('index-title')).toBeVisible() - - // Navigate back to sync-only via client-side navigation (use nav link to be specific) - await page - .getByRole('navigation') - .getByRole('link', { name: 'Sync Only' }) - .click() - await expect(page.getByTestId('sync-title')).toBeVisible() -}) - -test('Sync-only route has bootstrap scripts in initial HTML', async ({ - page, -}) => { - // Intercept the response to check the raw HTML - let responseHtml = '' - await page.route('/sync-only', async (route) => { - const response = await route.fetch() - responseHtml = await response.text() - await route.fulfill({ response }) - }) - - await page.goto('/sync-only') - - // Wait for page to load - await expect(page.getByTestId('sync-title')).toBeVisible() - - // Bootstrap, end record, and the boundary rendered by . - expectRouterHydrationMarkers(responseHtml) -}) - -test('Navigating to sync-only from home page', async ({ page }) => { - await page.goto('/') - - await page.getByTestId('link-sync-only').click() - - await expect(page.getByTestId('sync-title')).toContainText( - 'Synchronous Serialization Test', - ) - await expect(page.getByTestId('sync-message')).toContainText( - 'Hello from sync loader!', - ) -}) diff --git a/e2e/vue-router/basepath-file-based/package.json b/e2e/vue-router/basepath-file-based/package.json index 3af9176e83..f39c09dda9 100644 --- a/e2e/vue-router/basepath-file-based/package.json +++ b/e2e/vue-router/basepath-file-based/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/vue-router/basepath-file-based/playwright.config.ts b/e2e/vue-router/basepath-file-based/playwright.config.ts index 4eead86444..6069bbe59f 100644 --- a/e2e/vue-router/basepath-file-based/playwright.config.ts +++ b/e2e/vue-router/basepath-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/basepath-file-based/tests/setup/global.setup.ts b/e2e/vue-router/basepath-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basepath-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basepath-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/basepath-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basepath-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-esbuild-file-based/package.json b/e2e/vue-router/basic-esbuild-file-based/package.json index a51cf9149c..7eec606557 100644 --- a/e2e/vue-router/basic-esbuild-file-based/package.json +++ b/e2e/vue-router/basic-esbuild-file-based/package.json @@ -7,7 +7,7 @@ "build": "node src/esbuild.run.js build && vue-tsc --noEmit", "preview": "node src/esbuild.run.js preview", "start": "pnpm dev", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/router-plugin": "workspace:^", diff --git a/e2e/vue-router/basic-esbuild-file-based/playwright.config.ts b/e2e/vue-router/basic-esbuild-file-based/playwright.config.ts index 9d9c8d49a3..836ea41bd8 100644 --- a/e2e/vue-router/basic-esbuild-file-based/playwright.config.ts +++ b/e2e/vue-router/basic-esbuild-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-esbuild-file-based/src/esbuild.config.js b/e2e/vue-router/basic-esbuild-file-based/src/esbuild.config.js index 16f6fbca44..c4aba8798e 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/esbuild.config.js +++ b/e2e/vue-router/basic-esbuild-file-based/src/esbuild.config.js @@ -9,6 +9,7 @@ export default { }), tanstackRouter({ target: 'vue', + autoCodeSplitting: true, }), ], } diff --git a/e2e/vue-router/basic-esbuild-file-based/src/esbuild.run.js b/e2e/vue-router/basic-esbuild-file-based/src/esbuild.run.js index 0ab294f2bf..19e882c1a9 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/esbuild.run.js +++ b/e2e/vue-router/basic-esbuild-file-based/src/esbuild.run.js @@ -1,7 +1,8 @@ -import http from 'node:http' -import { createReadStream, promises as fs } from 'node:fs' -import path from 'node:path' import * as esbuild from 'esbuild' +import http from 'node:http' +import { createReadStream } from 'node:fs' +import { promises as fs } from 'node:fs' +import path from 'node:path' import esbuildConfig from './esbuild.config.js' const args = process.argv.slice(2) @@ -17,7 +18,7 @@ function getPort() { const fromArg = getArgValue('--port') const fromEnv = process.env.VITE_SERVER_PORT const port = Number(fromArg ?? fromEnv ?? 5601) - if (!Number.isFinite(port) || port < 0) { + if (!Number.isFinite(port) || port <= 0) { throw new Error(`Invalid port: ${String(fromArg ?? fromEnv)}`) } return port @@ -137,7 +138,7 @@ function startStaticServer({ port }) { return new Promise((resolve) => { server.listen(port, () => { - console.log(`E2E app: http://localhost:${server.address().port}`) + console.log(`http://localhost:${port}`) resolve(server) }) }) diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/(another-group)/onlyrouteinside.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/(another-group)/onlyrouteinside.tsx index 8869cefc01..727c1b4d94 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/(another-group)/onlyrouteinside.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/(another-group)/onlyrouteinside.tsx @@ -1,32 +1,27 @@ -import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' -const OnlyRouteInsideComponent = defineComponent({ - setup() { - const searchViaHook = useSearch({ - from: '/(another-group)/onlyrouteinside', - }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return () => ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) - export const Route = createFileRoute('/(another-group)/onlyrouteinside')({ validateSearch: z.object({ hello: z.string().optional() }), component: OnlyRouteInsideComponent, }) const routeApi = getRouteApi('/(another-group)/onlyrouteinside') + +function OnlyRouteInsideComponent() { + const searchViaHook = useSearch({ from: '/(another-group)/onlyrouteinside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) +} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/_layout.insidelayout.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/_layout.insidelayout.tsx index f2998803fd..4b239f3ef4 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/_layout.insidelayout.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/_layout.insidelayout.tsx @@ -1,30 +1,27 @@ -import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' -const InsideLayoutComponent = defineComponent({ - setup() { - const searchViaHook = useSearch({ from: '/(group)/_layout/insidelayout' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return () => ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) - export const Route = createFileRoute('/(group)/_layout/insidelayout')({ validateSearch: z.object({ hello: z.string().optional() }), component: InsideLayoutComponent, }) const routeApi = getRouteApi('/(group)/_layout/insidelayout') + +function InsideLayoutComponent() { + const searchViaHook = useSearch({ from: '/(group)/_layout/insidelayout' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) +} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/inside.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/inside.tsx index 20e0d5afdb..f12ca517d3 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/inside.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/inside.tsx @@ -1,30 +1,27 @@ -import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' -const InsideComponent = defineComponent({ - setup() { - const searchViaHook = useSearch({ from: '/(group)/inside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return () => ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) - export const Route = createFileRoute('/(group)/inside')({ validateSearch: z.object({ hello: z.string().optional() }), component: InsideComponent, }) const routeApi = getRouteApi('/(group)/inside') + +function InsideComponent() { + const searchViaHook = useSearch({ from: '/(group)/inside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) +} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/lazyinside.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/lazyinside.tsx index a46da658d6..05b34eb201 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/lazyinside.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/lazyinside.tsx @@ -1,30 +1,27 @@ -import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' -const LazyInsideComponent = defineComponent({ - setup() { - const searchViaHook = useSearch({ from: '/(group)/lazyinside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return () => ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) - export const Route = createFileRoute('/(group)/lazyinside')({ validateSearch: z.object({ hello: z.string().optional() }), component: LazyInsideComponent, }) const routeApi = getRouteApi('/(group)/lazyinside') + +function LazyInsideComponent() { + const searchViaHook = useSearch({ from: '/(group)/lazyinside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) +} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/subfolder/inside.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/subfolder/inside.tsx index 715d2cc972..317c766186 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/subfolder/inside.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/subfolder/inside.tsx @@ -1,30 +1,27 @@ -import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' -const SubfolderInsideComponent = defineComponent({ - setup() { - const searchViaHook = useSearch({ from: '/(group)/subfolder/inside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return () => ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) - export const Route = createFileRoute('/(group)/subfolder/inside')({ validateSearch: z.object({ hello: z.string().optional() }), component: SubfolderInsideComponent, }) const routeApi = getRouteApi('/(group)/subfolder/inside') + +function SubfolderInsideComponent() { + const searchViaHook = useSearch({ from: '/(group)/subfolder/inside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) +} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/__root.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/__root.tsx index 62c4af3aa4..59c9e6fa48 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/__root.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/__root.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { HeadContent, Link, @@ -11,97 +10,95 @@ import { import { TanStackRouterDevtools } from '@tanstack/vue-router-devtools' import NotFoundComponent from '../components/NotFoundComponent.vue' -const RootComponent = defineComponent({ - setup() { - const router = useRouter() - const canGoBack = useCanGoBack() - // test useRouterState doesn't crash client side navigation - const _state = useRouterState() - - return () => ( - <> - -
- - - Home - - - Posts - - - Layout - - - Only Route Inside Group - - - Inside Group - - - Inside Subfolder Inside Group - - - Inside Group Inside Layout - - - Lazy Inside Group - - - unicode path - - - This Route Does Not Exist - -
-
- - - - ) - }, -}) - export const Route = createRootRoute({ component: RootComponent, notFoundComponent: NotFoundComponent, }) + +function RootComponent() { + const router = useRouter() + const canGoBack = useCanGoBack() + // test useRouterState doesn't crash client side navigation + const _state = useRouterState() + + return ( + <> + +
+ + + Home + + + Posts + + + Layout + + + Only Route Inside Group + + + Inside Group + + + Inside Subfolder Inside Group + + + Inside Group Inside Layout + + + Lazy Inside Group + + + unicode path + + + This Route Does Not Exist + +
+
+ + + + ) +} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/posts.$postId.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/posts.$postId.tsx index 54ae789c8e..15d17387c8 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/posts.$postId.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/posts.$postId.tsx @@ -1,27 +1,24 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import PostErrorComponent from '../components/PostErrorComponent.vue' import { fetchPost } from '../posts' import type { PostType } from '../posts' -const PostComponent = defineComponent({ - setup() { - const post = Route.useLoaderData() - - return () => ( -
-

- {(post.value as PostType).title} -

-
{(post.value as PostType).body}
-
- ) - }, -}) - export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost(postId), component: PostComponent, errorComponent: PostErrorComponent, notFoundComponent: () =>

Post not found

, }) + +function PostComponent() { + const post = Route.useLoaderData() + + return ( +
+

+ {(post.value as PostType).title} +

+
{(post.value as PostType).body}
+
+ ) +} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/posts.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/posts.tsx index e0afd27b4c..ae580dfc02 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/posts.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/posts.tsx @@ -1,38 +1,7 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../posts' import type { PostType } from '../posts' -const PostsComponent = defineComponent({ - setup() { - const posts = Route.useLoaderData() - - return () => ( -
-
    - {[ - ...(posts.value as Array), - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ))} -
-
- -
- ) - }, -}) - export const Route = createFileRoute('/posts')({ head: () => ({ meta: [ @@ -44,3 +13,31 @@ export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) + +function PostsComponent() { + const posts = Route.useLoaderData() + + return ( +
+
    + {[ + ...(posts.value as Array), + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ))} +
+
+ +
+ ) +} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/posts_.$postId.edit.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/posts_.$postId.edit.tsx index 22979c93c9..57963c6b64 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/posts_.$postId.edit.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/posts_.$postId.edit.tsx @@ -1,28 +1,23 @@ -import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useParams } from '@tanstack/vue-router' -const PostEditComponent = defineComponent({ - setup() { - const paramsViaApi = api.useParams() - const paramsViaHook = useParams({ from: '/posts_/$postId/edit' }) - const paramsViaRouteHook = api.useParams() - - return () => ( -
-
{paramsViaHook.value.postId}
-
- {paramsViaRouteHook.value.postId} -
-
- {paramsViaApi.value.postId} -
-
- ) - }, -}) - export const Route = createFileRoute('/posts_/$postId/edit')({ component: PostEditComponent, }) const api = getRouteApi('/posts_/$postId/edit') + +function PostEditComponent() { + const paramsViaApi = api.useParams() + const paramsViaHook = useParams({ from: '/posts_/$postId/edit' }) + const paramsViaRouteHook = api.useParams() + + return ( +
+
{paramsViaHook.value.postId}
+
+ {paramsViaRouteHook.value.postId} +
+
{paramsViaApi.value.postId}
+
+ ) +} diff --git a/e2e/vue-router/basic-esbuild-file-based/tests/app.spec.ts b/e2e/vue-router/basic-esbuild-file-based/tests/app.spec.ts index 7380859e7b..543746d64d 100644 --- a/e2e/vue-router/basic-esbuild-file-based/tests/app.spec.ts +++ b/e2e/vue-router/basic-esbuild-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import type { Page } from '@playwright/test' test.beforeEach(async ({ page }) => { diff --git a/e2e/vue-router/basic-esbuild-file-based/tests/setup/global.setup.ts b/e2e/vue-router/basic-esbuild-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basic-esbuild-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-esbuild-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/basic-esbuild-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basic-esbuild-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-file-based-jsx/package.json b/e2e/vue-router/basic-file-based-jsx/package.json index 9ab7f21e82..0cdca0cd87 100644 --- a/e2e/vue-router/basic-file-based-jsx/package.json +++ b/e2e/vue-router/basic-file-based-jsx/package.json @@ -8,7 +8,7 @@ "build": "vite build && vue-tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/vue-router/basic-file-based-jsx/playwright.config.ts b/e2e/vue-router/basic-file-based-jsx/playwright.config.ts index 4eead86444..836ea41bd8 100644 --- a/e2e/vue-router/basic-file-based-jsx/playwright.config.ts +++ b/e2e/vue-router/basic-file-based-jsx/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-file-based-jsx/src/posts.tsx b/e2e/vue-router/basic-file-based-jsx/src/posts.tsx index f7a1941605..1b4c92b41d 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/posts.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/basic-file-based-jsx/src/routeTree.gen.ts b/e2e/vue-router/basic-file-based-jsx/src/routeTree.gen.ts index 5922c5f7b1..3922025c82 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routeTree.gen.ts +++ b/e2e/vue-router/basic-file-based-jsx/src/routeTree.gen.ts @@ -364,7 +364,7 @@ declare module '@tanstack/vue-router' { '/(group)/_layout': { id: '/(group)/_layout' path: '' - fullPath: '/' + fullPath: '' preLoaderRoute: typeof groupLayoutRouteImport parentRoute: typeof rootRouteImport } diff --git a/e2e/vue-router/basic-file-based-jsx/src/routes/(another-group)/onlyrouteinside.tsx b/e2e/vue-router/basic-file-based-jsx/src/routes/(another-group)/onlyrouteinside.tsx index 8869cefc01..727c1b4d94 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routes/(another-group)/onlyrouteinside.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/routes/(another-group)/onlyrouteinside.tsx @@ -1,32 +1,27 @@ -import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' -const OnlyRouteInsideComponent = defineComponent({ - setup() { - const searchViaHook = useSearch({ - from: '/(another-group)/onlyrouteinside', - }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return () => ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) - export const Route = createFileRoute('/(another-group)/onlyrouteinside')({ validateSearch: z.object({ hello: z.string().optional() }), component: OnlyRouteInsideComponent, }) const routeApi = getRouteApi('/(another-group)/onlyrouteinside') + +function OnlyRouteInsideComponent() { + const searchViaHook = useSearch({ from: '/(another-group)/onlyrouteinside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) +} diff --git a/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/_layout.insidelayout.tsx b/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/_layout.insidelayout.tsx index f2998803fd..4b239f3ef4 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/_layout.insidelayout.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/_layout.insidelayout.tsx @@ -1,30 +1,27 @@ -import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' -const InsideLayoutComponent = defineComponent({ - setup() { - const searchViaHook = useSearch({ from: '/(group)/_layout/insidelayout' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return () => ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) - export const Route = createFileRoute('/(group)/_layout/insidelayout')({ validateSearch: z.object({ hello: z.string().optional() }), component: InsideLayoutComponent, }) const routeApi = getRouteApi('/(group)/_layout/insidelayout') + +function InsideLayoutComponent() { + const searchViaHook = useSearch({ from: '/(group)/_layout/insidelayout' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) +} diff --git a/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/inside.tsx b/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/inside.tsx index 20e0d5afdb..f12ca517d3 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/inside.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/inside.tsx @@ -1,30 +1,27 @@ -import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' -const InsideComponent = defineComponent({ - setup() { - const searchViaHook = useSearch({ from: '/(group)/inside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return () => ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) - export const Route = createFileRoute('/(group)/inside')({ validateSearch: z.object({ hello: z.string().optional() }), component: InsideComponent, }) const routeApi = getRouteApi('/(group)/inside') + +function InsideComponent() { + const searchViaHook = useSearch({ from: '/(group)/inside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) +} diff --git a/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/lazyinside.tsx b/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/lazyinside.tsx index a46da658d6..05b34eb201 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/lazyinside.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/lazyinside.tsx @@ -1,30 +1,27 @@ -import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' -const LazyInsideComponent = defineComponent({ - setup() { - const searchViaHook = useSearch({ from: '/(group)/lazyinside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return () => ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) - export const Route = createFileRoute('/(group)/lazyinside')({ validateSearch: z.object({ hello: z.string().optional() }), component: LazyInsideComponent, }) const routeApi = getRouteApi('/(group)/lazyinside') + +function LazyInsideComponent() { + const searchViaHook = useSearch({ from: '/(group)/lazyinside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) +} diff --git a/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/subfolder/inside.tsx b/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/subfolder/inside.tsx index 715d2cc972..317c766186 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/subfolder/inside.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/subfolder/inside.tsx @@ -1,30 +1,27 @@ -import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' -const SubfolderInsideComponent = defineComponent({ - setup() { - const searchViaHook = useSearch({ from: '/(group)/subfolder/inside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return () => ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) - export const Route = createFileRoute('/(group)/subfolder/inside')({ validateSearch: z.object({ hello: z.string().optional() }), component: SubfolderInsideComponent, }) const routeApi = getRouteApi('/(group)/subfolder/inside') + +function SubfolderInsideComponent() { + const searchViaHook = useSearch({ from: '/(group)/subfolder/inside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) +} diff --git a/e2e/vue-router/basic-file-based-jsx/src/routes/__root.tsx b/e2e/vue-router/basic-file-based-jsx/src/routes/__root.tsx index 62c4af3aa4..59c9e6fa48 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routes/__root.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/routes/__root.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { HeadContent, Link, @@ -11,97 +10,95 @@ import { import { TanStackRouterDevtools } from '@tanstack/vue-router-devtools' import NotFoundComponent from '../components/NotFoundComponent.vue' -const RootComponent = defineComponent({ - setup() { - const router = useRouter() - const canGoBack = useCanGoBack() - // test useRouterState doesn't crash client side navigation - const _state = useRouterState() - - return () => ( - <> - -
- - - Home - - - Posts - - - Layout - - - Only Route Inside Group - - - Inside Group - - - Inside Subfolder Inside Group - - - Inside Group Inside Layout - - - Lazy Inside Group - - - unicode path - - - This Route Does Not Exist - -
-
- - - - ) - }, -}) - export const Route = createRootRoute({ component: RootComponent, notFoundComponent: NotFoundComponent, }) + +function RootComponent() { + const router = useRouter() + const canGoBack = useCanGoBack() + // test useRouterState doesn't crash client side navigation + const _state = useRouterState() + + return ( + <> + +
+ + + Home + + + Posts + + + Layout + + + Only Route Inside Group + + + Inside Group + + + Inside Subfolder Inside Group + + + Inside Group Inside Layout + + + Lazy Inside Group + + + unicode path + + + This Route Does Not Exist + +
+
+ + + + ) +} diff --git a/e2e/vue-router/basic-file-based-jsx/src/routes/posts.$postId.tsx b/e2e/vue-router/basic-file-based-jsx/src/routes/posts.$postId.tsx index 54ae789c8e..15d17387c8 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routes/posts.$postId.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/routes/posts.$postId.tsx @@ -1,27 +1,24 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import PostErrorComponent from '../components/PostErrorComponent.vue' import { fetchPost } from '../posts' import type { PostType } from '../posts' -const PostComponent = defineComponent({ - setup() { - const post = Route.useLoaderData() - - return () => ( -
-

- {(post.value as PostType).title} -

-
{(post.value as PostType).body}
-
- ) - }, -}) - export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost(postId), component: PostComponent, errorComponent: PostErrorComponent, notFoundComponent: () =>

Post not found

, }) + +function PostComponent() { + const post = Route.useLoaderData() + + return ( +
+

+ {(post.value as PostType).title} +

+
{(post.value as PostType).body}
+
+ ) +} diff --git a/e2e/vue-router/basic-file-based-jsx/src/routes/posts.tsx b/e2e/vue-router/basic-file-based-jsx/src/routes/posts.tsx index e0afd27b4c..ae580dfc02 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routes/posts.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/routes/posts.tsx @@ -1,38 +1,7 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../posts' import type { PostType } from '../posts' -const PostsComponent = defineComponent({ - setup() { - const posts = Route.useLoaderData() - - return () => ( -
-
    - {[ - ...(posts.value as Array), - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ))} -
-
- -
- ) - }, -}) - export const Route = createFileRoute('/posts')({ head: () => ({ meta: [ @@ -44,3 +13,31 @@ export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) + +function PostsComponent() { + const posts = Route.useLoaderData() + + return ( +
+
    + {[ + ...(posts.value as Array), + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ))} +
+
+ +
+ ) +} diff --git a/e2e/vue-router/basic-file-based-jsx/src/routes/posts_.$postId.edit.tsx b/e2e/vue-router/basic-file-based-jsx/src/routes/posts_.$postId.edit.tsx index 22979c93c9..57963c6b64 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routes/posts_.$postId.edit.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/routes/posts_.$postId.edit.tsx @@ -1,28 +1,23 @@ -import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useParams } from '@tanstack/vue-router' -const PostEditComponent = defineComponent({ - setup() { - const paramsViaApi = api.useParams() - const paramsViaHook = useParams({ from: '/posts_/$postId/edit' }) - const paramsViaRouteHook = api.useParams() - - return () => ( -
-
{paramsViaHook.value.postId}
-
- {paramsViaRouteHook.value.postId} -
-
- {paramsViaApi.value.postId} -
-
- ) - }, -}) - export const Route = createFileRoute('/posts_/$postId/edit')({ component: PostEditComponent, }) const api = getRouteApi('/posts_/$postId/edit') + +function PostEditComponent() { + const paramsViaApi = api.useParams() + const paramsViaHook = useParams({ from: '/posts_/$postId/edit' }) + const paramsViaRouteHook = api.useParams() + + return ( +
+
{paramsViaHook.value.postId}
+
+ {paramsViaRouteHook.value.postId} +
+
{paramsViaApi.value.postId}
+
+ ) +} diff --git a/e2e/vue-router/basic-file-based-jsx/tests/app.spec.ts b/e2e/vue-router/basic-file-based-jsx/tests/app.spec.ts index 7380859e7b..543746d64d 100644 --- a/e2e/vue-router/basic-file-based-jsx/tests/app.spec.ts +++ b/e2e/vue-router/basic-file-based-jsx/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import type { Page } from '@playwright/test' test.beforeEach(async ({ page }) => { diff --git a/e2e/vue-router/basic-file-based-jsx/tests/setup/global.setup.ts b/e2e/vue-router/basic-file-based-jsx/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basic-file-based-jsx/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-file-based-jsx/tests/setup/global.teardown.ts b/e2e/vue-router/basic-file-based-jsx/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basic-file-based-jsx/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-file-based-sfc/package.json b/e2e/vue-router/basic-file-based-sfc/package.json index e6ffa156f9..c3e7d69bfa 100644 --- a/e2e/vue-router/basic-file-based-sfc/package.json +++ b/e2e/vue-router/basic-file-based-sfc/package.json @@ -8,7 +8,7 @@ "build": "vite build && vue-tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/vue-router/basic-file-based-sfc/playwright.config.ts b/e2e/vue-router/basic-file-based-sfc/playwright.config.ts index 4eead86444..836ea41bd8 100644 --- a/e2e/vue-router/basic-file-based-sfc/playwright.config.ts +++ b/e2e/vue-router/basic-file-based-sfc/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-file-based-sfc/src/posts.ts b/e2e/vue-router/basic-file-based-sfc/src/posts.ts index f7a1941605..1b4c92b41d 100644 --- a/e2e/vue-router/basic-file-based-sfc/src/posts.ts +++ b/e2e/vue-router/basic-file-based-sfc/src/posts.ts @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/basic-file-based-sfc/src/routeTree.gen.ts b/e2e/vue-router/basic-file-based-sfc/src/routeTree.gen.ts index 0bfdddab3d..09d62b0706 100644 --- a/e2e/vue-router/basic-file-based-sfc/src/routeTree.gen.ts +++ b/e2e/vue-router/basic-file-based-sfc/src/routeTree.gen.ts @@ -454,7 +454,7 @@ declare module '@tanstack/vue-router' { '/(group)/_layout': { id: '/(group)/_layout' path: '' - fullPath: '/' + fullPath: '' preLoaderRoute: typeof groupLayoutRouteImport parentRoute: typeof rootRouteImport } diff --git a/e2e/vue-router/basic-file-based-sfc/tests/app.spec.ts b/e2e/vue-router/basic-file-based-sfc/tests/app.spec.ts index 7380859e7b..543746d64d 100644 --- a/e2e/vue-router/basic-file-based-sfc/tests/app.spec.ts +++ b/e2e/vue-router/basic-file-based-sfc/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import type { Page } from '@playwright/test' test.beforeEach(async ({ page }) => { diff --git a/e2e/vue-router/basic-file-based-sfc/tests/setup/global.setup.ts b/e2e/vue-router/basic-file-based-sfc/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basic-file-based-sfc/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-file-based-sfc/tests/setup/global.teardown.ts b/e2e/vue-router/basic-file-based-sfc/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basic-file-based-sfc/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-scroll-restoration/package.json b/e2e/vue-router/basic-scroll-restoration/package.json index f4616a5651..965a59aa79 100644 --- a/e2e/vue-router/basic-scroll-restoration/package.json +++ b/e2e/vue-router/basic-scroll-restoration/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/vue-router/basic-scroll-restoration/playwright.config.ts b/e2e/vue-router/basic-scroll-restoration/playwright.config.ts index 6a684ac89e..0c5cee43e4 100644 --- a/e2e/vue-router/basic-scroll-restoration/playwright.config.ts +++ b/e2e/vue-router/basic-scroll-restoration/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-virtual-file-based/package.json b/e2e/vue-router/basic-virtual-file-based/package.json index 3701c2254c..374ea348e2 100644 --- a/e2e/vue-router/basic-virtual-file-based/package.json +++ b/e2e/vue-router/basic-virtual-file-based/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/vue-router/basic-virtual-file-based/playwright.config.ts b/e2e/vue-router/basic-virtual-file-based/playwright.config.ts index 4eead86444..836ea41bd8 100644 --- a/e2e/vue-router/basic-virtual-file-based/playwright.config.ts +++ b/e2e/vue-router/basic-virtual-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-virtual-file-based/src/posts.tsx b/e2e/vue-router/basic-virtual-file-based/src/posts.tsx index 5f5463a668..8576a3799a 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/posts.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts-detail.tsx b/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts-detail.tsx index aa5387a4d8..b4c91d3e85 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts-detail.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts-detail.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -7,19 +6,6 @@ export function PostErrorComponent({ error }: ErrorComponentProps) { return } -const PostComponent = defineComponent({ - setup() { - const post = Route.useLoaderData() - - return () => ( -
-

{post.value?.title}

-
{post.value?.body}
-
- ) - }, -}) - export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost(postId), errorComponent: PostErrorComponent as any, @@ -28,3 +14,14 @@ export const Route = createFileRoute('/posts/$postId')({ }, component: PostComponent, }) + +function PostComponent() { + const post = Route.useLoaderData() + + return ( +
+

{post.value?.title}

+
{post.value?.body}
+
+ ) +} diff --git a/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts.tsx b/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts.tsx index 2a4e8deddd..265faaf650 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts.tsx @@ -1,42 +1,39 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../../posts' -const PostsComponent = defineComponent({ - setup() { - const posts = Route.useLoaderData() - - return () => ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
-
- -
- ) - }, -}) - export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) + +function PostsComponent() { + const posts = Route.useLoaderData() + + return ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+
+ +
+ ) +} diff --git a/e2e/vue-router/basic-virtual-file-based/tests/app.spec.ts b/e2e/vue-router/basic-virtual-file-based/tests/app.spec.ts index fbf093cd51..3e5a69ccaa 100644 --- a/e2e/vue-router/basic-virtual-file-based/tests/app.spec.ts +++ b/e2e/vue-router/basic-virtual-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/basic-virtual-file-based/tests/setup/global.setup.ts b/e2e/vue-router/basic-virtual-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basic-virtual-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-virtual-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/basic-virtual-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basic-virtual-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/package.json b/e2e/vue-router/basic-virtual-named-export-config-file-based/package.json index d3a69ed573..2e368cbd72 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/package.json +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/playwright.config.ts b/e2e/vue-router/basic-virtual-named-export-config-file-based/playwright.config.ts index 4eead86444..836ea41bd8 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/playwright.config.ts +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/posts.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/posts.tsx index 5f5463a668..8576a3799a 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/posts.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts-detail.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts-detail.tsx index aa5387a4d8..b4c91d3e85 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts-detail.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts-detail.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -7,19 +6,6 @@ export function PostErrorComponent({ error }: ErrorComponentProps) { return } -const PostComponent = defineComponent({ - setup() { - const post = Route.useLoaderData() - - return () => ( -
-

{post.value?.title}

-
{post.value?.body}
-
- ) - }, -}) - export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost(postId), errorComponent: PostErrorComponent as any, @@ -28,3 +14,14 @@ export const Route = createFileRoute('/posts/$postId')({ }, component: PostComponent, }) + +function PostComponent() { + const post = Route.useLoaderData() + + return ( +
+

{post.value?.title}

+
{post.value?.body}
+
+ ) +} diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx index 2a4e8deddd..265faaf650 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx @@ -1,42 +1,39 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../../posts' -const PostsComponent = defineComponent({ - setup() { - const posts = Route.useLoaderData() - - return () => ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
-
- -
- ) - }, -}) - export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) + +function PostsComponent() { + const posts = Route.useLoaderData() + + return ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+
+ +
+ ) +} diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts b/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts index fbf093cd51..3e5a69ccaa 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts b/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-vue-query-file-based/package.json b/e2e/vue-router/basic-vue-query-file-based/package.json index 3b4422d8d8..9b2e3cca0d 100644 --- a/e2e/vue-router/basic-vue-query-file-based/package.json +++ b/e2e/vue-router/basic-vue-query-file-based/package.json @@ -8,7 +8,7 @@ "build": "vite build && vue-tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/vue-router/basic-vue-query-file-based/playwright.config.ts b/e2e/vue-router/basic-vue-query-file-based/playwright.config.ts index fbda9bd451..6e7c123f74 100644 --- a/e2e/vue-router/basic-vue-query-file-based/playwright.config.ts +++ b/e2e/vue-router/basic-vue-query-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -12,15 +17,17 @@ export default defineConfig({ workers: 1, reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-vue-query-file-based/src/posts.tsx b/e2e/vue-router/basic-vue-query-file-based/src/posts.tsx index 1f6cb8e308..1becc2c242 100644 --- a/e2e/vue-router/basic-vue-query-file-based/src/posts.tsx +++ b/e2e/vue-router/basic-vue-query-file-based/src/posts.tsx @@ -8,7 +8,11 @@ export type PostType = { export class PostNotFoundError extends Error {} -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/basic-vue-query-file-based/src/routes/posts.$postId.tsx b/e2e/vue-router/basic-vue-query-file-based/src/routes/posts.$postId.tsx index e8b66ddf5d..72109fc891 100644 --- a/e2e/vue-router/basic-vue-query-file-based/src/routes/posts.$postId.tsx +++ b/e2e/vue-router/basic-vue-query-file-based/src/routes/posts.$postId.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { ErrorComponent, useRouter } from '@tanstack/vue-router' import { useQuery } from '@tanstack/vue-query' @@ -6,21 +5,6 @@ import { PostNotFoundError } from '../posts' import { postQueryOptions } from '../postQueryOptions' import type { ErrorComponentProps } from '@tanstack/vue-router' -const PostComponent = defineComponent({ - setup() { - const params = Route.useParams() - useQuery(() => postQueryOptions(params.value.postId)) - const post = Route.useLoaderData() - - return () => ( -
-

{post.value.title}

-
{post.value.body}
-
- ) - }, -}) - export const Route = createFileRoute('/posts/$postId')({ loader: ({ context: { queryClient }, params: { postId } }) => { return queryClient.ensureQueryData(postQueryOptions(postId)) @@ -48,3 +32,16 @@ export function PostErrorComponent({ error }: ErrorComponentProps) {
) } + +function PostComponent() { + const postId = Route.useParams().value.postId + useQuery(postQueryOptions(postId)) + const post = Route.useLoaderData() + + return ( +
+

{post.value.title}

+
{post.value.body}
+
+ ) +} diff --git a/e2e/vue-router/basic-vue-query-file-based/src/routes/posts.tsx b/e2e/vue-router/basic-vue-query-file-based/src/routes/posts.tsx index e1c35d59ad..f9e20f99d6 100644 --- a/e2e/vue-router/basic-vue-query-file-based/src/routes/posts.tsx +++ b/e2e/vue-router/basic-vue-query-file-based/src/routes/posts.tsx @@ -1,45 +1,42 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { useQuery } from '@tanstack/vue-query' import { postsQueryOptions } from '../postsQueryOptions' -const PostsComponent = defineComponent({ - setup() { - useQuery(postsQueryOptions) - const posts = Route.useLoaderData() - - return () => ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
-
- -
- ) - }, -}) - export const Route = createFileRoute('/posts')({ loader: ({ context: { queryClient } }) => queryClient.ensureQueryData(postsQueryOptions), component: PostsComponent, }) + +function PostsComponent() { + useQuery(postsQueryOptions) + const posts = Route.useLoaderData() + + return ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+
+ +
+ ) +} diff --git a/e2e/vue-router/basic-vue-query-file-based/tests/app.spec.ts b/e2e/vue-router/basic-vue-query-file-based/tests/app.spec.ts index 2b42d6d589..d80e8dada5 100644 --- a/e2e/vue-router/basic-vue-query-file-based/tests/app.spec.ts +++ b/e2e/vue-router/basic-vue-query-file-based/tests/app.spec.ts @@ -1,23 +1,24 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' +import { getDummyServerPort } from '@tanstack/router-e2e-utils' +import packageJson from '../package.json' with { type: 'json' } test.beforeEach(async ({ page }) => { await page.goto('/') }) -test('GetPosts with networking disabled', async ({ page, context }) => { - await page.goto('about:blank') - await context.setOffline(true) - const { status, posts, post } = await page.evaluate(async () => { - const response = await fetch('https://jsonplaceholder.typicode.com/posts') - const posts = await response.json() - const post = await fetch( - 'https://jsonplaceholder.typicode.com/posts/1', - ).then((r) => r.json()) - return { status: response.status, posts, post } - }) - expect(status).toBe(200) +test('GetPosts', async () => { + const port = await getDummyServerPort(packageJson.name) + const res = await fetch(`http://localhost:${port}/posts`) + + expect(res.status).toBe(200) + + const posts = await res.json() + expect(posts.length).toBeGreaterThan(0) + + const postRes = await fetch(`http://localhost:${port}/posts/1`) + expect(postRes.status).toBe(200) + const post = await postRes.json() expect(post).toEqual(posts[0]) }) diff --git a/e2e/vue-router/basic-vue-query-file-based/tests/setup/global.setup.ts b/e2e/vue-router/basic-vue-query-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basic-vue-query-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-vue-query-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/basic-vue-query-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basic-vue-query-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-vue-query-file-based/tsconfig.json b/e2e/vue-router/basic-vue-query-file-based/tsconfig.json index 28889522fc..123a2f4122 100644 --- a/e2e/vue-router/basic-vue-query-file-based/tsconfig.json +++ b/e2e/vue-router/basic-vue-query-file-based/tsconfig.json @@ -10,7 +10,7 @@ "skipLibCheck": true, "noEmit": true, "resolveJsonModule": true, - "types": ["vite/client", "node"] + "types": ["vite/client"] }, "include": ["src", "tests"], "exclude": ["node_modules", "dist"] diff --git a/e2e/vue-router/basic-vue-query/package.json b/e2e/vue-router/basic-vue-query/package.json index 68f1a8c9ea..ba3f4295d5 100644 --- a/e2e/vue-router/basic-vue-query/package.json +++ b/e2e/vue-router/basic-vue-query/package.json @@ -8,7 +8,7 @@ "build": "vite build && vue-tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/vue-router/basic-vue-query/playwright.config.ts b/e2e/vue-router/basic-vue-query/playwright.config.ts index 4eead86444..836ea41bd8 100644 --- a/e2e/vue-router/basic-vue-query/playwright.config.ts +++ b/e2e/vue-router/basic-vue-query/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-vue-query/src/main.tsx b/e2e/vue-router/basic-vue-query/src/main.tsx index 3235f26ce3..4f862a9b31 100644 --- a/e2e/vue-router/basic-vue-query/src/main.tsx +++ b/e2e/vue-router/basic-vue-query/src/main.tsx @@ -1,4 +1,4 @@ -import { createApp, defineComponent } from 'vue' +import { createApp } from 'vue' import { ErrorComponent, Link, @@ -108,21 +108,6 @@ function PostsIndexRouteComponent() { return
Select a post.
} -const PostRouteComponent = defineComponent({ - setup() { - const params = postRoute.useParams() - useQuery(() => postQueryOptions(params.value.postId)) - const post = postRoute.useLoaderData() - - return () => ( -
-

{post.value.title}

-
{post.value.body}
-
- ) - }, -}) - const postRoute = createRoute({ getParentRoute: () => postsRoute, path: '$postId', @@ -152,6 +137,19 @@ function PostErrorComponent({ error }: ErrorComponentProps) { ) } +function PostRouteComponent() { + const postId = postRoute.useParams().value.postId + useQuery(postQueryOptions(postId)) + const post = postRoute.useLoaderData() + + return ( +
+

{post.value.title}

+
{post.value.body}
+
+ ) +} + const layoutRoute = createRoute({ getParentRoute: () => rootRoute, id: '_layout', diff --git a/e2e/vue-router/basic-vue-query/src/posts.lazy.tsx b/e2e/vue-router/basic-vue-query/src/posts.lazy.tsx index d42d3d49dc..eb844bc68d 100644 --- a/e2e/vue-router/basic-vue-query/src/posts.lazy.tsx +++ b/e2e/vue-router/basic-vue-query/src/posts.lazy.tsx @@ -1,42 +1,39 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createLazyRoute } from '@tanstack/vue-router' import { useQuery } from '@tanstack/vue-query' import { postsQueryOptions } from './posts' -const PostsComponent = defineComponent({ - setup() { - const postsQuery = useQuery(postsQueryOptions) - const posts = postsQuery.data - - return () => ( -
-
    - {[ - ...((posts.value ?? []) as Array<{ id: string; title: string }>), - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
- -
- ) - }, -}) - export const Route = createLazyRoute('/posts')({ component: PostsComponent, }) + +function PostsComponent() { + const postsQuery = useQuery(postsQueryOptions) + const posts = postsQuery.data + + return ( +
+
    + {[ + ...((posts.value ?? []) as Array<{ id: string; title: string }>), + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+ +
+ ) +} diff --git a/e2e/vue-router/basic-vue-query/src/posts.ts b/e2e/vue-router/basic-vue-query/src/posts.ts index 69e1814af5..18f8a9f93f 100644 --- a/e2e/vue-router/basic-vue-query/src/posts.ts +++ b/e2e/vue-router/basic-vue-query/src/posts.ts @@ -9,7 +9,11 @@ type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} const fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/vue-router/basic-vue-query/tests/app.spec.ts b/e2e/vue-router/basic-vue-query/tests/app.spec.ts index fbf093cd51..3e5a69ccaa 100644 --- a/e2e/vue-router/basic-vue-query/tests/app.spec.ts +++ b/e2e/vue-router/basic-vue-query/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/basic-vue-query/tests/setup/global.setup.ts b/e2e/vue-router/basic-vue-query/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basic-vue-query/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-vue-query/tests/setup/global.teardown.ts b/e2e/vue-router/basic-vue-query/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basic-vue-query/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic/package.json b/e2e/vue-router/basic/package.json index 1b57dae772..e1b7f0ae1a 100644 --- a/e2e/vue-router/basic/package.json +++ b/e2e/vue-router/basic/package.json @@ -8,7 +8,7 @@ "build": "vite build && vue-tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/vue-router/basic/playwright.config.ts b/e2e/vue-router/basic/playwright.config.ts index 4eead86444..836ea41bd8 100644 --- a/e2e/vue-router/basic/playwright.config.ts +++ b/e2e/vue-router/basic/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic/src/main.tsx b/e2e/vue-router/basic/src/main.tsx index c2293018fc..3e5ac6f1e0 100644 --- a/e2e/vue-router/basic/src/main.tsx +++ b/e2e/vue-router/basic/src/main.tsx @@ -1,4 +1,4 @@ -import { createApp, defineComponent } from 'vue' +import { createApp } from 'vue' import { ErrorComponent, Link, @@ -133,20 +133,6 @@ function PostErrorComponent({ error }: ErrorComponentProps) { return } -const PostComponent = defineComponent({ - setup() { - const post = postRoute.useLoaderData() - - return () => ( -
-

{post.value.title}

-
-
{post.value.body}
-
- ) - }, -}) - const postRoute = createRoute({ getParentRoute: () => postsRoute, path: '$postId', @@ -155,6 +141,18 @@ const postRoute = createRoute({ component: PostComponent, }) +function PostComponent() { + const post = postRoute.useLoaderData() + + return ( +
+

{post.value.title}

+
+
{post.value.body}
+
+ ) +} + const layoutRoute = createRoute({ getParentRoute: () => rootRoute, id: '_layout', @@ -317,30 +315,14 @@ const paramsPsNamedIndexRoute = createRoute({ }, }) -const ParamsNamedFoo = defineComponent({ - setup() { - const p = paramsPsNamedFooRoute.useParams() - return () => ( -
-

ParamsNamedFoo

-
{JSON.stringify(p.value)}
-
- ) - }, -}) - const paramsPsNamedFooRoute = createRoute({ getParentRoute: () => paramsPsNamedRoute, path: '/$foo', - component: ParamsNamedFoo, -}) - -const ParamsNamedFooMarkdown = defineComponent({ - setup() { - const p = paramsPsNamedFooPrefixRoute.useParams() - return () => ( + component: function ParamsNamedFoo() { + const p = paramsPsNamedFooRoute.useParams() + return (
-

ParamsNamedFooPrefix

+

ParamsNamedFoo

{JSON.stringify(p.value)}
) @@ -350,15 +332,11 @@ const ParamsNamedFooMarkdown = defineComponent({ const paramsPsNamedFooPrefixRoute = createRoute({ getParentRoute: () => paramsPsNamedRoute, path: '/prefix{$foo}', - component: ParamsNamedFooMarkdown, -}) - -const ParamsNamedFooSuffix = defineComponent({ - setup() { - const p = paramsPsNamedFooSuffixRoute.useParams() - return () => ( + component: function ParamsNamedFooMarkdown() { + const p = paramsPsNamedFooPrefixRoute.useParams() + return (
-

ParamsNamedFooSuffix

+

ParamsNamedFooPrefix

{JSON.stringify(p.value)}
) @@ -368,7 +346,15 @@ const ParamsNamedFooSuffix = defineComponent({ const paramsPsNamedFooSuffixRoute = createRoute({ getParentRoute: () => paramsPsNamedRoute, path: '/{$foo}suffix', - component: ParamsNamedFooSuffix, + component: function ParamsNamedFooSuffix() { + const p = paramsPsNamedFooSuffixRoute.useParams() + return ( +
+

ParamsNamedFooSuffix

+
{JSON.stringify(p.value)}
+
+ ) + }, }) const paramsPsWildcardRoute = createRoute({ @@ -384,30 +370,14 @@ const paramsPsWildcardIndexRoute = createRoute({ }, }) -const ParamsWildcardSplat = defineComponent({ - setup() { - const p = paramsPsWildcardSplatRoute.useParams() - return () => ( -
-

ParamsWildcardSplat

-
{JSON.stringify(p.value)}
-
- ) - }, -}) - const paramsPsWildcardSplatRoute = createRoute({ getParentRoute: () => paramsPsWildcardRoute, path: '$', - component: ParamsWildcardSplat, -}) - -const ParamsWildcardSplatPrefix = defineComponent({ - setup() { - const p = paramsPsWildcardSplatPrefixRoute.useParams() - return () => ( + component: function ParamsWildcardSplat() { + const p = paramsPsWildcardSplatRoute.useParams() + return (
-

ParamsWildcardSplatPrefix

+

ParamsWildcardSplat

{JSON.stringify(p.value)}
) @@ -417,15 +387,11 @@ const ParamsWildcardSplatPrefix = defineComponent({ const paramsPsWildcardSplatPrefixRoute = createRoute({ getParentRoute: () => paramsPsWildcardRoute, path: 'prefix{$}', - component: ParamsWildcardSplatPrefix, -}) - -const ParamsWildcardSplatSuffix = defineComponent({ - setup() { - const p = paramsPsWildcardSplatSuffixRoute.useParams() - return () => ( + component: function ParamsWildcardSplatPrefix() { + const p = paramsPsWildcardSplatPrefixRoute.useParams() + return (
-

ParamsWildcardSplatSuffix

+

ParamsWildcardSplatPrefix

{JSON.stringify(p.value)}
) @@ -435,7 +401,15 @@ const ParamsWildcardSplatSuffix = defineComponent({ const paramsPsWildcardSplatSuffixRoute = createRoute({ getParentRoute: () => paramsPsWildcardRoute, path: '{$}suffix', - component: ParamsWildcardSplatSuffix, + component: function ParamsWildcardSplatSuffix() { + const p = paramsPsWildcardSplatSuffixRoute.useParams() + return ( +
+

ParamsWildcardSplatSuffix

+
{JSON.stringify(p.value)}
+
+ ) + }, }) const routeTree = rootRoute.addChildren([ diff --git a/e2e/vue-router/basic/src/posts.lazy.tsx b/e2e/vue-router/basic/src/posts.lazy.tsx index a236404d84..b2df740010 100644 --- a/e2e/vue-router/basic/src/posts.lazy.tsx +++ b/e2e/vue-router/basic/src/posts.lazy.tsx @@ -1,39 +1,36 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createLazyRoute } from '@tanstack/vue-router' -const PostsComponent = defineComponent({ - setup() { - const posts = Route.useLoaderData() - - return () => ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
- -
- ) - }, -}) - export const Route = createLazyRoute('/posts')({ component: PostsComponent, }) + +function PostsComponent() { + const posts = Route.useLoaderData() + + return ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+ +
+ ) +} diff --git a/e2e/vue-router/basic/src/posts.ts b/e2e/vue-router/basic/src/posts.ts index f72d16fee3..e859645746 100644 --- a/e2e/vue-router/basic/src/posts.ts +++ b/e2e/vue-router/basic/src/posts.ts @@ -8,7 +8,11 @@ type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/vue-router/basic/tests/app.spec.ts b/e2e/vue-router/basic/tests/app.spec.ts index 9c0a6b6901..ec0e24d8a4 100644 --- a/e2e/vue-router/basic/tests/app.spec.ts +++ b/e2e/vue-router/basic/tests/app.spec.ts @@ -1,7 +1,8 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from '../package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/basic/tests/params.spec.ts b/e2e/vue-router/basic/tests/params.spec.ts index f673138047..ac18f39864 100644 --- a/e2e/vue-router/basic/tests/params.spec.ts +++ b/e2e/vue-router/basic/tests/params.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.describe('params operations + prefix/suffix', () => { test.beforeEach(async ({ page }) => { diff --git a/e2e/vue-router/basic/tests/setup/global.setup.ts b/e2e/vue-router/basic/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basic/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic/tests/setup/global.teardown.ts b/e2e/vue-router/basic/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basic/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/generator-cli-only/package.json b/e2e/vue-router/generator-cli-only/package.json index f9324643ac..53e2cc1366 100644 --- a/e2e/vue-router/generator-cli-only/package.json +++ b/e2e/vue-router/generator-cli-only/package.json @@ -8,7 +8,7 @@ "build": "tsr generate && vite build && tsc --noEmit", "preview": "vite preview", "start": "tsr generate && vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/vue-router/generator-cli-only/playwright.config.ts b/e2e/vue-router/generator-cli-only/playwright.config.ts index 4eead86444..c9d9a76ae7 100644 --- a/e2e/vue-router/generator-cli-only/playwright.config.ts +++ b/e2e/vue-router/generator-cli-only/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/generator-cli-only/src/posts.ts b/e2e/vue-router/generator-cli-only/src/posts.ts index f72d16fee3..e859645746 100644 --- a/e2e/vue-router/generator-cli-only/src/posts.ts +++ b/e2e/vue-router/generator-cli-only/src/posts.ts @@ -8,7 +8,11 @@ type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/vue-router/generator-cli-only/src/routes/posts.$postId.tsx b/e2e/vue-router/generator-cli-only/src/routes/posts.$postId.tsx index bb2d728afd..f4f1b04f88 100644 --- a/e2e/vue-router/generator-cli-only/src/routes/posts.$postId.tsx +++ b/e2e/vue-router/generator-cli-only/src/routes/posts.$postId.tsx @@ -1,21 +1,7 @@ -import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' -const PostComponent = defineComponent({ - setup() { - const post = Route.useLoaderData() - - return () => ( -
-

{post.value.title}

-
{post.value.body}
-
- ) - }, -}) - export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost(postId), errorComponent: PostErrorComponent, @@ -28,3 +14,14 @@ export const Route = createFileRoute('/posts/$postId')({ export function PostErrorComponent({ error }: ErrorComponentProps) { return } + +function PostComponent() { + const post = Route.useLoaderData() + + return ( +
+

{post.value.title}

+
{post.value.body}
+
+ ) +} diff --git a/e2e/vue-router/generator-cli-only/src/routes/posts.route.tsx b/e2e/vue-router/generator-cli-only/src/routes/posts.route.tsx index 518bdc3d70..eaaa35fd5c 100644 --- a/e2e/vue-router/generator-cli-only/src/routes/posts.route.tsx +++ b/e2e/vue-router/generator-cli-only/src/routes/posts.route.tsx @@ -1,42 +1,39 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../posts' -const PostsLayoutComponent = defineComponent({ - setup() { - const posts = Route.useLoaderData() - - return () => ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
-
- -
- ) - }, -}) - export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsLayoutComponent, }) + +function PostsLayoutComponent() { + const posts = Route.useLoaderData() + + return ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+
+ +
+ ) +} diff --git a/e2e/vue-router/generator-cli-only/tests/app.spec.ts b/e2e/vue-router/generator-cli-only/tests/app.spec.ts index ced5ac9310..5a83a314f2 100644 --- a/e2e/vue-router/generator-cli-only/tests/app.spec.ts +++ b/e2e/vue-router/generator-cli-only/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/generator-cli-only/tests/setup/global.setup.ts b/e2e/vue-router/generator-cli-only/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/generator-cli-only/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/generator-cli-only/tests/setup/global.teardown.ts b/e2e/vue-router/generator-cli-only/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/generator-cli-only/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/js-only-file-based/package.json b/e2e/vue-router/js-only-file-based/package.json index cda098978c..0ac86a7a56 100644 --- a/e2e/vue-router/js-only-file-based/package.json +++ b/e2e/vue-router/js-only-file-based/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/vue-router/js-only-file-based/playwright.config.ts b/e2e/vue-router/js-only-file-based/playwright.config.ts index 0925936d55..4f93bc1413 100644 --- a/e2e/vue-router/js-only-file-based/playwright.config.ts +++ b/e2e/vue-router/js-only-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,15 +18,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/js-only-file-based/src/posts.js b/e2e/vue-router/js-only-file-based/src/posts.js index 36c1c281f6..979e5e381c 100644 --- a/e2e/vue-router/js-only-file-based/src/posts.js +++ b/e2e/vue-router/js-only-file-based/src/posts.js @@ -2,7 +2,11 @@ import axios from 'redaxios' export class NotFoundError extends Error {} -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/vue-router/js-only-file-based/src/routes/posts.$postId.jsx b/e2e/vue-router/js-only-file-based/src/routes/posts.$postId.jsx index 05599a6780..b769e23862 100644 --- a/e2e/vue-router/js-only-file-based/src/routes/posts.$postId.jsx +++ b/e2e/vue-router/js-only-file-based/src/routes/posts.$postId.jsx @@ -1,22 +1,8 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { ErrorComponent } from '@tanstack/vue-router' import { fetchPost } from '../posts' -const PostComponent = defineComponent({ - setup() { - const post = Route.useLoaderData() - - return () => ( -
-

{post.value.title}

-
{post.value.body}
-
- ) - }, -}) - export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost(postId), errorComponent: PostErrorComponent, @@ -29,3 +15,14 @@ export const Route = createFileRoute('/posts/$postId')({ export function PostErrorComponent({ error }) { return } + +function PostComponent() { + const post = Route.useLoaderData() + + return ( +
+

{post.value.title}

+
{post.value.body}
+
+ ) +} diff --git a/e2e/vue-router/js-only-file-based/src/routes/posts.route.jsx b/e2e/vue-router/js-only-file-based/src/routes/posts.route.jsx index 5925dbed54..c1fef7213d 100644 --- a/e2e/vue-router/js-only-file-based/src/routes/posts.route.jsx +++ b/e2e/vue-router/js-only-file-based/src/routes/posts.route.jsx @@ -1,44 +1,41 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { Link, Outlet } from '@tanstack/vue-router' import { fetchPosts } from '../posts' -const PostsLayoutComponent = defineComponent({ - setup() { - const posts = Route.useLoaderData() - - return () => ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
-
- -
- ) - }, -}) - export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsLayoutComponent, }) + +function PostsLayoutComponent() { + const posts = Route.useLoaderData() + + return ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+
+ +
+ ) +} diff --git a/e2e/vue-router/js-only-file-based/tests/app.spec.ts b/e2e/vue-router/js-only-file-based/tests/app.spec.ts index ced5ac9310..5a83a314f2 100644 --- a/e2e/vue-router/js-only-file-based/tests/app.spec.ts +++ b/e2e/vue-router/js-only-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/js-only-file-based/tests/setup/global.setup.ts b/e2e/vue-router/js-only-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/js-only-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/js-only-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/js-only-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/js-only-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/rspack-basic-file-based/package.json b/e2e/vue-router/rspack-basic-file-based/package.json index 93439f7d5b..449511d8fd 100644 --- a/e2e/vue-router/rspack-basic-file-based/package.json +++ b/e2e/vue-router/rspack-basic-file-based/package.json @@ -7,7 +7,7 @@ "build": "rsbuild build && tsc --noEmit", "preview": "rsbuild preview", "start": "rsbuild preview", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -17,7 +17,7 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-babel": "^1.1.2", "@rsbuild/plugin-vue": "^1.2.7", "@rsbuild/plugin-vue-jsx": "^2.0.0", diff --git a/e2e/vue-router/rspack-basic-file-based/playwright.config.ts b/e2e/vue-router/rspack-basic-file-based/playwright.config.ts index 4eead86444..5f20415459 100644 --- a/e2e/vue-router/rspack-basic-file-based/playwright.config.ts +++ b/e2e/vue-router/rspack-basic-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `PUBLIC_NODE_ENV="test" PUBLIC_EXTERNAL_PORT=${EXTERNAL_PORT} PUBLIC_SERVER_PORT=${PORT} pnpm build && PUBLIC_NODE_ENV="test" PUBLIC_EXTERNAL_PORT=${EXTERNAL_PORT} PUBLIC_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/rspack-basic-file-based/rsbuild.config.ts b/e2e/vue-router/rspack-basic-file-based/rsbuild.config.ts index c91449b6c3..d5e4b7456c 100644 --- a/e2e/vue-router/rspack-basic-file-based/rsbuild.config.ts +++ b/e2e/vue-router/rspack-basic-file-based/rsbuild.config.ts @@ -12,6 +12,19 @@ export default defineConfig({ pluginVue(), pluginVueJsx(), ], + source: { + define: { + // Rsbuild only defines `import.meta.env.PUBLIC_*` when the env var exists. + // When it doesn't, rspack can transform `import.meta.env` to `void 0`, which + // makes `import.meta.env.PUBLIC_*` crash at runtime. + 'import.meta.env.PUBLIC_NODE_ENV': JSON.stringify( + process.env.PUBLIC_NODE_ENV ?? '', + ), + 'import.meta.env.PUBLIC_EXTERNAL_PORT': JSON.stringify( + process.env.PUBLIC_EXTERNAL_PORT ?? '', + ), + }, + }, tools: { rspack: { plugins: [tanstackRouter({ target: 'vue', autoCodeSplitting: true })], diff --git a/e2e/vue-router/rspack-basic-file-based/src/posts.tsx b/e2e/vue-router/rspack-basic-file-based/src/posts.tsx index 5f5463a668..0b557a0f65 100644 --- a/e2e/vue-router/rspack-basic-file-based/src/posts.tsx +++ b/e2e/vue-router/rspack-basic-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.PUBLIC_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.PUBLIC_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/rspack-basic-file-based/src/routes/posts.$postId.tsx b/e2e/vue-router/rspack-basic-file-based/src/routes/posts.$postId.tsx index a86ea0762f..e271c139f5 100644 --- a/e2e/vue-router/rspack-basic-file-based/src/routes/posts.$postId.tsx +++ b/e2e/vue-router/rspack-basic-file-based/src/routes/posts.$postId.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -7,19 +6,6 @@ export function PostErrorComponent({ error }: ErrorComponentProps) { return } -const PostComponent = defineComponent({ - setup() { - const post = Route.useLoaderData() - - return () => ( -
-

{post.value.title}

-
{post.value.body}
-
- ) - }, -}) - export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost(postId), errorComponent: PostErrorComponent, @@ -28,3 +14,14 @@ export const Route = createFileRoute('/posts/$postId')({ }, component: PostComponent, }) + +function PostComponent() { + const post = Route.useLoaderData() + + return ( +
+

{post.value.title}

+
{post.value.body}
+
+ ) +} diff --git a/e2e/vue-router/rspack-basic-file-based/src/routes/posts.tsx b/e2e/vue-router/rspack-basic-file-based/src/routes/posts.tsx index 90744370ff..653918c370 100644 --- a/e2e/vue-router/rspack-basic-file-based/src/routes/posts.tsx +++ b/e2e/vue-router/rspack-basic-file-based/src/routes/posts.tsx @@ -1,43 +1,40 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../posts' -const PostsComponent = defineComponent({ - setup() { - const posts = Route.useLoaderData() - - return () => ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
-
- -
- ) - }, -}) - export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) + +function PostsComponent() { + const posts = Route.useLoaderData() + + return ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+
+ +
+ ) +} diff --git a/e2e/vue-router/rspack-basic-file-based/tests/app.spec.ts b/e2e/vue-router/rspack-basic-file-based/tests/app.spec.ts index d230263bfe..10beff655f 100644 --- a/e2e/vue-router/rspack-basic-file-based/tests/app.spec.ts +++ b/e2e/vue-router/rspack-basic-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/rspack-basic-file-based/tests/setup/global.setup.ts b/e2e/vue-router/rspack-basic-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/rspack-basic-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/rspack-basic-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/rspack-basic-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/rspack-basic-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/package.json b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/package.json index 536435a09e..944210cd10 100644 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/package.json +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/package.json @@ -7,7 +7,7 @@ "build": "rsbuild build && tsc --noEmit", "preview": "rsbuild preview", "start": "rsbuild preview", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -17,7 +17,7 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-babel": "^1.1.2", "@rsbuild/plugin-vue": "^1.2.7", "@rsbuild/plugin-vue-jsx": "^2.0.0", diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts index 1c1d021f2f..bf3adc082c 100644 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm start --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `PUBLIC_NODE_ENV="test" PUBLIC_EXTERNAL_PORT=${EXTERNAL_PORT} PUBLIC_SERVER_PORT=${PORT} pnpm build && PUBLIC_SERVER_PORT=${PORT} pnpm start --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/rsbuild.config.ts b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/rsbuild.config.ts index e5c7e8b77e..b09f6ccda8 100644 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/rsbuild.config.ts +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/rsbuild.config.ts @@ -12,6 +12,19 @@ export default defineConfig({ pluginVue(), pluginVueJsx(), ], + source: { + define: { + // Rsbuild only defines `import.meta.env.PUBLIC_*` when the env var exists. + // When it doesn't, rspack can transform `import.meta.env` to `void 0`, which + // makes `import.meta.env.PUBLIC_*` crash at runtime. + 'import.meta.env.PUBLIC_NODE_ENV': JSON.stringify( + process.env.PUBLIC_NODE_ENV ?? '', + ), + 'import.meta.env.PUBLIC_EXTERNAL_PORT': JSON.stringify( + process.env.PUBLIC_EXTERNAL_PORT ?? '', + ), + }, + }, tools: { rspack: { plugins: [ diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx index 5f5463a668..0b557a0f65 100644 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.PUBLIC_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.PUBLIC_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/routes/posts/posts-detail.tsx b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/routes/posts/posts-detail.tsx index 5e3fe4d130..cb1924e993 100644 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/routes/posts/posts-detail.tsx +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/routes/posts/posts-detail.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -7,19 +6,6 @@ export function PostErrorComponent({ error }: ErrorComponentProps) { return } -const PostComponent = defineComponent({ - setup() { - const post = Route.useLoaderData() - - return () => ( -
-

{post.value.title}

-
{post.value.body}
-
- ) - }, -}) - export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost(postId), errorComponent: PostErrorComponent as any, @@ -28,3 +14,14 @@ export const Route = createFileRoute('/posts/$postId')({ }, component: PostComponent, }) + +function PostComponent() { + const post = Route.useLoaderData() + + return ( +
+

{post.value.title}

+
{post.value.body}
+
+ ) +} diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx index 2a4e8deddd..265faaf650 100644 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx @@ -1,42 +1,39 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../../posts' -const PostsComponent = defineComponent({ - setup() { - const posts = Route.useLoaderData() - - return () => ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
-
- -
- ) - }, -}) - export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) + +function PostsComponent() { + const posts = Route.useLoaderData() + + return ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+
+ +
+ ) +} diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts index d230263bfe..10beff655f 100644 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/package.json b/e2e/vue-router/scroll-restoration-sandbox-vite/package.json index d071ee546a..f735fce364 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/package.json +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/package.json @@ -11,7 +11,7 @@ "start": "vite", "test:e2e:browser": "VITE_APP_HISTORY=browser playwright test --config=playwright.browser.config.ts --project=chromium", "test:e2e:hash": "VITE_APP_HISTORY=hash playwright test --config=playwright.hash.config.ts --project=chromium", - "test:e2e": "pnpm run test:e2e:browser && pnpm run test:e2e:hash" + "test:e2e": "rm -rf port*.txt; pnpm run test:e2e:browser && pnpm run test:e2e:hash" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -31,15 +31,5 @@ "typescript": "~5.8.3", "vite": "^8.0.14", "vue-tsc": "^3.3.8" - }, - "nx": { - "targets": { - "test:e2e": { - "outputs": [ - "...", - "{projectRoot}/dist-hash" - ] - } - } } } diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts index e2681daea5..9d7691f0fd 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts @@ -1,7 +1,15 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, + resolveRuntimeSuffix, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort( + packageJson.name + `-${resolveRuntimeSuffix('browser')}`, +) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +20,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_APP_HISTORY=browser pnpm build && VITE_APP_HISTORY=browser pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=browser pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=browser pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts index 445616b9bd..80a340cef4 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts @@ -1,7 +1,15 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, + resolveRuntimeSuffix, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort( + packageJson.name + `-${resolveRuntimeSuffix('hash')}`, +) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +20,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_APP_HISTORY=hash vite build --outDir dist-hash && VITE_APP_HISTORY=hash pnpm preview --port ${PORT} --outDir dist-hash`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=hash vite build --outDir dist-hash && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=hash pnpm preview --port ${PORT} --outDir dist-hash`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/src/posts.tsx b/e2e/vue-router/scroll-restoration-sandbox-vite/src/posts.tsx index bc56dff904..c6cba486ab 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/src/posts.tsx +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/src/posts.tsx @@ -12,7 +12,11 @@ export type PostType = { export class PostNotFoundError extends Error {} -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/tests/app.spec.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/tests/app.spec.ts index 067f0341c4..5f226c6db3 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/tests/app.spec.ts +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import { toRuntimePath } from '@tanstack/router-e2e-utils' test('Smoke - Renders home', async ({ page }) => { diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/tsconfig.json b/e2e/vue-router/scroll-restoration-sandbox-vite/tsconfig.json index b47cca9589..3e5b04987f 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/tsconfig.json +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/tsconfig.json @@ -12,5 +12,5 @@ "allowJs": true, "types": ["vite/client", "node"] }, - "exclude": ["node_modules", "dist", "dist-hash"] + "exclude": ["node_modules", "dist"] } diff --git a/e2e/vue-router/sentry-integration/package.json b/e2e/vue-router/sentry-integration/package.json index 045ddd99be..344a338a27 100644 --- a/e2e/vue-router/sentry-integration/package.json +++ b/e2e/vue-router/sentry-integration/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@sentry/vue": "^10.32.0", diff --git a/e2e/vue-router/sentry-integration/playwright.config.ts b/e2e/vue-router/sentry-integration/playwright.config.ts index 6a684ac89e..0c5cee43e4 100644 --- a/e2e/vue-router/sentry-integration/playwright.config.ts +++ b/e2e/vue-router/sentry-integration/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/view-transitions/package.json b/e2e/vue-router/view-transitions/package.json index 21a0f1d8a0..5466ded0ed 100644 --- a/e2e/vue-router/view-transitions/package.json +++ b/e2e/vue-router/view-transitions/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/vue-router/view-transitions/playwright.config.ts b/e2e/vue-router/view-transitions/playwright.config.ts index 4eead86444..c5de6b5611 100644 --- a/e2e/vue-router/view-transitions/playwright.config.ts +++ b/e2e/vue-router/view-transitions/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,10 +22,13 @@ export default defineConfig({ baseURL, }, + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/view-transitions/src/routes/posts.$postId.tsx b/e2e/vue-router/view-transitions/src/routes/posts.$postId.tsx index a86ea0762f..e271c139f5 100644 --- a/e2e/vue-router/view-transitions/src/routes/posts.$postId.tsx +++ b/e2e/vue-router/view-transitions/src/routes/posts.$postId.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -7,19 +6,6 @@ export function PostErrorComponent({ error }: ErrorComponentProps) { return } -const PostComponent = defineComponent({ - setup() { - const post = Route.useLoaderData() - - return () => ( -
-

{post.value.title}

-
{post.value.body}
-
- ) - }, -}) - export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost(postId), errorComponent: PostErrorComponent, @@ -28,3 +14,14 @@ export const Route = createFileRoute('/posts/$postId')({ }, component: PostComponent, }) + +function PostComponent() { + const post = Route.useLoaderData() + + return ( +
+

{post.value.title}

+
{post.value.body}
+
+ ) +} diff --git a/e2e/vue-router/view-transitions/src/routes/posts.route.tsx b/e2e/vue-router/view-transitions/src/routes/posts.route.tsx index 6802b073f6..01d90b7ad6 100644 --- a/e2e/vue-router/view-transitions/src/routes/posts.route.tsx +++ b/e2e/vue-router/view-transitions/src/routes/posts.route.tsx @@ -1,46 +1,43 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../posts' -const PostsLayoutComponent = defineComponent({ - setup() { - const posts = Route.useLoaderData() - - return () => ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
-
-
- -
-
- ) - }, -}) - export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsLayoutComponent, }) + +function PostsLayoutComponent() { + const posts = Route.useLoaderData() + + return ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+
+
+ +
+
+ ) +} diff --git a/e2e/vue-router/view-transitions/tests/app.spec.ts b/e2e/vue-router/view-transitions/tests/app.spec.ts index 6c1ccf1a6e..472bd6ed0b 100644 --- a/e2e/vue-router/view-transitions/tests/app.spec.ts +++ b/e2e/vue-router/view-transitions/tests/app.spec.ts @@ -1,4 +1,4 @@ -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/view-transitions/tests/setup/global.setup.ts b/e2e/vue-router/view-transitions/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/view-transitions/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/view-transitions/tests/setup/global.teardown.ts b/e2e/vue-router/view-transitions/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/view-transitions/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/view-transitions/tests/view-transitions.spec.ts b/e2e/vue-router/view-transitions/tests/view-transitions.spec.ts index e62662a1d2..31d8b12b04 100644 --- a/e2e/vue-router/view-transitions/tests/view-transitions.spec.ts +++ b/e2e/vue-router/view-transitions/tests/view-transitions.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.addInitScript(() => { diff --git a/e2e/vue-start/basic-auth/package.json b/e2e/vue-start/basic-auth/package.json index 7f6fb798da..0c22edfc4c 100644 --- a/e2e/vue-start/basic-auth/package.json +++ b/e2e/vue-start/basic-auth/package.json @@ -10,7 +10,7 @@ "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", "prisma-generate": "prisma generate", - "test:e2e": "mkdir -p .tmp; rm -f .tmp/dev.db .tmp/dev.db-journal .tmp/dev.db-wal .tmp/dev.db-shm; export DATABASE_URL=file:./.tmp/dev.db; pnpm run prisma-generate && pnpm exec prisma migrate deploy && playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; mkdir -p .tmp; rm -f .tmp/dev.db .tmp/dev.db-journal .tmp/dev.db-wal .tmp/dev.db-shm; export DATABASE_URL=file:./.tmp/dev.db; pnpm run prisma-generate && pnpm exec prisma migrate deploy && playwright test --project=chromium" }, "dependencies": { "@libsql/client": "^0.15.15", @@ -19,7 +19,6 @@ "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", - "iron-session": "^9.0.1", "redaxios": "catalog:", "tailwind-merge": "^3.6.0", "vue": "^3.5.25" @@ -33,21 +32,10 @@ "@vitejs/plugin-vue-jsx": "^5.1.5", "dotenv": "^17.2.3", "prisma": "^7.0.0", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" - }, - "nx": { - "targets": { - "test:e2e": { - "outputs": [ - "...", - "{projectRoot}/.tmp", - "{projectRoot}/src/prisma-generated" - ] - } - } } } diff --git a/e2e/vue-start/basic-auth/playwright.config.ts b/e2e/vue-start/basic-auth/playwright.config.ts index 82678ac00b..18b8905468 100644 --- a/e2e/vue-start/basic-auth/playwright.config.ts +++ b/e2e/vue-start/basic-auth/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/basic-auth/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/basic-auth/src/components/DefaultCatchBoundary.tsx index 0687372ae0..02caf56456 100644 --- a/e2e/vue-start/basic-auth/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/basic-auth/src/components/DefaultCatchBoundary.tsx @@ -1,5 +1,3 @@ -import { defineComponent } from 'vue' -import type { PropType } from 'vue' import { ErrorComponent, Link, @@ -8,54 +6,46 @@ import { } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -export const DefaultCatchBoundary = defineComponent({ - props: { - error: { - type: Object as PropType, - required: true, - }, - }, - setup(props) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - return () => { - console.error(props.error) - return ( -
- -
- - {isRoot.value ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) - } - }, -}) +export function DefaultCatchBoundary({ error }: ErrorComponentProps) { + const router = useRouter() + const isRoot = useLocation({ + select: (location) => location.pathname === '/', + }) + + console.error(error) + + return ( +
+ +
+ + {isRoot.value ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
+
+ ) +} diff --git a/e2e/vue-start/basic-auth/src/routes/__root.tsx b/e2e/vue-start/basic-auth/src/routes/__root.tsx index e5b6f6778f..89802cfd2f 100644 --- a/e2e/vue-start/basic-auth/src/routes/__root.tsx +++ b/e2e/vue-start/basic-auth/src/routes/__root.tsx @@ -1,5 +1,4 @@ /// -import { defineComponent } from 'vue' import { Body, HeadContent, @@ -16,69 +15,21 @@ import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary.js' import { NotFound } from '~/components/NotFound.js' import appCss from '~/styles/app.css?url' import { seo } from '~/utils/seo.js' -import { getAppSession } from '~/utils/session.js' +import { useAppSession } from '~/utils/session.js' const fetchUser = createServerFn({ method: 'GET' }).handler(async () => { // We need to auth on the server so we have access to secure cookies - const session = await getAppSession() + const session = await useAppSession() - if (!session.userEmail) { + if (!session.data.userEmail) { return null } return { - email: session.userEmail, + email: session.data.userEmail, } }) -const RootShell = defineComponent({ - setup(_, { slots }) { - const routeContext = Route.useRouteContext() - return () => ( - - - - - -
- - Home - {' '} - - Posts - -
- {routeContext.value.user ? ( - <> - {routeContext.value.user.email} - Logout - - ) : ( - Login - )} -
-
-
- {slots.default?.()} - - - - - ) - }, -}) - export const Route = createRootRoute({ beforeLoad: async () => { const user = await fetchUser() @@ -130,3 +81,50 @@ export const Route = createRootRoute({ notFoundComponent: () => , component: () => , }) + +function RootShell(_: unknown, { slots }: { slots: any }) { + const routeContext = Route.useRouteContext() + + return ( + + + + + +
+ + Home + {' '} + + Posts + +
+ {routeContext.value.user ? ( + <> + {routeContext.value.user.email} + Logout + + ) : ( + Login + )} +
+
+
+ {slots.default?.()} + + + + + ) +} diff --git a/e2e/vue-start/basic-auth/src/routes/_authed.tsx b/e2e/vue-start/basic-auth/src/routes/_authed.tsx index 606de3e487..ba88e3beac 100644 --- a/e2e/vue-start/basic-auth/src/routes/_authed.tsx +++ b/e2e/vue-start/basic-auth/src/routes/_authed.tsx @@ -3,7 +3,7 @@ import { createServerFn } from '@tanstack/vue-start' import { hashPassword, prismaClient } from '~/utils/prisma' import { Login } from '~/components/Login' -import { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' export const loginFn = createServerFn({ method: 'POST', @@ -37,11 +37,12 @@ export const loginFn = createServerFn({ } // Create a session - const session = await getAppSession() + const session = await useAppSession() // Store the user's email in the session - session.userEmail = user.email - await session.save() + await session.update({ + userEmail: user.email, + }) }) export const Route = createFileRoute('/_authed')({ diff --git a/e2e/vue-start/basic-auth/src/routes/_authed/posts.$postId.tsx b/e2e/vue-start/basic-auth/src/routes/_authed/posts.$postId.tsx index 45d6bbab0d..da0c26f27f 100644 --- a/e2e/vue-start/basic-auth/src/routes/_authed/posts.$postId.tsx +++ b/e2e/vue-start/basic-auth/src/routes/_authed/posts.$postId.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -9,18 +8,6 @@ export function PostErrorComponent({ error }: ErrorComponentProps) { return } -const PostComponent = defineComponent({ - setup() { - const post = Route.useLoaderData() - return () => ( -
-

{post.value.title}

-
{post.value.body}
-
- ) - }, -}) - export const Route = createFileRoute('/_authed/posts/$postId')({ loader: ({ params: { postId } }) => fetchPost({ data: postId }), errorComponent: PostErrorComponent, @@ -29,3 +16,14 @@ export const Route = createFileRoute('/_authed/posts/$postId')({ return Post not found }, }) + +function PostComponent() { + const post = Route.useLoaderData() + + return ( +
+

{post.value.title}

+
{post.value.body}
+
+ ) +} diff --git a/e2e/vue-start/basic-auth/src/routes/_authed/posts.tsx b/e2e/vue-start/basic-auth/src/routes/_authed/posts.tsx index 6b8b54c666..cfac133b51 100644 --- a/e2e/vue-start/basic-auth/src/routes/_authed/posts.tsx +++ b/e2e/vue-start/basic-auth/src/routes/_authed/posts.tsx @@ -1,38 +1,36 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '~/utils/posts.js' -const PostsComponent = defineComponent({ - setup() { - const posts = Route.useLoaderData() - return () => ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ))} -
-
- -
- ) - }, -}) +function PostsComponent() { + const posts = Route.useLoaderData() + + return ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ))} +
+
+ +
+ ) +} export const Route = createFileRoute('/_authed/posts')({ loader: () => fetchPosts(), diff --git a/e2e/vue-start/basic-auth/src/routes/logout.tsx b/e2e/vue-start/basic-auth/src/routes/logout.tsx index 8372b33608..f1d7b58e29 100644 --- a/e2e/vue-start/basic-auth/src/routes/logout.tsx +++ b/e2e/vue-start/basic-auth/src/routes/logout.tsx @@ -1,12 +1,12 @@ import { redirect, createFileRoute } from '@tanstack/vue-router' import { createServerFn } from '@tanstack/vue-start' -import { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await getAppSession() + const session = await useAppSession() - session.destroy() + session.clear() throw redirect({ href: '/', diff --git a/e2e/vue-start/basic-auth/src/routes/signup.tsx b/e2e/vue-start/basic-auth/src/routes/signup.tsx index 5f37f109c7..eade8363e6 100644 --- a/e2e/vue-start/basic-auth/src/routes/signup.tsx +++ b/e2e/vue-start/basic-auth/src/routes/signup.tsx @@ -5,7 +5,7 @@ import { defineComponent } from 'vue' import { hashPassword, prismaClient } from '~/utils/prisma' import { useMutation } from '~/hooks/useMutation' import { Auth } from '~/components/Auth' -import { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' export const signupFn = createServerFn({ method: 'POST', @@ -25,7 +25,7 @@ export const signupFn = createServerFn({ const password = await hashPassword(payload.password) // Create a session - const session = await getAppSession() + const session = await useAppSession() if (found) { if (found.password !== password) { @@ -37,8 +37,9 @@ export const signupFn = createServerFn({ } // Store the user's email in the session - session.userEmail = found.email - await session.save() + await session.update({ + userEmail: found.email, + }) // Redirect to the prev page stored in the "redirect" search param throw redirect({ @@ -55,8 +56,9 @@ export const signupFn = createServerFn({ }) // Store the user's email in the session - session.userEmail = user.email - await session.save() + await session.update({ + userEmail: user.email, + }) // Redirect to the prev page stored in the "redirect" search param throw redirect({ diff --git a/e2e/vue-start/basic-auth/src/utils/session.ts b/e2e/vue-start/basic-auth/src/utils/session.ts index 7d078225a0..7cf2a41792 100644 --- a/e2e/vue-start/basic-auth/src/utils/session.ts +++ b/e2e/vue-start/basic-auth/src/utils/session.ts @@ -1,25 +1,13 @@ -import { getIronSession } from 'iron-session' -import { getCookie, setCookie } from '@tanstack/vue-start/server' +// src/services/session.server.ts +import { useSession } from '@tanstack/vue-start/server' import type { User } from '~/prisma-generated/client' type SessionUser = { userEmail: User['email'] } -export function getAppSession() { - return getIronSession( - { read: getCookie, write: setCookie }, - { - cookieName: 'test-auth-session', - // This fixture only runs locally with test credentials. - password: 'local-e2e-only-session-password-at-least-32-characters', - ttl: 60 * 60, - cookieOptions: { - httpOnly: true, - secure: false, - sameSite: 'lax', - path: '/', - }, - }, - ) +export function useAppSession() { + return useSession({ + password: 'ChangeThisBeforeShippingToProdOrYouWillBeFired', + }) } diff --git a/e2e/vue-start/basic-cloudflare/package.json b/e2e/vue-start/basic-cloudflare/package.json index 5ab77db8fc..612a6b8d19 100644 --- a/e2e/vue-start/basic-cloudflare/package.json +++ b/e2e/vue-start/basic-cloudflare/package.json @@ -10,7 +10,7 @@ "preview": "vite preview", "cf-typegen": "wrangler types", "postinstall": "WRANGLER_LOG=warn npm run --silent cf-typegen", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -31,15 +31,5 @@ "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "wrangler": "^4.74.0" - }, - "nx": { - "targets": { - "test:e2e": { - "outputs": [ - "...", - "{projectRoot}/.wrangler/deploy" - ] - } - } } } diff --git a/e2e/vue-start/basic-cloudflare/playwright.config.ts b/e2e/vue-start/basic-cloudflare/playwright.config.ts index 0925936d55..a545dff891 100644 --- a/e2e/vue-start/basic-cloudflare/playwright.config.ts +++ b/e2e/vue-start/basic-cloudflare/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,6 +14,9 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, @@ -20,8 +24,8 @@ export default defineConfig({ webServer: { command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx index 0687372ae0..02caf56456 100644 --- a/e2e/vue-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx @@ -1,5 +1,3 @@ -import { defineComponent } from 'vue' -import type { PropType } from 'vue' import { ErrorComponent, Link, @@ -8,54 +6,46 @@ import { } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -export const DefaultCatchBoundary = defineComponent({ - props: { - error: { - type: Object as PropType, - required: true, - }, - }, - setup(props) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - return () => { - console.error(props.error) - return ( -
- -
- - {isRoot.value ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) - } - }, -}) +export function DefaultCatchBoundary({ error }: ErrorComponentProps) { + const router = useRouter() + const isRoot = useLocation({ + select: (location) => location.pathname === '/', + }) + + console.error(error) + + return ( +
+ +
+ + {isRoot.value ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
+
+ ) +} diff --git a/e2e/vue-start/basic-cloudflare/src/routes/index.tsx b/e2e/vue-start/basic-cloudflare/src/routes/index.tsx index d3a020c7ad..1c708a7ec6 100644 --- a/e2e/vue-start/basic-cloudflare/src/routes/index.tsx +++ b/e2e/vue-start/basic-cloudflare/src/routes/index.tsx @@ -1,21 +1,7 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { createServerFn } from '@tanstack/vue-start' import { env } from 'cloudflare:workers' -const Home = defineComponent({ - setup() { - const data = Route.useLoaderData() - return () => ( -
-

Welcome Home!!!

-

{data.value.message}

-

{data.value.myVar}

-
- ) - }, -}) - export const Route = createFileRoute('/')({ loader: () => getData(), component: Home, @@ -27,3 +13,15 @@ const getData = createServerFn().handler(() => { myVar: env.MY_VAR, } }) + +function Home() { + const data = Route.useLoaderData() + + return ( +
+

Welcome Home!!!

+

{data.value.message}

+

{data.value.myVar}

+
+ ) +} diff --git a/e2e/vue-start/basic-cloudflare/src/routes/static.tsx b/e2e/vue-start/basic-cloudflare/src/routes/static.tsx index 14d0c06294..7b0f9fd232 100644 --- a/e2e/vue-start/basic-cloudflare/src/routes/static.tsx +++ b/e2e/vue-start/basic-cloudflare/src/routes/static.tsx @@ -1,20 +1,7 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { createServerFn } from '@tanstack/vue-start' import { env } from 'cloudflare:workers' -const StaticPage = defineComponent({ - setup() { - const data = Route.useLoaderData() - return () => ( -
-

Static Page

-

The value is {data.value.myVar}

-
- ) - }, -}) - export const Route = createFileRoute('/static')({ loader: () => getData(), component: StaticPage, @@ -25,3 +12,14 @@ const getData = createServerFn().handler(() => { myVar: env.MY_VAR, } }) + +function StaticPage() { + const data = Route.useLoaderData() + + return ( +
+

Static Page

+

The value is {data.value.myVar}

+
+ ) +} diff --git a/e2e/vue-start/basic-cloudflare/tests/setup/global.setup.ts b/e2e/vue-start/basic-cloudflare/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-start/basic-cloudflare/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/basic-cloudflare/tests/setup/global.teardown.ts b/e2e/vue-start/basic-cloudflare/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-start/basic-cloudflare/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/basic-tsr-config/package.json b/e2e/vue-start/basic-tsr-config/package.json index 828dce5b2a..9884efa343 100644 --- a/e2e/vue-start/basic-tsr-config/package.json +++ b/e2e/vue-start/basic-tsr-config/package.json @@ -8,7 +8,7 @@ "dev:e2e": "vite dev", "build": "rimraf ./count.txt && vite build && tsc --noEmit", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -19,7 +19,7 @@ "devDependencies": { "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "@vitejs/plugin-vue": "^6.0.5", diff --git a/e2e/vue-start/basic-tsr-config/playwright.config.ts b/e2e/vue-start/basic-tsr-config/playwright.config.ts index e6b92ce385..f6dd61ba6c 100644 --- a/e2e/vue-start/basic-tsr-config/playwright.config.ts +++ b/e2e/vue-start/basic-tsr-config/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/basic-tsr-config/src/app/routes/index.tsx b/e2e/vue-start/basic-tsr-config/src/app/routes/index.tsx index b4b520e8af..3f4de50817 100644 --- a/e2e/vue-start/basic-tsr-config/src/app/routes/index.tsx +++ b/e2e/vue-start/basic-tsr-config/src/app/routes/index.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import * as fs from 'node:fs' import { createFileRoute, useRouter } from '@tanstack/vue-router' import { createServerFn } from '@tanstack/vue-start' @@ -18,26 +17,25 @@ const updateCount = createServerFn({ method: 'POST' }) const count = await getCount() await fs.promises.writeFile(filePath, `${count + data}`) }) -const Home = defineComponent({ - setup() { - const router = useRouter() - const state = Route.useLoaderData() - return () => ( - - ) - }, -}) - export const Route = createFileRoute('/')({ component: Home, loader: async () => await getCount(), }) + +function Home() { + const router = useRouter() + const state = Route.useLoaderData() + + return ( + + ) +} diff --git a/e2e/vue-start/basic-vue-query/package.json b/e2e/vue-start/basic-vue-query/package.json index ab9589376d..1003bd2e27 100644 --- a/e2e/vue-start/basic-vue-query/package.json +++ b/e2e/vue-start/basic-vue-query/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-query": "^5.92.1", @@ -30,7 +30,7 @@ "@types/node": "^22.10.2", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/vue-start/basic-vue-query/playwright.config.ts b/e2e/vue-start/basic-vue-query/playwright.config.ts index 0618b7272a..84636ab0f9 100644 --- a/e2e/vue-start/basic-vue-query/playwright.config.ts +++ b/e2e/vue-start/basic-vue-query/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` @@ -11,18 +16,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { baseURL, }, webServer: { - command: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', - env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, - }, }, projects: [ diff --git a/e2e/vue-start/basic-vue-query/src/routes/api.users.ts b/e2e/vue-start/basic-vue-query/src/routes/api.users.ts index f9330a87db..cab4cafc3f 100644 --- a/e2e/vue-start/basic-vue-query/src/routes/api.users.ts +++ b/e2e/vue-start/basic-vue-query/src/routes/api.users.ts @@ -2,7 +2,11 @@ import { createFileRoute } from '@tanstack/vue-router' import axios from 'redaxios' import type { User } from '../utils/users' -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const Route = createFileRoute('/api/users')({ server: { diff --git a/e2e/vue-start/basic-vue-query/src/routes/api/users.$id.ts b/e2e/vue-start/basic-vue-query/src/routes/api/users.$id.ts index d138746730..4cc4b33a0b 100644 --- a/e2e/vue-start/basic-vue-query/src/routes/api/users.$id.ts +++ b/e2e/vue-start/basic-vue-query/src/routes/api/users.$id.ts @@ -2,7 +2,11 @@ import { createFileRoute } from '@tanstack/vue-router' import axios from 'redaxios' import type { User } from '../../utils/users' -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const Route = createFileRoute('/api/users/$id')({ server: { diff --git a/e2e/vue-start/basic-vue-query/src/routes/posts.$postId.tsx b/e2e/vue-start/basic-vue-query/src/routes/posts.$postId.tsx index fd8deaf291..27baf4bd5f 100644 --- a/e2e/vue-start/basic-vue-query/src/routes/posts.$postId.tsx +++ b/e2e/vue-start/basic-vue-query/src/routes/posts.$postId.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { useQuery } from '@tanstack/vue-query' import { ErrorComponent, @@ -12,30 +11,27 @@ export function PostErrorComponent(props: ErrorComponentProps) { return } -const PostComponent = defineComponent({ - setup() { - const params = Route.useParams() - const postQuery = useQuery(() => postQueryOptions(params.value.postId)) - return () => ( -
-

- {postQuery.data.value?.title} -

-
{postQuery.data.value?.body}
- - Deep View - -
- ) - }, -}) +function PostComponent() { + const params = Route.useParams() + const postQuery = useQuery(() => postQueryOptions(params.value.postId)) + + return ( +
+

{postQuery.data.value?.title}

+
{postQuery.data.value?.body}
+ + Deep View + +
+ ) +} export const Route = createFileRoute('/posts/$postId')({ loader: async ({ context, params }) => { diff --git a/e2e/vue-start/basic-vue-query/src/routes/posts_.$postId.deep.tsx b/e2e/vue-start/basic-vue-query/src/routes/posts_.$postId.deep.tsx index 211b3ca4b1..38e7429f6e 100644 --- a/e2e/vue-start/basic-vue-query/src/routes/posts_.$postId.deep.tsx +++ b/e2e/vue-start/basic-vue-query/src/routes/posts_.$postId.deep.tsx @@ -1,26 +1,22 @@ -import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' import { useQuery } from '@tanstack/vue-query' import { postQueryOptions } from '../utils/posts' import { PostErrorComponent } from './posts.$postId' -const PostDeepComponent = defineComponent({ - setup() { - const params = Route.useParams() - const postQuery = useQuery(() => postQueryOptions(params.value.postId)) - return () => ( -
- - ← All Posts - -

- {postQuery.data.value?.title} -

-
{postQuery.data.value?.body}
-
- ) - }, -}) +function PostDeepComponent() { + const params = Route.useParams() + const postQuery = useQuery(() => postQueryOptions(params.value.postId)) + + return ( +
+ + ← All Posts + +

{postQuery.data.value?.title}

+
{postQuery.data.value?.body}
+
+ ) +} export const Route = createFileRoute('/posts_/$postId/deep')({ loader: async ({ params: { postId }, context }) => { diff --git a/e2e/vue-start/basic-vue-query/src/routes/suspense-transition.tsx b/e2e/vue-start/basic-vue-query/src/routes/suspense-transition.tsx index f5004aa21d..6d12790dc9 100644 --- a/e2e/vue-start/basic-vue-query/src/routes/suspense-transition.tsx +++ b/e2e/vue-start/basic-vue-query/src/routes/suspense-transition.tsx @@ -1,6 +1,6 @@ import { queryOptions, useQuery } from '@tanstack/vue-query' import { Link, createFileRoute } from '@tanstack/vue-router' -import { defineComponent, ref, watchEffect } from 'vue' +import { ref, watchEffect } from 'vue' const doubleQueryOptions = (n: number) => queryOptions({ @@ -19,37 +19,6 @@ export const Route = createFileRoute('/suspense-transition')({ ssr: false, // Disable SSR to avoid suspense issues during initial load }) -const Result = defineComponent({ - setup() { - const search = Route.useSearch() - const doubleQuery = useQuery(() => doubleQueryOptions(search.value.n)) - const displayedN = ref(search.value.n) - const displayedDouble = ref(undefined) - watchEffect(() => { - if (doubleQuery.data.value !== undefined) { - displayedN.value = search.value.n - displayedDouble.value = doubleQuery.data.value - } - }) - return () => ( -
-
- Loading... -
-
-
- n: {displayedN.value} -
-
- double:{' '} - {displayedDouble.value} -
-
-
- ) - }, -}) - function SuspenseTransitionComponent() { return (
@@ -70,3 +39,34 @@ function SuspenseTransitionComponent() {
) } + +function Result() { + const search = Route.useSearch() + const doubleQuery = useQuery(() => doubleQueryOptions(search.value.n)) + const displayedN = ref(search.value.n) + const displayedDouble = ref(undefined) + + watchEffect(() => { + if (doubleQuery.data.value !== undefined) { + displayedN.value = search.value.n + displayedDouble.value = doubleQuery.data.value + } + }) + + return ( +
+
+ Loading... +
+
+
+ n: {displayedN.value} +
+
+ double:{' '} + {displayedDouble.value} +
+
+
+ ) +} diff --git a/e2e/vue-start/basic-vue-query/src/routes/transition/count/query.tsx b/e2e/vue-start/basic-vue-query/src/routes/transition/count/query.tsx index 32b1943c71..2ab0562203 100644 --- a/e2e/vue-start/basic-vue-query/src/routes/transition/count/query.tsx +++ b/e2e/vue-start/basic-vue-query/src/routes/transition/count/query.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' import { queryOptions, useQuery } from '@tanstack/vue-query' import { z } from 'zod' @@ -17,32 +16,6 @@ const doubleQueryOptions = (n: number) => placeholderData: (oldData) => oldData, }) -const TransitionPage = defineComponent({ - setup() { - const search = Route.useSearch() - const doubleQuery = useQuery(() => doubleQueryOptions(search.value.n)) - return () => ( -
- ({ n: s.n + 1 })} - > - Increase - - -
-
n: {doubleQuery.data.value?.n}
-
- double: {doubleQuery.data.value?.double} -
-
-
- ) - }, -}) - export const Route = createFileRoute('/transition/count/query')({ validateSearch: searchSchema, loader: ({ context: { queryClient }, location }) => { @@ -51,3 +24,28 @@ export const Route = createFileRoute('/transition/count/query')({ }, component: TransitionPage, }) + +function TransitionPage() { + const search = Route.useSearch() + const doubleQuery = useQuery(() => doubleQueryOptions(search.value.n)) + + return ( +
+ ({ n: s.n + 1 })} + > + Increase + + +
+
n: {doubleQuery.data.value?.n}
+
+ double: {doubleQuery.data.value?.double} +
+
+
+ ) +} diff --git a/e2e/vue-start/basic-vue-query/src/routes/users.$userId.tsx b/e2e/vue-start/basic-vue-query/src/routes/users.$userId.tsx index bf1b75861e..91376b9498 100644 --- a/e2e/vue-start/basic-vue-query/src/routes/users.$userId.tsx +++ b/e2e/vue-start/basic-vue-query/src/routes/users.$userId.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { useQuery } from '@tanstack/vue-query' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -6,20 +5,19 @@ import type { ErrorComponentProps } from '@tanstack/vue-router' import { NotFound } from '~/components/NotFound' import { userQueryOptions } from '~/utils/users' -const UserComponent = defineComponent({ - setup() { - const params = Route.useParams() - const userQuery = useQuery(() => userQueryOptions(params.value.userId)) - return () => ( -
-

- {userQuery.data.value?.name ?? 'loading...'} -

-
{userQuery.data.value?.email ?? ''}
-
- ) - }, -}) +function UserComponent() { + const params = Route.useParams() + const userQuery = useQuery(() => userQueryOptions(params.value.userId)) + + return ( +
+

+ {userQuery.data.value?.name ?? 'loading...'} +

+
{userQuery.data.value?.email ?? ''}
+
+ ) +} export const Route = createFileRoute('/users/$userId')({ loader: async ({ context, params: { userId } }) => { diff --git a/e2e/vue-start/basic-vue-query/src/utils/posts.tsx b/e2e/vue-start/basic-vue-query/src/utils/posts.tsx index c6b5e70a0b..b0a0b8f60d 100644 --- a/e2e/vue-start/basic-vue-query/src/utils/posts.tsx +++ b/e2e/vue-start/basic-vue-query/src/utils/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const postsQueryOptions = () => queryOptions({ diff --git a/e2e/vue-start/basic-vue-query/src/utils/users.tsx b/e2e/vue-start/basic-vue-query/src/utils/users.tsx index fe7a902fa2..29bf08c315 100644 --- a/e2e/vue-start/basic-vue-query/src/utils/users.tsx +++ b/e2e/vue-start/basic-vue-query/src/utils/users.tsx @@ -1,6 +1,4 @@ import { queryOptions } from '@tanstack/vue-query' -import { createIsomorphicFn } from '@tanstack/vue-start' -import { getRequestUrl } from '@tanstack/vue-start/server' import axios from 'redaxios' export type User = { @@ -9,16 +7,17 @@ export type User = { email: string } -const getOrigin = createIsomorphicFn() - .server(() => getRequestUrl().origin) - .client(() => window.location.origin) +const PORT = + import.meta.env.VITE_SERVER_PORT || process.env.VITE_SERVER_PORT || 3000 + +export const DEPLOY_URL = `http://localhost:${PORT}` export const usersQueryOptions = () => queryOptions({ queryKey: ['users'], queryFn: () => axios - .get>(getOrigin() + '/api/users') + .get>(DEPLOY_URL + '/api/users') .then((r) => r.data) .catch(() => { throw new Error('Failed to fetch users') @@ -30,7 +29,7 @@ export const userQueryOptions = (id: string) => queryKey: ['users', id], queryFn: () => axios - .get(getOrigin() + '/api/users/' + id) + .get(DEPLOY_URL + '/api/users/' + id) .then((r) => r.data) .catch(() => { throw new Error('Failed to fetch user') diff --git a/e2e/vue-start/basic-vue-query/tests/app.spec.ts b/e2e/vue-start/basic-vue-query/tests/app.spec.ts index 4ce5c20ef7..ab2469f68d 100644 --- a/e2e/vue-start/basic-vue-query/tests/app.spec.ts +++ b/e2e/vue-start/basic-vue-query/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test('Navigating to post', async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-start/basic-vue-query/tests/setup/global.setup.ts b/e2e/vue-start/basic-vue-query/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-start/basic-vue-query/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/basic-vue-query/tests/setup/global.teardown.ts b/e2e/vue-start/basic-vue-query/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-start/basic-vue-query/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/basic-vue-query/tests/transition.spec.ts b/e2e/vue-start/basic-vue-query/tests/transition.spec.ts index a0f3bf0964..2c28fc72a2 100644 --- a/e2e/vue-start/basic-vue-query/tests/transition.spec.ts +++ b/e2e/vue-start/basic-vue-query/tests/transition.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test('transitions/count/query should keep old values visible during navigation', async ({ page, diff --git a/e2e/vue-start/basic/package.json b/e2e/vue-start/basic/package.json index 2ff8329543..6d456525b5 100644 --- a/e2e/vue-start/basic/package.json +++ b/e2e/vue-start/basic/package.json @@ -6,12 +6,12 @@ "scripts": { "dev": "vite dev --port 3000", "dev:e2e": "vite dev", - "build": "pnpm build:vite", + "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "node server.js", - "test:e2e:local": "playwright test --project=chromium", - "build:vite": "vite build && tsc --noEmit", - "build:rsbuild": "rsbuild build && tsc --noEmit" + "test:e2e:startDummyServer": "node -e 'import(\"./tests/setup/global.setup.ts\").then(m => m.default())' & node -e 'import(\"./tests/setup/waitForDummyServer.ts\").then(m => m.default())'", + "test:e2e:stopDummyServer": "node -e 'import(\"./tests/setup/global.teardown.ts\").then(m => m.default())'", + "test:e2e:local": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -27,7 +27,7 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-babel": "^1.1.2", "@rsbuild/plugin-vue": "^1.2.7", "@rsbuild/plugin-vue-jsx": "^2.0.0", @@ -39,7 +39,7 @@ "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "combinate": "^1.1.11", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", @@ -59,10 +59,7 @@ }, { "toolchain": "vite", - "mode": "prerender", - "env": { - "NODE_OPTIONS": "--import=@tanstack/router-e2e-utils/mock-api" - } + "mode": "prerender" }, { "toolchain": "vite", diff --git a/e2e/vue-start/basic/playwright.config.ts b/e2e/vue-start/basic/playwright.config.ts index 9322874f3a..6924134cd1 100644 --- a/e2e/vue-start/basic/playwright.config.ts +++ b/e2e/vue-start/basic/playwright.config.ts @@ -1,37 +1,59 @@ +import fs from 'node:fs' import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } const mode = process.env.MODE ?? 'ssr' - +const e2ePortKey = process.env.E2E_PORT_KEY ?? packageJson.name const distDir = process.env.E2E_DIST_DIR ?? 'dist' -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +if (process.env.TEST_WORKER_INDEX === undefined) { + for (const portFile of [ + `port-${e2ePortKey}.txt`, + `port-${e2ePortKey}_start.txt`, + `port-${e2ePortKey}-external.txt`, + ]) { + fs.rmSync(portFile, { force: true }) + } +} + +const PORT = await getTestServerPort(e2ePortKey) +const START_PORT = await getTestServerPort(`${e2ePortKey}_start`) +const EXTERNAL_PORT = await getDummyServerPort(e2ePortKey) const baseURL = `http://localhost:${PORT}` const commandByMode = mode === 'preview' - ? `pnpm preview --host 0.0.0.0 --outDir ${distDir} --port ${PORT}` - : `pnpm start` + ? `pnpm run test:e2e:startDummyServer && pnpm preview --outDir ${distDir} --port ${PORT}` + : `pnpm run test:e2e:startDummyServer && pnpm start` export default defineConfig({ testDir: './tests', workers: 1, reporter: [['line']], + globalTeardown: './tests/setup/global.teardown.ts', + use: { baseURL, }, webServer: { command: commandByMode, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, MODE: mode, - START_PORT: '0', + VITE_NODE_ENV: 'test', + VITE_EXTERNAL_PORT: String(EXTERNAL_PORT), + VITE_SERVER_PORT: String(PORT), + START_PORT: String(START_PORT), PORT: String(PORT), E2E_DIST_DIR: distDir, + E2E_PORT_KEY: e2ePortKey, }, }, diff --git a/e2e/vue-start/basic/server.js b/e2e/vue-start/basic/server.js index 3e1ddab400..69c1e4ca91 100644 --- a/e2e/vue-start/basic/server.js +++ b/e2e/vue-start/basic/server.js @@ -1,12 +1,12 @@ +import { toNodeHandler } from 'srvx/node' import fs from 'node:fs' import path from 'node:path' -import { toNodeHandler } from 'srvx/node' import express from 'express' import { createProxyMiddleware } from 'http-proxy-middleware' -const port = Number(process.env.PORT ?? 3000) +const port = process.env.PORT || 3000 -const startPort = Number(process.env.START_PORT ?? 0) +const startPort = process.env.START_PORT || 3001 const isSpaMode = process.env.MODE === 'spa' const isPrerender = process.env.MODE === 'prerender' @@ -49,13 +49,13 @@ export async function createStartServer() { return { app } } -export async function createSpaServer(backendPort) { +export async function createSpaServer() { const app = express() app.use( '/api', createProxyMiddleware({ - target: `http://localhost:${backendPort}/api`, // Replace with your target server's URL + target: `http://localhost:${startPort}/api`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) @@ -63,7 +63,7 @@ export async function createSpaServer(backendPort) { app.use( '/_serverFn', createProxyMiddleware({ - target: `http://localhost:${backendPort}/_serverFn`, // Replace with your target server's URL + target: `http://localhost:${startPort}/_serverFn`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) @@ -71,28 +71,31 @@ export async function createSpaServer(backendPort) { app.use(express.static(distClientDir)) app.get('/{*splat}', (req, res) => { - res.sendFile('index.html', { root: distClientDir }) + res.sendFile(path.resolve(distClientDir, 'index.html')) }) return { app } } -// Bind the backend first so the SPA proxy receives the port actually held by it. -const { app: startApp } = await createStartServer() -const backend = startApp.listen(isSpaMode ? startPort : port, async (error) => { - if (error) { - throw error - } - const backendPort = backend.address().port - if (isSpaMode) { - const { app } = await createSpaServer(backendPort) - const frontend = app.listen(port, (frontendError) => { - if (frontendError) { - throw frontendError - } - console.info(`E2E app: http://localhost:${frontend.address().port}`) - }) - } else { - console.info(`E2E app: http://localhost:${backendPort}`) - } -}) +if (isSpaMode) { + createSpaServer().then(async ({ app }) => + app.listen(port, (error) => { + if (error) throw error + console.info(`Client Server: http://localhost:${port}`) + }), + ) + + createStartServer().then(async ({ app }) => + app.listen(startPort, (error) => { + if (error) throw error + console.info(`Start Server: http://localhost:${startPort}`) + }), + ) +} else { + createStartServer().then(async ({ app }) => + app.listen(port, (error) => { + if (error) throw error + console.info(`Start Server: http://localhost:${port}`) + }), + ) +} diff --git a/e2e/vue-start/basic/src/routes/__root.tsx b/e2e/vue-start/basic/src/routes/__root.tsx index 9da2c581fe..4a4bd08afe 100644 --- a/e2e/vue-start/basic/src/routes/__root.tsx +++ b/e2e/vue-start/basic/src/routes/__root.tsx @@ -1,5 +1,4 @@ /// -import { defineComponent } from 'vue' import { Body, ClientOnly, @@ -17,119 +16,6 @@ import { NotFound } from '~/components/NotFound' import '~/styles/app.css' import { seo } from '~/utils/seo' -const RootComponent = defineComponent({ - setup() { - const routerState = useRouterState({ - select: (state) => ({ isLoading: state.isLoading, status: state.status }), - }) - return () => ( - - - - - -
- - Home - {' '} - - Posts - {' '} - - Users - {' '} - - Layout - {' '} - - Scripts - {' '} - - Inline Scripts - {' '} - - Deferred - {' '} - - redirect - {' '} - - Raw Stream - {' '} - - This Route Does Not Exist - -
- - - - -
This is an inline styled div
- - - - - ) - }, -}) - export const Route = createRootRoute({ head: () => ({ meta: [ @@ -184,3 +70,115 @@ export const Route = createRootRoute({ notFoundComponent: () => , component: RootComponent, }) + +function RootComponent() { + const routerState = useRouterState({ + select: (state) => ({ isLoading: state.isLoading, status: state.status }), + }) + + return ( + + + + + +
+ + Home + {' '} + + Posts + {' '} + + Users + {' '} + + Layout + {' '} + + Scripts + {' '} + + Inline Scripts + {' '} + + Deferred + {' '} + + redirect + {' '} + + Raw Stream + {' '} + + This Route Does Not Exist + +
+ + + + +
This is an inline styled div
+ + + + + ) +} diff --git a/e2e/vue-start/basic/src/routes/api/users.$userId.ts b/e2e/vue-start/basic/src/routes/api/users.$userId.ts index 24938d51c2..50b9ca995a 100644 --- a/e2e/vue-start/basic/src/routes/api/users.$userId.ts +++ b/e2e/vue-start/basic/src/routes/api/users.$userId.ts @@ -1,15 +1,19 @@ import { createFileRoute } from '@tanstack/vue-router' import type { User } from '~/utils/users' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} + export const Route = createFileRoute('/api/users/$userId')({ server: { handlers: { GET: async ({ params, request }) => { console.info(`Fetching users by id=${params.userId}... @`, request.url) try { - const res = await fetch( - `https://jsonplaceholder.typicode.com/users/${params.userId}`, - ) + const res = await fetch(`${queryURL}/users/${params.userId}`) if (!res.ok) { throw new Error('Failed to fetch user') } diff --git a/e2e/vue-start/basic/src/routes/api/users.ts b/e2e/vue-start/basic/src/routes/api/users.ts index c6045977b8..97989b93ca 100644 --- a/e2e/vue-start/basic/src/routes/api/users.ts +++ b/e2e/vue-start/basic/src/routes/api/users.ts @@ -38,13 +38,19 @@ const testMiddleware = createMiddleware() return result }) +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} + export const Route = createFileRoute('/api/users')({ server: { middleware: [testMiddleware, userLoggerMiddleware, testParentMiddleware], handlers: { GET: async ({ request }) => { console.info('Fetching users... @', request.url) - const res = await fetch('https://jsonplaceholder.typicode.com/users') + const res = await fetch(`${queryURL}/users`) if (!res.ok) { throw new Error('Failed to fetch users') } diff --git a/e2e/vue-start/basic/src/routes/not-found/index.tsx b/e2e/vue-start/basic/src/routes/not-found/index.tsx index ecd12d1dad..9f7e3b4b33 100644 --- a/e2e/vue-start/basic/src/routes/not-found/index.tsx +++ b/e2e/vue-start/basic/src/routes/not-found/index.tsx @@ -1,10 +1,9 @@ -import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' -const RouteComponent = defineComponent({ - setup() { +export const Route = createFileRoute('/not-found/')({ + component: () => { const preload = Route.useSearch({ select: (s) => s.preload }) - return () => ( + return (
( -
-
- {loaderData.value.parentLoaderData} -
-
- ) - }, -}) - export const Route = createFileRoute('/not-found/parent-boundary')({ loader: () => ({ parentLoaderData: 'ready', @@ -29,3 +15,15 @@ function RouteComponent() {
) } + +function ParentBoundaryNotFoundComponent() { + const loaderData = Route.useLoaderData() + + return ( +
+
+ {loaderData.value.parentLoaderData} +
+
+ ) +} diff --git a/e2e/vue-start/basic/src/routes/posts.$postId.tsx b/e2e/vue-start/basic/src/routes/posts.$postId.tsx index edda7f0017..4d71080d64 100644 --- a/e2e/vue-start/basic/src/routes/posts.$postId.tsx +++ b/e2e/vue-start/basic/src/routes/posts.$postId.tsx @@ -1,32 +1,9 @@ -import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '~/utils/posts' import { NotFound } from '~/components/NotFound' import { PostErrorComponent } from '~/components/PostErrorComponent' -const PostComponent = defineComponent({ - setup() { - const post = Route.useLoaderData() - return () => ( -
-

{post.value.title}

-
{post.value.body}
- - Deep View - -
- ) - }, -}) - export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost({ data: postId }), errorComponent: PostErrorComponent, @@ -35,3 +12,24 @@ export const Route = createFileRoute('/posts/$postId')({ return Post not found }, }) + +function PostComponent() { + const post = Route.useLoaderData() + + return ( +
+

{post.value.title}

+
{post.value.body}
+ + Deep View + +
+ ) +} diff --git a/e2e/vue-start/basic/src/routes/posts.tsx b/e2e/vue-start/basic/src/routes/posts.tsx index 64d4754f2f..1a9d58a31d 100644 --- a/e2e/vue-start/basic/src/routes/posts.tsx +++ b/e2e/vue-start/basic/src/routes/posts.tsx @@ -1,36 +1,7 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '~/utils/posts' -const PostsComponent = defineComponent({ - setup() { - const posts = Route.useLoaderData() - return () => ( -
-
    - {posts.value.map((post) => ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ))} -
-
- -
- ) - }, -}) - export const Route = createFileRoute('/posts')({ head: () => ({ meta: [ @@ -42,3 +13,30 @@ export const Route = createFileRoute('/posts')({ loader: async () => fetchPosts(), component: PostsComponent, }) + +function PostsComponent() { + const posts = Route.useLoaderData() + + return ( +
+
    + {posts.value.map((post) => ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ))} +
+
+ +
+ ) +} diff --git a/e2e/vue-start/basic/src/routes/posts_.$postId.deep.tsx b/e2e/vue-start/basic/src/routes/posts_.$postId.deep.tsx index f77ae7d3ab..a52c6f32f7 100644 --- a/e2e/vue-start/basic/src/routes/posts_.$postId.deep.tsx +++ b/e2e/vue-start/basic/src/routes/posts_.$postId.deep.tsx @@ -1,26 +1,24 @@ -import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' import { PostErrorComponent } from '~/components/PostErrorComponent' import { fetchPost } from '~/utils/posts' -const PostDeepComponent = defineComponent({ - setup() { - const post = Route.useLoaderData() - return () => ( -
- - ← All Posts - -

{post.value.title}

-
{post.value.body}
-
- ) - }, -}) - export const Route = createFileRoute('/posts_/$postId/deep')({ loader: async ({ params: { postId } }) => fetchPost({ data: postId }), errorComponent: PostErrorComponent, component: PostDeepComponent, }) + +function PostDeepComponent() { + const post = Route.useLoaderData() + + return ( +
+ + ← All Posts + +

{post.value.title}

+
{post.value.body}
+
+ ) +} diff --git a/e2e/vue-start/basic/src/routes/redirect/$target/index.tsx b/e2e/vue-start/basic/src/routes/redirect/$target/index.tsx index e39bda5bcf..a8c3c75b1f 100644 --- a/e2e/vue-start/basic/src/routes/redirect/$target/index.tsx +++ b/e2e/vue-start/basic/src/routes/redirect/$target/index.tsx @@ -1,10 +1,9 @@ -import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' -const RouteComponent = defineComponent({ - setup() { +export const Route = createFileRoute('/redirect/$target/')({ + component: () => { const preload = Route.useSearch({ select: (s) => s.preload }) - return () => ( + return (
{ const params = Route.useParams() - return () => ( + return (

redirect test with server functions (target {params.value.target}) @@ -88,7 +87,3 @@ const RouteComponent = defineComponent({ ) }, }) - -export const Route = createFileRoute('/redirect/$target/serverFn/')({ - component: RouteComponent, -}) diff --git a/e2e/vue-start/basic/src/routes/redirect/$target/serverFn/via-useServerFn.tsx b/e2e/vue-start/basic/src/routes/redirect/$target/serverFn/via-useServerFn.tsx index 093a591636..399e8ac995 100644 --- a/e2e/vue-start/basic/src/routes/redirect/$target/serverFn/via-useServerFn.tsx +++ b/e2e/vue-start/basic/src/routes/redirect/$target/serverFn/via-useServerFn.tsx @@ -1,12 +1,13 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { RedirectOnClick } from '~/components/RedirectOnClick' -const RouteComponent = defineComponent({ - setup() { +export const Route = createFileRoute( + '/redirect/$target/serverFn/via-useServerFn', +)({ + component: () => { const params = Route.useParams() const search = Route.useSearch() - return () => ( + return ( ( - <> -
{search.value.default}
-
{context.value.hello}
- - ) - }, -}) - export const Route = createFileRoute('/search-params/default')({ validateSearch: z.object({ default: z.string().default('d1'), @@ -29,5 +15,14 @@ export const Route = createFileRoute('/search-params/default')({ throw new Error('Context hello is not "world"') } }, - component: RouteComponent, + component: () => { + const search = Route.useSearch() + const context = Route.useRouteContext() + return ( + <> +
{search.value.default}
+
{context.value.hello}
+ + ) + }, }) diff --git a/e2e/vue-start/basic/src/routes/search-params/loader-throws-redirect.tsx b/e2e/vue-start/basic/src/routes/search-params/loader-throws-redirect.tsx index ccd1276387..14b137abc6 100644 --- a/e2e/vue-start/basic/src/routes/search-params/loader-throws-redirect.tsx +++ b/e2e/vue-start/basic/src/routes/search-params/loader-throws-redirect.tsx @@ -1,19 +1,6 @@ -import { defineComponent } from 'vue' import { redirect, createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' -const RouteComponent = defineComponent({ - setup() { - const search = Route.useSearch() - return () => ( -
-

SearchParams

-
{search.value.step}
-
- ) - }, -}) - export const Route = createFileRoute('/search-params/loader-throws-redirect')({ validateSearch: z.object({ step: z.enum(['a', 'b', 'c']).optional(), @@ -27,5 +14,13 @@ export const Route = createFileRoute('/search-params/loader-throws-redirect')({ }) } }, - component: RouteComponent, + component: () => { + const search = Route.useSearch() + return ( +
+

SearchParams

+
{search.value.step}
+
+ ) + }, }) diff --git a/e2e/vue-start/basic/src/routes/specialChars/$param.tsx b/e2e/vue-start/basic/src/routes/specialChars/$param.tsx index ec315ede1f..de3cba0a97 100644 --- a/e2e/vue-start/basic/src/routes/specialChars/$param.tsx +++ b/e2e/vue-start/basic/src/routes/specialChars/$param.tsx @@ -1,18 +1,15 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' -const RouteComponent = defineComponent({ - setup() { - const params = Route.useParams() - return () => ( -
- Hello "/specialChars/$param":{' '} - {params.value.param} -
- ) - }, -}) - export const Route = createFileRoute('/specialChars/$param')({ component: RouteComponent, }) + +function RouteComponent() { + const params = Route.useParams() + return ( +
+ Hello "/specialChars/$param":{' '} + {params.value.param} +
+ ) +} diff --git a/e2e/vue-start/basic/src/routes/specialChars/malformed/$param.tsx b/e2e/vue-start/basic/src/routes/specialChars/malformed/$param.tsx index 2b19e7e36e..7160964549 100644 --- a/e2e/vue-start/basic/src/routes/specialChars/malformed/$param.tsx +++ b/e2e/vue-start/basic/src/routes/specialChars/malformed/$param.tsx @@ -1,20 +1,15 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' -const RouteComponent = defineComponent({ - setup() { - const params = Route.useParams() - return () => ( -
- Hello "/specialChars/malformed/$param":{' '} - - {params.value.param} - -
- ) - }, -}) - export const Route = createFileRoute('/specialChars/malformed/$param')({ component: RouteComponent, }) + +function RouteComponent() { + const params = Route.useParams() + return ( +
+ Hello "/specialChars/malformed/$param":{' '} + {params.value.param} +
+ ) +} diff --git a/e2e/vue-start/basic/src/routes/specialChars/malformed/search.tsx b/e2e/vue-start/basic/src/routes/specialChars/malformed/search.tsx index 8d6ad5b1dd..2438604954 100644 --- a/e2e/vue-start/basic/src/routes/specialChars/malformed/search.tsx +++ b/e2e/vue-start/basic/src/routes/specialChars/malformed/search.tsx @@ -1,24 +1,22 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import z from 'zod' -const RouteComponent = defineComponent({ - setup() { - const search = Route.useSearch() - return () => ( -
- Hello "/specialChars/malformed/search"! - - {search.value.searchParam} - -
- ) - }, -}) - export const Route = createFileRoute('/specialChars/malformed/search')({ validateSearch: z.object({ searchParam: z.string(), }), component: RouteComponent, }) + +function RouteComponent() { + const search = Route.useSearch() + + return ( +
+ Hello "/specialChars/malformed/search"! + + {search.value.searchParam} + +
+ ) +} diff --git a/e2e/vue-start/basic/src/routes/specialChars/search.tsx b/e2e/vue-start/basic/src/routes/specialChars/search.tsx index b4e022639d..5ba858e747 100644 --- a/e2e/vue-start/basic/src/routes/specialChars/search.tsx +++ b/e2e/vue-start/basic/src/routes/specialChars/search.tsx @@ -1,24 +1,22 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import z from 'zod' -const RouteComponent = defineComponent({ - setup() { - const search = Route.useSearch() - return () => ( -
- Hello "/specialChars/search"! - - {search.value.searchParam} - -
- ) - }, -}) - export const Route = createFileRoute('/specialChars/search')({ validateSearch: z.object({ searchParam: z.string(), }), component: RouteComponent, }) + +function RouteComponent() { + const search = Route.useSearch() + + return ( +
+ Hello "/specialChars/search"! + + {search.value.searchParam} + +
+ ) +} diff --git a/e2e/vue-start/basic/src/routes/users.$userId.tsx b/e2e/vue-start/basic/src/routes/users.$userId.tsx index 76340cf9fb..420b7e4a50 100644 --- a/e2e/vue-start/basic/src/routes/users.$userId.tsx +++ b/e2e/vue-start/basic/src/routes/users.$userId.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import axios from 'redaxios' @@ -7,18 +6,6 @@ import type { User } from '~/utils/users' import { NotFound } from '~/components/NotFound' import { UserErrorComponent } from '~/components/UserErrorComponent' -const UserComponent = defineComponent({ - setup() { - const user = Route.useLoaderData() - return () => ( -
-

{user.value.name}

-
{user.value.email}
-
- ) - }, -}) - export const Route = createFileRoute('/users/$userId')({ loader: async ({ params: { userId } }) => { const router = await getRouterInstance() @@ -35,3 +22,14 @@ export const Route = createFileRoute('/users/$userId')({ return User not found }, }) + +function UserComponent() { + const user = Route.useLoaderData() + + return ( +
+

{user.value.name}

+
{user.value.email}
+
+ ) +} diff --git a/e2e/vue-start/basic/src/routes/users.tsx b/e2e/vue-start/basic/src/routes/users.tsx index 3d8ef31598..1e0b297dd2 100644 --- a/e2e/vue-start/basic/src/routes/users.tsx +++ b/e2e/vue-start/basic/src/routes/users.tsx @@ -1,41 +1,9 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { getRouterInstance } from '@tanstack/vue-start' import axios from 'redaxios' import type { User } from '~/utils/users' -const UsersComponent = defineComponent({ - setup() { - const users = Route.useLoaderData() - return () => ( -
-
    - {[ - ...users.value, - { id: 'i-do-not-exist', name: 'Non-existent User', email: '' }, - ].map((user) => ( -
  • - -
    {user.name}
    - -
  • - ))} -
-
- -
- ) - }, -}) - export const Route = createFileRoute('/users')({ loader: async () => { const router = await getRouterInstance() @@ -48,3 +16,33 @@ export const Route = createFileRoute('/users')({ }, component: UsersComponent, }) + +function UsersComponent() { + const users = Route.useLoaderData() + + return ( +
+
    + {[ + ...users.value, + { id: 'i-do-not-exist', name: 'Non-existent User', email: '' }, + ].map((user) => ( +
  • + +
    {user.name}
    + +
  • + ))} +
+
+ +
+ ) +} diff --git a/e2e/vue-start/basic/src/utils/posts.tsx b/e2e/vue-start/basic/src/utils/posts.tsx index d8e2dc7450..66cb298f83 100644 --- a/e2e/vue-start/basic/src/utils/posts.tsx +++ b/e2e/vue-start/basic/src/utils/posts.tsx @@ -8,12 +8,18 @@ export type PostType = { body: string } +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} + export const fetchPost = createServerFn({ method: 'GET' }) .validator((postId: string) => postId) .handler(async ({ data: postId }) => { console.info(`Fetching post with id ${postId}...`) const post = await axios - .get(`https://jsonplaceholder.typicode.com/posts/${postId}`) + .get(`${queryURL}/posts/${postId}`) .then((r) => r.data) .catch((err) => { console.error(err) @@ -30,7 +36,7 @@ export const fetchPosts = createServerFn({ method: 'GET' }).handler( async () => { console.info('Fetching posts...') return axios - .get>('https://jsonplaceholder.typicode.com/posts') + .get>(`${queryURL}/posts`) .then((r) => r.data.slice(0, 10)) }, ) diff --git a/e2e/vue-start/basic/src/utils/users.tsx b/e2e/vue-start/basic/src/utils/users.tsx index 7ba645b383..46be4b1580 100644 --- a/e2e/vue-start/basic/src/utils/users.tsx +++ b/e2e/vue-start/basic/src/utils/users.tsx @@ -3,3 +3,7 @@ export type User = { name: string email: string } + +const PORT = process.env.VITE_SERVER_PORT || 3000 + +export const DEPLOY_URL = `http://localhost:${PORT}` diff --git a/e2e/vue-start/basic/src/vite-env.d.ts b/e2e/vue-start/basic/src/vite-env.d.ts index 4da6234c8a..e8259b1e33 100644 --- a/e2e/vue-start/basic/src/vite-env.d.ts +++ b/e2e/vue-start/basic/src/vite-env.d.ts @@ -2,6 +2,7 @@ interface ImportMetaEnv { readonly VITE_NODE_ENV: string + readonly VITE_EXTERNAL_PORT: string readonly VITE_SERVER_PORT: string } diff --git a/e2e/vue-start/basic/tests/fixture-api.spec.ts b/e2e/vue-start/basic/tests/fixture-api.spec.ts deleted file mode 100644 index 6c9b26dc4c..0000000000 --- a/e2e/vue-start/basic/tests/fixture-api.spec.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { expect, test } from '@playwright/test' - -test('server API receives canned users without a fixture listener', async ({ - request, -}) => { - const response = await request.get('/api/users') - expect(response.ok()).toBe(true) - const users = await response.json() - expect(users).toHaveLength(10) - expect(users[0]).toMatchObject({ id: 1, name: 'Leanne Graham' }) -}) diff --git a/e2e/vue-start/basic/tests/redirect.spec.ts b/e2e/vue-start/basic/tests/redirect.spec.ts index 8e6ceba5b9..2f6354aa81 100644 --- a/e2e/vue-start/basic/tests/redirect.spec.ts +++ b/e2e/vue-start/basic/tests/redirect.spec.ts @@ -1,14 +1,19 @@ import queryString from 'node:querystring' -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' +import { expect, type Page } from '@playwright/test' import combinateImport from 'combinate' -import type { Page } from '@playwright/test' +import { + getDummyServerPort, + getTestServerPort, + test, +} from '@tanstack/router-e2e-utils' +import { getE2EPortKey } from './utils/getE2EPortKey.ts' // somehow playwright does not correctly import default exports const combinate = (combinateImport as any).default as typeof combinateImport -const PORT = Number(process.env.E2E_APP_PORT ?? 0) -const EXTERNAL_ORIGIN = `http://127.0.0.1:${PORT}` +const e2ePortKey = getE2EPortKey() +const PORT = await getTestServerPort(e2ePortKey) +const EXTERNAL_HOST_PORT = await getDummyServerPort(e2ePortKey) const POSTS_URL = `http://localhost:${PORT}/posts` async function waitForRouterIdle(page: Page) { @@ -101,7 +106,7 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, }) if (scenario === 'navigate') { @@ -114,7 +119,7 @@ test.describe('redirects', () => { await page.goto(`/redirect/external/via-${thrower}?${q}`) } - const url = `${EXTERNAL_ORIGIN}/` + const url = `http://localhost:${EXTERNAL_HOST_PORT}/` await page.waitForURL(url) expect(page.url()).toBe(url) @@ -135,7 +140,7 @@ test.describe('redirects', () => { }) => { let fullPageLoad = false const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, reloadDocument, }) @@ -154,7 +159,10 @@ test.describe('redirects', () => { await page.goto(`/redirect/${target}/serverFn/via-${thrower}?${q}`) } - const url = target === 'internal' ? POSTS_URL : `${EXTERNAL_ORIGIN}/` + const url = + target === 'internal' + ? POSTS_URL + : `http://localhost:${EXTERNAL_HOST_PORT}/` await page.waitForURL(url) expect(page.url()).toBe(url) if (target === 'internal' && scenario === 'navigate') { @@ -176,7 +184,7 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, reloadDocument, }) @@ -193,7 +201,10 @@ test.describe('redirects', () => { await button.click() - const url = target === 'internal' ? POSTS_URL : `${EXTERNAL_ORIGIN}/` + const url = + target === 'internal' + ? POSTS_URL + : `http://localhost:${EXTERNAL_HOST_PORT}/` await page.waitForURL(url) expect(page.url()).toBe(url) if (target === 'internal') { diff --git a/e2e/vue-start/basic/tests/setup/global.setup.ts b/e2e/vue-start/basic/tests/setup/global.setup.ts new file mode 100644 index 0000000000..cd38c35885 --- /dev/null +++ b/e2e/vue-start/basic/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import { getE2EPortKey } from '../utils/getE2EPortKey.ts' + +export default async function setup() { + await e2eStartDummyServer(getE2EPortKey()) +} diff --git a/e2e/vue-start/basic/tests/setup/global.teardown.ts b/e2e/vue-start/basic/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..36e5c92858 --- /dev/null +++ b/e2e/vue-start/basic/tests/setup/global.teardown.ts @@ -0,0 +1,8 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import { getE2EPortKey } from '../utils/getE2EPortKey.ts' + +export default async function teardown() { + try { + await e2eStopDummyServer(getE2EPortKey()) + } catch {} +} diff --git a/e2e/vue-start/basic/tests/setup/waitForDummyServer.ts b/e2e/vue-start/basic/tests/setup/waitForDummyServer.ts new file mode 100644 index 0000000000..88c18fd79e --- /dev/null +++ b/e2e/vue-start/basic/tests/setup/waitForDummyServer.ts @@ -0,0 +1,24 @@ +import { getDummyServerPort } from '@tanstack/router-e2e-utils' +import { getE2EPortKey } from '../utils/getE2EPortKey.ts' + +const timeoutMs = 10_000 +const retryIntervalMs = 100 + +export default async function waitForDummyServer() { + const port = await getDummyServerPort(getE2EPortKey()) + const deadline = Date.now() + timeoutMs + + while (Date.now() < deadline) { + try { + const response = await fetch(`http://localhost:${port}/`) + + if (response.ok) { + return + } + } catch {} + + await new Promise((resolve) => setTimeout(resolve, retryIntervalMs)) + } + + throw new Error(`Timed out waiting for dummy server on port ${port}`) +} diff --git a/e2e/vue-start/basic/tests/utils/getE2EPortKey.ts b/e2e/vue-start/basic/tests/utils/getE2EPortKey.ts new file mode 100644 index 0000000000..48be6a9027 --- /dev/null +++ b/e2e/vue-start/basic/tests/utils/getE2EPortKey.ts @@ -0,0 +1,5 @@ +import { getPackageName } from './getPackageName.ts' + +export function getE2EPortKey() { + return process.env.E2E_PORT_KEY ?? getPackageName() +} diff --git a/e2e/vue-start/css-modules/package.json b/e2e/vue-start/css-modules/package.json index 3671774644..c739f09ea0 100644 --- a/e2e/vue-start/css-modules/package.json +++ b/e2e/vue-start/css-modules/package.json @@ -11,7 +11,7 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js", "test:e2e:dev": "MODE=dev playwright test --project=chromium", "test:e2e:prod": "playwright test --project=chromium", - "test:e2e": "pnpm run test:e2e:dev" + "test:e2e": "rm -rf port*.txt; pnpm run test:e2e:dev" }, "dependencies": { "@tanstack/vue-router": "workspace:*", @@ -24,7 +24,7 @@ "@types/node": "^22.10.2", "@vitejs/plugin-vue-jsx": "^5.1.5", "sass": "^1.97.2", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" diff --git a/e2e/vue-start/css-modules/playwright.config.ts b/e2e/vue-start/css-modules/playwright.config.ts index a50ac5ae63..0b810d5372 100644 --- a/e2e/vue-start/css-modules/playwright.config.ts +++ b/e2e/vue-start/css-modules/playwright.config.ts @@ -1,9 +1,10 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } const mode = process.env.MODE ?? 'prod' const isDev = mode === 'dev' -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -12,17 +13,16 @@ export default defineConfig({ reporter: [['line']], globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', use: { baseURL, }, webServer: { - command: isDev - ? `pnpm dev:e2e --port 0` - : `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: isDev ? `pnpm dev:e2e` : `pnpm build && PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { VITE_NODE_ENV: 'test', diff --git a/e2e/vue-start/css-modules/tests/setup/global.setup.ts b/e2e/vue-start/css-modules/tests/setup/global.setup.ts index 17be637f77..2d3a1db946 100644 --- a/e2e/vue-start/css-modules/tests/setup/global.setup.ts +++ b/e2e/vue-start/css-modules/tests/setup/global.setup.ts @@ -1,9 +1,17 @@ -import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' +import { + e2eStartDummyServer, + getTestServerPort, + preOptimizeDevServer, + waitForServer, +} from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } export default async function setup() { + await e2eStartDummyServer(packageJson.name) + if (process.env.MODE !== 'dev') return - const port = Number(process.env.E2E_APP_PORT ?? 0) + const port = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${port}` await waitForServer(baseURL) diff --git a/e2e/vue-start/css-modules/tests/setup/global.teardown.ts b/e2e/vue-start/css-modules/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-start/css-modules/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/custom-basepath/express-server.ts b/e2e/vue-start/custom-basepath/express-server.ts index b9bf393466..1884c5eb5a 100644 --- a/e2e/vue-start/custom-basepath/express-server.ts +++ b/e2e/vue-start/custom-basepath/express-server.ts @@ -1,6 +1,5 @@ import express from 'express' import { toNodeHandler } from 'srvx/node' -import type { AddressInfo } from 'node:net' import type { NodeHttp1Handler } from 'srvx' const DEVELOPMENT = process.env.NODE_ENV === 'development' @@ -41,11 +40,7 @@ if (DEVELOPMENT) { }) } -const httpServer = app.listen(PORT, (error) => { - if (error) { - throw error - } - console.log( - `E2E app: http://localhost:${(httpServer.address() as AddressInfo).port}`, - ) +app.listen(PORT, (error) => { + if (error) throw error + console.log(`Server is running on http://localhost:${PORT}`) }) diff --git a/e2e/vue-start/custom-basepath/package.json b/e2e/vue-start/custom-basepath/package.json index c1032ea88b..afc7d13c25 100644 --- a/e2e/vue-start/custom-basepath/package.json +++ b/e2e/vue-start/custom-basepath/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "tsx express-server.ts", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -25,7 +25,7 @@ "@types/express": "^5.0.6", "@types/node": "^22.10.2", "cross-env": "^10.0.0", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "tsx": "^4.20.3", "@typescript/native": "npm:typescript@^7.0.2", diff --git a/e2e/vue-start/custom-basepath/playwright.config.ts b/e2e/vue-start/custom-basepath/playwright.config.ts index e113ce64ad..5095425f47 100644 --- a/e2e/vue-start/custom-basepath/playwright.config.ts +++ b/e2e/vue-start/custom-basepath/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}/custom/basepath` /** @@ -13,19 +18,19 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', - env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, - }, }, projects: [ diff --git a/e2e/vue-start/custom-basepath/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/custom-basepath/src/components/DefaultCatchBoundary.tsx index 77c03c5afa..d06f4a948b 100644 --- a/e2e/vue-start/custom-basepath/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/custom-basepath/src/components/DefaultCatchBoundary.tsx @@ -1,5 +1,3 @@ -import { defineComponent } from 'vue' -import type { PropType } from 'vue' import { ErrorComponent, Link, @@ -8,54 +6,46 @@ import { } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -export const DefaultCatchBoundary = defineComponent({ - props: { - error: { - type: Object as PropType, - required: true, - }, - }, - setup(props) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - return () => { - console.error(props.error) - return ( -
- -
- - {isRoot.value ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) - } - }, -}) +export function DefaultCatchBoundary({ error }: ErrorComponentProps) { + const router = useRouter() + const isRoot = useLocation({ + select: (location) => location.pathname === '/', + }) + + console.error(error) + + return ( +
+ +
+ + {isRoot.value ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
+
+ ) +} diff --git a/e2e/vue-start/custom-basepath/src/routes/api/users.$userId.ts b/e2e/vue-start/custom-basepath/src/routes/api/users.$userId.ts index 7e3f528d68..50b9ca995a 100644 --- a/e2e/vue-start/custom-basepath/src/routes/api/users.$userId.ts +++ b/e2e/vue-start/custom-basepath/src/routes/api/users.$userId.ts @@ -1,7 +1,11 @@ import { createFileRoute } from '@tanstack/vue-router' import type { User } from '~/utils/users' -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const Route = createFileRoute('/api/users/$userId')({ server: { diff --git a/e2e/vue-start/custom-basepath/src/routes/api/users.ts b/e2e/vue-start/custom-basepath/src/routes/api/users.ts index dfdb5cd844..97989b93ca 100644 --- a/e2e/vue-start/custom-basepath/src/routes/api/users.ts +++ b/e2e/vue-start/custom-basepath/src/routes/api/users.ts @@ -38,7 +38,11 @@ const testMiddleware = createMiddleware() return result }) -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const Route = createFileRoute('/api/users')({ server: { diff --git a/e2e/vue-start/custom-basepath/src/routes/posts.$postId.tsx b/e2e/vue-start/custom-basepath/src/routes/posts.$postId.tsx index 599e0f046e..b4e5a8a6a2 100644 --- a/e2e/vue-start/custom-basepath/src/routes/posts.$postId.tsx +++ b/e2e/vue-start/custom-basepath/src/routes/posts.$postId.tsx @@ -1,32 +1,9 @@ -import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '~/utils/posts' import { NotFound } from '~/components/NotFound' import { PostErrorComponent } from '~/components/PostErrorComponent' -const PostComponent = defineComponent({ - setup() { - const post = Route.useLoaderData() - return () => ( -
-

{post.value.title}

-
{post.value.body}
- - Deep View - -
- ) - }, -}) - export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost({ data: postId }), errorComponent: PostErrorComponent, @@ -35,3 +12,24 @@ export const Route = createFileRoute('/posts/$postId')({ return Post not found }, }) + +function PostComponent() { + const post = Route.useLoaderData() + + return ( +
+

{post.value.title}

+
{post.value.body}
+ + Deep View + +
+ ) +} diff --git a/e2e/vue-start/custom-basepath/src/routes/posts.tsx b/e2e/vue-start/custom-basepath/src/routes/posts.tsx index 64d4754f2f..1a9d58a31d 100644 --- a/e2e/vue-start/custom-basepath/src/routes/posts.tsx +++ b/e2e/vue-start/custom-basepath/src/routes/posts.tsx @@ -1,36 +1,7 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '~/utils/posts' -const PostsComponent = defineComponent({ - setup() { - const posts = Route.useLoaderData() - return () => ( -
-
    - {posts.value.map((post) => ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ))} -
-
- -
- ) - }, -}) - export const Route = createFileRoute('/posts')({ head: () => ({ meta: [ @@ -42,3 +13,30 @@ export const Route = createFileRoute('/posts')({ loader: async () => fetchPosts(), component: PostsComponent, }) + +function PostsComponent() { + const posts = Route.useLoaderData() + + return ( +
+
    + {posts.value.map((post) => ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ))} +
+
+ +
+ ) +} diff --git a/e2e/vue-start/custom-basepath/src/routes/posts_.$postId.deep.tsx b/e2e/vue-start/custom-basepath/src/routes/posts_.$postId.deep.tsx index f77ae7d3ab..a52c6f32f7 100644 --- a/e2e/vue-start/custom-basepath/src/routes/posts_.$postId.deep.tsx +++ b/e2e/vue-start/custom-basepath/src/routes/posts_.$postId.deep.tsx @@ -1,26 +1,24 @@ -import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' import { PostErrorComponent } from '~/components/PostErrorComponent' import { fetchPost } from '~/utils/posts' -const PostDeepComponent = defineComponent({ - setup() { - const post = Route.useLoaderData() - return () => ( -
- - ← All Posts - -

{post.value.title}

-
{post.value.body}
-
- ) - }, -}) - export const Route = createFileRoute('/posts_/$postId/deep')({ loader: async ({ params: { postId } }) => fetchPost({ data: postId }), errorComponent: PostErrorComponent, component: PostDeepComponent, }) + +function PostDeepComponent() { + const post = Route.useLoaderData() + + return ( +
+ + ← All Posts + +

{post.value.title}

+
{post.value.body}
+
+ ) +} diff --git a/e2e/vue-start/custom-basepath/src/routes/users.$userId.tsx b/e2e/vue-start/custom-basepath/src/routes/users.$userId.tsx index 4effec0d5b..fb7fce5f4c 100644 --- a/e2e/vue-start/custom-basepath/src/routes/users.$userId.tsx +++ b/e2e/vue-start/custom-basepath/src/routes/users.$userId.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import axios from 'redaxios' @@ -7,18 +6,6 @@ import { NotFound } from '~/components/NotFound' import { UserErrorComponent } from '~/components/UserErrorComponent' import { basepath } from '~/utils/basepath' -const UserComponent = defineComponent({ - setup() { - const user = Route.useLoaderData() - return () => ( -
-

{user.value.name}

-
{user.value.email}
-
- ) - }, -}) - export const Route = createFileRoute('/users/$userId')({ loader: async ({ params: { userId } }) => { return await axios @@ -34,3 +21,14 @@ export const Route = createFileRoute('/users/$userId')({ return User not found }, }) + +function UserComponent() { + const user = Route.useLoaderData() + + return ( +
+

{user.value.name}

+
{user.value.email}
+
+ ) +} diff --git a/e2e/vue-start/custom-basepath/src/routes/users.tsx b/e2e/vue-start/custom-basepath/src/routes/users.tsx index fe926d0a44..1432e50451 100644 --- a/e2e/vue-start/custom-basepath/src/routes/users.tsx +++ b/e2e/vue-start/custom-basepath/src/routes/users.tsx @@ -1,40 +1,8 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import axios from 'redaxios' import type { User } from '~/utils/users' import { basepath } from '~/utils/basepath' -const UsersComponent = defineComponent({ - setup() { - const users = Route.useLoaderData() - return () => ( -
-
    - {[ - ...users.value, - { id: 'i-do-not-exist', name: 'Non-existent User', email: '' }, - ].map((user) => ( -
  • - -
    {user.name}
    - -
  • - ))} -
-
- -
- ) - }, -}) - export const Route = createFileRoute('/users')({ loader: async () => { return await axios @@ -46,3 +14,33 @@ export const Route = createFileRoute('/users')({ }, component: UsersComponent, }) + +function UsersComponent() { + const users = Route.useLoaderData() + + return ( +
+
    + {[ + ...users.value, + { id: 'i-do-not-exist', name: 'Non-existent User', email: '' }, + ].map((user) => ( +
  • + +
    {user.name}
    + +
  • + ))} +
+
+ +
+ ) +} diff --git a/e2e/vue-start/custom-basepath/src/utils/posts.tsx b/e2e/vue-start/custom-basepath/src/utils/posts.tsx index 11d80d08b5..66cb298f83 100644 --- a/e2e/vue-start/custom-basepath/src/utils/posts.tsx +++ b/e2e/vue-start/custom-basepath/src/utils/posts.tsx @@ -8,7 +8,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = createServerFn({ method: 'GET' }) .validator((postId: string) => postId) diff --git a/e2e/vue-start/custom-basepath/src/utils/users.tsx b/e2e/vue-start/custom-basepath/src/utils/users.tsx index 7ba645b383..46be4b1580 100644 --- a/e2e/vue-start/custom-basepath/src/utils/users.tsx +++ b/e2e/vue-start/custom-basepath/src/utils/users.tsx @@ -3,3 +3,7 @@ export type User = { name: string email: string } + +const PORT = process.env.VITE_SERVER_PORT || 3000 + +export const DEPLOY_URL = `http://localhost:${PORT}` diff --git a/e2e/vue-start/custom-basepath/tests/setup/global.setup.ts b/e2e/vue-start/custom-basepath/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-start/custom-basepath/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/custom-basepath/tests/setup/global.teardown.ts b/e2e/vue-start/custom-basepath/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-start/custom-basepath/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/dev-ssr-styles/.gitignore b/e2e/vue-start/dev-ssr-styles/.gitignore deleted file mode 100644 index 950326609c..0000000000 --- a/e2e/vue-start/dev-ssr-styles/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -node_modules -dist -.routeTree.gen.ts -src/routeTree.gen.ts -test-results -playwright-report -port*.txt diff --git a/e2e/vue-start/dev-ssr-styles/package.json b/e2e/vue-start/dev-ssr-styles/package.json deleted file mode 100644 index 0033a0a5cc..0000000000 --- a/e2e/vue-start/dev-ssr-styles/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "tanstack-vue-start-e2e-dev-ssr-styles", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "vite dev --port 3000", - "dev:e2e": "vite dev --port 0", - "build": "vite build && tsc --noEmit", - "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e:dev": "MODE=dev playwright test --project=chromium", - "test:e2e": "pnpm run test:e2e:dev && pnpm run test:e2e:dev:bundled-dev", - "test:e2e:dev:bundled-dev": "MODE=dev E2E_VITE_BUNDLED_DEV=true playwright test --project=chromium" - }, - "dependencies": { - "@tanstack/vue-router": "workspace:*", - "@tanstack/vue-start": "workspace:*", - "vue": "^3.5.16" - }, - "devDependencies": { - "@playwright/test": "^1.61.0", - "@tanstack/router-core": "workspace:*", - "@tanstack/router-e2e-utils": "workspace:*", - "@types/node": "^22.10.2", - "@vitejs/plugin-vue": "^6.0.5", - "@vitejs/plugin-vue-jsx": "^5.1.5", - "srvx": "^1.0.0", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "@typescript/native": "npm:typescript@^7.0.2" - } -} diff --git a/e2e/vue-start/dev-ssr-styles/playwright.config.ts b/e2e/vue-start/dev-ssr-styles/playwright.config.ts deleted file mode 100644 index 723cd32789..0000000000 --- a/e2e/vue-start/dev-ssr-styles/playwright.config.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' - -const PORT = Number(process.env.E2E_APP_PORT ?? 0) -const baseURL = `http://localhost:${PORT}` - -export default defineConfig({ - testDir: './tests', - workers: 1, - reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - use: { baseURL }, - webServer: { - command: 'pnpm dev:e2e', - wait: appServerReady, - reuseExistingServer: false, - stdout: 'pipe', - env: { - VITE_NODE_ENV: 'test', - }, - }, - projects: [ - { - name: 'chromium', - use: { ...devices['Desktop Chrome'] }, - }, - ], -}) diff --git a/e2e/vue-start/dev-ssr-styles/src/components/SfcStyledBox.vue b/e2e/vue-start/dev-ssr-styles/src/components/SfcStyledBox.vue deleted file mode 100644 index bd92215136..0000000000 --- a/e2e/vue-start/dev-ssr-styles/src/components/SfcStyledBox.vue +++ /dev/null @@ -1,14 +0,0 @@ - - - diff --git a/e2e/vue-start/dev-ssr-styles/src/router.tsx b/e2e/vue-start/dev-ssr-styles/src/router.tsx deleted file mode 100644 index c0d7f2b200..0000000000 --- a/e2e/vue-start/dev-ssr-styles/src/router.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - scrollRestoration: true, - defaultPreload: false, - }) -} diff --git a/e2e/vue-start/dev-ssr-styles/src/routes/__root.tsx b/e2e/vue-start/dev-ssr-styles/src/routes/__root.tsx deleted file mode 100644 index 0dec479a07..0000000000 --- a/e2e/vue-start/dev-ssr-styles/src/routes/__root.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import { - Body, - HeadContent, - Html, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/vue-router' -import '~/styles/app.css' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/e2e/vue-start/dev-ssr-styles/src/routes/index.tsx b/e2e/vue-start/dev-ssr-styles/src/routes/index.tsx deleted file mode 100644 index 733bc1d559..0000000000 --- a/e2e/vue-start/dev-ssr-styles/src/routes/index.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' -import SfcStyledBox from '../components/SfcStyledBox.vue' - -export const Route = createFileRoute('/')({ - component: Home, -}) - -function Home() { - return ( -
-

Vue Dev SSR Styles Test

- -
- ) -} diff --git a/e2e/vue-start/dev-ssr-styles/src/styles/app.css b/e2e/vue-start/dev-ssr-styles/src/styles/app.css deleted file mode 100644 index 9a67f9b153..0000000000 --- a/e2e/vue-start/dev-ssr-styles/src/styles/app.css +++ /dev/null @@ -1,5 +0,0 @@ -body { - font-family: sans-serif; - margin: 0; - padding: 20px; -} diff --git a/e2e/vue-start/dev-ssr-styles/src/vue-shim.d.ts b/e2e/vue-start/dev-ssr-styles/src/vue-shim.d.ts deleted file mode 100644 index fe00a856b2..0000000000 --- a/e2e/vue-start/dev-ssr-styles/src/vue-shim.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -declare module '*.vue' { - import type { DefineComponent } from 'vue' - - const component: DefineComponent - export default component -} diff --git a/e2e/vue-start/dev-ssr-styles/tests/app.spec.ts b/e2e/vue-start/dev-ssr-styles/tests/app.spec.ts deleted file mode 100644 index 0e052441b7..0000000000 --- a/e2e/vue-start/dev-ssr-styles/tests/app.spec.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { expect } from '@playwright/test' -import { DEV_STYLES_ATTR } from '@tanstack/router-core' -import { test } from '@tanstack/router-e2e-utils' - -const whitelistErrors = [ - 'Failed to load resource: net::ERR_NAME_NOT_RESOLVED', - 'Failed to load resource: the server responded with a status of 504', -] - -test.describe('dev SSR styles', () => { - test.use({ whitelistErrors }) - - test.describe('with JavaScript disabled', () => { - test.use({ javaScriptEnabled: false, whitelistErrors }) - - test('includes a Vue SFC style block during SSR', async ({ page }) => { - await page.goto('/') - - const element = page.getByTestId('styled-box') - await expect(element).toBeVisible() - await expect(element).toHaveCSS('background-color', 'rgb(126, 34, 206)') - - const href = await page - .locator(`link[${DEV_STYLES_ATTR}]`) - .getAttribute('href') - expect(href).toBeTruthy() - - const response = await page.request.get(new URL(href!, page.url()).href) - expect(response.ok()).toBeTruthy() - const css = await response.text() - expect(css).toContain('--vue-sfc-style-marker') - expect(css).toMatch( - /\/src\/components\/SfcStyledBox\.vue\?vue&type=style[^\n]*&lang\.css/, - ) - }) - }) - - test('keeps CSS output stable after client modules load', async ({ - page, - }) => { - const initialResponsePromise = page.waitForResponse((response) => - new URL(response.url()).pathname.endsWith('/@tanstack-start/styles.css'), - ) - await page.goto('/') - await expect(page.getByTestId('styled-box')).toBeVisible() - const initialResponse = await initialResponsePromise - expect(initialResponse.ok()).toBeTruthy() - const initialCss = await initialResponse.text() - - const reloadedResponsePromise = page.waitForResponse((response) => - new URL(response.url()).pathname.endsWith('/@tanstack-start/styles.css'), - ) - await page.reload() - await expect(page.getByTestId('styled-box')).toBeVisible() - const reloadedResponse = await reloadedResponsePromise - expect(reloadedResponse.ok()).toBeTruthy() - const reloadedCss = await reloadedResponse.text() - - expect(reloadedCss).toBe(initialCss) - }) -}) diff --git a/e2e/vue-start/dev-ssr-styles/tests/setup/global.setup.ts b/e2e/vue-start/dev-ssr-styles/tests/setup/global.setup.ts deleted file mode 100644 index b03b6485c8..0000000000 --- a/e2e/vue-start/dev-ssr-styles/tests/setup/global.setup.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' - -export default async function setup() { - if (process.env.MODE !== 'dev') { - return - } - - const port = Number(process.env.E2E_APP_PORT ?? 0) - const baseURL = `http://localhost:${port}` - await waitForServer(baseURL) - await preOptimizeDevServer({ - baseURL, - readyTestId: 'home-heading', - }) -} diff --git a/e2e/vue-start/dev-ssr-styles/tsconfig.json b/e2e/vue-start/dev-ssr-styles/tsconfig.json deleted file mode 100644 index 898ea214b1..0000000000 --- a/e2e/vue-start/dev-ssr-styles/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "include": ["**/*.ts", "**/*.tsx", "**/*.vue"], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "preserve", - "jsxImportSource": "vue", - "module": "ESNext", - "moduleResolution": "Bundler", - "lib": ["DOM", "DOM.Iterable", "ES2022"], - "isolatedModules": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "target": "ES2022", - "allowJs": true, - "forceConsistentCasingInFileNames": true, - "paths": { - "~/*": ["./src/*"] - }, - "noEmit": true, - "types": ["vite/client"] - } -} diff --git a/e2e/vue-start/dev-ssr-styles/vite.config.ts b/e2e/vue-start/dev-ssr-styles/vite.config.ts deleted file mode 100644 index f8b7293af9..0000000000 --- a/e2e/vue-start/dev-ssr-styles/vite.config.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { defineConfig } from 'vite' -import { tanstackStart } from '@tanstack/vue-start/plugin/vite' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' - -export default defineConfig({ - resolve: { tsconfigPaths: true }, - experimental: - process.env.E2E_VITE_BUNDLED_DEV === 'true' - ? { bundledDev: true } - : undefined, - server: { port: 3000 }, - plugins: [tanstackStart(), vue(), vueJsx()], -}) diff --git a/e2e/vue-start/query-integration/package.json b/e2e/vue-start/query-integration/package.json index 617ce4f430..a3b775e0eb 100644 --- a/e2e/vue-start/query-integration/package.json +++ b/e2e/vue-start/query-integration/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-query": "^5.90.0", diff --git a/e2e/vue-start/query-integration/playwright.config.ts b/e2e/vue-start/query-integration/playwright.config.ts index 82678ac00b..4d86a1dbe7 100644 --- a/e2e/vue-start/query-integration/playwright.config.ts +++ b/e2e/vue-start/query-integration/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { derivePort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await derivePort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/query-integration/src/routes/loader-fetchQuery/$type.tsx b/e2e/vue-start/query-integration/src/routes/loader-fetchQuery/$type.tsx index 38f1e209dc..9e928feafe 100644 --- a/e2e/vue-start/query-integration/src/routes/loader-fetchQuery/$type.tsx +++ b/e2e/vue-start/query-integration/src/routes/loader-fetchQuery/$type.tsx @@ -1,29 +1,8 @@ -import { defineComponent } from 'vue' import { useQuery } from '@tanstack/vue-query' import { createFileRoute } from '@tanstack/vue-router' import z from 'zod' import { makeQueryOptions } from '~/queryOptions' -const RouteComponent = defineComponent({ - setup() { - const loaderData = Route.useLoaderData() - const context = Route.useRouteContext() - const query = useQuery(() => context.value.queryOptions) - return () => ( -
-
- loader data:{' '} -
{loaderData.value ?? 'undefined'}
-
-
- query data:{' '} -
{query.data.value ?? 'loading...'}
-
-
- ) - }, -}) - export const Route = createFileRoute('/loader-fetchQuery/$type')({ component: RouteComponent, params: { @@ -45,3 +24,21 @@ export const Route = createFileRoute('/loader-fetchQuery/$type')({ }, ssr: 'data-only', }) + +function RouteComponent() { + const loaderData = Route.useLoaderData() + const context = Route.useRouteContext() + const query = useQuery(context.value.queryOptions) + return ( +
+
+ loader data:{' '} +
{loaderData.value ?? 'undefined'}
+
+
+ query data:{' '} +
{query.data.value ?? 'loading...'}
+
+
+ ) +} diff --git a/e2e/vue-start/scroll-restoration/package.json b/e2e/vue-start/scroll-restoration/package.json index 025b0225be..21a4fbff8d 100644 --- a/e2e/vue-start/scroll-restoration/package.json +++ b/e2e/vue-start/scroll-restoration/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -28,7 +28,7 @@ "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "combinate": "^1.1.11", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/vue-start/scroll-restoration/playwright.config.ts b/e2e/vue-start/scroll-restoration/playwright.config.ts index 1862174905..b0c365f8bd 100644 --- a/e2e/vue-start/scroll-restoration/playwright.config.ts +++ b/e2e/vue-start/scroll-restoration/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,19 +18,19 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', - env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, - }, }, projects: [ diff --git a/e2e/vue-start/scroll-restoration/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/scroll-restoration/src/components/DefaultCatchBoundary.tsx index 77c03c5afa..d06f4a948b 100644 --- a/e2e/vue-start/scroll-restoration/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/scroll-restoration/src/components/DefaultCatchBoundary.tsx @@ -1,5 +1,3 @@ -import { defineComponent } from 'vue' -import type { PropType } from 'vue' import { ErrorComponent, Link, @@ -8,54 +6,46 @@ import { } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -export const DefaultCatchBoundary = defineComponent({ - props: { - error: { - type: Object as PropType, - required: true, - }, - }, - setup(props) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - return () => { - console.error(props.error) - return ( -
- -
- - {isRoot.value ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) - } - }, -}) +export function DefaultCatchBoundary({ error }: ErrorComponentProps) { + const router = useRouter() + const isRoot = useLocation({ + select: (location) => location.pathname === '/', + }) + + console.error(error) + + return ( +
+ +
+ + {isRoot.value ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
+
+ ) +} diff --git a/e2e/vue-start/scroll-restoration/src/utils/posts.tsx b/e2e/vue-start/scroll-restoration/src/utils/posts.tsx index c4a2d0dcca..e45ef52969 100644 --- a/e2e/vue-start/scroll-restoration/src/utils/posts.tsx +++ b/e2e/vue-start/scroll-restoration/src/utils/posts.tsx @@ -10,7 +10,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export class PostNotFoundError extends Error {} diff --git a/e2e/vue-start/scroll-restoration/src/utils/users.tsx b/e2e/vue-start/scroll-restoration/src/utils/users.tsx index 7ba645b383..46be4b1580 100644 --- a/e2e/vue-start/scroll-restoration/src/utils/users.tsx +++ b/e2e/vue-start/scroll-restoration/src/utils/users.tsx @@ -3,3 +3,7 @@ export type User = { name: string email: string } + +const PORT = process.env.VITE_SERVER_PORT || 3000 + +export const DEPLOY_URL = `http://localhost:${PORT}` diff --git a/e2e/vue-start/scroll-restoration/tests/scroll-restoration-lifecycle.spec.ts b/e2e/vue-start/scroll-restoration/tests/scroll-restoration-lifecycle.spec.ts deleted file mode 100644 index df75cba73c..0000000000 --- a/e2e/vue-start/scroll-restoration/tests/scroll-restoration-lifecycle.spec.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { test } from '@tanstack/router-e2e-utils' -import { scrollRestorationLifecycleTests } from '../../../scroll-restoration-lifecycle' - -scrollRestorationLifecycleTests(test) diff --git a/e2e/vue-start/scroll-restoration/tests/setup/global.setup.ts b/e2e/vue-start/scroll-restoration/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-start/scroll-restoration/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/scroll-restoration/tests/setup/global.teardown.ts b/e2e/vue-start/scroll-restoration/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-start/scroll-restoration/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/selective-ssr/package.json b/e2e/vue-start/selective-ssr/package.json index b555a01c26..7ffcaae743 100644 --- a/e2e/vue-start/selective-ssr/package.json +++ b/e2e/vue-start/selective-ssr/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -22,7 +22,7 @@ "@tanstack/router-e2e-utils": "workspace:^", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/vue-start/selective-ssr/playwright.config.ts b/e2e/vue-start/selective-ssr/playwright.config.ts index 630989e41f..badd6db0eb 100644 --- a/e2e/vue-start/selective-ssr/playwright.config.ts +++ b/e2e/vue-start/selective-ssr/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/selective-ssr/src/routes/__root.tsx b/e2e/vue-start/selective-ssr/src/routes/__root.tsx index 9319a0982a..a952abd4e0 100644 --- a/e2e/vue-start/selective-ssr/src/routes/__root.tsx +++ b/e2e/vue-start/selective-ssr/src/routes/__root.tsx @@ -1,5 +1,4 @@ /// -import { defineComponent } from 'vue' import { Body, ClientOnly, @@ -15,93 +14,6 @@ import { z } from 'zod' import { ssrSchema } from '~/search' import appCss from '~/styles/app.css?url' -const RootDocument = defineComponent({ - setup(_, { slots }) { - const routerState = useRouterState({ - select: (state) => ({ - isLoading: state.isLoading, - status: state.status, - }), - }) - return () => ( - - - - - -
-

Selective SSR E2E Test

- - Home - -
-
- -
- router isLoading:{' '} - - {routerState.value.isLoading ? 'true' : 'false'} - -
-
- router status:{' '} - {routerState.value.status} -
-
-
- {slots.default?.()} - - - - ) - }, -}) - -const RouteComponent = defineComponent({ - setup() { - const search = Route.useSearch() - const loaderData = Route.useLoaderData() - const context = Route.useRouteContext() - return () => { - if ( - typeof window === 'undefined' && - search.value.root?.expected?.render === 'client-only' - ) { - const error = `Expected component for ${Route.id} to be executed on the client, but it is running on the server` - console.error(error) - throw new Error(error) - } - return ( -
-

root

-
- ssr: {JSON.stringify(search.value.root?.ssr ?? 'undefined')} -
-
- expected data location execution:{' '} - - {search.value.root?.expected?.data} - -
-
- loader: {loaderData.value.root} -
-
- context: {context.value.root} -
-
- -
- ) - } - }, -}) - export const Route = createRootRoute({ head: () => ({ meta: [ @@ -162,5 +74,84 @@ export const Route = createRootRoute({ return { root: typeof window === 'undefined' ? 'server' : 'client' } }, shellComponent: RootDocument, - component: RouteComponent, + component: () => { + const search = Route.useSearch() + if ( + typeof window === 'undefined' && + search.value.root?.expected?.render === 'client-only' + ) { + const error = `Expected component for ${Route.id} to be executed on the client, but it is running on the server` + console.error(error) + throw new Error(error) + } + const loaderData = Route.useLoaderData() + const context = Route.useRouteContext() + return ( +
+

root

+
+ ssr: {JSON.stringify(search.value.root?.ssr ?? 'undefined')} +
+
+ expected data location execution:{' '} + + {search.value.root?.expected?.data} + +
+
+ loader: {loaderData.value.root} +
+
+ context: {context.value.root} +
+
+ +
+ ) + }, }) + +function RootDocument(_: unknown, { slots }: { slots: any }) { + const routerState = useRouterState({ + select: (state) => ({ + isLoading: state.isLoading, + status: state.status, + }), + }) + return ( + + + + + +
+

Selective SSR E2E Test

+ + Home + +
+
+ +
+ router isLoading:{' '} + + {routerState.value.isLoading ? 'true' : 'false'} + +
+
+ router status:{' '} + {routerState.value.status} +
+
+
+ {slots.default?.()} + + + + ) +} diff --git a/e2e/vue-start/selective-ssr/src/routes/posts.$postId.tsx b/e2e/vue-start/selective-ssr/src/routes/posts.$postId.tsx index 522b5e9b8e..4e7065cc48 100644 --- a/e2e/vue-start/selective-ssr/src/routes/posts.$postId.tsx +++ b/e2e/vue-start/selective-ssr/src/routes/posts.$postId.tsx @@ -1,47 +1,7 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import z from 'zod' import { ssrSchema } from '~/search' -const RouteComponent = defineComponent({ - setup() { - const search = Route.useSearch() - const loaderData = Route.useLoaderData() - const context = Route.useRouteContext() - return () => { - if ( - typeof window === 'undefined' && - search.value.postId?.expected?.render === 'client-only' - ) { - const error = `Expected component for ${Route.id} to be executed on the client, but it is running on the server` - console.error(error) - throw new Error(error) - } - return ( -
-

postId

-
- ssr:{' '} - {JSON.stringify(search.value.postId?.ssr ?? 'undefined')} -
-
- expected data location execution:{' '} - - {search.value.postId?.expected?.data} - -
-
- loader: {loaderData.value.postId} -
-
- context: {context.value.postId} -
-
- ) - } - }, -}) - export const Route = createFileRoute('/posts/$postId')({ validateSearch: z.object({ postId: ssrSchema }), ssr: ({ search }) => { @@ -86,5 +46,37 @@ export const Route = createFileRoute('/posts/$postId')({ } return { postId: typeof window === 'undefined' ? 'server' : 'client' } }, - component: RouteComponent, + component: () => { + const search = Route.useSearch() + const loaderData = Route.useLoaderData() + const context = Route.useRouteContext() + if ( + typeof window === 'undefined' && + search.value.postId?.expected?.render === 'client-only' + ) { + const error = `Expected component for ${Route.id} to be executed on the client, but it is running on the server` + console.error(error) + throw new Error(error) + } + return ( +
+

postId

+
+ ssr: {JSON.stringify(search.value.postId?.ssr ?? 'undefined')} +
+
+ expected data location execution:{' '} + + {search.value.postId?.expected?.data} + +
+
+ loader: {loaderData.value.postId} +
+
+ context: {context.value.postId} +
+
+ ) + }, }) diff --git a/e2e/vue-start/selective-ssr/src/routes/posts.tsx b/e2e/vue-start/selective-ssr/src/routes/posts.tsx index 514628b229..6c4e490dde 100644 --- a/e2e/vue-start/selective-ssr/src/routes/posts.tsx +++ b/e2e/vue-start/selective-ssr/src/routes/posts.tsx @@ -1,48 +1,7 @@ -import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' import z from 'zod' import { ssrSchema } from '~/search' -const RouteComponent = defineComponent({ - setup() { - const search = Route.useSearch() - const loaderData = Route.useLoaderData() - const context = Route.useRouteContext() - return () => { - if ( - typeof window === 'undefined' && - search.value.posts?.expected?.render === 'client-only' - ) { - const error = `Expected component for ${Route.id} to be executed on the client, but it is running on the server` - console.error(error) - throw new Error(error) - } - return ( -
-

posts

-
- ssr: {JSON.stringify(search.value.posts?.ssr ?? 'undefined')} -
-
- expected data location execution:{' '} - - {search.value.posts?.expected?.data} - -
-
- loader: {loaderData.value.posts} -
-
- context: {context.value.posts} -
-
- -
- ) - } - }, -}) - export const Route = createFileRoute('/posts')({ validateSearch: z.object({ posts: ssrSchema }), ssr: ({ search }) => { @@ -87,5 +46,39 @@ export const Route = createFileRoute('/posts')({ } return { posts: typeof window === 'undefined' ? 'server' : 'client' } }, - component: RouteComponent, + component: () => { + const search = Route.useSearch() + const loaderData = Route.useLoaderData() + const context = Route.useRouteContext() + if ( + typeof window === 'undefined' && + search.value.posts?.expected?.render === 'client-only' + ) { + const error = `Expected component for ${Route.id} to be executed on the client, but it is running on the server` + console.error(error) + throw new Error(error) + } + return ( +
+

posts

+
+ ssr: {JSON.stringify(search.value.posts?.ssr ?? 'undefined')} +
+
+ expected data location execution:{' '} + + {search.value.posts?.expected?.data} + +
+
+ loader: {loaderData.value.posts} +
+
+ context: {context.value.posts} +
+
+ +
+ ) + }, }) diff --git a/e2e/vue-start/serialization-adapters/package.json b/e2e/vue-start/serialization-adapters/package.json index a056e21da3..c5b80bdced 100644 --- a/e2e/vue-start/serialization-adapters/package.json +++ b/e2e/vue-start/serialization-adapters/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -23,7 +23,7 @@ "@tanstack/router-e2e-utils": "workspace:^", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/vue-start/serialization-adapters/playwright.config.ts b/e2e/vue-start/serialization-adapters/playwright.config.ts index 630989e41f..badd6db0eb 100644 --- a/e2e/vue-start/serialization-adapters/playwright.config.ts +++ b/e2e/vue-start/serialization-adapters/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/serialization-adapters/src/routes/__root.tsx b/e2e/vue-start/serialization-adapters/src/routes/__root.tsx index 3ea36c7d46..96911d2500 100644 --- a/e2e/vue-start/serialization-adapters/src/routes/__root.tsx +++ b/e2e/vue-start/serialization-adapters/src/routes/__root.tsx @@ -1,5 +1,4 @@ /// -import { defineComponent } from 'vue' import { Body, ClientOnly, @@ -13,51 +12,6 @@ import { import { TanStackRouterDevtoolsInProd } from '@tanstack/vue-router-devtools' import appCss from '~/styles/app.css?url' -const RootDocument = defineComponent({ - setup(_, { slots }) { - const routerState = useRouterState({ - select: (state) => ({ isLoading: state.isLoading, status: state.status }), - }) - return () => ( - - - - - -
-

Serialization Adapters E2E Test

- - Home - -
-
- -
- router isLoading:{' '} - - {routerState.value.isLoading ? 'true' : 'false'} - -
-
- router status:{' '} - {routerState.value.status} -
-
-
- {slots.default?.()} - - - - - ) - }, -}) - export const Route = createRootRoute({ head: () => ({ meta: [ @@ -77,3 +31,46 @@ export const Route = createRootRoute({ shellComponent: RootDocument, notFoundComponent: (e) =>
404 - Not Found {JSON.stringify(e.data)}
, }) + +function RootDocument(_: unknown, { slots }: { slots: any }) { + const routerState = useRouterState({ + select: (state) => ({ isLoading: state.isLoading, status: state.status }), + }) + return ( + + + + + +
+

Serialization Adapters E2E Test

+ + Home + +
+
+ +
+ router isLoading:{' '} + + {routerState.value.isLoading ? 'true' : 'false'} + +
+
+ router status:{' '} + {routerState.value.status} +
+
+
+ {slots.default?.()} + + + + + ) +} diff --git a/e2e/vue-start/serialization-adapters/src/routes/ssr/data-only.tsx b/e2e/vue-start/serialization-adapters/src/routes/ssr/data-only.tsx index e71906f03e..ecb35d0a55 100644 --- a/e2e/vue-start/serialization-adapters/src/routes/ssr/data-only.tsx +++ b/e2e/vue-start/serialization-adapters/src/routes/ssr/data-only.tsx @@ -1,47 +1,6 @@ -import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' import { RenderData, makeData } from '~/data' -const RouteComponent = defineComponent({ - setup() { - const context = Route.useRouteContext() - const loaderData = Route.useLoaderData() - return () => { - const localData = makeData() - const expectedHonkState = localData.car.singleInstance.honk() - const honkState = loaderData.value.car.singleInstance.honk() - return ( -
-

data-only

-
- context: -
-
- loader: -
-
-

honk

-
- expected:{' '} -
- {JSON.stringify(expectedHonkState)} -
-
-
- actual:{' '} -
- {JSON.stringify(honkState)} -
-
-
-
- -
- ) - } - }, -}) - export const Route = createFileRoute('/ssr/data-only')({ ssr: 'data-only', beforeLoad: () => { @@ -50,6 +9,43 @@ export const Route = createFileRoute('/ssr/data-only')({ loader: ({ context }) => { return context }, - component: RouteComponent, + component: () => { + const context = Route.useRouteContext() + const loaderData = Route.useLoaderData() + + const localData = makeData() + const expectedHonkState = localData.car.singleInstance.honk() + + const honkState = loaderData.value.car.singleInstance.honk() + + return ( +
+

data-only

+
+ context: +
+
+ loader: +
+
+

honk

+
+ expected:{' '} +
+ {JSON.stringify(expectedHonkState)} +
+
+
+ actual:{' '} +
+ {JSON.stringify(honkState)} +
+
+
+
+ +
+ ) + }, pendingComponent: () =>
posts Loading...
, }) diff --git a/e2e/vue-start/serialization-adapters/src/routes/ssr/nested.tsx b/e2e/vue-start/serialization-adapters/src/routes/ssr/nested.tsx index b4f7fd8f23..bbc240b96d 100644 --- a/e2e/vue-start/serialization-adapters/src/routes/ssr/nested.tsx +++ b/e2e/vue-start/serialization-adapters/src/routes/ssr/nested.tsx @@ -1,14 +1,6 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { RenderNestedData, makeNested } from '~/data' -const RouteComponent = defineComponent({ - setup() { - const loaderData = Route.useLoaderData() - return () => - }, -}) - export const Route = createFileRoute('/ssr/nested')({ beforeLoad: () => { return { nested: makeNested() } @@ -16,5 +8,8 @@ export const Route = createFileRoute('/ssr/nested')({ loader: ({ context }) => { return context }, - component: RouteComponent, + component: () => { + const loaderData = Route.useLoaderData() + return + }, }) diff --git a/e2e/vue-start/serialization-adapters/src/routes/ssr/stream.tsx b/e2e/vue-start/serialization-adapters/src/routes/ssr/stream.tsx index f6056699af..ea1e770e5b 100644 --- a/e2e/vue-start/serialization-adapters/src/routes/ssr/stream.tsx +++ b/e2e/vue-start/serialization-adapters/src/routes/ssr/stream.tsx @@ -1,32 +1,7 @@ import { Await, createFileRoute } from '@tanstack/vue-router' -import { defineComponent, Suspense } from 'vue' +import { Suspense } from 'vue' import { RenderData, makeData } from '~/data' -const RouteComponent = defineComponent({ - setup() { - const loaderData = Route.useLoaderData() - return () => ( -
-

Stream

-
{loaderData.value.someString}
- - {{ - default: () => ( - ) => ( - - )} - /> - ), - fallback: () =>
Loading...
, - }} -
-
- ) - }, -}) - export const Route = createFileRoute('/ssr/stream')({ loader: () => { const dataPromise = new Promise>((r) => @@ -43,3 +18,26 @@ export const Route = createFileRoute('/ssr/stream')({ ), component: RouteComponent, }) + +function RouteComponent() { + const loaderData = Route.useLoaderData() + return ( +
+

Stream

+
{loaderData.value.someString}
+ + {{ + default: () => ( + ) => ( + + )} + /> + ), + fallback: () =>
Loading...
, + }} +
+
+ ) +} diff --git a/e2e/vue-start/server-functions/package.json b/e2e/vue-start/server-functions/package.json index dd1a7a9c6b..3bf9ba33a8 100644 --- a/e2e/vue-start/server-functions/package.json +++ b/e2e/vue-start/server-functions/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-query": "^5.90.9", @@ -32,7 +32,7 @@ "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "combinate": "^1.1.11", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/vue-start/server-functions/playwright.config.ts b/e2e/vue-start/server-functions/playwright.config.ts index 48e14683f4..cb1da03b94 100644 --- a/e2e/vue-start/server-functions/playwright.config.ts +++ b/e2e/vue-start/server-functions/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -export const PORT = Number(process.env.E2E_APP_PORT ?? 0) +export const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/server-functions/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/server-functions/src/components/DefaultCatchBoundary.tsx index 77c03c5afa..d06f4a948b 100644 --- a/e2e/vue-start/server-functions/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/server-functions/src/components/DefaultCatchBoundary.tsx @@ -1,5 +1,3 @@ -import { defineComponent } from 'vue' -import type { PropType } from 'vue' import { ErrorComponent, Link, @@ -8,54 +6,46 @@ import { } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -export const DefaultCatchBoundary = defineComponent({ - props: { - error: { - type: Object as PropType, - required: true, - }, - }, - setup(props) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - return () => { - console.error(props.error) - return ( -
- -
- - {isRoot.value ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) - } - }, -}) +export function DefaultCatchBoundary({ error }: ErrorComponentProps) { + const router = useRouter() + const isRoot = useLocation({ + select: (location) => location.pathname === '/', + }) + + console.error(error) + + return ( +
+ +
+ + {isRoot.value ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
+
+ ) +} diff --git a/e2e/vue-start/server-functions/src/routes/cookies/index.tsx b/e2e/vue-start/server-functions/src/routes/cookies/index.tsx index 90dddad0af..d7fef10223 100644 --- a/e2e/vue-start/server-functions/src/routes/cookies/index.tsx +++ b/e2e/vue-start/server-functions/src/routes/cookies/index.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' @@ -6,23 +5,21 @@ const cookieSchema = z .object({ value: z.string().default(() => `CLIENT-${Date.now()}`) }) .prefault({}) .catch(() => ({ value: `CLIENT-${Date.now()}` })) -const RouteComponent = defineComponent({ - setup() { - const search = Route.useSearch() - return () => ( - - got to route that sets the cookies with {JSON.stringify(search.value)} - - ) - }, -}) - export const Route = createFileRoute('/cookies/')({ validateSearch: cookieSchema, component: RouteComponent, }) + +function RouteComponent() { + const search = Route.useSearch() + return ( + + got to route that sets the cookies with {JSON.stringify(search.value)} + + ) +} diff --git a/e2e/vue-start/server-functions/src/routes/formdata-redirect/index.tsx b/e2e/vue-start/server-functions/src/routes/formdata-redirect/index.tsx index 8bfcc55ca3..8b0c623b8c 100644 --- a/e2e/vue-start/server-functions/src/routes/formdata-redirect/index.tsx +++ b/e2e/vue-start/server-functions/src/routes/formdata-redirect/index.tsx @@ -1,51 +1,7 @@ -import { defineComponent } from 'vue' import { createFileRoute, redirect } from '@tanstack/vue-router' import { createServerFn, useServerFn } from '@tanstack/vue-start' import { z } from 'zod' -const SubmitPostFormDataFn = defineComponent({ - setup() { - const mode = Route.useSearch({ select: (search) => search.mode }) - const greetUserFn = useServerFn(greetUser) - return () => ( -
-

Submit POST FormData Fn Call

-
- It should return redirect to /formdata-redirect/target/ - {testValues.name} and greet the user with their name: - -
-              {testValues.name}
-            
-
-
-
{ - if (mode.value === 'js') { - evt.preventDefault() - const data = new FormData(evt.currentTarget as HTMLFormElement) - await greetUserFn({ data }) - } - }} - > - - -
-
- ) - }, -}) - export const Route = createFileRoute('/formdata-redirect/')({ component: SubmitPostFormDataFn, validateSearch: z.object({ @@ -75,3 +31,44 @@ export const greetUser = createServerFn({ method: 'POST' }) .handler(({ data: { name } }) => { throw redirect({ to: '/formdata-redirect/target/$name', params: { name } }) }) + +function SubmitPostFormDataFn() { + const mode = Route.useSearch({ select: (search) => search.mode }) + const greetUserFn = useServerFn(greetUser) + return ( +
+

Submit POST FormData Fn Call

+
+ It should return redirect to /formdata-redirect/target/{testValues.name}{' '} + and greet the user with their name: + +
+            {testValues.name}
+          
+
+
+
{ + if (mode.value === 'js') { + evt.preventDefault() + const data = new FormData(evt.currentTarget as HTMLFormElement) + await greetUserFn({ data }) + } + }} + > + + +
+
+ ) +} diff --git a/e2e/vue-start/server-functions/src/routes/formdata-redirect/target.$name.tsx b/e2e/vue-start/server-functions/src/routes/formdata-redirect/target.$name.tsx index 099a8665bf..958aeaf617 100644 --- a/e2e/vue-start/server-functions/src/routes/formdata-redirect/target.$name.tsx +++ b/e2e/vue-start/server-functions/src/routes/formdata-redirect/target.$name.tsx @@ -1,21 +1,18 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' -const RouteComponent = defineComponent({ - setup() { - const params = Route.useParams() - return () => ( -
- Hello{' '} - - {params.value.name} - - ! -
- ) - }, -}) - export const Route = createFileRoute('/formdata-redirect/target/$name')({ component: RouteComponent, }) + +function RouteComponent() { + const params = Route.useParams() + return ( +
+ Hello{' '} + + {params.value.name} + + ! +
+ ) +} diff --git a/e2e/vue-start/server-routes/package.json b/e2e/vue-start/server-routes/package.json index 6a8e1babed..40d285d1d9 100644 --- a/e2e/vue-start/server-routes/package.json +++ b/e2e/vue-start/server-routes/package.json @@ -32,7 +32,7 @@ "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "combinate": "^1.1.11", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/vue-start/server-routes/playwright.config.ts b/e2e/vue-start/server-routes/playwright.config.ts index 48e14683f4..cb1da03b94 100644 --- a/e2e/vue-start/server-routes/playwright.config.ts +++ b/e2e/vue-start/server-routes/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -export const PORT = Number(process.env.E2E_APP_PORT ?? 0) +export const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/server-routes/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/server-routes/src/components/DefaultCatchBoundary.tsx index 77c03c5afa..d06f4a948b 100644 --- a/e2e/vue-start/server-routes/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/server-routes/src/components/DefaultCatchBoundary.tsx @@ -1,5 +1,3 @@ -import { defineComponent } from 'vue' -import type { PropType } from 'vue' import { ErrorComponent, Link, @@ -8,54 +6,46 @@ import { } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -export const DefaultCatchBoundary = defineComponent({ - props: { - error: { - type: Object as PropType, - required: true, - }, - }, - setup(props) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - return () => { - console.error(props.error) - return ( -
- -
- - {isRoot.value ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) - } - }, -}) +export function DefaultCatchBoundary({ error }: ErrorComponentProps) { + const router = useRouter() + const isRoot = useLocation({ + select: (location) => location.pathname === '/', + }) + + console.error(error) + + return ( +
+ +
+ + {isRoot.value ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
+
+ ) +} diff --git a/e2e/vue-start/spa-mode/package.json b/e2e/vue-start/spa-mode/package.json index c4270cfccd..b33ed9c859 100644 --- a/e2e/vue-start/spa-mode/package.json +++ b/e2e/vue-start/spa-mode/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "npx serve dist/client", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", diff --git a/e2e/vue-start/spa-mode/playwright.config.ts b/e2e/vue-start/spa-mode/playwright.config.ts index 630989e41f..badd6db0eb 100644 --- a/e2e/vue-start/spa-mode/playwright.config.ts +++ b/e2e/vue-start/spa-mode/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/spa-mode/src/routes/__root.tsx b/e2e/vue-start/spa-mode/src/routes/__root.tsx index 45aee73c06..1e38664739 100644 --- a/e2e/vue-start/spa-mode/src/routes/__root.tsx +++ b/e2e/vue-start/spa-mode/src/routes/__root.tsx @@ -1,5 +1,4 @@ /// -import { defineComponent } from 'vue' import { Body, ClientOnly, @@ -14,71 +13,6 @@ import { import { TanStackRouterDevtools } from '@tanstack/vue-router-devtools' import appCss from '~/styles/app.css?url' -const RootDocument = defineComponent({ - setup(_, { slots }) { - const routerState = useRouterState({ - select: (state) => ({ isLoading: state.isLoading, status: state.status }), - }) - return () => ( - - - - - -
-

SPA Mode E2E Test

- - Home - -
-
- -
- router isLoading:{' '} - - {routerState.value.isLoading ? 'true' : 'false'} - -
-
- router status:{' '} - {routerState.value.status} -
-
-
- {slots.default?.()} - - - - - ) - }, -}) - -const RouteComponent = defineComponent({ - setup() { - const loaderData = Route.useLoaderData() - const context = Route.useRouteContext() - return () => ( -
-

root

-
- loader: {loaderData.value.root} -
-
- context: {context.value.root} -
-
- -
- ) - }, -}) - export const Route = createRootRoute({ head: () => ({ meta: [ @@ -110,6 +44,65 @@ export const Route = createRootRoute({ return { root: typeof window === 'undefined' ? 'server' : 'client' } }, shellComponent: RootDocument, - component: RouteComponent, + component: () => { + const loaderData = Route.useLoaderData() + const context = Route.useRouteContext() + return ( +
+

root

+
+ loader: {loaderData.value.root} +
+
+ context: {context.value.root} +
+
+ +
+ ) + }, pendingComponent: () =>
__root Loading...
, }) + +function RootDocument(_: unknown, { slots }: { slots: any }) { + const routerState = useRouterState({ + select: (state) => ({ isLoading: state.isLoading, status: state.status }), + }) + return ( + + + + + +
+

SPA Mode E2E Test

+ + Home + +
+
+ +
+ router isLoading:{' '} + + {routerState.value.isLoading ? 'true' : 'false'} + +
+
+ router status:{' '} + {routerState.value.status} +
+
+
+ {slots.default?.()} + + + + + ) +} diff --git a/e2e/vue-start/spa-mode/src/routes/posts.$postId.tsx b/e2e/vue-start/spa-mode/src/routes/posts.$postId.tsx index 9c25cbad25..6733ef7436 100644 --- a/e2e/vue-start/spa-mode/src/routes/posts.$postId.tsx +++ b/e2e/vue-start/spa-mode/src/routes/posts.$postId.tsx @@ -1,24 +1,5 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' -const RouteComponent = defineComponent({ - setup() { - const loaderData = Route.useLoaderData() - const context = Route.useRouteContext() - return () => ( -
-

postId

-
- loader: {loaderData.value.postId} -
-
- context: {context.value.postId} -
-
- ) - }, -}) - export const Route = createFileRoute('/posts/$postId')({ beforeLoad: () => { console.log( @@ -34,6 +15,20 @@ export const Route = createFileRoute('/posts/$postId')({ ) return { postId: typeof window === 'undefined' ? 'server' : 'client' } }, - component: RouteComponent, + component: () => { + const loaderData = Route.useLoaderData() + const context = Route.useRouteContext() + return ( +
+

postId

+
+ loader: {loaderData.value.postId} +
+
+ context: {context.value.postId} +
+
+ ) + }, pendingComponent: () =>
$postId Loading...
, }) diff --git a/e2e/vue-start/spa-mode/src/routes/posts.tsx b/e2e/vue-start/spa-mode/src/routes/posts.tsx index 44c536adc4..e69ae1ea86 100644 --- a/e2e/vue-start/spa-mode/src/routes/posts.tsx +++ b/e2e/vue-start/spa-mode/src/routes/posts.tsx @@ -1,26 +1,5 @@ -import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' -const RouteComponent = defineComponent({ - setup() { - const loaderData = Route.useLoaderData() - const context = Route.useRouteContext() - return () => ( -
-

posts

-
- loader: {loaderData.value.posts} -
-
- context: {context.value.posts} -
-
- -
- ) - }, -}) - export const Route = createFileRoute('/posts')({ beforeLoad: () => { console.log( @@ -37,6 +16,22 @@ export const Route = createFileRoute('/posts')({ return { posts: typeof window === 'undefined' ? 'server' : 'client' } }, - component: RouteComponent, + component: () => { + const loaderData = Route.useLoaderData() + const context = Route.useRouteContext() + return ( +
+

posts

+
+ loader: {loaderData.value.posts} +
+
+ context: {context.value.posts} +
+
+ +
+ ) + }, pendingComponent: () =>
posts Loading...
, }) diff --git a/e2e/vue-start/start-manifest/package.json b/e2e/vue-start/start-manifest/package.json index ae682f7a9d..dbf889db71 100644 --- a/e2e/vue-start/start-manifest/package.json +++ b/e2e/vue-start/start-manifest/package.json @@ -19,7 +19,7 @@ "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", "@vitejs/plugin-vue-jsx": "^5.1.5", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" diff --git a/e2e/vue-start/start-manifest/playwright.config.ts b/e2e/vue-start/start-manifest/playwright.config.ts index 653e08253f..b9f835c16a 100644 --- a/e2e/vue-start/start-manifest/playwright.config.ts +++ b/e2e/vue-start/start-manifest/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -15,8 +16,8 @@ export default defineConfig({ webServer: { command: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/start-manifest/tests/start-manifest.spec.ts b/e2e/vue-start/start-manifest/tests/start-manifest.spec.ts index 4d5bea0a33..6c0f0d15ab 100644 --- a/e2e/vue-start/start-manifest/tests/start-manifest.spec.ts +++ b/e2e/vue-start/start-manifest/tests/start-manifest.spec.ts @@ -372,19 +372,24 @@ test('shared widget CSS stays applied when navigating from static to lazy route' const widget = page.getByTestId('shared-widget') await expect(widget).toBeVisible() - await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) + expect(await getBackgroundColor('shared-widget', page)).toBe(SHARED_WIDGET_BG) + expect( + await widget.evaluate( + (element) => getComputedStyle(element).borderTopColor, + ), + ).toBe(SHARED_WIDGET_BORDER) await expect(page.getByTestId('lazy-css-static-hydrated')).toBeVisible() await page.getByTestId('nav-/lazy-css-lazy').click() await page.waitForURL('**/lazy-css-lazy') - // Both routes render `shared-widget`: wait for the destination route before - // asserting on it, so the assertions cannot match the departing widget. await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() - await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) }) test('shared widget CSS stays applied when navigating from lazy to static route', async ({ @@ -394,19 +399,27 @@ test('shared widget CSS stays applied when navigating from lazy to static route' await page.goto(buildUrl(baseURL!, '/lazy-css-lazy')) await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() - const widget = page.getByTestId('shared-widget') - await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) await page.getByTestId('nav-/lazy-css-static').click() await page.waitForURL('**/lazy-css-static') - // The URL updates before the lazy route unmounts, and both routes render - // `shared-widget`: wait for a marker only the static route renders. - await expect(page.getByTestId('lazy-css-static-hydrated')).toBeVisible() + const widget = page.getByTestId('shared-widget') await expect(widget).toBeVisible() - await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) + expect( + await widget.evaluate( + (element) => getComputedStyle(element).borderTopColor, + ), + ).toBe(SHARED_WIDGET_BORDER) }) test('shared widget CSS is applied on direct navigation to lazy route', async ({ @@ -418,8 +431,17 @@ test('shared widget CSS is applied on direct navigation to lazy route', async ({ const widget = page.getByTestId('shared-widget') await expect(widget).toBeVisible() - await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) + + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) + expect( + await widget.evaluate( + (element) => getComputedStyle(element).borderTopColor, + ), + ).toBe(SHARED_WIDGET_BORDER) }) test('shared widget CSS persists after navigating away from lazy and back', async ({ @@ -429,21 +451,19 @@ test('shared widget CSS persists after navigating away from lazy and back', asyn await page.goto(buildUrl(baseURL!, '/lazy-css-static')) await expect(page.getByTestId('lazy-css-static-hydrated')).toBeVisible() - const widget = page.getByTestId('shared-widget') - await page.getByTestId('nav-/lazy-css-lazy').click() await page.waitForURL('**/lazy-css-lazy') - await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() - await expect(widget).toBeVisible() + await expect(page.getByTestId('shared-widget')).toBeVisible() await page.getByTestId('nav-home').click() - await page.waitForURL((url) => url.pathname === '/') - await expect(page.getByTestId('home-copy')).toBeVisible() + await page.waitForURL(/\/([^/]*)(\/)?($|\?)/) await page.getByTestId('nav-/lazy-css-lazy').click() await page.waitForURL('**/lazy-css-lazy') - await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() - await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) }) diff --git a/e2e/vue-start/streaming-ssr/package.json b/e2e/vue-start/streaming-ssr/package.json deleted file mode 100644 index 382120860a..0000000000 --- a/e2e/vue-start/streaming-ssr/package.json +++ /dev/null @@ -1,59 +0,0 @@ -{ - "name": "tanstack-vue-start-e2e-streaming-ssr", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "vite dev --port 3000", - "dev:e2e": "vite dev", - "build": "vite build && tsc --noEmit", - "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "preview": "vite preview", - "test:e2e": "playwright test --project=chromium", - "test:e2e:preview": "MODE=preview playwright test preview-streaming.spec.ts --project=chromium" - }, - "dependencies": { - "@tanstack/vue-query": "^5.90.0", - "@tanstack/vue-router": "workspace:^", - "@tanstack/vue-router-ssr-query": "workspace:^", - "@tanstack/vue-start": "workspace:^", - "vue": "^3.5.16" - }, - "devDependencies": { - "@playwright/test": "^1.61.0", - "@tanstack/router-e2e-utils": "workspace:^", - "@types/node": "^22.10.2", - "@vitejs/plugin-vue-jsx": "^5.1.5", - "srvx": "^1.0.0", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" - }, - "nx": { - "targets": { - "build": { - "inputs": [ - "buildProduction", - "^buildProduction", - "dependentTaskOutputs", - "streamingSsrTests" - ] - }, - "test:e2e": { - "inputs": [ - "default", - "^production", - "dependentTaskOutputs", - "streamingSsrTests" - ] - }, - "test:e2e:preview": { - "inputs": [ - "default", - "^production", - "streamingSsrTests" - ] - } - } - } -} diff --git a/e2e/vue-start/streaming-ssr/playwright.config.ts b/e2e/vue-start/streaming-ssr/playwright.config.ts deleted file mode 100644 index c2f3b67a0c..0000000000 --- a/e2e/vue-start/streaming-ssr/playwright.config.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' - -const isPreview = process.env.MODE === 'preview' - -const PORT = Number(process.env.E2E_APP_PORT ?? 0) -const baseURL = `http://localhost:${PORT}` - -const ssrCommand = `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start` -const previewCommand = `VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}` - -/** - * See https://playwright.dev/docs/test-configuration. - */ -export default defineConfig({ - testDir: './tests', - workers: 1, - - reporter: [['line']], - - use: { - /* Base URL to use in actions like `await page.goto('/')`. */ - baseURL, - }, - - webServer: { - command: isPreview ? previewCommand : ssrCommand, - wait: appServerReady, - reuseExistingServer: false, - stdout: 'pipe', - }, - - projects: [ - { - name: 'chromium', - use: { ...devices['Desktop Chrome'] }, - }, - ], -}) diff --git a/e2e/vue-start/streaming-ssr/src/routeTree.gen.ts b/e2e/vue-start/streaming-ssr/src/routeTree.gen.ts deleted file mode 100644 index ac4c9ab156..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routeTree.gen.ts +++ /dev/null @@ -1,282 +0,0 @@ -/* 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 ConcurrentRouteImport } from './routes/concurrent' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as DeferredRejectionRouteImport } from './routes/deferred-rejection' -import { Route as FastSerialRouteImport } from './routes/fast-serial' -import { Route as ManyPromisesRouteImport } from './routes/many-promises' -import { Route as NestedDeferredRouteImport } from './routes/nested-deferred' -import { Route as QueryHeavyRouteImport } from './routes/query-heavy' -import { Route as SlowRenderRouteImport } from './routes/slow-render' -import { Route as StreamRouteImport } from './routes/stream' -import { Route as SyncOnlyRouteImport } from './routes/sync-only' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ConcurrentRoute = ConcurrentRouteImport.update({ - id: '/concurrent', - path: '/concurrent', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRejectionRoute = DeferredRejectionRouteImport.update({ - id: '/deferred-rejection', - path: '/deferred-rejection', - getParentRoute: () => rootRouteImport, -} as any) -const FastSerialRoute = FastSerialRouteImport.update({ - id: '/fast-serial', - path: '/fast-serial', - getParentRoute: () => rootRouteImport, -} as any) -const ManyPromisesRoute = ManyPromisesRouteImport.update({ - id: '/many-promises', - path: '/many-promises', - getParentRoute: () => rootRouteImport, -} as any) -const NestedDeferredRoute = NestedDeferredRouteImport.update({ - id: '/nested-deferred', - path: '/nested-deferred', - getParentRoute: () => rootRouteImport, -} as any) -const QueryHeavyRoute = QueryHeavyRouteImport.update({ - id: '/query-heavy', - path: '/query-heavy', - getParentRoute: () => rootRouteImport, -} as any) -const SlowRenderRoute = SlowRenderRouteImport.update({ - id: '/slow-render', - path: '/slow-render', - getParentRoute: () => rootRouteImport, -} as any) -const StreamRoute = StreamRouteImport.update({ - id: '/stream', - path: '/stream', - getParentRoute: () => rootRouteImport, -} as any) -const SyncOnlyRoute = SyncOnlyRouteImport.update({ - id: '/sync-only', - path: '/sync-only', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/concurrent': typeof ConcurrentRoute - '/deferred': typeof DeferredRoute - '/deferred-rejection': typeof DeferredRejectionRoute - '/fast-serial': typeof FastSerialRoute - '/many-promises': typeof ManyPromisesRoute - '/nested-deferred': typeof NestedDeferredRoute - '/query-heavy': typeof QueryHeavyRoute - '/slow-render': typeof SlowRenderRoute - '/stream': typeof StreamRoute - '/sync-only': typeof SyncOnlyRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/concurrent': typeof ConcurrentRoute - '/deferred': typeof DeferredRoute - '/deferred-rejection': typeof DeferredRejectionRoute - '/fast-serial': typeof FastSerialRoute - '/many-promises': typeof ManyPromisesRoute - '/nested-deferred': typeof NestedDeferredRoute - '/query-heavy': typeof QueryHeavyRoute - '/slow-render': typeof SlowRenderRoute - '/stream': typeof StreamRoute - '/sync-only': typeof SyncOnlyRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/concurrent': typeof ConcurrentRoute - '/deferred': typeof DeferredRoute - '/deferred-rejection': typeof DeferredRejectionRoute - '/fast-serial': typeof FastSerialRoute - '/many-promises': typeof ManyPromisesRoute - '/nested-deferred': typeof NestedDeferredRoute - '/query-heavy': typeof QueryHeavyRoute - '/slow-render': typeof SlowRenderRoute - '/stream': typeof StreamRoute - '/sync-only': typeof SyncOnlyRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/concurrent' - | '/deferred' - | '/deferred-rejection' - | '/fast-serial' - | '/many-promises' - | '/nested-deferred' - | '/query-heavy' - | '/slow-render' - | '/stream' - | '/sync-only' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/concurrent' - | '/deferred' - | '/deferred-rejection' - | '/fast-serial' - | '/many-promises' - | '/nested-deferred' - | '/query-heavy' - | '/slow-render' - | '/stream' - | '/sync-only' - id: - | '__root__' - | '/' - | '/concurrent' - | '/deferred' - | '/deferred-rejection' - | '/fast-serial' - | '/many-promises' - | '/nested-deferred' - | '/query-heavy' - | '/slow-render' - | '/stream' - | '/sync-only' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ConcurrentRoute: typeof ConcurrentRoute - DeferredRoute: typeof DeferredRoute - DeferredRejectionRoute: typeof DeferredRejectionRoute - FastSerialRoute: typeof FastSerialRoute - ManyPromisesRoute: typeof ManyPromisesRoute - NestedDeferredRoute: typeof NestedDeferredRoute - QueryHeavyRoute: typeof QueryHeavyRoute - SlowRenderRoute: typeof SlowRenderRoute - StreamRoute: typeof StreamRoute - SyncOnlyRoute: typeof SyncOnlyRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/concurrent': { - id: '/concurrent' - path: '/concurrent' - fullPath: '/concurrent' - preLoaderRoute: typeof ConcurrentRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred-rejection': { - id: '/deferred-rejection' - path: '/deferred-rejection' - fullPath: '/deferred-rejection' - preLoaderRoute: typeof DeferredRejectionRouteImport - parentRoute: typeof rootRouteImport - } - '/fast-serial': { - id: '/fast-serial' - path: '/fast-serial' - fullPath: '/fast-serial' - preLoaderRoute: typeof FastSerialRouteImport - parentRoute: typeof rootRouteImport - } - '/many-promises': { - id: '/many-promises' - path: '/many-promises' - fullPath: '/many-promises' - preLoaderRoute: typeof ManyPromisesRouteImport - parentRoute: typeof rootRouteImport - } - '/nested-deferred': { - id: '/nested-deferred' - path: '/nested-deferred' - fullPath: '/nested-deferred' - preLoaderRoute: typeof NestedDeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/query-heavy': { - id: '/query-heavy' - path: '/query-heavy' - fullPath: '/query-heavy' - preLoaderRoute: typeof QueryHeavyRouteImport - parentRoute: typeof rootRouteImport - } - '/slow-render': { - id: '/slow-render' - path: '/slow-render' - fullPath: '/slow-render' - preLoaderRoute: typeof SlowRenderRouteImport - parentRoute: typeof rootRouteImport - } - '/stream': { - id: '/stream' - path: '/stream' - fullPath: '/stream' - preLoaderRoute: typeof StreamRouteImport - parentRoute: typeof rootRouteImport - } - '/sync-only': { - id: '/sync-only' - path: '/sync-only' - fullPath: '/sync-only' - preLoaderRoute: typeof SyncOnlyRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ConcurrentRoute: ConcurrentRoute, - DeferredRoute: DeferredRoute, - DeferredRejectionRoute: DeferredRejectionRoute, - FastSerialRoute: FastSerialRoute, - ManyPromisesRoute: ManyPromisesRoute, - NestedDeferredRoute: NestedDeferredRoute, - QueryHeavyRoute: QueryHeavyRoute, - SlowRenderRoute: SlowRenderRoute, - StreamRoute: StreamRoute, - SyncOnlyRoute: SyncOnlyRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/vue-start' -declare module '@tanstack/vue-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/e2e/vue-start/streaming-ssr/src/router.tsx b/e2e/vue-start/streaming-ssr/src/router.tsx deleted file mode 100644 index 257eb8dac9..0000000000 --- a/e2e/vue-start/streaming-ssr/src/router.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { QueryClient } from '@tanstack/vue-query' -import { createRouter } from '@tanstack/vue-router' -import { setupRouterSsrQueryIntegration } from '@tanstack/vue-router-ssr-query' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - const queryClient = new QueryClient() - const router = createRouter({ - routeTree, - context: { queryClient }, - scrollRestoration: true, - }) - setupRouterSsrQueryIntegration({ - router, - queryClient, - }) - return router -} diff --git a/e2e/vue-start/streaming-ssr/src/routes/__root.tsx b/e2e/vue-start/streaming-ssr/src/routes/__root.tsx deleted file mode 100644 index d3b3339720..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routes/__root.tsx +++ /dev/null @@ -1,103 +0,0 @@ -import { - Body, - HeadContent, - Html, - Link, - Outlet, - Scripts, - createRootRouteWithContext, -} from '@tanstack/vue-router' -import { defineComponent, ref } from 'vue' -import type { QueryClient } from '@tanstack/vue-query' - -export const Route = createRootRouteWithContext<{ - queryClient: QueryClient -}>()({ - head: () => ({ - meta: [ - { charSet: 'utf-8' }, - { name: 'viewport', content: 'width=device-width, initial-scale=1' }, - { title: 'Streaming SSR Tests' }, - ], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - - - ) -} - -const HydrationCheck = defineComponent({ - setup() { - const status = ref<'pending' | 'hydrated'>('pending') - - return () => ( -
- - - {status.value} - -
- ) - }, -}) diff --git a/e2e/vue-start/streaming-ssr/src/routes/concurrent.tsx b/e2e/vue-start/streaming-ssr/src/routes/concurrent.tsx deleted file mode 100644 index 5fed8ab517..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routes/concurrent.tsx +++ /dev/null @@ -1,54 +0,0 @@ -import { Await, createFileRoute } from '@tanstack/vue-router' -import { Suspense } from 'vue' -import { createConcurrentLoaderData } from '../../../../streaming-ssr-fixtures' - -export const Route = createFileRoute('/concurrent')({ - loader: async () => createConcurrentLoaderData(), - component: Concurrent, -}) - -function PromiseItem(props: { promise: Promise; testId: string }) { - return ( - - {{ - default: () => ( - ( -
{value}
- )} - /> - ), - fallback: () => ( -
Loading...
- ), - }} -
- ) -} - -function Concurrent() { - const data = Route.useLoaderData() - - return ( -
-

Concurrent Resolution Test (15 promises in 3 batches)

-

Tests multiple promises resolving at the exact same instant.

- - - - - - - - - - - - - - - -
- ) -} diff --git a/e2e/vue-start/streaming-ssr/src/routes/deferred-rejection.tsx b/e2e/vue-start/streaming-ssr/src/routes/deferred-rejection.tsx deleted file mode 100644 index 5018f9e07c..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routes/deferred-rejection.tsx +++ /dev/null @@ -1,49 +0,0 @@ -import { Await, createFileRoute } from '@tanstack/vue-router' -import { Suspense } from 'vue' -import { - deferredDataDelay, - deferredErrorMessage, -} from '../../../../streaming-ssr-fixtures' - -export const Route = createFileRoute('/deferred-rejection')({ - loader: async () => { - return { - deferredData: new Promise((_resolve, reject) => { - setTimeout(() => { - reject(new Error(deferredErrorMessage)) - }, deferredDataDelay) - }), - } - }, - errorComponent: ({ error }) => ( -
- {error instanceof Error ? error.message : String(error)} -
- ), - component: DeferredRejection, -}) - -function DeferredRejection() { - const data = Route.useLoaderData() - - return ( -
-

Deferred Rejection Test

- - {{ - default: () => ( - ( -
{value}
- )} - /> - ), - fallback: () => ( -
Loading deferred...
- ), - }} -
-
- ) -} diff --git a/e2e/vue-start/streaming-ssr/src/routes/deferred.tsx b/e2e/vue-start/streaming-ssr/src/routes/deferred.tsx deleted file mode 100644 index 6a8affe1b4..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routes/deferred.tsx +++ /dev/null @@ -1,100 +0,0 @@ -import { Await, createFileRoute } from '@tanstack/vue-router' -import { createServerFn } from '@tanstack/vue-start' -import { Suspense } from 'vue' -import { - deferredDataDelay, - deferredDataMessage, - deferredImmediateName, - deferredServerDelay, - deferredSlowName, - delay, - makeDeferredMessage, - makeServerData, - sourceMarker, -} from '../../../../streaming-ssr-fixtures' - -const getImmediateData = createServerFn({ method: 'GET' }) - .validator((data: { name: string }) => data) - .handler(({ data }) => makeServerData(data.name)) - -const getSlowData = createServerFn({ method: 'GET' }) - .validator((data: { name: string; delay: number }) => data) - .handler(async ({ data }) => { - await delay(data.delay) - return makeServerData(data.name) - }) - -export const Route = createFileRoute('/deferred')({ - loader: async () => { - return { - deferredData: makeDeferredMessage(deferredDataMessage, deferredDataDelay), - deferredServerData: getSlowData({ - data: { name: deferredSlowName, delay: deferredServerDelay }, - }), - immediateData: await getImmediateData({ - data: { name: deferredImmediateName }, - }), - loaderSource: sourceMarker(), - } - }, - component: Deferred, -}) - -function Deferred() { - const data = Route.useLoaderData() - - return ( -
-

Deferred Data Test

-
- Immediate: {data.value.immediateData.name} @{' '} - {data.value.immediateData.timestamp} -
-
- Immediate source: {data.value.immediateData.source} -
-
- Loader source: {data.value.loaderSource} -
- - {{ - default: () => ( - ( -
- {value.message} (source: {value.source}) -
- )} - /> - ), - fallback: () => ( -
Loading deferred...
- ), - }} -
- - {{ - default: () => ( - ( -
- Server: {value.name} @ {value.timestamp} (source:{' '} - {value.source}) -
- )} - /> - ), - fallback: () => ( -
Loading server data...
- ), - }} -
-
- ) -} diff --git a/e2e/vue-start/streaming-ssr/src/routes/fast-serial.tsx b/e2e/vue-start/streaming-ssr/src/routes/fast-serial.tsx deleted file mode 100644 index ac004b041c..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routes/fast-serial.tsx +++ /dev/null @@ -1,49 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' -import { createServerFn } from '@tanstack/vue-start' -import { - fastSerialStaticData, - makeFastSerialSmallData, - sourceMarker, -} from '../../../../streaming-ssr-fixtures' - -const getSmallData = createServerFn({ method: 'GET' }).handler(() => - makeFastSerialSmallData(), -) - -export const Route = createFileRoute('/fast-serial')({ - loader: async () => { - const data = await getSmallData() - return { - serverData: data, - staticData: fastSerialStaticData, - timestamp: Date.now(), - loaderSource: sourceMarker(), - } - }, - component: FastSerial, -}) - -function FastSerial() { - const data = Route.useLoaderData() - - return ( -
-

Fast Serialization Test

-

This route tests when serialization completes before render.

-
- Server: {data.value.serverData.value} @{' '} - {data.value.serverData.timestamp} -
-
- Server function source: {data.value.serverData.source} -
-
- Loader source: {data.value.loaderSource} -
-
Static: {data.value.staticData}
-
- Loader timestamp: {data.value.timestamp} -
-
- ) -} diff --git a/e2e/vue-start/streaming-ssr/src/routes/index.tsx b/e2e/vue-start/streaming-ssr/src/routes/index.tsx deleted file mode 100644 index 0350eb5d4a..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routes/index.tsx +++ /dev/null @@ -1,58 +0,0 @@ -import { Link, createFileRoute } from '@tanstack/vue-router' - -export const Route = createFileRoute('/')({ - component: Index, -}) - -function Index() { - return ( -
-

Streaming SSR Test Scenarios

-

This e2e project tests various SSR streaming scenarios:

-
    -
  • - - Sync Only - {' '} - - Tests synchronous serialization with no deferred/streaming data -
  • -
  • - - Deferred Data - {' '} - - Tests deferred promises resolving after initial render -
  • -
  • - - Deferred Rejection - {' '} - - Tests deferred promise rejections render through the error boundary -
  • -
  • - - ReadableStream - {' '} - - Tests streaming data via ReadableStream -
  • -
  • - - Fast Serialization - {' '} - - Tests when serialization completes before render finishes -
  • -
  • - - Slow Render - {' '} - - Tests when render takes longer than serialization -
  • -
  • - - Nested Deferred - {' '} - - Tests nested components with deferred data -
  • -
-
- ) -} diff --git a/e2e/vue-start/streaming-ssr/src/routes/many-promises.tsx b/e2e/vue-start/streaming-ssr/src/routes/many-promises.tsx deleted file mode 100644 index 4361696107..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routes/many-promises.tsx +++ /dev/null @@ -1,94 +0,0 @@ -import { Await, createFileRoute } from '@tanstack/vue-router' -import { Suspense } from 'vue' -import { createManyPromises } from '../../../../streaming-ssr-fixtures' - -export const Route = createFileRoute('/many-promises')({ - loader: async () => createManyPromises(), - component: ManyPromises, -}) - -function PromiseItem(props: { - promise: Promise - testId: string - label: string -}) { - return ( - - {{ - default: () => ( - ( -
- {props.label}: {value} -
- )} - /> - ), - fallback: () => ( -
- Loading {props.label}... -
- ), - }} -
- ) -} - -function ManyPromises() { - const data = Route.useLoaderData() - - return ( -
-

Many Promises Test (15 deferred)

-

Tests streaming with many concurrent deferred promises.

- - - - - - - - - - - - - - - -
- ) -} diff --git a/e2e/vue-start/streaming-ssr/src/routes/nested-deferred.tsx b/e2e/vue-start/streaming-ssr/src/routes/nested-deferred.tsx deleted file mode 100644 index b24336ec40..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routes/nested-deferred.tsx +++ /dev/null @@ -1,143 +0,0 @@ -import { Await, createFileRoute } from '@tanstack/vue-router' -import { createServerFn } from '@tanstack/vue-start' -import { Suspense } from 'vue' -import { - delay, - makeDeferred, - makeLevelData, - nestedLevelDelays, - nestedPlainDelay, - nestedPlainMessage, -} from '../../../../streaming-ssr-fixtures' - -const getLevel1Data = createServerFn({ method: 'GET' }).handler(async () => { - await delay(nestedLevelDelays[0]) - return makeLevelData(1) -}) - -const getLevel2Data = createServerFn({ method: 'GET' }).handler(async () => { - await delay(nestedLevelDelays[1]) - return makeLevelData(2) -}) - -const getLevel3Data = createServerFn({ method: 'GET' }).handler(async () => { - await delay(nestedLevelDelays[2]) - return makeLevelData(3) -}) - -export const Route = createFileRoute('/nested-deferred')({ - loader: async () => { - return { - level1: getLevel1Data(), - level2: getLevel2Data(), - level3: getLevel3Data(), - plainDeferred: makeDeferred(nestedPlainMessage, nestedPlainDelay), - } - }, - component: NestedDeferred, -}) - -function Level2Content(props: { - level3: Promise<{ level: number; timestamp: number }> -}) { - return ( -
- - {{ - default: () => ( - ( -
- Level 3: {value.level} @ {value.timestamp} -
- )} - /> - ), - fallback: () => ( -
Loading level 3...
- ), - }} -
-
- ) -} - -function Level1Content(props: { - level2: Promise<{ level: number; timestamp: number }> - level3: Promise<{ level: number; timestamp: number }> -}) { - return ( -
- - {{ - default: () => ( - ( -
- Level 2: {value.level} @ {value.timestamp} - -
- )} - /> - ), - fallback: () => ( -
Loading level 2...
- ), - }} -
-
- ) -} - -function NestedDeferred() { - const data = Route.useLoaderData() - - return ( -
-

Nested Deferred Test

-

- Tests multiple nested deferred promises resolving at different times. -

- - {{ - default: () => ( - ( -
{value}
- )} - /> - ), - fallback: () => ( -
Loading plain...
- ), - }} -
-
- - {{ - default: () => ( - ( -
- Level 1: {value.level} @ {value.timestamp} - -
- )} - /> - ), - fallback: () => ( -
Loading level 1...
- ), - }} -
-
-
- ) -} diff --git a/e2e/vue-start/streaming-ssr/src/routes/query-heavy.tsx b/e2e/vue-start/streaming-ssr/src/routes/query-heavy.tsx deleted file mode 100644 index b22154b78e..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routes/query-heavy.tsx +++ /dev/null @@ -1,168 +0,0 @@ -import { queryOptions, useQuery } from '@tanstack/vue-query' -import { createFileRoute } from '@tanstack/vue-router' -import { Suspense, defineComponent } from 'vue' -import type { PropType } from 'vue' - -import { - delay, - makeQueryData, - queryHeavyItems, -} from '../../../../streaming-ssr-fixtures' -import type { QueryData } from '../../../../streaming-ssr-fixtures' - -function makeQueryOptions(item: (typeof queryHeavyItems)[number]) { - return queryOptions({ - queryKey: ['streaming-ssr-query-heavy', item.type, item.id], - queryFn: async (): Promise => { - if (item.delayMs > 0) { - await delay(item.delayMs) - } - - return makeQueryData(item) - }, - staleTime: Infinity, - }) -} - -const syncQuery1 = makeQueryOptions(queryHeavyItems[0]) -const syncQuery2 = makeQueryOptions(queryHeavyItems[1]) -const syncQuery3 = makeQueryOptions(queryHeavyItems[2]) -const fastAsyncQuery1 = makeQueryOptions(queryHeavyItems[3]) -const fastAsyncQuery2 = makeQueryOptions(queryHeavyItems[4]) -const fastAsyncQuery3 = makeQueryOptions(queryHeavyItems[5]) -const slowAsyncQuery1 = makeQueryOptions(queryHeavyItems[6]) -const slowAsyncQuery2 = makeQueryOptions(queryHeavyItems[7]) -const slowAsyncQuery3 = makeQueryOptions(queryHeavyItems[8]) - -type QueryOptions = ReturnType - -const QueryDisplay = defineComponent({ - props: { - queryOpts: { - type: Object as PropType, - required: true, - }, - testId: { - type: String, - required: true, - }, - }, - async setup(props) { - const query = useQuery(props.queryOpts) - await query.suspense() - - return () => { - const data = query.data.value - - return ( -
- {data?.value} (source: {data?.source}) -
- ) - } - }, -}) - -function QuerySuspense(props: { - queryOpts: QueryOptions - testId: string - fallback: string -}) { - return ( - - {{ - default: () => ( - - ), - fallback: () => ( -
{props.fallback}
- ), - }} -
- ) -} - -const QueryHeavy = defineComponent({ - setup() { - return () => ( -
-

Query Heavy Test (9 useQuery calls)

-

Tests multiple useQuery with mixed sync/async queryFn.

-

- All queries should show "source: server" if SSR streaming works - correctly. -

- -
-
-

Sync Queries (immediate)

- - - -
- -
-

Fast Async Queries (50-100ms)

- - - -
- -
-

Slow Async Queries (200-400ms)

- - - -
-
-
- ) - }, -}) - -export const Route = createFileRoute('/query-heavy')({ - component: QueryHeavy, -}) diff --git a/e2e/vue-start/streaming-ssr/src/routes/slow-render.tsx b/e2e/vue-start/streaming-ssr/src/routes/slow-render.tsx deleted file mode 100644 index f897e03ff0..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routes/slow-render.tsx +++ /dev/null @@ -1,77 +0,0 @@ -import { Await, createFileRoute } from '@tanstack/vue-router' -import { createServerFn } from '@tanstack/vue-start' -import { Suspense } from 'vue' -import { - makeDeferredMessage, - makeServerData, - slowRenderComponents, - slowRenderDeferredDelay, - slowRenderDeferredMessage, - slowRenderQuickName, - sourceMarker, -} from '../../../../streaming-ssr-fixtures' - -const getQuickData = createServerFn({ method: 'GET' }).handler(() => - makeServerData(slowRenderQuickName), -) - -function SlowComponent(props: { data: string; index: number }) { - const startTime = Date.now() - while (Date.now() - startTime < 100) { - // Simulate slow render work. - } - return
{props.data}
-} - -export const Route = createFileRoute('/slow-render')({ - loader: async () => { - const quickData = await getQuickData() - return { - quickData, - deferredData: makeDeferredMessage( - slowRenderDeferredMessage, - slowRenderDeferredDelay, - ), - loaderSource: sourceMarker(), - } - }, - component: SlowRender, -}) - -function SlowRender() { - const data = Route.useLoaderData() - - return ( -
-

Slow Render Test

-

Tests when render takes longer than serialization.

-
- Quick: {data.value.quickData.name} @ {data.value.quickData.timestamp} -
-
- Quick data source: {data.value.quickData.source} -
-
- Loader source: {data.value.loaderSource} -
- - {{ - default: () => ( - ( -
- {value.message} (source: {value.source}) -
- )} - /> - ), - fallback: () =>
Loading...
, - }} -
- {slowRenderComponents.map((data, index) => ( - - ))} -
- ) -} diff --git a/e2e/vue-start/streaming-ssr/src/routes/stream.tsx b/e2e/vue-start/streaming-ssr/src/routes/stream.tsx deleted file mode 100644 index 31368bedfc..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routes/stream.tsx +++ /dev/null @@ -1,171 +0,0 @@ -import { Await, createFileRoute, useRouter } from '@tanstack/vue-router' -import { - Suspense, - defineComponent, - onMounted, - onUnmounted, - ref, - watch, -} from 'vue' -import { - createChunkStream, - createStreamPromise, -} from '../../../../streaming-ssr-fixtures' - -export const Route = createFileRoute('/stream')({ - component: () => , - loader() { - return { - promise: createStreamPromise(), - stream: createChunkStream(), - } - }, -}) - -const decoder = new TextDecoder('utf-8') - -const StreamRoute = defineComponent({ - setup() { - const data = Route.useLoaderData() - const router = useRouter() - const streamData = ref>([]) - const streamComplete = ref(false) - const streamReadCount = ref(0) - let reader: ReadableStreamDefaultReader | undefined - let mounted = false - let activeStream: ReadableStream | undefined - let reading = false - let readTimer: ReturnType | undefined - - function clearReadTimer() { - if (readTimer) { - clearTimeout(readTimer) - readTimer = undefined - } - } - - function scheduleRead(delay = 0) { - if (!mounted || reading) { - return - } - - clearReadTimer() - readTimer = setTimeout(() => { - readTimer = undefined - void readStream() - }, delay) - } - - async function readStream() { - const stream = data.value.stream - if (!mounted || reading || activeStream === stream) { - return - } - - if (stream.locked) { - scheduleRead(10) - return - } - - streamData.value = [] - streamComplete.value = false - - let activeReader: ReadableStreamDefaultReader | undefined - - try { - const currentReader = stream.getReader() - activeReader = currentReader - reader = currentReader - activeStream = stream - reading = true - streamReadCount.value++ - - let chunk - while (!(chunk = await currentReader.read()).done) { - let value = chunk.value - if (typeof value !== 'string') { - value = decoder.decode(value, { stream: !chunk.done }) - } - streamData.value = [...streamData.value, value] - } - streamComplete.value = true - } catch (e) { - const message = String(e) - if (e instanceof TypeError && message.includes('locked')) { - activeStream = undefined - scheduleRead(10) - } else if (!(e instanceof TypeError && message.includes('cancelled'))) { - console.error('Stream error:', e) - } - } finally { - activeReader?.releaseLock() - if (reader === activeReader) { - reader = undefined - } - reading = false - if (activeStream !== data.value.stream) { - scheduleRead() - } - } - } - - onMounted(() => { - mounted = true - scheduleRead() - }) - watch( - () => data.value.stream, - () => { - activeStream = undefined - scheduleRead() - }, - ) - onUnmounted(() => { - mounted = false - clearReadTimer() - reader?.cancel().catch(() => {}) - reader = undefined - }) - - return () => ( -
-

ReadableStream Test

- - - {{ - default: () => ( - ( -
{value}
- )} - /> - ), - fallback: () => ( -
Loading promise...
- ), - }} -
-
-

Stream chunks:

-
- {streamData.value.map((chunk, i) => ( -
{chunk}
- ))} -
- {streamComplete.value && ( -
Stream complete!
- )} -
-
- ) - }, -}) diff --git a/e2e/vue-start/streaming-ssr/src/routes/sync-only.tsx b/e2e/vue-start/streaming-ssr/src/routes/sync-only.tsx deleted file mode 100644 index bbad10839e..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routes/sync-only.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' -import { makeSyncOnlyData } from '../../../../streaming-ssr-fixtures' - -export const Route = createFileRoute('/sync-only')({ - loader: async () => makeSyncOnlyData(), - component: SyncOnly, -}) - -function SyncOnly() { - const data = Route.useLoaderData() - - return ( -
-

Synchronous Serialization Test

-

{data.value.message}

-

Loaded at: {data.value.timestamp}

-

Source: {data.value.source}

-
    - {data.value.items.map((item: string) => ( -
  • {item}
  • - ))} -
-
- ) -} diff --git a/e2e/vue-start/streaming-ssr/tests/client-navigation.spec.ts b/e2e/vue-start/streaming-ssr/tests/client-navigation.spec.ts deleted file mode 100644 index 8b9b3a8dcc..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/client-navigation.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/client-navigation' diff --git a/e2e/vue-start/streaming-ssr/tests/concurrent.spec.ts b/e2e/vue-start/streaming-ssr/tests/concurrent.spec.ts deleted file mode 100644 index 8625473a58..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/concurrent.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/concurrent' diff --git a/e2e/vue-start/streaming-ssr/tests/deferred-rejection.spec.ts b/e2e/vue-start/streaming-ssr/tests/deferred-rejection.spec.ts deleted file mode 100644 index 355b5019bc..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/deferred-rejection.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/deferred-rejection' diff --git a/e2e/vue-start/streaming-ssr/tests/deferred.spec.ts b/e2e/vue-start/streaming-ssr/tests/deferred.spec.ts deleted file mode 100644 index 3145897d7b..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/deferred.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/deferred' diff --git a/e2e/vue-start/streaming-ssr/tests/fast-serial.spec.ts b/e2e/vue-start/streaming-ssr/tests/fast-serial.spec.ts deleted file mode 100644 index 95df0555e2..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/fast-serial.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/fast-serial' diff --git a/e2e/vue-start/streaming-ssr/tests/home.spec.ts b/e2e/vue-start/streaming-ssr/tests/home.spec.ts deleted file mode 100644 index 5d49d34a56..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/home.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/home' diff --git a/e2e/vue-start/streaming-ssr/tests/many-promises.spec.ts b/e2e/vue-start/streaming-ssr/tests/many-promises.spec.ts deleted file mode 100644 index b747bd7d0a..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/many-promises.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/many-promises' diff --git a/e2e/vue-start/streaming-ssr/tests/nested-deferred.spec.ts b/e2e/vue-start/streaming-ssr/tests/nested-deferred.spec.ts deleted file mode 100644 index 8df20a8a95..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/nested-deferred.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/nested-deferred' diff --git a/e2e/vue-start/streaming-ssr/tests/preview-streaming.spec.ts b/e2e/vue-start/streaming-ssr/tests/preview-streaming.spec.ts deleted file mode 100644 index 34241cfbaa..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/preview-streaming.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/preview-streaming' diff --git a/e2e/vue-start/streaming-ssr/tests/query-heavy.spec.ts b/e2e/vue-start/streaming-ssr/tests/query-heavy.spec.ts deleted file mode 100644 index d15c092f6e..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/query-heavy.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/query-heavy' diff --git a/e2e/vue-start/streaming-ssr/tests/slow-render.spec.ts b/e2e/vue-start/streaming-ssr/tests/slow-render.spec.ts deleted file mode 100644 index 0d5a87363f..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/slow-render.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/slow-render' diff --git a/e2e/vue-start/streaming-ssr/tests/stream.spec.ts b/e2e/vue-start/streaming-ssr/tests/stream.spec.ts deleted file mode 100644 index 9dfc6820ad..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/stream.spec.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { expect, testWithHydration } from '../../../streaming-ssr-assertions' -import '../../../streaming-ssr-specs/stream' - -testWithHydration( - 'reads a replacement stream after an active read', - async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - await page.getByRole('link', { name: 'Stream' }).first().click() - await expect(page.getByTestId('stream-chunk-0')).toHaveText('chunk-0') - await expect(page.getByTestId('stream-complete')).toHaveCount(0) - - await page.getByTestId('refresh-stream').click() - - const streamData = page.getByTestId('stream-data') - await expect(streamData).toHaveAttribute('data-read-count', '2') - await expect(page.getByTestId('stream-complete')).toBeVisible() - await expect( - streamData.locator('[data-testid^="stream-chunk-"]'), - ).toHaveText(['chunk-0', 'chunk-1', 'chunk-2', 'chunk-3', 'chunk-4']) - }, -) diff --git a/e2e/vue-start/streaming-ssr/tests/sync-only.spec.ts b/e2e/vue-start/streaming-ssr/tests/sync-only.spec.ts deleted file mode 100644 index b25572f615..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/sync-only.spec.ts +++ /dev/null @@ -1,7 +0,0 @@ -import '../../../streaming-ssr-specs/sync-only' -import { expect, test } from '../../../streaming-ssr-assertions' - -test('Vue renders an unwrapped document root', async ({ request }) => { - const response = await request.get('/sync-only') - expect(await response.text()).toMatch(/^)/) -}) diff --git a/e2e/vue-start/streaming-ssr/tsconfig.json b/e2e/vue-start/streaming-ssr/tsconfig.json deleted file mode 100644 index 390dad84c0..0000000000 --- a/e2e/vue-start/streaming-ssr/tsconfig.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "include": ["**/*.ts", "**/*.tsx"], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "preserve", - "jsxImportSource": "vue", - "module": "ESNext", - "moduleResolution": "Bundler", - "lib": ["DOM", "DOM.Iterable", "ES2022"], - "isolatedModules": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "target": "ES2022", - "allowJs": true, - "forceConsistentCasingInFileNames": true, - "paths": { - "~/*": ["./src/*"] - }, - "noEmit": true - } -} diff --git a/e2e/vue-start/streaming-ssr/vite.config.ts b/e2e/vue-start/streaming-ssr/vite.config.ts deleted file mode 100644 index 6519ec54c8..0000000000 --- a/e2e/vue-start/streaming-ssr/vite.config.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { defineConfig } from 'vite' -import { tanstackStart } from '@tanstack/vue-start/plugin/vite' -import vueJsx from '@vitejs/plugin-vue-jsx' - -export default defineConfig({ - server: { - port: 3000, - }, - plugins: [tanstackStart(), vueJsx()], -}) diff --git a/e2e/vue-start/virtual-routes/package.json b/e2e/vue-start/virtual-routes/package.json index 90f09ce911..3697e87e52 100644 --- a/e2e/vue-start/virtual-routes/package.json +++ b/e2e/vue-start/virtual-routes/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/virtual-file-routes": "workspace:^", @@ -29,7 +29,7 @@ "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "combinate": "^1.1.11", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/vue-start/virtual-routes/playwright.config.ts b/e2e/vue-start/virtual-routes/playwright.config.ts index 1862174905..b0c365f8bd 100644 --- a/e2e/vue-start/virtual-routes/playwright.config.ts +++ b/e2e/vue-start/virtual-routes/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,19 +18,19 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', - env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, - }, }, projects: [ diff --git a/e2e/vue-start/virtual-routes/src/posts.tsx b/e2e/vue-start/virtual-routes/src/posts.tsx index f7a1941605..1b4c92b41d 100644 --- a/e2e/vue-start/virtual-routes/src/posts.tsx +++ b/e2e/vue-start/virtual-routes/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-start/virtual-routes/src/routes/posts/posts-detail.tsx b/e2e/vue-start/virtual-routes/src/routes/posts/posts-detail.tsx index 4bc3824f62..5086e3ad88 100644 --- a/e2e/vue-start/virtual-routes/src/routes/posts/posts-detail.tsx +++ b/e2e/vue-start/virtual-routes/src/routes/posts/posts-detail.tsx @@ -1,20 +1,7 @@ -import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' -const PostComponent = defineComponent({ - setup() { - const post = Route.useLoaderData() - return () => ( -
-

{post.value.title}

-
{post.value.body}
-
- ) - }, -}) - export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost(postId), errorComponent: PostErrorComponent, @@ -27,3 +14,14 @@ export const Route = createFileRoute('/posts/$postId')({ function PostErrorComponent({ error }: ErrorComponentProps) { return } + +function PostComponent() { + const post = Route.useLoaderData() + + return ( +
+

{post.value.title}

+
{post.value.body}
+
+ ) +} diff --git a/e2e/vue-start/virtual-routes/src/routes/posts/posts.tsx b/e2e/vue-start/virtual-routes/src/routes/posts/posts.tsx index dd380aa353..f56d6550a6 100644 --- a/e2e/vue-start/virtual-routes/src/routes/posts/posts.tsx +++ b/e2e/vue-start/virtual-routes/src/routes/posts/posts.tsx @@ -1,39 +1,37 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../../posts' -const PostsComponent = defineComponent({ - setup() { - const posts = Route.useLoaderData() - return () => ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ))} -
-
- -
- ) - }, -}) - export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) + +function PostsComponent() { + const posts = Route.useLoaderData() + + return ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ))} +
+
+ +
+ ) +} diff --git a/e2e/vue-start/virtual-routes/src/utils/posts.tsx b/e2e/vue-start/virtual-routes/src/utils/posts.tsx index 11d80d08b5..66cb298f83 100644 --- a/e2e/vue-start/virtual-routes/src/utils/posts.tsx +++ b/e2e/vue-start/virtual-routes/src/utils/posts.tsx @@ -8,7 +8,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = createServerFn({ method: 'GET' }) .validator((postId: string) => postId) diff --git a/e2e/vue-start/virtual-routes/src/utils/users.tsx b/e2e/vue-start/virtual-routes/src/utils/users.tsx index 7ba645b383..46be4b1580 100644 --- a/e2e/vue-start/virtual-routes/src/utils/users.tsx +++ b/e2e/vue-start/virtual-routes/src/utils/users.tsx @@ -3,3 +3,7 @@ export type User = { name: string email: string } + +const PORT = process.env.VITE_SERVER_PORT || 3000 + +export const DEPLOY_URL = `http://localhost:${PORT}` diff --git a/e2e/vue-start/virtual-routes/tests/app.spec.ts b/e2e/vue-start/virtual-routes/tests/app.spec.ts index e9db98e3f3..3182febfa0 100644 --- a/e2e/vue-start/virtual-routes/tests/app.spec.ts +++ b/e2e/vue-start/virtual-routes/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-start/virtual-routes/tests/setup/global.setup.ts b/e2e/vue-start/virtual-routes/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-start/virtual-routes/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/virtual-routes/tests/setup/global.teardown.ts b/e2e/vue-start/virtual-routes/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-start/virtual-routes/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/website/package.json b/e2e/vue-start/website/package.json index 6c30b1500f..5e92c93769 100644 --- a/e2e/vue-start/website/package.json +++ b/e2e/vue-start/website/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -27,7 +27,7 @@ "@types/node": "^22.10.2", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/vue-start/website/playwright.config.ts b/e2e/vue-start/website/playwright.config.ts index e6b92ce385..f6dd61ba6c 100644 --- a/e2e/vue-start/website/playwright.config.ts +++ b/e2e/vue-start/website/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/website/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/website/src/components/DefaultCatchBoundary.tsx index 77c03c5afa..d06f4a948b 100644 --- a/e2e/vue-start/website/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/website/src/components/DefaultCatchBoundary.tsx @@ -1,5 +1,3 @@ -import { defineComponent } from 'vue' -import type { PropType } from 'vue' import { ErrorComponent, Link, @@ -8,54 +6,46 @@ import { } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -export const DefaultCatchBoundary = defineComponent({ - props: { - error: { - type: Object as PropType, - required: true, - }, - }, - setup(props) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - return () => { - console.error(props.error) - return ( -
- -
- - {isRoot.value ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) - } - }, -}) +export function DefaultCatchBoundary({ error }: ErrorComponentProps) { + const router = useRouter() + const isRoot = useLocation({ + select: (location) => location.pathname === '/', + }) + + console.error(error) + + return ( +
+ +
+ + {isRoot.value ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
+
+ ) +} diff --git a/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.$.tsx b/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.$.tsx index 1d9173f200..f56c911b88 100644 --- a/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.$.tsx +++ b/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.$.tsx @@ -1,27 +1,9 @@ -import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' import { NotFound } from '~/components/NotFound' import { getDocument } from '~/server/document' import { capitalize, seo } from '~/utils/seo' -const Page = defineComponent({ - setup() { - const post = Route.useLoaderData() - return () => ( -
-

- {post.value.title} -

-
{post.value.content}
-
- ) - }, -}) - export const Route = createFileRoute( '/$project/$version/docs/framework/$framework/$', )({ @@ -44,3 +26,19 @@ export const Route = createFileRoute( function PostErrorComponent({ error }: ErrorComponentProps) { return } + +function Page() { + const post = Route.useLoaderData() + + return ( +
+

+ {post.value.title} +

+
{post.value.content}
+
+ ) +} diff --git a/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.examples.$.tsx b/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.examples.$.tsx index 1ca9e97cbe..97f8fdd49a 100644 --- a/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.examples.$.tsx +++ b/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.examples.$.tsx @@ -1,24 +1,7 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { NotFound } from '~/components/NotFound' import { capitalize, seo } from '~/utils/seo' -const Page = defineComponent({ - setup() { - const params = Route.useParams() - return () => ( -
-

- {params.value._splat} example -

-
- ) - }, -}) - export const Route = createFileRoute( '/$project/$version/docs/framework/$framework/examples/$', )({ @@ -32,3 +15,18 @@ export const Route = createFileRoute( return Example not found }, }) + +function Page() { + const params = Route.useParams() + + return ( +
+

+ {params.value._splat} example +

+
+ ) +} diff --git a/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.tsx b/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.tsx index e1c57491aa..1b422b2ea0 100644 --- a/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.tsx +++ b/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { Link, Outlet, @@ -8,108 +7,6 @@ import { import { getDocumentHeads } from '~/server/document' import { getProject } from '~/server/projects' -const Page = defineComponent({ - setup() { - const project = Route.useLoaderData({ select: (s) => s.library }) - const documents = Route.useLoaderData({ select: (s) => s.documents }) - const pathname = useLocation({ select: (s) => s.pathname }) - return () => ( -
- -
-

- {pathname.value} -

- -
-
- ) - }, -}) - export const Route = createFileRoute( '/$project/$version/docs/framework/$framework', )({ @@ -123,3 +20,104 @@ export const Route = createFileRoute( }, component: Page, }) + +function Page() { + const project = Route.useLoaderData({ select: (s) => s.library }) + const documents = Route.useLoaderData({ select: (s) => s.documents }) + const pathname = useLocation({ select: (s) => s.pathname }) + + return ( +
+ +
+

+ {pathname.value} +

+ +
+
+ ) +} diff --git a/e2e/vue-start/website/src/routes/_library.$project.$version.index.tsx b/e2e/vue-start/website/src/routes/_library.$project.$version.index.tsx index d6c9b00671..ed8e4d0bb4 100644 --- a/e2e/vue-start/website/src/routes/_library.$project.$version.index.tsx +++ b/e2e/vue-start/website/src/routes/_library.$project.$version.index.tsx @@ -1,31 +1,23 @@ -import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' -const Page = defineComponent({ - setup() { - const params = Route.useParams() - return () => ( -
-

- {params.value.project} landing page -

-

- version: {params.value.version} -

-

- - Get started with our documentation. - -

-
- ) - }, -}) - export const Route = createFileRoute('/_library/$project/$version/')({ component: Page, }) + +function Page() { + const params = Route.useParams() + + return ( +
+

+ {params.value.project} landing page +

+

version: {params.value.version}

+

+ + Get started with our documentation. + +

+
+ ) +} diff --git a/e2e/vue-start/website/src/routes/_library.tsx b/e2e/vue-start/website/src/routes/_library.tsx index b52198950d..fcbeaa35d0 100644 --- a/e2e/vue-start/website/src/routes/_library.tsx +++ b/e2e/vue-start/website/src/routes/_library.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { Link, Outlet, @@ -7,53 +6,6 @@ import { } from '@tanstack/vue-router' import { getProjects } from '~/server/projects' -const Layout = defineComponent({ - setup() { - const loaderData = Route.useLoaderData() - const pathname = useLocation({ select: (s) => s.pathname }) - return () => ( -
- -
-

- {pathname.value} -

- -
-
- ) - }, -}) - export const Route = createFileRoute('/_library')({ loader: async () => { const projects = await getProjects() @@ -63,3 +15,48 @@ export const Route = createFileRoute('/_library')({ }, component: Layout, }) + +function Layout() { + const loaderData = Route.useLoaderData() + const pathname = useLocation({ select: (s) => s.pathname }) + return ( +
+ +
+

+ {pathname.value} +

+ +
+
+ ) +} diff --git a/examples/AGENTS.md b/examples/AGENTS.md deleted file mode 100644 index eb47fbd925..0000000000 --- a/examples/AGENTS.md +++ /dev/null @@ -1,4 +0,0 @@ -# Examples - -- Versioned dependencies on this repository's packages resolve locally through `pnpm-workspace.yaml` overrides. Keep published version ranges in example manifests; do not replace them with `workspace:*` as a linking fix. -- Root `pnpm dev` watches package builds. To run an example app, use its own `dev` script after building its workspace dependencies. diff --git a/examples/react/authenticated-routes-firebase/package.json b/examples/react/authenticated-routes-firebase/package.json index 1efa172047..3c7361f319 100644 --- a/examples/react/authenticated-routes-firebase/package.json +++ b/examples/react/authenticated-routes-firebase/package.json @@ -10,13 +10,13 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.35", "firebase": "^11.4.0", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "simple-icons": "^14.9.0", "tailwindcss": "^4.2.2", "zod": "^4.4.3" diff --git a/examples/react/authenticated-routes/package.json b/examples/react/authenticated-routes/package.json index 6af48f1d34..cc6025d27c 100644 --- a/examples/react/authenticated-routes/package.json +++ b/examples/react/authenticated-routes/package.json @@ -10,12 +10,12 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.35", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, diff --git a/examples/react/basic-default-search-params/package.json b/examples/react/basic-default-search-params/package.json index 96c68fecd4..e0a5c34d55 100644 --- a/examples/react/basic-default-search-params/package.json +++ b/examples/react/basic-default-search-params/package.json @@ -10,12 +10,12 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.102.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-query": "^5.90.0", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, diff --git a/examples/react/basic-devtools-panel/package.json b/examples/react/basic-devtools-panel/package.json index ccae95d73f..cf94737bf2 100644 --- a/examples/react/basic-devtools-panel/package.json +++ b/examples/react/basic-devtools-panel/package.json @@ -10,13 +10,13 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.102.0", + "@tanstack/react-query": "catalog:", "@tanstack/react-query-devtools": "^5.67.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2" }, "devDependencies": { diff --git a/examples/react/basic-file-based/package.json b/examples/react/basic-file-based/package.json index 9c3cacada1..f147e235f1 100644 --- a/examples/react/basic-file-based/package.json +++ b/examples/react/basic-file-based/package.json @@ -10,12 +10,12 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.35", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, diff --git a/examples/react/basic-non-nested-devtools/package.json b/examples/react/basic-non-nested-devtools/package.json index 32e856ebcf..7cd8e94d3c 100644 --- a/examples/react/basic-non-nested-devtools/package.json +++ b/examples/react/basic-non-nested-devtools/package.json @@ -10,11 +10,11 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2" }, "devDependencies": { diff --git a/examples/react/basic-react-query-file-based/package.json b/examples/react/basic-react-query-file-based/package.json index d01a02872e..8c5aa7f4d5 100644 --- a/examples/react/basic-react-query-file-based/package.json +++ b/examples/react/basic-react-query-file-based/package.json @@ -10,14 +10,14 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.102.0", + "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.35", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, diff --git a/examples/react/basic-react-query/package.json b/examples/react/basic-react-query/package.json index edab96afac..a5fbaaf025 100644 --- a/examples/react/basic-react-query/package.json +++ b/examples/react/basic-react-query/package.json @@ -10,13 +10,13 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.102.0", + "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2" }, "devDependencies": { diff --git a/examples/react/basic-ssr-file-based/package.json b/examples/react/basic-ssr-file-based/package.json index 3222c33e19..50ce5b3044 100644 --- a/examples/react/basic-ssr-file-based/package.json +++ b/examples/react/basic-ssr-file-based/package.json @@ -11,8 +11,8 @@ "debug": "node --inspect-brk server" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.32", + "@tanstack/router-plugin": "^1.168.35", "compression": "^1.8.0", "express": "^5.2.1", "get-port": "^7.1.0", @@ -21,7 +21,7 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router-devtools": "^1.167.1", "@types/express": "^5.0.6", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.1", diff --git a/examples/react/basic-ssr-streaming-file-based/package.json b/examples/react/basic-ssr-streaming-file-based/package.json index c3c87c8d88..c0fa29aac0 100644 --- a/examples/react/basic-ssr-streaming-file-based/package.json +++ b/examples/react/basic-ssr-streaming-file-based/package.json @@ -11,8 +11,8 @@ "debug": "node --inspect-brk server" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.32", + "@tanstack/router-plugin": "^1.168.35", "compression": "^1.8.0", "express": "^5.2.1", "get-port": "^7.1.0", @@ -21,7 +21,7 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router-devtools": "^1.167.1", "@types/express": "^5.0.6", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.1", diff --git a/examples/react/basic-virtual-file-based/package.json b/examples/react/basic-virtual-file-based/package.json index 84d326435c..377a4af67f 100644 --- a/examples/react/basic-virtual-file-based/package.json +++ b/examples/react/basic-virtual-file-based/package.json @@ -10,13 +10,13 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.35", "@tanstack/virtual-file-routes": "^1.162.0", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, diff --git a/examples/react/basic-virtual-inside-file-based/package.json b/examples/react/basic-virtual-inside-file-based/package.json index c04cb6012e..140c523c36 100644 --- a/examples/react/basic-virtual-inside-file-based/package.json +++ b/examples/react/basic-virtual-inside-file-based/package.json @@ -10,13 +10,13 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.35", "@tanstack/virtual-file-routes": "^1.162.0", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, diff --git a/examples/react/basic/package.json b/examples/react/basic/package.json index 2c09a3dfdf..d8c62660cd 100644 --- a/examples/react/basic/package.json +++ b/examples/react/basic/package.json @@ -10,11 +10,11 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2" }, "devDependencies": { diff --git a/examples/react/deferred-data/package.json b/examples/react/deferred-data/package.json index 99afb661ee..ebcb3cb39a 100644 --- a/examples/react/deferred-data/package.json +++ b/examples/react/deferred-data/package.json @@ -10,11 +10,11 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, diff --git a/examples/react/i18n-paraglide/package.json b/examples/react/i18n-paraglide/package.json index 88140e8911..1b81ac6889 100644 --- a/examples/react/i18n-paraglide/package.json +++ b/examples/react/i18n-paraglide/package.json @@ -11,8 +11,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.32", + "@tanstack/router-plugin": "^1.168.35", "react": "^19.1.1", "react-dom": "^19.1.1", "tailwindcss": "^4.2.2" @@ -26,16 +26,5 @@ "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "@inlang/paraglide-js": "^2.4.0" - }, - "nx": { - "targets": { - "build": { - "outputs": [ - "...", - "{projectRoot}/src/paraglide", - "{projectRoot}/project.inlang/cache" - ] - } - } } } diff --git a/examples/react/kitchen-sink-file-based/package.json b/examples/react/kitchen-sink-file-based/package.json index e02defb3ce..0af55e0d16 100644 --- a/examples/react/kitchen-sink-file-based/package.json +++ b/examples/react/kitchen-sink-file-based/package.json @@ -10,13 +10,13 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.35", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, diff --git a/examples/react/kitchen-sink-react-query-file-based/package.json b/examples/react/kitchen-sink-react-query-file-based/package.json index e3dd032ac2..d30ce14849 100644 --- a/examples/react/kitchen-sink-react-query-file-based/package.json +++ b/examples/react/kitchen-sink-react-query-file-based/package.json @@ -10,15 +10,15 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.102.0", + "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.35", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, diff --git a/examples/react/kitchen-sink-react-query/package.json b/examples/react/kitchen-sink-react-query/package.json index 14d0dc8e86..6b081bda11 100644 --- a/examples/react/kitchen-sink-react-query/package.json +++ b/examples/react/kitchen-sink-react-query/package.json @@ -10,14 +10,14 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.102.0", + "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, diff --git a/examples/react/kitchen-sink/package.json b/examples/react/kitchen-sink/package.json index f738efc37e..0bc5ca3435 100644 --- a/examples/react/kitchen-sink/package.json +++ b/examples/react/kitchen-sink/package.json @@ -10,12 +10,12 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, diff --git a/examples/react/large-file-based/package.json b/examples/react/large-file-based/package.json index 23d469d120..e8de368481 100644 --- a/examples/react/large-file-based/package.json +++ b/examples/react/large-file-based/package.json @@ -12,13 +12,13 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.102.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-query": "^5.90.0", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.35", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, diff --git a/examples/react/location-masking/package.json b/examples/react/location-masking/package.json index fe005c0d2f..be688919fc 100644 --- a/examples/react/location-masking/package.json +++ b/examples/react/location-masking/package.json @@ -11,12 +11,12 @@ "dependencies": { "@radix-ui/react-dialog": "^1.1.6", "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.102.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-query": "^5.90.0", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2" }, "devDependencies": { diff --git a/examples/react/navigation-blocking/package.json b/examples/react/navigation-blocking/package.json index a7677dfd51..965e2529ae 100644 --- a/examples/react/navigation-blocking/package.json +++ b/examples/react/navigation-blocking/package.json @@ -10,12 +10,12 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.102.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-query": "^5.90.0", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2" }, "devDependencies": { diff --git a/examples/react/quickstart-esbuild-file-based/esbuild.config.js b/examples/react/quickstart-esbuild-file-based/esbuild.config.js index 2f83a79984..fb7950d1fa 100644 --- a/examples/react/quickstart-esbuild-file-based/esbuild.config.js +++ b/examples/react/quickstart-esbuild-file-based/esbuild.config.js @@ -7,5 +7,5 @@ export default { bundle: true, format: 'esm', target: ['esnext'], - plugins: [tanstackRouter({ target: 'react' })], + plugins: [tanstackRouter({ target: 'react', autoCodeSplitting: true })], } diff --git a/examples/react/quickstart-esbuild-file-based/package.json b/examples/react/quickstart-esbuild-file-based/package.json index d855694fec..45fa6dba7b 100644 --- a/examples/react/quickstart-esbuild-file-based/package.json +++ b/examples/react/quickstart-esbuild-file-based/package.json @@ -9,12 +9,12 @@ "start": "dev" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.35", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "zod": "^4.4.3" }, "devDependencies": { diff --git a/examples/react/quickstart-file-based/package.json b/examples/react/quickstart-file-based/package.json index 976ec838d1..d58d6749d1 100644 --- a/examples/react/quickstart-file-based/package.json +++ b/examples/react/quickstart-file-based/package.json @@ -10,12 +10,12 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.35", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, diff --git a/examples/react/quickstart-rspack-file-based/package.json b/examples/react/quickstart-rspack-file-based/package.json index 824998f428..62c46ebdf3 100644 --- a/examples/react/quickstart-rspack-file-based/package.json +++ b/examples/react/quickstart-rspack-file-based/package.json @@ -9,17 +9,17 @@ }, "dependencies": { "@tailwindcss/postcss": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", "postcss": "^8.5.1", "react": "^19.0.0", "react-dom": "^19.0.0", "tailwindcss": "^4.2.2" }, "devDependencies": { - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-react": "^2.0.0", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/router-plugin": "^1.168.35", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@typescript/native": "npm:typescript@^7.0.2", diff --git a/examples/react/quickstart-webpack-file-based/package.json b/examples/react/quickstart-webpack-file-based/package.json index baa14b89dd..198947a5da 100644 --- a/examples/react/quickstart-webpack-file-based/package.json +++ b/examples/react/quickstart-webpack-file-based/package.json @@ -7,14 +7,14 @@ "build": "webpack build && tsc --noEmit" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { "@swc/core": "^1.15.33", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/router-plugin": "^1.168.35", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "html-webpack-plugin": "^5.6.3", diff --git a/examples/react/quickstart/package.json b/examples/react/quickstart/package.json index b6db476ea8..8fd1ce0661 100644 --- a/examples/react/quickstart/package.json +++ b/examples/react/quickstart/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", "react": "^19.0.0", "react-dom": "^19.0.0", "tailwindcss": "^4.2.2" diff --git a/examples/react/router-monorepo-react-query/package.json b/examples/react/router-monorepo-react-query/package.json index b158eeda56..2e3ec03f01 100644 --- a/examples/react/router-monorepo-react-query/package.json +++ b/examples/react/router-monorepo-react-query/package.json @@ -10,14 +10,14 @@ "dev": "pnpm post-query build && pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/react-query": "^5.102.0", + "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.35", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1" + "redaxios": "catalog:" }, "devDependencies": { "@types/node": "^22.10.2", diff --git a/examples/react/router-monorepo-react-query/packages/app/package.json b/examples/react/router-monorepo-react-query/packages/app/package.json index f0994165c2..336998abe7 100644 --- a/examples/react/router-monorepo-react-query/packages/app/package.json +++ b/examples/react/router-monorepo-react-query/packages/app/package.json @@ -11,12 +11,12 @@ "dependencies": { "@router-mono-react-query/post-feature": "workspace:*", "@router-mono-react-query/router": "workspace:*", - "@tanstack/react-query": "^5.102.0", + "@tanstack/react-query": "^5.90.0", "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router-devtools": "^1.167.1", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", @@ -33,12 +33,6 @@ "dependsOn": [ "^build" ] - }, - "build": { - "inputs": [ - "...", - "{workspaceRoot}/examples/react/router-monorepo-react-query/.gitignore" - ] } } } diff --git a/examples/react/router-monorepo-react-query/packages/app/tsconfig.json b/examples/react/router-monorepo-react-query/packages/app/tsconfig.json index 196cb055a9..ce3a7d2339 100644 --- a/examples/react/router-monorepo-react-query/packages/app/tsconfig.json +++ b/examples/react/router-monorepo-react-query/packages/app/tsconfig.json @@ -8,6 +8,5 @@ "module": "ESNext", "lib": ["DOM", "DOM.Iterable", "ES2022"], "skipLibCheck": true - }, - "exclude": ["node_modules", "dist"] + } } diff --git a/examples/react/router-monorepo-react-query/packages/post-feature/package.json b/examples/react/router-monorepo-react-query/packages/post-feature/package.json index 7f5e186ab0..21dc0d7793 100644 --- a/examples/react/router-monorepo-react-query/packages/post-feature/package.json +++ b/examples/react/router-monorepo-react-query/packages/post-feature/package.json @@ -8,7 +8,7 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/react-query": "^5.102.0", + "@tanstack/react-query": "^5.90.0", "@router-mono-react-query/post-query": "workspace:*", "@router-mono-react-query/router": "workspace:*", "react": "^19.0.0", diff --git a/examples/react/router-monorepo-react-query/packages/post-query/package.json b/examples/react/router-monorepo-react-query/packages/post-query/package.json index 98a06051be..67bfcc419a 100644 --- a/examples/react/router-monorepo-react-query/packages/post-query/package.json +++ b/examples/react/router-monorepo-react-query/packages/post-query/package.json @@ -8,8 +8,8 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/react-query": "^5.102.0", - "redaxios": "^0.5.1", + "@tanstack/react-query": "^5.90.0", + "redaxios": "catalog:", "zod": "^4.4.3" }, "devDependencies": { diff --git a/examples/react/router-monorepo-react-query/packages/router/package.json b/examples/react/router-monorepo-react-query/packages/router/package.json index 1397db14b5..f656c97e3d 100644 --- a/examples/react/router-monorepo-react-query/packages/router/package.json +++ b/examples/react/router-monorepo-react-query/packages/router/package.json @@ -9,13 +9,13 @@ "types": "./dist/index.d.ts", "dependencies": { "@router-mono-react-query/post-query": "workspace:*", - "@tanstack/history": "^1.162.5", - "@tanstack/react-query": "^5.102.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/history": "^1.162.1", + "@tanstack/react-query": "^5.90.0", + "@tanstack/react-router": "^1.170.32", + "@tanstack/router-plugin": "^1.168.35", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "zod": "^4.4.3" }, "devDependencies": { diff --git a/examples/react/router-monorepo-simple-lazy/package.json b/examples/react/router-monorepo-simple-lazy/package.json index e044d86681..0d32f10828 100644 --- a/examples/react/router-monorepo-simple-lazy/package.json +++ b/examples/react/router-monorepo-simple-lazy/package.json @@ -8,12 +8,12 @@ "dev": "pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.35", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1" + "redaxios": "catalog:" }, "devDependencies": { "@types/node": "^22.7.4", diff --git a/examples/react/router-monorepo-simple-lazy/packages/app/package.json b/examples/react/router-monorepo-simple-lazy/packages/app/package.json index cfc7a94942..a1e792cc3d 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/app/package.json +++ b/examples/react/router-monorepo-simple-lazy/packages/app/package.json @@ -15,7 +15,7 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router-devtools": "^1.167.1", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", @@ -32,12 +32,6 @@ "dependsOn": [ "^build" ] - }, - "build": { - "inputs": [ - "...", - "{workspaceRoot}/examples/react/router-monorepo-simple-lazy/.gitignore" - ] } } } diff --git a/examples/react/router-monorepo-simple-lazy/packages/app/tsconfig.json b/examples/react/router-monorepo-simple-lazy/packages/app/tsconfig.json index 196cb055a9..ce3a7d2339 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/app/tsconfig.json +++ b/examples/react/router-monorepo-simple-lazy/packages/app/tsconfig.json @@ -8,6 +8,5 @@ "module": "ESNext", "lib": ["DOM", "DOM.Iterable", "ES2022"], "skipLibCheck": true - }, - "exclude": ["node_modules", "dist"] + } } diff --git a/examples/react/router-monorepo-simple-lazy/packages/post-feature/package.json b/examples/react/router-monorepo-simple-lazy/packages/post-feature/package.json index 65738d6025..5e387f61f4 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/post-feature/package.json +++ b/examples/react/router-monorepo-simple-lazy/packages/post-feature/package.json @@ -16,7 +16,7 @@ } }, "dependencies": { - "@tanstack/react-query": "^5.102.0", + "@tanstack/react-query": "^5.90.0", "@router-mono-simple-lazy/router": "workspace:*", "react": "^19.0.0", "react-dom": "^19.0.0" diff --git a/examples/react/router-monorepo-simple-lazy/packages/router/package.json b/examples/react/router-monorepo-simple-lazy/packages/router/package.json index afd4702b5d..f0fa2bf300 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/router/package.json +++ b/examples/react/router-monorepo-simple-lazy/packages/router/package.json @@ -8,12 +8,12 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/history": "^1.162.5", - "@tanstack/react-router": "^1.170.46", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/history": "^1.162.1", + "@tanstack/react-router": "^1.170.32", + "@tanstack/router-plugin": "^1.168.35", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "zod": "^4.4.3" }, "devDependencies": { diff --git a/examples/react/router-monorepo-simple/package.json b/examples/react/router-monorepo-simple/package.json index 800d948c81..b288020e69 100644 --- a/examples/react/router-monorepo-simple/package.json +++ b/examples/react/router-monorepo-simple/package.json @@ -8,12 +8,12 @@ "dev": "pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.35", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1" + "redaxios": "catalog:" }, "devDependencies": { "@types/node": "^22.7.4", diff --git a/examples/react/router-monorepo-simple/packages/app/package.json b/examples/react/router-monorepo-simple/packages/app/package.json index a06431ef86..01da864c38 100644 --- a/examples/react/router-monorepo-simple/packages/app/package.json +++ b/examples/react/router-monorepo-simple/packages/app/package.json @@ -15,7 +15,7 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router-devtools": "^1.167.1", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", @@ -32,12 +32,6 @@ "dependsOn": [ "^build" ] - }, - "build": { - "inputs": [ - "...", - "{workspaceRoot}/examples/react/router-monorepo-simple/.gitignore" - ] } } } diff --git a/examples/react/router-monorepo-simple/packages/app/tsconfig.json b/examples/react/router-monorepo-simple/packages/app/tsconfig.json index 196cb055a9..ce3a7d2339 100644 --- a/examples/react/router-monorepo-simple/packages/app/tsconfig.json +++ b/examples/react/router-monorepo-simple/packages/app/tsconfig.json @@ -8,6 +8,5 @@ "module": "ESNext", "lib": ["DOM", "DOM.Iterable", "ES2022"], "skipLibCheck": true - }, - "exclude": ["node_modules", "dist"] + } } diff --git a/examples/react/router-monorepo-simple/packages/router/package.json b/examples/react/router-monorepo-simple/packages/router/package.json index 391b72e610..05ac90f7ae 100644 --- a/examples/react/router-monorepo-simple/packages/router/package.json +++ b/examples/react/router-monorepo-simple/packages/router/package.json @@ -8,12 +8,12 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/history": "^1.162.5", - "@tanstack/react-router": "^1.170.46", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/history": "^1.162.1", + "@tanstack/react-router": "^1.170.32", + "@tanstack/router-plugin": "^1.168.35", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "zod": "^4.4.3" }, "devDependencies": { diff --git a/examples/react/scroll-restoration/package.json b/examples/react/scroll-restoration/package.json index 704ff13838..21c6ec714f 100644 --- a/examples/react/scroll-restoration/package.json +++ b/examples/react/scroll-restoration/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", "@tanstack/react-virtual": "^3.13.0", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/search-validator-adapters/package.json b/examples/react/search-validator-adapters/package.json index 35e041e825..ca53271477 100644 --- a/examples/react/search-validator-adapters/package.json +++ b/examples/react/search-validator-adapters/package.json @@ -12,10 +12,10 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/arktype-adapter": "^1.167.0", - "@tanstack/react-query": "^5.102.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-query": "^5.90.0", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.35", "@tanstack/valibot-adapter": "^1.167.0", "@tanstack/zod-adapter": "^1.167.0", "arktype": "^2.1.7", @@ -26,7 +26,7 @@ "zod": "^3.24.2" }, "devDependencies": { - "@testing-library/jest-dom": "^7.0.1", + "@testing-library/jest-dom": "^6.6.3", "@testing-library/react": "^16.2.0", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", @@ -35,6 +35,6 @@ "jsdom": "^27.0.0", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", - "vitest": "^5.0.4" + "vitest": "catalog:" } } diff --git a/examples/react/search-validator-adapters/tests/arktype.test.tsx b/examples/react/search-validator-adapters/tests/arktype.test.tsx index 776cc8369e..1c3a1baf76 100644 --- a/examples/react/search-validator-adapters/tests/arktype.test.tsx +++ b/examples/react/search-validator-adapters/tests/arktype.test.tsx @@ -8,6 +8,7 @@ import { createRouter, } from '@tanstack/react-router' +import '@testing-library/jest-dom/vitest' import { type } from 'arktype' test('can navigate to the route', async () => { diff --git a/examples/react/search-validator-adapters/tests/jest-dom.setup.ts b/examples/react/search-validator-adapters/tests/jest-dom.setup.ts deleted file mode 100644 index 8f7cbf15be..0000000000 --- a/examples/react/search-validator-adapters/tests/jest-dom.setup.ts +++ /dev/null @@ -1,18 +0,0 @@ -import * as jestDomMatchers from '@testing-library/jest-dom/matchers' -import { expect } from 'vitest' -import type { TestingLibraryMatchers } from '@testing-library/jest-dom/matchers' - -// Workaround for Vitest 5: remove once testing-library/jest-dom#742 is merged -// and released, and go back to `import '@testing-library/jest-dom/vitest'`. -// That entry imports `vitest` from its own install location, which can resolve -// a different Vitest copy than the one running these tests, and its types -// augment Vitest 4's `Assertion` instead of Vitest 5's `Matchers`. -// Keep `jest-dom` in this file name: vite-plugin-solid only skips injecting -// `@testing-library/jest-dom/vitest` when a setup file path contains it. -expect.extend(jestDomMatchers) - -declare module 'vitest' { - // Type parameter names must match Vitest's declaration for the interfaces to merge. - // eslint-disable-next-line @typescript-eslint/naming-convention - interface Matchers extends TestingLibraryMatchers {} -} diff --git a/examples/react/search-validator-adapters/tests/valibot.test.tsx b/examples/react/search-validator-adapters/tests/valibot.test.tsx index d3e18db414..3680d2302c 100644 --- a/examples/react/search-validator-adapters/tests/valibot.test.tsx +++ b/examples/react/search-validator-adapters/tests/valibot.test.tsx @@ -8,6 +8,7 @@ import { createRouter, } from '@tanstack/react-router' import * as v from 'valibot' +import '@testing-library/jest-dom/vitest' test('can navigate to the route', async () => { const rootRoute = createRootRoute() diff --git a/examples/react/search-validator-adapters/vite.config.ts b/examples/react/search-validator-adapters/vite.config.ts index e4b93f5cc3..5b41e6e26b 100644 --- a/examples/react/search-validator-adapters/vite.config.ts +++ b/examples/react/search-validator-adapters/vite.config.ts @@ -11,7 +11,6 @@ export default defineConfig({ watch: false, environment: 'jsdom', typecheck: { enabled: true }, - setupFiles: ['./tests/jest-dom.setup.ts'], }, plugins: [ tailwindcss(), diff --git a/examples/react/start-bare/package.json b/examples/react/start-bare/package.json index 4ab9aff272..2b3ebed71f 100644 --- a/examples/react/start-bare/package.json +++ b/examples/react/start-bare/package.json @@ -10,9 +10,9 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-start": "^1.168.49", "react": "^19.0.0", "react-dom": "^19.0.0", "zod": "^4.4.3" diff --git a/examples/react/start-basic-auth/README.md b/examples/react/start-basic-auth/README.md index 7f1b093ba5..4e5ee29b40 100644 --- a/examples/react/start-basic-auth/README.md +++ b/examples/react/start-basic-auth/README.md @@ -39,13 +39,3 @@ This example demonstrates: - Protected routes - Login/logout functionality - Redirect after authentication - -## Session configuration - -This example uses [iron-session](https://github.com/vvo/iron-session) through Start's `getCookie` and `setCookie` helpers. Set `SESSION_PASSWORD` to a random secret of at least 32 characters before starting the app, for example: - -```sh -export SESSION_PASSWORD="$(openssl rand -base64 32)" -``` - -Keep the same secret across instances and deployments that must read the same sessions. The cookie requires HTTPS in production. Each handler reads its own session, then awaits `session.save()` before redirecting or returning. diff --git a/examples/react/start-basic-auth/package.json b/examples/react/start-basic-auth/package.json index 9ab89bdac9..16ac9bc9a1 100644 --- a/examples/react/start-basic-auth/package.json +++ b/examples/react/start-basic-auth/package.json @@ -14,13 +14,12 @@ "@libsql/client": "^0.15.15", "@prisma/adapter-libsql": "^7.0.0", "@prisma/client": "^7.0.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", - "iron-session": "^9.0.1", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-start": "^1.168.49", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0" }, "devDependencies": { diff --git a/examples/react/start-basic-auth/src/routes/__root.tsx b/examples/react/start-basic-auth/src/routes/__root.tsx index 3367c62f27..5728345fcf 100644 --- a/examples/react/start-basic-auth/src/routes/__root.tsx +++ b/examples/react/start-basic-auth/src/routes/__root.tsx @@ -13,18 +13,18 @@ import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary.js' import { NotFound } from '~/components/NotFound.js' import appCss from '~/styles/app.css?url' import { seo } from '~/utils/seo.js' -import { getAppSession } from '~/utils/session.js' +import { useAppSession } from '~/utils/session.js' const fetchUser = createServerFn({ method: 'GET' }).handler(async () => { // We need to auth on the server so we have access to secure cookies - const session = await getAppSession() + const session = await useAppSession() - if (!session.userEmail) { + if (!session.data.userEmail) { return null } return { - email: session.userEmail, + email: session.data.userEmail, } }) diff --git a/examples/react/start-basic-auth/src/routes/_authed.tsx b/examples/react/start-basic-auth/src/routes/_authed.tsx index 0b5c6f9047..3af371e844 100644 --- a/examples/react/start-basic-auth/src/routes/_authed.tsx +++ b/examples/react/start-basic-auth/src/routes/_authed.tsx @@ -2,7 +2,7 @@ import { createFileRoute } from '@tanstack/react-router' import { createServerFn } from '@tanstack/react-start' import { hashPassword, prismaClient } from '~/utils/prisma' import { Login } from '~/components/Login' -import { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' export const loginFn = createServerFn({ method: 'POST' }) .validator((d: { email: string; password: string }) => d) @@ -33,10 +33,13 @@ export const loginFn = createServerFn({ method: 'POST' }) } } + // Create a session + const session = await useAppSession() + // Store the user's email in the session - const session = await getAppSession() - session.userEmail = user.email - await session.save() + await session.update({ + userEmail: user.email, + }) }) export const Route = createFileRoute('/_authed')({ diff --git a/examples/react/start-basic-auth/src/routes/logout.tsx b/examples/react/start-basic-auth/src/routes/logout.tsx index 73cdaf1600..28f3c9f8fe 100644 --- a/examples/react/start-basic-auth/src/routes/logout.tsx +++ b/examples/react/start-basic-auth/src/routes/logout.tsx @@ -1,10 +1,11 @@ import { redirect, createFileRoute } from '@tanstack/react-router' import { createServerFn } from '@tanstack/react-start' -import { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' const logoutFn = createServerFn().handler(async () => { - const session = await getAppSession() - session.destroy() + const session = await useAppSession() + + session.clear() throw redirect({ href: '/', diff --git a/examples/react/start-basic-auth/src/routes/signup.tsx b/examples/react/start-basic-auth/src/routes/signup.tsx index 4dc8e350ac..247a94c03c 100644 --- a/examples/react/start-basic-auth/src/routes/signup.tsx +++ b/examples/react/start-basic-auth/src/routes/signup.tsx @@ -3,7 +3,7 @@ import { createServerFn, useServerFn } from '@tanstack/react-start' import { hashPassword, prismaClient } from '~/utils/prisma' import { useMutation } from '~/hooks/useMutation' import { Auth } from '~/components/Auth' -import { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' export const signupFn = createServerFn({ method: 'POST' }) .validator( @@ -20,6 +20,9 @@ export const signupFn = createServerFn({ method: 'POST' }) // Encrypt the password using Sha256 into plaintext const password = await hashPassword(data.password) + // Create a session + const session = await useAppSession() + if (found) { if (found.password !== password) { return { @@ -30,9 +33,9 @@ export const signupFn = createServerFn({ method: 'POST' }) } // Store the user's email in the session - const session = await getAppSession() - session.userEmail = found.email - await session.save() + await session.update({ + userEmail: found.email, + }) // Redirect to the prev page stored in the "redirect" search param throw redirect({ @@ -49,9 +52,9 @@ export const signupFn = createServerFn({ method: 'POST' }) }) // Store the user's email in the session - const session = await getAppSession() - session.userEmail = user.email - await session.save() + await session.update({ + userEmail: user.email, + }) // Redirect to the prev page stored in the "redirect" search param throw redirect({ diff --git a/examples/react/start-basic-auth/src/utils/session.ts b/examples/react/start-basic-auth/src/utils/session.ts index 7df7bc4da2..c38bac1e48 100644 --- a/examples/react/start-basic-auth/src/utils/session.ts +++ b/examples/react/start-basic-auth/src/utils/session.ts @@ -1,29 +1,13 @@ -import { getIronSession } from 'iron-session' -import { getCookie, setCookie } from '@tanstack/react-start/server' +// src/services/session.server.ts +import { useSession } from '@tanstack/react-start/server' import type { User } from '@prisma/client' type SessionUser = { userEmail: User['email'] } -export function getAppSession() { - const password = process.env.SESSION_PASSWORD - if (!password || password.length < 32) { - throw new Error('Set SESSION_PASSWORD to at least 32 characters') - } - - return getIronSession( - { read: getCookie, write: setCookie }, - { - cookieName: 'app-session', - password, - ttl: 7 * 24 * 60 * 60, - cookieOptions: { - httpOnly: true, - sameSite: 'lax', - secure: process.env.NODE_ENV === 'production', - path: '/', - }, - }, - ) +export function useAppSession() { + return useSession({ + password: 'ChangeThisBeforeShippingToProdOrYouWillBeFired', + }) } diff --git a/examples/react/start-basic-authjs/package.json b/examples/react/start-basic-authjs/package.json index e9fa789ea6..46615ec00d 100644 --- a/examples/react/start-basic-authjs/package.json +++ b/examples/react/start-basic-authjs/package.json @@ -11,9 +11,9 @@ }, "dependencies": { "@auth/core": "^0.41.1", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-start": "^1.168.49", "react": "^19.0.0", "react-dom": "^19.0.0", "start-authjs": "^1.0.0", diff --git a/examples/react/start-basic-cloudflare/package.json b/examples/react/start-basic-cloudflare/package.json index 2108922446..1613349c1e 100644 --- a/examples/react/start-basic-cloudflare/package.json +++ b/examples/react/start-basic-cloudflare/package.json @@ -12,9 +12,9 @@ "postinstall": "WRANGLER_LOG=warn npm run --silent cf-typegen" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-start": "^1.168.49", "react": "^19.0.0", "react-dom": "^19.0.0" }, diff --git a/examples/react/start-basic-react-query/README.md b/examples/react/start-basic-react-query/README.md index 70cc728ae4..77c61c2504 100644 --- a/examples/react/start-basic-react-query/README.md +++ b/examples/react/start-basic-react-query/README.md @@ -38,18 +38,5 @@ This example demonstrates how to use TanStack Query with TanStack Start for: - Server-side data fetching - Client-side caching and synchronization -- Confirmed server mutations followed by query invalidation -- Explicit freshness and automatic refetching - -## SSR and mutation checks - -Read the [Start + TanStack Query guide](https://tanstack.com/start/latest/docs/framework/react/guide/tanstack-query). The `/preferences` page stores a harmless display name in a cookie, so its tests need no account or external API. This cookie is not authentication. The other post/user examples use JSONPlaceholder. - -```sh -pnpm exec playwright install chromium -pnpm test:e2e -pnpm build -QUERY_EXAMPLE_PRODUCTION=1 pnpm test:e2e -``` - -The tests check concurrent SSR request isolation, no duplicate hydration read, one refetch after mutation invalidation, and persistence on reload. Query data is fresh for 30 seconds by default in this example; choose a window appropriate for your application. +- Optimistic updates +- Automatic refetching diff --git a/examples/react/start-basic-react-query/package.json b/examples/react/start-basic-react-query/package.json index 9d819d4390..53d34ff482 100644 --- a/examples/react/start-basic-react-query/package.json +++ b/examples/react/start-basic-react-query/package.json @@ -7,19 +7,18 @@ "dev": "vite dev", "build": "vite build && tsc --noEmit", "preview": "vite preview", - "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test" + "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-query": "^5.102.0", + "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-router-ssr-query": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-router-ssr-query": "^1.167.2", + "@tanstack/react-start": "^1.168.49", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0" }, "devDependencies": { @@ -31,7 +30,6 @@ "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "@playwright/test": "^1.61.0" + "vite": "^8.0.14" } } diff --git a/examples/react/start-basic-react-query/playwright.config.ts b/examples/react/start-basic-react-query/playwright.config.ts deleted file mode 100644 index 298a1133e9..0000000000 --- a/examples/react/start-basic-react-query/playwright.config.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { defineConfig } from '@playwright/test' - -export default defineConfig({ - testDir: './tests', - use: { baseURL: 'http://localhost:3110', browserName: 'chromium' }, - webServer: { - command: - process.env.QUERY_EXAMPLE_PRODUCTION === '1' - ? 'PORT=3110 pnpm start' - : 'pnpm dev --port 3110', - url: 'http://localhost:3110/preferences', - timeout: 120_000, - }, -}) diff --git a/examples/react/start-basic-react-query/src/routeTree.gen.ts b/examples/react/start-basic-react-query/src/routeTree.gen.ts index 0c7a90d4a1..e010af19fe 100644 --- a/examples/react/start-basic-react-query/src/routeTree.gen.ts +++ b/examples/react/start-basic-react-query/src/routeTree.gen.ts @@ -13,7 +13,6 @@ import { Route as IndexRouteImport } from './routes/index' import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as DeferredRouteImport } from './routes/deferred' import { Route as PostsRouteRouteImport } from './routes/posts.route' -import { Route as PreferencesRouteImport } from './routes/preferences' import { Route as RedirectRouteImport } from './routes/redirect' import { Route as UsersRouteRouteImport } from './routes/users.route' import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' @@ -46,11 +45,6 @@ const PostsRouteRoute = PostsRouteRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const PreferencesRoute = PreferencesRouteImport.update({ - id: '/preferences', - path: '/preferences', - getParentRoute: () => rootRouteImport, -} as any) const RedirectRoute = RedirectRouteImport.update({ id: '/redirect', path: '/redirect', @@ -119,7 +113,6 @@ export interface FileRoutesByFullPath { '/posts': typeof PostsRouteRouteWithChildren '/users': typeof UsersRouteRouteWithChildren '/deferred': typeof DeferredRoute - '/preferences': typeof PreferencesRoute '/redirect': typeof RedirectRoute '/api/users': typeof ApiUsersRouteWithChildren '/posts/$postId': typeof PostsPostIdRoute @@ -134,7 +127,6 @@ export interface FileRoutesByFullPath { export interface FileRoutesByTo { '/': typeof IndexRoute '/deferred': typeof DeferredRoute - '/preferences': typeof PreferencesRoute '/redirect': typeof RedirectRoute '/api/users': typeof ApiUsersRouteWithChildren '/posts/$postId': typeof PostsPostIdRoute @@ -153,7 +145,6 @@ export interface FileRoutesById { '/users': typeof UsersRouteRouteWithChildren '/_pathlessLayout': typeof PathlessLayoutRouteWithChildren '/deferred': typeof DeferredRoute - '/preferences': typeof PreferencesRoute '/redirect': typeof RedirectRoute '/_pathlessLayout/_nested-layout': typeof PathlessLayoutNestedLayoutRouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren @@ -173,7 +164,6 @@ export interface FileRouteTypes { | '/posts' | '/users' | '/deferred' - | '/preferences' | '/redirect' | '/api/users' | '/posts/$postId' @@ -188,7 +178,6 @@ export interface FileRouteTypes { to: | '/' | '/deferred' - | '/preferences' | '/redirect' | '/api/users' | '/posts/$postId' @@ -206,7 +195,6 @@ export interface FileRouteTypes { | '/users' | '/_pathlessLayout' | '/deferred' - | '/preferences' | '/redirect' | '/_pathlessLayout/_nested-layout' | '/api/users' @@ -226,7 +214,6 @@ export interface RootRouteChildren { UsersRouteRoute: typeof UsersRouteRouteWithChildren PathlessLayoutRoute: typeof PathlessLayoutRouteWithChildren DeferredRoute: typeof DeferredRoute - PreferencesRoute: typeof PreferencesRoute RedirectRoute: typeof RedirectRoute ApiUsersRoute: typeof ApiUsersRouteWithChildren PostsPostIdDeepRoute: typeof PostsPostIdDeepRoute @@ -262,13 +249,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/preferences': { - id: '/preferences' - path: '/preferences' - fullPath: '/preferences' - preLoaderRoute: typeof PreferencesRouteImport - parentRoute: typeof rootRouteImport - } '/redirect': { id: '/redirect' path: '/redirect' @@ -432,7 +412,6 @@ const rootRouteChildren: RootRouteChildren = { UsersRouteRoute: UsersRouteRouteWithChildren, PathlessLayoutRoute: PathlessLayoutRouteWithChildren, DeferredRoute: DeferredRoute, - PreferencesRoute: PreferencesRoute, RedirectRoute: RedirectRoute, ApiUsersRoute: ApiUsersRouteWithChildren, PostsPostIdDeepRoute: PostsPostIdDeepRoute, @@ -442,11 +421,10 @@ export const routeTree = rootRouteImport ._addFileTypes() import type { getRouter } from './router.tsx' -import type { startInstance } from './start.ts' +import type { createStart } from '@tanstack/react-start' declare module '@tanstack/react-start' { interface Register { ssr: true router: Awaited> - config: Awaited> } } diff --git a/examples/react/start-basic-react-query/src/router.tsx b/examples/react/start-basic-react-query/src/router.tsx index 345055c116..314b29edd0 100644 --- a/examples/react/start-basic-react-query/src/router.tsx +++ b/examples/react/start-basic-react-query/src/router.tsx @@ -6,15 +6,12 @@ import { DefaultCatchBoundary } from './components/DefaultCatchBoundary' import { NotFound } from './components/NotFound' export function getRouter() { - const queryClient = new QueryClient({ - defaultOptions: { queries: { staleTime: 30_000 } }, - }) + const queryClient = new QueryClient() const router = createRouter({ routeTree, context: { queryClient }, defaultPreload: 'intent', - defaultPreloadStaleTime: 0, defaultErrorComponent: DefaultCatchBoundary, defaultNotFoundComponent: () => , }) diff --git a/examples/react/start-basic-react-query/src/routes/__root.tsx b/examples/react/start-basic-react-query/src/routes/__root.tsx index 71c19b2c6f..bc278f8036 100644 --- a/examples/react/start-basic-react-query/src/routes/__root.tsx +++ b/examples/react/start-basic-react-query/src/routes/__root.tsx @@ -83,7 +83,6 @@ function RootDocument({ children }: { children: React.ReactNode }) {
- Preferences { - await context.queryClient.query(readerNameOptions) - }, - headers: () => ({ 'Cache-Control': 'private, no-store' }), - head: () => ({ meta: [{ title: 'Reader preferences' }] }), - component: Preferences, -}) - -function Preferences() { - const { data: name } = useSuspenseQuery(readerNameOptions) - const queryClient = useQueryClient() - const save = useServerFn(saveReaderName) - const hydrated = useHydrated() - const mutation = useMutation({ - mutationFn: (name: string) => save({ data: name }), - onSuccess: () => - queryClient.invalidateQueries({ queryKey: readerNameOptions.queryKey }), - }) - - return ( -
-

Reader preferences

-

Hello, {name}

-
{ - event.preventDefault() - const value = new FormData(event.currentTarget).get('name') - if (typeof value === 'string') { - mutation.mutate(value) - } - }} - > -
- - -
- {mutation.isError ? ( -

Could not save your name. Try again.

- ) : null} -
-
- ) -} diff --git a/examples/react/start-basic-react-query/src/start.ts b/examples/react/start-basic-react-query/src/start.ts deleted file mode 100644 index 5fb1e247fb..0000000000 --- a/examples/react/start-basic-react-query/src/start.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { createCsrfMiddleware, createStart } from '@tanstack/react-start' - -export const startInstance = createStart(() => ({ - requestMiddleware: [ - createCsrfMiddleware({ - filter: (ctx) => ctx.handlerType === 'serverFn', - }), - ], -})) diff --git a/examples/react/start-basic-react-query/src/utils/preferences.ts b/examples/react/start-basic-react-query/src/utils/preferences.ts deleted file mode 100644 index 74c33e5848..0000000000 --- a/examples/react/start-basic-react-query/src/utils/preferences.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { queryOptions } from '@tanstack/react-query' -import { createServerFn } from '@tanstack/react-start' -import { - getCookie, - setCookie, - setResponseHeader, -} from '@tanstack/react-start/server' - -export const getReaderName = createServerFn({ method: 'GET' }).handler(() => { - setResponseHeader('Cache-Control', 'private, no-store') - return getCookie('reader-name') || 'Guest' -}) - -export const saveReaderName = createServerFn({ method: 'POST' }) - .validator((name: string) => { - if (typeof name !== 'string' || !name.trim() || name.length > 40) { - throw new Error('Enter a name between 1 and 40 characters') - } - return name.trim() - }) - .handler(({ data }) => { - setResponseHeader('Cache-Control', 'private, no-store') - setCookie('reader-name', data, { - httpOnly: true, - sameSite: 'lax', - secure: process.env.NODE_ENV === 'production', - path: '/', - }) - }) - -export const readerNameOptions = queryOptions({ - queryKey: ['reader-name'], - queryFn: () => getReaderName(), -}) diff --git a/examples/react/start-basic-react-query/tests/preferences.spec.ts b/examples/react/start-basic-react-query/tests/preferences.spec.ts deleted file mode 100644 index 309c402798..0000000000 --- a/examples/react/start-basic-react-query/tests/preferences.spec.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { expect, test } from '@playwright/test' - -test('concurrent SSR requests keep the same query key isolated by request', async ({ - request, -}) => { - const names = ['Lucia', 'Omar', 'Maya', 'Felix'] - const responses = await Promise.all( - names.map((name) => - request.get('/preferences', { - headers: { Cookie: `reader-name=${name}` }, - }), - ), - ) - for (const [index, response] of responses.entries()) { - expect(response.status()).toBe(200) - expect(response.headers()['cache-control']).toContain('no-store') - const html = await response.text() - expect(html).toContain(names[index]) - for (const other of names.filter((_, otherIndex) => otherIndex !== index)) { - expect(html).not.toContain(other) - } - } -}) - -test('hydration reuses SSR data and mutation invalidation refetches once', async ({ - page, -}) => { - const reads: string[] = [] - page.on('request', (request) => { - if ( - request.method() === 'GET' && - new URL(request.url()).pathname.startsWith('/_serverFn/') - ) { - reads.push(request.url()) - } - }) - await page.goto('/preferences') - await expect(page.getByTestId('reader-name')).toHaveText('Hello, Guest') - await expect(page.getByLabel('Display name')).toBeEnabled() - await page.waitForLoadState('networkidle') - expect(reads).toHaveLength(0) - - await page.getByLabel('Display name').fill('Ada') - const mutation = page.waitForRequest((request) => request.method() === 'POST') - await page.getByRole('button', { name: 'Save name' }).click() - await expect(page.getByTestId('reader-name')).toHaveText('Hello, Ada') - await expect(page.getByRole('button', { name: 'Save name' })).toBeEnabled() - await page.waitForLoadState('networkidle') - expect(reads).toHaveLength(1) - - const savedRequest = await mutation - const headers = await savedRequest.allHeaders() - delete headers['content-length'] - headers.origin = 'https://untrusted.example' - headers['sec-fetch-site'] = 'cross-site' - const denied = await page.request.post(savedRequest.url(), { - headers, - data: savedRequest.postData() ?? '', - }) - expect(denied.status()).toBe(403) - - await page.reload() - await expect(page.getByTestId('reader-name')).toHaveText('Hello, Ada') - await expect(page.getByLabel('Display name')).toBeEnabled() - await page.waitForLoadState('networkidle') - expect(reads).toHaveLength(1) -}) diff --git a/examples/react/start-basic-rsbuild/package.json b/examples/react/start-basic-rsbuild/package.json index bea4ba26ef..9d81e27829 100644 --- a/examples/react/start-basic-rsbuild/package.json +++ b/examples/react/start-basic-rsbuild/package.json @@ -10,22 +10,22 @@ "start": "srvx --prod -s ../client dist/server/index.js" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-start": "^1.168.49", "react": "^19.2.3", "react-dom": "^19.2.3", "tailwind-merge": "^3.6.0", "zod": "^4.4.3" }, "devDependencies": { - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.0.11", "@rsbuild/plugin-react": "^2.0.0", "@rsbuild/plugin-tailwindcss": "^2.0.3", "@types/node": "25.0.9", "@types/react": "^19.2.8", "@types/react-dom": "^19.2.3", - "srvx": "^1.0.0", + "srvx": "^0.11.18", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2" diff --git a/examples/react/start-basic-static/package.json b/examples/react/start-basic-static/package.json index 58d573ca36..023dcd8d5c 100644 --- a/examples/react/start-basic-static/package.json +++ b/examples/react/start-basic-static/package.json @@ -10,14 +10,14 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", - "@tanstack/start-static-server-functions": "^1.167.44", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-start": "^1.168.49", + "@tanstack/start-static-server-functions": "^1.167.32", "@vitejs/plugin-react": "^6.0.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0" }, "devDependencies": { diff --git a/examples/react/start-basic/package.json b/examples/react/start-basic/package.json index 46df8e4650..cb8d60746c 100644 --- a/examples/react/start-basic/package.json +++ b/examples/react/start-basic/package.json @@ -10,9 +10,9 @@ "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-start": "^1.168.49", "react": "^19.0.0", "react-dom": "^19.0.0", "tailwind-merge": "^3.6.0", @@ -24,7 +24,7 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "nitro": "^3.0.260903-beta", + "nitro": "^3.0.260311-beta", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/examples/react/start-bun/package.json b/examples/react/start-bun/package.json index 24f7113912..e0878bd558 100644 --- a/examples/react/start-bun/package.json +++ b/examples/react/start-bun/package.json @@ -15,11 +15,11 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/react-devtools": "^0.7.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-router-ssr-query": "^1.167.3", - "@tanstack/react-start": "^1.169.6", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-router-ssr-query": "^1.167.2", + "@tanstack/react-start": "^1.168.49", + "@tanstack/router-plugin": "^1.168.35", "react": "^19.1.1", "react-dom": "^19.1.1", "tailwindcss": "^4.2.2" @@ -38,7 +38,7 @@ "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", - "vitest": "^5.0.4", + "vitest": "catalog:", "web-vitals": "^5.1.0" } } diff --git a/examples/react/start-clerk-basic/package.json b/examples/react/start-clerk-basic/package.json index 022300e159..73e74404d9 100644 --- a/examples/react/start-clerk-basic/package.json +++ b/examples/react/start-clerk-basic/package.json @@ -11,14 +11,14 @@ }, "dependencies": { "@clerk/tanstack-react-start": "^0.27.14", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-start": "^1.168.49", "@vitejs/plugin-react": "^6.0.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", - "srvx": "^1.0.0", + "redaxios": "catalog:", + "srvx": "^0.11.9", "tailwind-merge": "^3.6.0" }, "devDependencies": { diff --git a/examples/react/start-convex-trellaux/package.json b/examples/react/start-convex-trellaux/package.json index 3452f910d0..07646c0fd1 100644 --- a/examples/react/start-convex-trellaux/package.json +++ b/examples/react/start-convex-trellaux/package.json @@ -13,12 +13,12 @@ }, "dependencies": { "@convex-dev/react-query": "0.0.0-alpha.8", - "@tanstack/react-query": "^5.102.0", + "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-router-ssr-query": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-router-ssr-query": "^1.167.2", + "@tanstack/react-start": "^1.168.49", "concurrently": "^8.2.2", "convex": "^1.19.0", "ky": "^1.7.4", @@ -26,7 +26,7 @@ "react": "^19.0.0", "react-dom": "^19.0.0", "react-hot-toast": "^2.5.1", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0", "zod": "^4.4.3" }, diff --git a/examples/react/start-counter/package.json b/examples/react/start-counter/package.json index 8f4673143e..a044c2b11e 100644 --- a/examples/react/start-counter/package.json +++ b/examples/react/start-counter/package.json @@ -10,9 +10,9 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-start": "^1.168.49", "react": "^19.0.0", "react-dom": "^19.0.0" }, diff --git a/examples/react/start-i18n-paraglide/package.json b/examples/react/start-i18n-paraglide/package.json index 074f714d5c..cd22ba5174 100644 --- a/examples/react/start-i18n-paraglide/package.json +++ b/examples/react/start-i18n-paraglide/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tanstack/react-devtools": "^0.7.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-start": "^1.168.49", "react": "^19.1.1", "react-dom": "^19.1.1" }, @@ -27,16 +27,5 @@ "@tailwindcss/vite": "^4.2.2", "tailwindcss": "^4.2.2", "@inlang/paraglide-js": "^2.4.0" - }, - "nx": { - "targets": { - "build": { - "outputs": [ - "...", - "{projectRoot}/src/paraglide", - "{projectRoot}/project.inlang/cache" - ] - } - } } } diff --git a/examples/react/start-large/package.json b/examples/react/start-large/package.json index f9f86b81d1..0cd7427a66 100644 --- a/examples/react/start-large/package.json +++ b/examples/react/start-large/package.json @@ -12,13 +12,13 @@ "test:types": "tsc --extendedDiagnostics" }, "dependencies": { - "@tanstack/react-query": "^5.102.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-query": "^5.90.0", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-start": "^1.168.49", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0", "valibot": "^1.0.0-beta.15" }, diff --git a/examples/react/start-material-ui/package.json b/examples/react/start-material-ui/package.json index 1647e95f20..b5b137181e 100644 --- a/examples/react/start-material-ui/package.json +++ b/examples/react/start-material-ui/package.json @@ -15,9 +15,9 @@ "@emotion/styled": "11.14.0", "@fontsource-variable/roboto": "5.2.5", "@mui/material": "6.4.7", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-start": "^1.168.49", "react": "^19.0.0", "react-dom": "^19.0.0", "zod": "^4.4.3" diff --git a/examples/react/start-next-migration/.gitignore b/examples/react/start-next-migration/.gitignore deleted file mode 100644 index 24e8148a7d..0000000000 --- a/examples/react/start-next-migration/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -node_modules -.next -.output -.nitro -.tanstack -test-results -playwright-report -.env -.env.local -*.tsbuildinfo -next-env.d.ts -next-app/AGENTS.md -next-app/CLAUDE.md diff --git a/examples/react/start-next-migration/README.md b/examples/react/start-next-migration/README.md deleted file mode 100644 index 03bb53244e..0000000000 --- a/examples/react/start-next-migration/README.md +++ /dev/null @@ -1,61 +0,0 @@ -# Next.js to TanStack Start - -Two versions of the same small article site. `next-app/` uses the Next.js App Router; `src/` uses TanStack Start. They keep the public paths, article content, titles, descriptions, canonical URLs, search parameter, and permanent redirect. - -The private page saves one article in an encrypted session cookie. This keeps the example runnable without a database or an auth-provider account. It is a migration reference, not an authentication starter: the single demo account has no registration, password recovery, rate limiting, or account database. Do not deploy it as a public sign-in service. - -## Run - -Use Node 24 or newer and pnpm 12. From the repository root: - -```sh -pnpm install -pnpm nx run @tanstack/react-start:build -cd examples/react/start-next-migration -``` - -In each terminal that starts a server, set these variables. Generate your own secret and choose a demo password: - -```sh -export SESSION_PASSWORD="$(node -e "console.log(require('node:crypto').randomBytes(32).toString('hex'))")" -export DEMO_PASSWORD='choose-a-local-demo-password' -``` - -Run `pnpm dev:next` for Next.js at and `pnpm dev` in another terminal for Start at . Sign in as `reader@example.com` using the password you set. - -Both apps use iron-session, with different cookie names. Signing in to one does not sign you in to the other. Changing `SESSION_PASSWORD` invalidates that app's session. Saved state is tied to that session, not durable account storage. - -## Check the migration - -From this directory, with those ports free: - -```sh -pnpm exec playwright install chromium -pnpm test:e2e -pnpm build:next -pnpm build -MIGRATION_PRODUCTION=1 pnpm test:e2e -``` - -Playwright starts both dev servers with test-only credentials. The same tests run against each app and check server-rendered metadata, public paths, search, a 308 redirect, a missing article, sitemap membership, login errors, session persistence, private cache headers, saved-state mutation, and rejection of a captured mutation after sign-out. - -For a production-mode smoke check, keep the environment variables set and run `pnpm start:next` or `PORT=3101 pnpm start` after building. The cookie settings assume HTTPS in production. Deployment infrastructure, a shared database, real account security, and CDN behavior are outside this local fixture. - -## Compare - -| Next.js | TanStack Start | -| --------------------------------------------- | ------------------------------------------------------- | -| `next-app/app/page.tsx`, async `searchParams` | `src/routes/index.tsx`, `validateSearch` | -| `next-app/app/posts/[slug]/page.tsx` | `src/routes/posts.$slug.tsx` | -| `generateMetadata` | Route `head` using `loaderData` | -| `next-app/app/actions.ts` | `src/server/account.ts` | -| Server Action form and `revalidatePath` | `useServerFn`, local pending state, `router.invalidate` | -| `cookies()` with `iron-session` | `iron-session` with `getCookie` / `setCookie` | -| `next-app/next.config.ts` redirect | `src/routes/old-notes.tsx` redirect | -| `next-app/app/sitemap.ts` | `src/routes/sitemap[.]xml.ts` server route | - -The Next.js forms use Server Actions. The Start forms in this example handle client submit events and require JavaScript. For a no-JavaScript form, use a FormData-compatible server function URL or an explicit server-route POST implementation, including validation and CSRF protection. Replacing an Action with `createServerFn` does not preserve progressive enhancement automatically. - -The canonical origin is intentionally `https://field-notes.example` in both content modules, so local ports do not change the comparison. Replace it with your real public origin before adapting the example. - -The Start app enables `createCsrfMiddleware` for server-function requests in `src/start.ts`. The paired browser tests replay a mutation with an authenticated cookie jar and cross-site request metadata, then verify that it was rejected and the saved value did not change. Endpoint authorization is still checked independently after sign-out. diff --git a/examples/react/start-next-migration/next-app/account.ts b/examples/react/start-next-migration/next-app/account.ts deleted file mode 100644 index 7073518994..0000000000 --- a/examples/react/start-next-migration/next-app/account.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { cookies } from 'next/headers' -import { getIronSession } from 'iron-session' -export async function getSession() { - const cookieStore = await cookies() - const password = process.env.SESSION_PASSWORD - if (!password || password.length < 32) { - throw new Error('Set SESSION_PASSWORD to at least 32 characters') - } - return getIronSession<{ email: string; saved: boolean }>(cookieStore, { - cookieName: 'next-migration-session', - password, - cookieOptions: { secure: process.env.NODE_ENV === 'production' }, - }) -} diff --git a/examples/react/start-next-migration/next-app/app/actions.ts b/examples/react/start-next-migration/next-app/app/actions.ts deleted file mode 100644 index 325a4de176..0000000000 --- a/examples/react/start-next-migration/next-app/app/actions.ts +++ /dev/null @@ -1,36 +0,0 @@ -'use server' -import { redirect } from 'next/navigation' -import { revalidatePath } from 'next/cache' -import { getSession } from '../account' -export async function signIn(_state: { error: string }, form: FormData) { - if (!process.env.DEMO_PASSWORD) { - throw new Error('Set DEMO_PASSWORD before running the example') - } - const email = form.get('email'), - password = form.get('password') - if ( - email !== 'reader@example.com' || - password !== process.env.DEMO_PASSWORD - ) { - return { error: 'Invalid credentials' } - } - const session = await getSession() - session.email = email - session.saved = false - await session.save() - redirect('/saved') -} -export async function toggleSaved() { - const session = await getSession() - if (!session.email) { - throw new Error('Unauthorized') - } - session.saved = !session.saved - await session.save() - revalidatePath('/saved') -} -export async function signOut() { - const session = await getSession() - session.destroy() - redirect('/login') -} diff --git a/examples/react/start-next-migration/next-app/app/layout.tsx b/examples/react/start-next-migration/next-app/app/layout.tsx deleted file mode 100644 index 2aafe653dd..0000000000 --- a/examples/react/start-next-migration/next-app/app/layout.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import Link from 'next/link' -import type { ReactNode } from 'react' -export default function Layout({ children }: { children: ReactNode }) { - return ( - - - - {children} - - - ) -} diff --git a/examples/react/start-next-migration/next-app/app/login/form.tsx b/examples/react/start-next-migration/next-app/app/login/form.tsx deleted file mode 100644 index 41347eb65b..0000000000 --- a/examples/react/start-next-migration/next-app/app/login/form.tsx +++ /dev/null @@ -1,25 +0,0 @@ -'use client' -import { useActionState } from 'react' -import { signIn } from '../actions' -export function LoginForm() { - const [state, action, pending] = useActionState(signIn, { error: '' }) - return ( -
- - - -

{state.error}

-
- ) -} diff --git a/examples/react/start-next-migration/next-app/app/login/page.tsx b/examples/react/start-next-migration/next-app/app/login/page.tsx deleted file mode 100644 index 9cbb900629..0000000000 --- a/examples/react/start-next-migration/next-app/app/login/page.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { LoginForm } from './form' -export const metadata = { - title: 'Sign in | Field notes', - robots: { index: false }, -} -export default function Login() { - return ( -
-

Sign in

- -
- ) -} diff --git a/examples/react/start-next-migration/next-app/app/not-found.tsx b/examples/react/start-next-migration/next-app/app/not-found.tsx deleted file mode 100644 index 5da341bf43..0000000000 --- a/examples/react/start-next-migration/next-app/app/not-found.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import Link from 'next/link' -export default function NotFound() { - return ( -
-

Article not found

- All articles -
- ) -} diff --git a/examples/react/start-next-migration/next-app/app/page.tsx b/examples/react/start-next-migration/next-app/app/page.tsx deleted file mode 100644 index 75653b8344..0000000000 --- a/examples/react/start-next-migration/next-app/app/page.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import Link from 'next/link' -import { articles, siteUrl } from '../content' -export const metadata = { - title: 'Field notes', - description: - 'Notes on moving a web application without losing its public URLs.', - alternates: { canonical: siteUrl }, -} -export default async function Page({ - searchParams, -}: { - searchParams: Promise<{ q?: string | string[] }> -}) { - const search = await searchParams - const q = typeof search.q === 'string' ? search.q : '' - const visible = articles.filter((article) => - article.title.toLowerCase().includes(q.toLowerCase()), - ) - return ( -
-

Field notes

-
- - -
-
    - {visible.map((article) => ( -
  • - {article.title} -
  • - ))} -
-
- ) -} diff --git a/examples/react/start-next-migration/next-app/app/posts/[slug]/page.tsx b/examples/react/start-next-migration/next-app/app/posts/[slug]/page.tsx deleted file mode 100644 index 36ed5b62da..0000000000 --- a/examples/react/start-next-migration/next-app/app/posts/[slug]/page.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import { notFound } from 'next/navigation' -import { articles, siteUrl } from '../../../content' -async function getArticle(params: Promise<{ slug: string }>) { - const { slug } = await params - const article = articles.find((item) => item.slug === slug) - if (!article) { - notFound() - } - return article -} -export async function generateMetadata({ - params, -}: { - params: Promise<{ slug: string }> -}) { - const article = await getArticle(params) - return { - title: article.title, - description: article.description, - openGraph: { title: article.title }, - alternates: { canonical: `${siteUrl}/posts/${article.slug}` }, - } -} -export default async function Page({ - params, -}: { - params: Promise<{ slug: string }> -}) { - const article = await getArticle(params) - return ( -
-

{article.title}

-

{article.body}

-
- ) -} diff --git a/examples/react/start-next-migration/next-app/app/saved/page.tsx b/examples/react/start-next-migration/next-app/app/saved/page.tsx deleted file mode 100644 index 5310dbc37e..0000000000 --- a/examples/react/start-next-migration/next-app/app/saved/page.tsx +++ /dev/null @@ -1,28 +0,0 @@ -import { redirect } from 'next/navigation' -import { getSession } from '../../account' -import { signOut, toggleSaved } from '../actions' -export const metadata = { - title: 'Saved articles | Field notes', - robots: { index: false }, -} -export default async function Saved() { - const session = await getSession() - if (!session.email) { - redirect('/login') - } - return ( -
-

Saved articles

-

{session.email}

-

- {session.saved ? 'Keeping your URLs is saved' : 'No saved articles'} -

-
- -
-
- -
-
- ) -} diff --git a/examples/react/start-next-migration/next-app/app/sitemap.ts b/examples/react/start-next-migration/next-app/app/sitemap.ts deleted file mode 100644 index 9859cffa17..0000000000 --- a/examples/react/start-next-migration/next-app/app/sitemap.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { articles, siteUrl } from '../content' -export default function sitemap() { - return [ - { url: siteUrl }, - ...articles.map((article) => ({ url: `${siteUrl}/posts/${article.slug}` })), - ] -} diff --git a/examples/react/start-next-migration/next-app/content.ts b/examples/react/start-next-migration/next-app/content.ts deleted file mode 100644 index 2a9d15c1c0..0000000000 --- a/examples/react/start-next-migration/next-app/content.ts +++ /dev/null @@ -1,15 +0,0 @@ -export const articles = [ - { - slug: 'keeping-your-urls', - title: 'Keeping your URLs', - description: 'Preserve public URLs when changing frameworks.', - body: 'A framework migration can keep the URLs your readers already use.', - }, - { - slug: 'checking-your-metadata', - title: 'Checking your metadata', - description: 'Compare rendered titles and canonical URLs before launch.', - body: 'Check the server response as well as the page after client navigation.', - }, -] -export const siteUrl = 'https://field-notes.example' diff --git a/examples/react/start-next-migration/next-app/next.config.ts b/examples/react/start-next-migration/next-app/next.config.ts deleted file mode 100644 index dc72c3ae72..0000000000 --- a/examples/react/start-next-migration/next-app/next.config.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { NextConfig } from 'next' -const config: NextConfig = { - async redirects() { - return [ - { - source: '/old-notes', - destination: '/posts/keeping-your-urls', - permanent: true, - }, - ] - }, -} -export default config diff --git a/examples/react/start-next-migration/next-app/tsconfig.json b/examples/react/start-next-migration/next-app/tsconfig.json deleted file mode 100644 index 8786ab9834..0000000000 --- a/examples/react/start-next-migration/next-app/tsconfig.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2024", - "lib": ["dom", "dom.iterable", "esnext"], - "allowJs": true, - "skipLibCheck": true, - "strict": true, - "noEmit": true, - "esModuleInterop": true, - "module": "esnext", - "moduleResolution": "bundler", - "resolveJsonModule": true, - "isolatedModules": true, - "jsx": "react-jsx", - "incremental": true, - "plugins": [ - { - "name": "next" - } - ] - }, - "include": [ - "next-env.d.ts", - "**/*.ts", - "**/*.tsx", - ".next/types/**/*.ts", - ".next/dev/types/**/*.ts" - ], - "exclude": ["node_modules"] -} diff --git a/examples/react/start-next-migration/package.json b/examples/react/start-next-migration/package.json deleted file mode 100644 index 0c2a2a9563..0000000000 --- a/examples/react/start-next-migration/package.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "name": "tanstack-start-example-next-migration", - "private": true, - "type": "module", - "scripts": { - "dev": "vite dev --port 3101", - "dev:next": "next dev next-app --port 3100", - "build": "vite build && tsc --noEmit", - "build:next": "next build next-app", - "start": "node .output/server/index.mjs", - "start:next": "next start next-app --port 3100", - "test:e2e": "playwright test" - }, - "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-start": "^1.169.6", - "iron-session": "^9.0.1", - "next": "16.3.4", - "react": "^19.2.3", - "react-dom": "^19.2.3" - }, - "devDependencies": { - "@playwright/test": "^1.61.0", - "@types/node": "^22.10.2", - "@types/react": "^19.2.8", - "@types/react-dom": "^19.2.3", - "@vitejs/plugin-react": "^6.0.1", - "nitro": "^3.0.260903-beta", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" - }, - "nx": { - "targets": { - "test:e2e": { - "outputs": [ - "...", - "{projectRoot}/next-app/.next", - "{projectRoot}/next-app/next-env.d.ts" - ] - } - } - } -} diff --git a/examples/react/start-next-migration/playwright.config.ts b/examples/react/start-next-migration/playwright.config.ts deleted file mode 100644 index ce48715df4..0000000000 --- a/examples/react/start-next-migration/playwright.config.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { defineConfig } from '@playwright/test' - -const production = process.env.MIGRATION_PRODUCTION === '1' -const env = { - SESSION_PASSWORD: 'migration-reference-test-secret-at-least-32-characters', - DEMO_PASSWORD: 'migration-test-password', -} - -export default defineConfig({ - testDir: './tests', - use: { browserName: 'chromium' }, - projects: [ - { name: 'next', use: { baseURL: 'http://localhost:3100' } }, - { name: 'start', use: { baseURL: 'http://localhost:3101' } }, - ], - webServer: [ - { - command: production ? 'pnpm start:next' : 'pnpm dev:next', - url: 'http://localhost:3100', - env, - timeout: 120_000, - }, - { - command: production ? 'PORT=3101 pnpm start' : 'pnpm dev', - url: 'http://localhost:3101', - env, - timeout: 120_000, - }, - ], -}) diff --git a/examples/react/start-next-migration/src/content.ts b/examples/react/start-next-migration/src/content.ts deleted file mode 100644 index 2a9d15c1c0..0000000000 --- a/examples/react/start-next-migration/src/content.ts +++ /dev/null @@ -1,15 +0,0 @@ -export const articles = [ - { - slug: 'keeping-your-urls', - title: 'Keeping your URLs', - description: 'Preserve public URLs when changing frameworks.', - body: 'A framework migration can keep the URLs your readers already use.', - }, - { - slug: 'checking-your-metadata', - title: 'Checking your metadata', - description: 'Compare rendered titles and canonical URLs before launch.', - body: 'Check the server response as well as the page after client navigation.', - }, -] -export const siteUrl = 'https://field-notes.example' diff --git a/examples/react/start-next-migration/src/routeTree.gen.ts b/examples/react/start-next-migration/src/routeTree.gen.ts deleted file mode 100644 index 15eeafce02..0000000000 --- a/examples/react/start-next-migration/src/routeTree.gen.ts +++ /dev/null @@ -1,167 +0,0 @@ -/* 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 LoginRouteImport } from './routes/login' -import { Route as OldNotesRouteImport } from './routes/old-notes' -import { Route as SavedRouteImport } from './routes/saved' -import { Route as SitemapDotxmlRouteImport } from './routes/sitemap[.]xml' -import { Route as PostsSlugRouteImport } from './routes/posts.$slug' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', - getParentRoute: () => rootRouteImport, -} as any) -const OldNotesRoute = OldNotesRouteImport.update({ - id: '/old-notes', - path: '/old-notes', - getParentRoute: () => rootRouteImport, -} as any) -const SavedRoute = SavedRouteImport.update({ - id: '/saved', - path: '/saved', - getParentRoute: () => rootRouteImport, -} as any) -const SitemapDotxmlRoute = SitemapDotxmlRouteImport.update({ - id: '/sitemap.xml', - path: '/sitemap.xml', - getParentRoute: () => rootRouteImport, -} as any) -const PostsSlugRoute = PostsSlugRouteImport.update({ - id: '/posts/$slug', - path: '/posts/$slug', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/login': typeof LoginRoute - '/old-notes': typeof OldNotesRoute - '/saved': typeof SavedRoute - '/sitemap.xml': typeof SitemapDotxmlRoute - '/posts/$slug': typeof PostsSlugRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/login': typeof LoginRoute - '/old-notes': typeof OldNotesRoute - '/saved': typeof SavedRoute - '/sitemap.xml': typeof SitemapDotxmlRoute - '/posts/$slug': typeof PostsSlugRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/login': typeof LoginRoute - '/old-notes': typeof OldNotesRoute - '/saved': typeof SavedRoute - '/sitemap.xml': typeof SitemapDotxmlRoute - '/posts/$slug': typeof PostsSlugRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - '/' | '/login' | '/old-notes' | '/saved' | '/sitemap.xml' | '/posts/$slug' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/login' | '/old-notes' | '/saved' | '/sitemap.xml' | '/posts/$slug' - id: - | '__root__' - | '/' - | '/login' - | '/old-notes' - | '/saved' - | '/sitemap.xml' - | '/posts/$slug' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - LoginRoute: typeof LoginRoute - OldNotesRoute: typeof OldNotesRoute - SavedRoute: typeof SavedRoute - SitemapDotxmlRoute: typeof SitemapDotxmlRoute - PostsSlugRoute: typeof PostsSlugRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport - parentRoute: typeof rootRouteImport - } - '/old-notes': { - id: '/old-notes' - path: '/old-notes' - fullPath: '/old-notes' - preLoaderRoute: typeof OldNotesRouteImport - parentRoute: typeof rootRouteImport - } - '/saved': { - id: '/saved' - path: '/saved' - fullPath: '/saved' - preLoaderRoute: typeof SavedRouteImport - parentRoute: typeof rootRouteImport - } - '/sitemap.xml': { - id: '/sitemap.xml' - path: '/sitemap.xml' - fullPath: '/sitemap.xml' - preLoaderRoute: typeof SitemapDotxmlRouteImport - parentRoute: typeof rootRouteImport - } - '/posts/$slug': { - id: '/posts/$slug' - path: '/posts/$slug' - fullPath: '/posts/$slug' - preLoaderRoute: typeof PostsSlugRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - LoginRoute: LoginRoute, - OldNotesRoute: OldNotesRoute, - SavedRoute: SavedRoute, - SitemapDotxmlRoute: SitemapDotxmlRoute, - PostsSlugRoute: PostsSlugRoute, -} -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/examples/react/start-next-migration/src/router.tsx b/examples/react/start-next-migration/src/router.tsx deleted file mode 100644 index 9711e610bf..0000000000 --- a/examples/react/start-next-migration/src/router.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' -export function getRouter() { - return createRouter({ routeTree, scrollRestoration: true }) -} diff --git a/examples/react/start-next-migration/src/routes/__root.tsx b/examples/react/start-next-migration/src/routes/__root.tsx deleted file mode 100644 index a7eaa0168f..0000000000 --- a/examples/react/start-next-migration/src/routes/__root.tsx +++ /dev/null @@ -1,46 +0,0 @@ -import { - createRootRoute, - HeadContent, - Link, - Outlet, - Scripts, -} from '@tanstack/react-router' -import type { ReactNode } from 'react' -export const Route = createRootRoute({ - head: () => ({ - meta: [ - { charSet: 'utf-8' }, - { name: 'viewport', content: 'width=device-width, initial-scale=1' }, - ], - }), - component: Outlet, - shellComponent: Document, - notFoundComponent: () => ( -
-

Article not found

- - All articles - -
- ), -}) -function Document({ children }: { children: ReactNode }) { - return ( - - - - - - - {children} - - - - ) -} diff --git a/examples/react/start-next-migration/src/routes/index.tsx b/examples/react/start-next-migration/src/routes/index.tsx deleted file mode 100644 index 8778d9d01f..0000000000 --- a/examples/react/start-next-migration/src/routes/index.tsx +++ /dev/null @@ -1,45 +0,0 @@ -import { createFileRoute, Link } from '@tanstack/react-router' -import { articles, siteUrl } from '../content' -export const Route = createFileRoute('/')({ - validateSearch: (search) => ({ - q: typeof search.q === 'string' ? search.q : '', - }), - head: () => ({ - meta: [ - { title: 'Field notes' }, - { - name: 'description', - content: - 'Notes on moving a web application without losing its public URLs.', - }, - ], - links: [{ rel: 'canonical', href: siteUrl }], - }), - component: Articles, -}) -function Articles() { - const { q } = Route.useSearch() - const visible = articles.filter((article) => - article.title.toLowerCase().includes(q.toLowerCase()), - ) - return ( -
-

Field notes

-
- - -
-
    - {visible.map((article) => ( -
  • - - {article.title} - -
  • - ))} -
-
- ) -} diff --git a/examples/react/start-next-migration/src/routes/login.tsx b/examples/react/start-next-migration/src/routes/login.tsx deleted file mode 100644 index 628261cc8e..0000000000 --- a/examples/react/start-next-migration/src/routes/login.tsx +++ /dev/null @@ -1,70 +0,0 @@ -import { createFileRoute, useHydrated, useRouter } from '@tanstack/react-router' -import { useServerFn } from '@tanstack/react-start' -import { useState } from 'react' -import { signIn } from '../server/account' -export const Route = createFileRoute('/login')({ - head: () => ({ - meta: [ - { title: 'Sign in | Field notes' }, - { name: 'robots', content: 'noindex' }, - ], - }), - component: Login, -}) -function Login() { - const hydrated = useHydrated() - const login = useServerFn(signIn) - const router = useRouter() - const [error, setError] = useState('') - const [pending, setPending] = useState(false) - return ( -
-

Sign in

-
{ - event.preventDefault() - const form = new FormData(event.currentTarget) - const email = form.get('email'), - password = form.get('password') - if (typeof email !== 'string' || typeof password !== 'string') { - return - } - setPending(true) - setError('') - try { - const result = await login({ data: { email, password } }) - if (result.error) { - setError(result.error) - return - } - await router.invalidate() - await router.navigate({ to: '/saved' }) - } catch { - setError('Sign-in failed. Try again.') - } finally { - setPending(false) - } - }} - > -
- - - -
-

{error}

-
-
- ) -} diff --git a/examples/react/start-next-migration/src/routes/old-notes.tsx b/examples/react/start-next-migration/src/routes/old-notes.tsx deleted file mode 100644 index 1fb5ce846b..0000000000 --- a/examples/react/start-next-migration/src/routes/old-notes.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { createFileRoute, redirect } from '@tanstack/react-router' -export const Route = createFileRoute('/old-notes')({ - beforeLoad: () => { - throw redirect({ - to: '/posts/$slug', - params: { slug: 'keeping-your-urls' }, - statusCode: 308, - }) - }, -}) diff --git a/examples/react/start-next-migration/src/routes/posts.$slug.tsx b/examples/react/start-next-migration/src/routes/posts.$slug.tsx deleted file mode 100644 index 1998717393..0000000000 --- a/examples/react/start-next-migration/src/routes/posts.$slug.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import { createFileRoute, notFound } from '@tanstack/react-router' -import { articles, siteUrl } from '../content' -export const Route = createFileRoute('/posts/$slug')({ - loader: ({ params }) => { - const article = articles.find((item) => item.slug === params.slug) - if (!article) { - throw notFound() - } - return article - }, - head: ({ loaderData }) => - loaderData - ? { - meta: [ - { title: loaderData.title }, - { name: 'description', content: loaderData.description }, - { property: 'og:title', content: loaderData.title }, - ], - links: [ - { rel: 'canonical', href: `${siteUrl}/posts/${loaderData.slug}` }, - ], - } - : {}, - component: Article, -}) -function Article() { - const article = Route.useLoaderData() - return ( -
-

{article.title}

-

{article.body}

-
- ) -} diff --git a/examples/react/start-next-migration/src/routes/saved.tsx b/examples/react/start-next-migration/src/routes/saved.tsx deleted file mode 100644 index 2f526eb7b5..0000000000 --- a/examples/react/start-next-migration/src/routes/saved.tsx +++ /dev/null @@ -1,79 +0,0 @@ -import { - createFileRoute, - redirect, - useHydrated, - useRouter, -} from '@tanstack/react-router' -import { useServerFn } from '@tanstack/react-start' -import { useState } from 'react' -import { getAccount, signOut, toggleSaved } from '../server/account' -export const Route = createFileRoute('/saved')({ - loader: async () => { - const account = await getAccount() - if (!account) { - throw redirect({ to: '/login' }) - } - return account - }, - headers: () => ({ 'Cache-Control': 'private, no-store' }), - head: () => ({ - meta: [ - { title: 'Saved articles | Field notes' }, - { name: 'robots', content: 'noindex' }, - ], - }), - component: Saved, -}) -function Saved() { - const hydrated = useHydrated() - const account = Route.useLoaderData() - const toggle = useServerFn(toggleSaved), - logout = useServerFn(signOut) - const router = useRouter() - const [pending, setPending] = useState(false), - [error, setError] = useState('') - return ( -
-

Saved articles

-

{account.email}

-

- {account.saved ? 'Keeping your URLs is saved' : 'No saved articles'} -

- - -

{error}

-
- ) -} diff --git a/examples/react/start-next-migration/src/routes/sitemap[.]xml.ts b/examples/react/start-next-migration/src/routes/sitemap[.]xml.ts deleted file mode 100644 index a7dfcaa594..0000000000 --- a/examples/react/start-next-migration/src/routes/sitemap[.]xml.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { articles, siteUrl } from '../content' -export const Route = createFileRoute('/sitemap.xml')({ - server: { - handlers: { - GET: () => - new Response( - `${siteUrl}${articles.map((article) => `${siteUrl}/posts/${article.slug}`).join('')}`, - { headers: { 'Content-Type': 'application/xml' } }, - ), - }, - }, -}) diff --git a/examples/react/start-next-migration/src/server/account.ts b/examples/react/start-next-migration/src/server/account.ts deleted file mode 100644 index 85e921c74b..0000000000 --- a/examples/react/start-next-migration/src/server/account.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { getIronSession } from 'iron-session' -import { createServerFn } from '@tanstack/react-start' -import { - getCookie, - setCookie, - setResponseStatus, - setResponseHeader, -} from '@tanstack/react-start/server' -import { redirect } from '@tanstack/react-router' -async function session() { - setResponseHeader('Cache-Control', 'private, no-store') - const password = process.env.SESSION_PASSWORD - if (!password || password.length < 32) { - throw new Error('Set SESSION_PASSWORD to at least 32 characters') - } - return getIronSession<{ email: string; saved: boolean }>( - { read: getCookie, write: setCookie }, - { - cookieName: 'start-migration-session', - password, - ttl: 7 * 24 * 60 * 60, - cookieOptions: { - httpOnly: true, - secure: process.env.NODE_ENV === 'production', - sameSite: 'lax', - path: '/', - }, - }, - ) -} -export const getAccount = createServerFn({ method: 'GET' }).handler( - async () => { - const current = await session() - return current.email - ? { email: current.email, saved: current.saved ?? false } - : null - }, -) -export const signIn = createServerFn({ method: 'POST' }) - .validator((input: { email: string; password: string }) => { - if (typeof input.email !== 'string' || typeof input.password !== 'string') { - throw new Error('Invalid credentials') - } - return input - }) - .handler(async ({ data }) => { - if (!process.env.DEMO_PASSWORD) { - throw new Error('Set DEMO_PASSWORD before running the example') - } - if ( - data.email !== 'reader@example.com' || - data.password !== process.env.DEMO_PASSWORD - ) { - return { error: 'Invalid credentials' } - } - const current = await session() - current.email = data.email - current.saved = false - await current.save() - return { error: '' } - }) -export const toggleSaved = createServerFn({ method: 'POST' }).handler( - async () => { - const current = await session() - if (!current.email) { - setResponseStatus(401) - throw new Error('Unauthorized') - } - current.saved = !current.saved - await current.save() - }, -) -export const signOut = createServerFn({ method: 'POST' }).handler(async () => { - const current = await session() - current.destroy() - throw redirect({ to: '/login' }) -}) diff --git a/examples/react/start-next-migration/src/start.ts b/examples/react/start-next-migration/src/start.ts deleted file mode 100644 index 5fb1e247fb..0000000000 --- a/examples/react/start-next-migration/src/start.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { createCsrfMiddleware, createStart } from '@tanstack/react-start' - -export const startInstance = createStart(() => ({ - requestMiddleware: [ - createCsrfMiddleware({ - filter: (ctx) => ctx.handlerType === 'serverFn', - }), - ], -})) diff --git a/examples/react/start-next-migration/tests/migration.spec.ts b/examples/react/start-next-migration/tests/migration.spec.ts deleted file mode 100644 index 7009095977..0000000000 --- a/examples/react/start-next-migration/tests/migration.spec.ts +++ /dev/null @@ -1,163 +0,0 @@ -import { expect, test } from '@playwright/test' - -test('public URLs, server metadata, search, redirects, and missing pages survive migration', async ({ - page, - request, -}) => { - const response = await request.get('/posts/keeping-your-urls') - expect(response.status()).toBe(200) - const html = await response.text() - expect(html).toContain('Keeping your URLs') - expect(html).toMatch( - /]+name="description"[^>]+content="Preserve public URLs when changing frameworks\."/, - ) - expect(html).toMatch( - /]+rel="canonical"[^>]+href="https:\/\/field-notes\.example\/posts\/keeping-your-urls"/, - ) - expect(html).toMatch( - /]+property="og:title"[^>]+content="Keeping your URLs"/, - ) - expect(html).toContain( - 'A framework migration can keep the URLs your readers already use.', - ) - - const old = await request.get('/old-notes', { maxRedirects: 0 }) - expect(old.status()).toBe(308) - expect(new URL(old.headers().location, old.url()).pathname).toBe( - '/posts/keeping-your-urls', - ) - expect((await request.get('/posts/missing')).status()).toBe(404) - const sitemap = await (await request.get('/sitemap.xml')).text() - expect(sitemap).toContain( - 'https://field-notes.example/posts/keeping-your-urls', - ) - expect(sitemap).not.toContain('/saved') - - await page.goto('/?q=metadata') - await expect( - page.getByRole('link', { name: 'Checking your metadata' }), - ).toBeVisible() - await expect( - page.getByRole('link', { name: 'Keeping your URLs' }), - ).toHaveCount(0) - await page.getByRole('link', { name: 'Checking your metadata' }).click() - await expect(page).toHaveURL(/\/posts\/checking-your-metadata$/) - await expect(page).toHaveTitle('Checking your metadata') - await expect(page.locator('link[rel="canonical"]')).toHaveAttribute( - 'href', - 'https://field-notes.example/posts/checking-your-metadata', - ) -}) - -test('sessions and protected mutations survive reload but cannot run after sign-out', async ({ - page, -}, testInfo) => { - await page.goto('/saved') - await expect(page).toHaveURL(/\/login$/) - await page.getByLabel('Email', { exact: true }).fill('reader@example.com') - await page.getByLabel('Password', { exact: true }).fill('wrong-password') - await page.getByRole('button', { name: 'Sign in', exact: true }).click() - await expect(page.getByRole('main').getByRole('alert')).toHaveText( - 'Invalid credentials', - ) - await page.getByLabel('Email', { exact: true }).fill('reader@example.com') - await page - .getByLabel('Password', { exact: true }) - .fill('migration-test-password') - await page.getByRole('button', { name: 'Sign in', exact: true }).click() - await expect(page).toHaveURL(/\/saved$/) - await expect(page.getByTestId('saved-state')).toHaveText('No saved articles') - const mutation = page.waitForRequest((request) => request.method() === 'POST') - await page.getByRole('button', { name: 'Save article', exact: true }).click() - const savedRequest = await mutation - await expect(page.getByTestId('saved-state')).toHaveText( - 'Keeping your URLs is saved', - ) - // Keep the authenticated cookie jar while replaying a cross-site request. - const crossSiteHeaders = await savedRequest.allHeaders() - delete crossSiteHeaders.cookie - delete crossSiteHeaders['content-length'] - crossSiteHeaders.origin = 'https://untrusted.example' - crossSiteHeaders['sec-fetch-site'] = 'cross-site' - const crossSite = await page.request.post(savedRequest.url(), { - headers: crossSiteHeaders, - data: savedRequest.postData() ?? '', - }) - if (testInfo.project.name === 'start') { - expect(crossSite.status()).toBe(403) - } else { - expect(crossSite.status()).toBeGreaterThanOrEqual(400) - } - - const response = await page.reload() - expect(response?.headers()['cache-control']).toMatch( - process.env.MIGRATION_PRODUCTION ? /no-store/ : /no-store|no-cache/, - ) - await expect(page.getByTestId('saved-state')).toHaveText( - 'Keeping your URLs is saved', - ) - await page.getByRole('button', { name: 'Sign out', exact: true }).click() - await expect(page).toHaveURL(/\/login$/) - - // Replay the real mutation with the now-signed-out browser cookie jar. - const headers = await savedRequest.allHeaders() - delete headers.cookie - delete headers['content-length'] - const denied = await page.request.post(savedRequest.url(), { - headers, - data: savedRequest.postData() ?? '', - }) - expect(denied.status()).toBeGreaterThanOrEqual(400) - await page.goto('/saved') - await expect(page).toHaveURL(/\/login$/) -}) - -test('Start serializes saving and signing out so their responses cannot arrive out of order', async ({ - page, -}, testInfo) => { - test.skip(testInfo.project.name !== 'start', 'Start event-handler regression') - await page.goto('/login') - await page.getByLabel('Email', { exact: true }).fill('reader@example.com') - await page - .getByLabel('Password', { exact: true }) - .fill('migration-test-password') - await page.getByRole('button', { name: 'Sign in', exact: true }).click() - await expect(page).toHaveURL(/\/saved$/) - - for (const action of ['Save article', 'Sign out']) { - let release = () => {} - const held = new Promise((resolve) => { - release = resolve - }) - await page.route('**/_serverFn/**', async (route) => { - if (route.request().method() === 'POST') { - await held - } - await route.continue() - }) - await page.getByRole('button', { name: action, exact: true }).click() - try { - await expect( - page.getByRole('button', { name: /^(Save|Remove) article$/ }), - ).toBeDisabled() - await expect( - page.getByRole('button', { name: 'Sign out', exact: true }), - ).toBeDisabled() - } finally { - release() - } - if (action === 'Save article') { - await expect(page.getByTestId('saved-state')).toHaveText( - 'Keeping your URLs is saved', - ) - await expect( - page.getByRole('button', { name: 'Sign out', exact: true }), - ).toBeEnabled() - } else { - await expect(page).toHaveURL(/\/login$/) - } - await page.unrouteAll({ behavior: 'wait' }) - } - await page.goto('/saved') - await expect(page).toHaveURL(/\/login$/) -}) diff --git a/examples/react/start-next-migration/tsconfig.json b/examples/react/start-next-migration/tsconfig.json deleted file mode 100644 index a41553b9a1..0000000000 --- a/examples/react/start-next-migration/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "include": [ - "src/**/*.ts", - "src/**/*.tsx", - "vite.config.ts", - "playwright.config.ts", - "tests/**/*.ts" - ], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "react-jsx", - "module": "ESNext", - "moduleResolution": "Bundler", - "lib": ["DOM", "DOM.Iterable", "ES2024"], - "skipLibCheck": true, - "target": "ES2024", - "noEmit": true, - "types": ["vite/client"] - } -} diff --git a/examples/react/start-next-migration/vite.config.ts b/examples/react/start-next-migration/vite.config.ts deleted file mode 100644 index 26d0e455d5..0000000000 --- a/examples/react/start-next-migration/vite.config.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { defineConfig } from 'vite' -import react from '@vitejs/plugin-react' -import { tanstackStart } from '@tanstack/react-start/plugin/vite' -import { nitro } from 'nitro/vite' -export default defineConfig({ plugins: [tanstackStart(), react(), nitro()] }) diff --git a/examples/react/start-rscs/package.json b/examples/react/start-rscs/package.json index 00c88681d7..ed0946409f 100644 --- a/examples/react/start-rscs/package.json +++ b/examples/react/start-rscs/package.json @@ -10,9 +10,9 @@ "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-start": "^1.168.49", "dexie": "^4.0.10", "react": "^19.2.0", "react-dom": "^19.2.0", @@ -26,8 +26,8 @@ "@types/react": "^19.2.2", "@types/react-dom": "^19.2.2", "@vitejs/plugin-react": "^6.0.1", - "@vitejs/plugin-rsc": "^0.5.39", - "nitro": "^3.0.260903-beta", + "@vitejs/plugin-rsc": "^0.5.30", + "nitro": "^3.0.260311-beta", "tailwindcss": "^4.1.18", "typescript": "^5.7.2", "vite": "^8.0.14" diff --git a/examples/react/start-streaming-data-from-server-functions/package.json b/examples/react/start-streaming-data-from-server-functions/package.json index 762bbff733..b4fb2dfd88 100644 --- a/examples/react/start-streaming-data-from-server-functions/package.json +++ b/examples/react/start-streaming-data-from-server-functions/package.json @@ -10,9 +10,9 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-start": "^1.168.49", "react": "^19.0.0", "react-dom": "^19.0.0", "zod": "^4.4.3" diff --git a/examples/react/start-supabase-basic/.gitignore b/examples/react/start-supabase-basic/.gitignore index 372dc30373..8293849e8d 100644 --- a/examples/react/start-supabase-basic/.gitignore +++ b/examples/react/start-supabase-basic/.gitignore @@ -1,11 +1,12 @@ node_modules +# Keep environment variables out of version control +!.env package-lock.json yarn.lock .DS_Store .cache -# The checked-in .env contains public demo values used by the build. -!.env +.env .vercel .output /build/ diff --git a/examples/react/start-supabase-basic/package.json b/examples/react/start-supabase-basic/package.json index 0bf4b2c246..0b62b6ec20 100644 --- a/examples/react/start-supabase-basic/package.json +++ b/examples/react/start-supabase-basic/package.json @@ -15,12 +15,12 @@ "dependencies": { "@supabase/ssr": "^0.5.2", "@supabase/supabase-js": "^2.48.1", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-start": "^1.168.49", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1" + "redaxios": "catalog:" }, "devDependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/examples/react/start-tailwind-v4/package.json b/examples/react/start-tailwind-v4/package.json index b58fbe4ff0..0186a89985 100644 --- a/examples/react/start-tailwind-v4/package.json +++ b/examples/react/start-tailwind-v4/package.json @@ -10,9 +10,9 @@ "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-start": "^1.168.49", "react": "^19.0.0", "react-dom": "^19.0.0", "tailwind-merge": "^3.6.0", diff --git a/examples/react/start-trellaux/package.json b/examples/react/start-trellaux/package.json index 7755d227fc..68e4445070 100644 --- a/examples/react/start-trellaux/package.json +++ b/examples/react/start-trellaux/package.json @@ -10,18 +10,18 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-query": "^5.102.0", + "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-router-ssr-query": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-router-ssr-query": "^1.167.2", + "@tanstack/react-start": "^1.168.49", "ky": "^1.7.4", "msw": "^2.7.0", "react": "^19.0.0", "react-dom": "^19.0.0", "react-hot-toast": "^2.5.1", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0", "zod": "^4.4.3" }, diff --git a/examples/react/start-workos/package.json b/examples/react/start-workos/package.json index 0ab7e89c2d..5a52634035 100644 --- a/examples/react/start-workos/package.json +++ b/examples/react/start-workos/package.json @@ -14,9 +14,9 @@ "license": "MIT", "dependencies": { "@radix-ui/themes": "^3.3.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-start": "^1.168.49", "@workos/authkit-tanstack-react-start": "^0.5.0", "react": "^19.0.0", "react-dom": "^19.0.0" diff --git a/examples/react/view-transitions/package.json b/examples/react/view-transitions/package.json index 0be3c60e8f..6b0b479286 100644 --- a/examples/react/view-transitions/package.json +++ b/examples/react/view-transitions/package.json @@ -10,12 +10,12 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.35", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, diff --git a/examples/react/with-framer-motion/package.json b/examples/react/with-framer-motion/package.json index c606070dfb..1ff8c98391 100644 --- a/examples/react/with-framer-motion/package.json +++ b/examples/react/with-framer-motion/package.json @@ -10,12 +10,12 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", "framer-motion": "^11.18.2", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, diff --git a/examples/react/with-trpc-react-query/package.json b/examples/react/with-trpc-react-query/package.json index 11df7bf03b..4e5f5c8d99 100644 --- a/examples/react/with-trpc-react-query/package.json +++ b/examples/react/with-trpc-react-query/package.json @@ -11,18 +11,18 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.102.0", + "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.35", "@trpc/client": "^11.4.3", "@trpc/server": "^11.4.3", "@trpc/tanstack-react-query": "^11.4.3", "express": "^5.2.1", "react": "^19.1.0", "react-dom": "^19.1.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, diff --git a/examples/react/with-trpc/package.json b/examples/react/with-trpc/package.json index 5612419cae..131a35e7e9 100644 --- a/examples/react/with-trpc/package.json +++ b/examples/react/with-trpc/package.json @@ -11,15 +11,15 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.32", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.35", "@trpc/client": "^11.4.3", "@trpc/server": "^11.4.3", "express": "^5.2.1", "react": "^19.1.0", "react-dom": "^19.1.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, diff --git a/examples/solid/authenticated-routes-firebase/package.json b/examples/solid/authenticated-routes-firebase/package.json index 110b4d2621..56d161acd5 100644 --- a/examples/solid/authenticated-routes-firebase/package.json +++ b/examples/solid/authenticated-routes-firebase/package.json @@ -10,11 +10,11 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.169.0", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.168.35", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", "firebase": "^11.4.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "simple-icons": "^14.9.0", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", diff --git a/examples/solid/authenticated-routes/package.json b/examples/solid/authenticated-routes/package.json index ea7d05c902..e8d25167d6 100644 --- a/examples/solid/authenticated-routes/package.json +++ b/examples/solid/authenticated-routes/package.json @@ -10,10 +10,10 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.169.0", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "redaxios": "^0.5.1", + "@tanstack/router-plugin": "^1.168.35", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "redaxios": "catalog:", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", "zod": "^4.4.3" diff --git a/examples/solid/basic-default-search-params/package.json b/examples/solid/basic-default-search-params/package.json index 830df7b9cf..bb706d2053 100644 --- a/examples/solid/basic-default-search-params/package.json +++ b/examples/solid/basic-default-search-params/package.json @@ -11,9 +11,9 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "redaxios": "^0.5.1", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "redaxios": "catalog:", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", "zod": "^4.4.3" diff --git a/examples/solid/basic-devtools-panel/package.json b/examples/solid/basic-devtools-panel/package.json index e7d608f5fe..2491e38a2d 100644 --- a/examples/solid/basic-devtools-panel/package.json +++ b/examples/solid/basic-devtools-panel/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "redaxios": "^0.5.1", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "redaxios": "catalog:", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2" }, diff --git a/examples/solid/basic-file-based/package.json b/examples/solid/basic-file-based/package.json index 867118382e..24a367c30c 100644 --- a/examples/solid/basic-file-based/package.json +++ b/examples/solid/basic-file-based/package.json @@ -10,15 +10,15 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "redaxios": "^0.5.1", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "redaxios": "catalog:", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, "devDependencies": { - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/router-plugin": "^1.168.35", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", diff --git a/examples/solid/basic-non-nested-devtools/package.json b/examples/solid/basic-non-nested-devtools/package.json index c8e00ee43e..906f6816b7 100644 --- a/examples/solid/basic-non-nested-devtools/package.json +++ b/examples/solid/basic-non-nested-devtools/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "redaxios": "^0.5.1", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "redaxios": "catalog:", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2" }, diff --git a/examples/solid/basic-solid-query-file-based/package.json b/examples/solid/basic-solid-query-file-based/package.json index fdb5f05f52..26e9984e1b 100644 --- a/examples/solid/basic-solid-query-file-based/package.json +++ b/examples/solid/basic-solid-query-file-based/package.json @@ -13,15 +13,15 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-query": "^5.90.9", "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "redaxios": "^0.5.1", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "redaxios": "catalog:", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, "devDependencies": { - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/router-plugin": "^1.168.35", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", diff --git a/examples/solid/basic-solid-query/package.json b/examples/solid/basic-solid-query/package.json index 7b132b11a1..cee3be345c 100644 --- a/examples/solid/basic-solid-query/package.json +++ b/examples/solid/basic-solid-query/package.json @@ -12,14 +12,14 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-query": "^5.90.9", "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "redaxios": "^0.5.1", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "redaxios": "catalog:", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2" }, "devDependencies": { - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/router-plugin": "^1.168.35", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", diff --git a/examples/solid/basic-ssr-file-based/package.json b/examples/solid/basic-ssr-file-based/package.json index e3699970a9..c26e6431a7 100644 --- a/examples/solid/basic-ssr-file-based/package.json +++ b/examples/solid/basic-ssr-file-based/package.json @@ -11,8 +11,8 @@ "debug": "node --inspect-brk server" }, "dependencies": { - "@tanstack/solid-router": "^1.170.43", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/router-plugin": "^1.168.35", "compression": "^1.8.0", "express": "^5.2.1", "get-port": "^7.1.0", @@ -20,7 +20,7 @@ "solid-js": "^1.9.10" }, "devDependencies": { - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router-devtools": "^1.167.1", "@types/express": "^5.0.6", "vite-plugin-solid": "^2.11.11", "@typescript/native": "npm:typescript@^7.0.2", diff --git a/examples/solid/basic-ssr-streaming-file-based/package.json b/examples/solid/basic-ssr-streaming-file-based/package.json index 92367442fc..8418a571a0 100644 --- a/examples/solid/basic-ssr-streaming-file-based/package.json +++ b/examples/solid/basic-ssr-streaming-file-based/package.json @@ -12,19 +12,19 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", "compression": "^1.8.0", "express": "^5.2.1", "get-port": "^7.1.0", "node-fetch": "^3.3.2", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, "devDependencies": { - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/router-plugin": "^1.168.35", "@types/express": "^5.0.6", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/examples/solid/basic-virtual-file-based/package.json b/examples/solid/basic-virtual-file-based/package.json index 801b452192..7339afb094 100644 --- a/examples/solid/basic-virtual-file-based/package.json +++ b/examples/solid/basic-virtual-file-based/package.json @@ -10,11 +10,11 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.169.0", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.168.35", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", "@tanstack/virtual-file-routes": "^1.162.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", "zod": "^4.4.3" diff --git a/examples/solid/basic-virtual-inside-file-based/package.json b/examples/solid/basic-virtual-inside-file-based/package.json index a9cc6360a5..d9c8642057 100644 --- a/examples/solid/basic-virtual-inside-file-based/package.json +++ b/examples/solid/basic-virtual-inside-file-based/package.json @@ -10,11 +10,11 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.169.0", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.168.35", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", "@tanstack/virtual-file-routes": "^1.162.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", "zod": "^4.4.3" diff --git a/examples/solid/basic/package.json b/examples/solid/basic/package.json index 95ec804011..1e363f43f8 100644 --- a/examples/solid/basic/package.json +++ b/examples/solid/basic/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "redaxios": "^0.5.1", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "redaxios": "catalog:", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2" }, diff --git a/examples/solid/deferred-data/package.json b/examples/solid/deferred-data/package.json index 56114afd04..a0d7360761 100644 --- a/examples/solid/deferred-data/package.json +++ b/examples/solid/deferred-data/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "redaxios": "^0.5.1", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "redaxios": "catalog:", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", "zod": "^4.4.3" diff --git a/examples/solid/i18n-paraglide/package.json b/examples/solid/i18n-paraglide/package.json index 6493a3c7c8..6d1bbf1aa7 100644 --- a/examples/solid/i18n-paraglide/package.json +++ b/examples/solid/i18n-paraglide/package.json @@ -11,8 +11,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/router-plugin": "^1.168.35", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2" }, @@ -23,16 +23,5 @@ "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "@inlang/paraglide-js": "^2.4.0" - }, - "nx": { - "targets": { - "build": { - "outputs": [ - "...", - "{projectRoot}/src/paraglide", - "{projectRoot}/project.inlang/cache" - ] - } - } } } diff --git a/examples/solid/kitchen-sink-file-based/package.json b/examples/solid/kitchen-sink-file-based/package.json index 8cd73e38ff..60a67358ea 100644 --- a/examples/solid/kitchen-sink-file-based/package.json +++ b/examples/solid/kitchen-sink-file-based/package.json @@ -10,16 +10,16 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", "immer": "^10.1.1", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, "devDependencies": { - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/router-plugin": "^1.168.35", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", diff --git a/examples/solid/kitchen-sink-solid-query-file-based/package.json b/examples/solid/kitchen-sink-solid-query-file-based/package.json index 25a1c29953..ac69d59c03 100644 --- a/examples/solid/kitchen-sink-solid-query-file-based/package.json +++ b/examples/solid/kitchen-sink-solid-query-file-based/package.json @@ -10,13 +10,13 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/router-plugin": "^1.168.35", "@tanstack/solid-query": "^5.90.9", "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", "immer": "^10.1.1", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", "zod": "^4.4.3" diff --git a/examples/solid/kitchen-sink-solid-query/package.json b/examples/solid/kitchen-sink-solid-query/package.json index 7a7dc81025..963248dfac 100644 --- a/examples/solid/kitchen-sink-solid-query/package.json +++ b/examples/solid/kitchen-sink-solid-query/package.json @@ -12,10 +12,10 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-query": "^5.90.9", "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", "immer": "^10.1.1", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", "zod": "^4.4.3" diff --git a/examples/solid/kitchen-sink/package.json b/examples/solid/kitchen-sink/package.json index 08ad918a60..af85b82e6e 100644 --- a/examples/solid/kitchen-sink/package.json +++ b/examples/solid/kitchen-sink/package.json @@ -10,10 +10,10 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", "immer": "^10.1.1", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", "zod": "^4.4.3" diff --git a/examples/solid/large-file-based/package.json b/examples/solid/large-file-based/package.json index cd758ab704..89dae435d6 100644 --- a/examples/solid/large-file-based/package.json +++ b/examples/solid/large-file-based/package.json @@ -12,11 +12,11 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/router-plugin": "^1.168.35", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "redaxios": "^0.5.1", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "redaxios": "catalog:", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", "zod": "^4.4.3" diff --git a/examples/solid/location-masking/package.json b/examples/solid/location-masking/package.json index 7d2fbb6756..7bbaad7a97 100644 --- a/examples/solid/location-masking/package.json +++ b/examples/solid/location-masking/package.json @@ -11,10 +11,10 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", "solid-js": "^1.9.10", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2" }, "devDependencies": { diff --git a/examples/solid/navigation-blocking/package.json b/examples/solid/navigation-blocking/package.json index 2338d32305..97e3f8db52 100644 --- a/examples/solid/navigation-blocking/package.json +++ b/examples/solid/navigation-blocking/package.json @@ -11,10 +11,10 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", "solid-js": "^1.9.10", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2" }, "devDependencies": { diff --git a/examples/solid/quickstart-esbuild-file-based/build.js b/examples/solid/quickstart-esbuild-file-based/build.js index af5e01b4cd..f8d31fbbd9 100644 --- a/examples/solid/quickstart-esbuild-file-based/build.js +++ b/examples/solid/quickstart-esbuild-file-based/build.js @@ -14,7 +14,10 @@ const ctx = await esbuild.context({ target: ['esnext'], sourcemap: true, conditions: ['style'], - plugins: [solidPlugin(), tanstackRouter({ target: 'solid' })], + plugins: [ + solidPlugin(), + tanstackRouter({ target: 'solid', autoCodeSplitting: true }), + ], }) if (isDev) { diff --git a/examples/solid/quickstart-esbuild-file-based/package.json b/examples/solid/quickstart-esbuild-file-based/package.json index 9bcc9a08d0..eba14026b0 100644 --- a/examples/solid/quickstart-esbuild-file-based/package.json +++ b/examples/solid/quickstart-esbuild-file-based/package.json @@ -9,10 +9,10 @@ "start": "dev" }, "dependencies": { - "@tanstack/router-plugin": "^1.169.0", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "redaxios": "^0.5.1", + "@tanstack/router-plugin": "^1.168.35", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "redaxios": "catalog:", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", "zod": "^4.4.3" diff --git a/examples/solid/quickstart-file-based/package.json b/examples/solid/quickstart-file-based/package.json index 920154566d..2fb902781f 100644 --- a/examples/solid/quickstart-file-based/package.json +++ b/examples/solid/quickstart-file-based/package.json @@ -10,15 +10,15 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "redaxios": "^0.5.1", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "redaxios": "catalog:", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, "devDependencies": { - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/router-plugin": "^1.168.35", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", diff --git a/examples/solid/quickstart-rspack-file-based/package.json b/examples/solid/quickstart-rspack-file-based/package.json index 2d9c886ac3..ae8bd637e9 100644 --- a/examples/solid/quickstart-rspack-file-based/package.json +++ b/examples/solid/quickstart-rspack-file-based/package.json @@ -9,17 +9,17 @@ }, "dependencies": { "@tailwindcss/postcss": "^4.2.2", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", "postcss": "^8.5.1", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2" }, "devDependencies": { - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-babel": "^1.1.2", "@rsbuild/plugin-solid": "^1.1.1", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/router-plugin": "^1.168.35", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2" } diff --git a/examples/solid/quickstart-webpack-file-based/package.json b/examples/solid/quickstart-webpack-file-based/package.json index 16167be207..cd86525670 100644 --- a/examples/solid/quickstart-webpack-file-based/package.json +++ b/examples/solid/quickstart-webpack-file-based/package.json @@ -7,15 +7,15 @@ "build": "webpack build && tsc --noEmit" }, "dependencies": { - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2" }, "devDependencies": { "@babel/core": "^7.28.5", "@babel/preset-typescript": "^7.27.1", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/router-plugin": "^1.168.35", "babel-loader": "^10.0.0", "babel-preset-solid": "^1.9.10", "css-loader": "^7.1.2", diff --git a/examples/solid/quickstart/package.json b/examples/solid/quickstart/package.json index 454382e8cc..44b1dadef3 100644 --- a/examples/solid/quickstart/package.json +++ b/examples/solid/quickstart/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2" }, diff --git a/examples/solid/router-monorepo-simple-lazy/package.json b/examples/solid/router-monorepo-simple-lazy/package.json index 1d60ab2765..23dc3d4e8b 100644 --- a/examples/solid/router-monorepo-simple-lazy/package.json +++ b/examples/solid/router-monorepo-simple-lazy/package.json @@ -8,11 +8,11 @@ "dev": "pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.35", "solid-js": "^1.9.10", - "redaxios": "^0.5.1" + "redaxios": "catalog:" }, "devDependencies": { "@types/node": "^22.7.4", diff --git a/examples/solid/router-monorepo-simple-lazy/packages/app/package.json b/examples/solid/router-monorepo-simple-lazy/packages/app/package.json index a2e018fa96..3cfa6a1377 100644 --- a/examples/solid/router-monorepo-simple-lazy/packages/app/package.json +++ b/examples/solid/router-monorepo-simple-lazy/packages/app/package.json @@ -20,7 +20,7 @@ "@vitejs/plugin-react": "^6.0.1", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router-devtools": "^1.167.1", "tailwindcss": "^4.2.2", "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4", diff --git a/examples/solid/router-monorepo-simple-lazy/packages/router/package.json b/examples/solid/router-monorepo-simple-lazy/packages/router/package.json index 0672c42931..10b53f665c 100644 --- a/examples/solid/router-monorepo-simple-lazy/packages/router/package.json +++ b/examples/solid/router-monorepo-simple-lazy/packages/router/package.json @@ -8,9 +8,9 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/history": "^1.162.5", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/history": "^1.162.1", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/router-plugin": "^1.168.35", "redaxios": "^0.5.1", "zod": "^4.4.3", "solid-js": "^1.9.10" diff --git a/examples/solid/router-monorepo-simple/package.json b/examples/solid/router-monorepo-simple/package.json index 3770256692..552677ce2a 100644 --- a/examples/solid/router-monorepo-simple/package.json +++ b/examples/solid/router-monorepo-simple/package.json @@ -8,11 +8,11 @@ "dev": "pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.35", "solid-js": "^1.9.10", - "redaxios": "^0.5.1" + "redaxios": "catalog:" }, "devDependencies": { "@types/node": "^22.7.4", diff --git a/examples/solid/router-monorepo-simple/packages/app/package.json b/examples/solid/router-monorepo-simple/packages/app/package.json index 61234ac455..937bf9795c 100644 --- a/examples/solid/router-monorepo-simple/packages/app/package.json +++ b/examples/solid/router-monorepo-simple/packages/app/package.json @@ -17,7 +17,7 @@ "vite-plugin-solid": "^2.11.11", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router-devtools": "^1.167.1", "vite": "^8.0.14", "tailwindcss": "^4.2.2", "vite-plugin-dts": "^4.5.4", diff --git a/examples/solid/router-monorepo-simple/packages/router/package.json b/examples/solid/router-monorepo-simple/packages/router/package.json index ca08511d3e..676ea1bdbd 100644 --- a/examples/solid/router-monorepo-simple/packages/router/package.json +++ b/examples/solid/router-monorepo-simple/packages/router/package.json @@ -8,9 +8,9 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/history": "^1.162.5", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/history": "^1.162.1", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/router-plugin": "^1.168.35", "redaxios": "^0.5.1", "zod": "^4.4.3", "solid-js": "^1.9.10" diff --git a/examples/solid/router-monorepo-solid-query/package.json b/examples/solid/router-monorepo-solid-query/package.json index 3d9fd2e2d0..498b90e409 100644 --- a/examples/solid/router-monorepo-solid-query/package.json +++ b/examples/solid/router-monorepo-solid-query/package.json @@ -12,11 +12,11 @@ "dependencies": { "@tanstack/solid-query": "^5.90.9", "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.35", "solid-js": "^1.9.10", - "redaxios": "^0.5.1" + "redaxios": "catalog:" }, "devDependencies": { "@types/node": "^22.10.2", diff --git a/examples/solid/router-monorepo-solid-query/packages/app/package.json b/examples/solid/router-monorepo-solid-query/packages/app/package.json index 76bb059de5..bf2cc8ab04 100644 --- a/examples/solid/router-monorepo-solid-query/packages/app/package.json +++ b/examples/solid/router-monorepo-solid-query/packages/app/package.json @@ -18,7 +18,7 @@ "vite-plugin-solid": "^2.11.11", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router-devtools": "^1.167.1", "tailwindcss": "^4.2.2", "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4", diff --git a/examples/solid/router-monorepo-solid-query/packages/router/package.json b/examples/solid/router-monorepo-solid-query/packages/router/package.json index 93943a1df8..15fdbb47bc 100644 --- a/examples/solid/router-monorepo-solid-query/packages/router/package.json +++ b/examples/solid/router-monorepo-solid-query/packages/router/package.json @@ -8,10 +8,10 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/history": "^1.162.5", + "@tanstack/history": "^1.162.1", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/router-plugin": "^1.168.35", "@router-solid-mono-solid-query/post-query": "workspace:*", "redaxios": "^0.5.1", "zod": "^4.4.3", diff --git a/examples/solid/scroll-restoration/package.json b/examples/solid/scroll-restoration/package.json index eaa5a5aaea..545040a435 100644 --- a/examples/solid/scroll-restoration/package.json +++ b/examples/solid/scroll-restoration/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", "@tanstack/solid-virtual": "^3.13.0", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2" diff --git a/examples/solid/search-validator-adapters/package.json b/examples/solid/search-validator-adapters/package.json index 59991edb36..74c7f87f47 100644 --- a/examples/solid/search-validator-adapters/package.json +++ b/examples/solid/search-validator-adapters/package.json @@ -13,9 +13,9 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/arktype-adapter": "^1.167.0", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.35", "@tanstack/valibot-adapter": "^1.167.0", "@tanstack/zod-adapter": "^1.167.0", "arktype": "^2.1.7", @@ -25,13 +25,13 @@ "zod": "^3.24.2" }, "devDependencies": { - "@testing-library/jest-dom": "^7.0.1", + "@testing-library/jest-dom": "^6.6.3", "@solidjs/testing-library": "^0.8.10", "vite-plugin-solid": "^2.11.11", "@typescript/native": "npm:typescript@^7.0.2", "jsdom": "^27.0.0", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", - "vitest": "^5.0.4" + "vitest": "catalog:" } } diff --git a/examples/solid/search-validator-adapters/tests/arktype.test.tsx b/examples/solid/search-validator-adapters/tests/arktype.test.tsx index f22a359995..4ec555fc7b 100644 --- a/examples/solid/search-validator-adapters/tests/arktype.test.tsx +++ b/examples/solid/search-validator-adapters/tests/arktype.test.tsx @@ -8,6 +8,7 @@ import { createRouter, } from '@tanstack/solid-router' +import '@testing-library/jest-dom/vitest' import { type } from 'arktype' test('can navigate to the route', async () => { diff --git a/examples/solid/search-validator-adapters/tests/jest-dom.setup.ts b/examples/solid/search-validator-adapters/tests/jest-dom.setup.ts deleted file mode 100644 index 8f7cbf15be..0000000000 --- a/examples/solid/search-validator-adapters/tests/jest-dom.setup.ts +++ /dev/null @@ -1,18 +0,0 @@ -import * as jestDomMatchers from '@testing-library/jest-dom/matchers' -import { expect } from 'vitest' -import type { TestingLibraryMatchers } from '@testing-library/jest-dom/matchers' - -// Workaround for Vitest 5: remove once testing-library/jest-dom#742 is merged -// and released, and go back to `import '@testing-library/jest-dom/vitest'`. -// That entry imports `vitest` from its own install location, which can resolve -// a different Vitest copy than the one running these tests, and its types -// augment Vitest 4's `Assertion` instead of Vitest 5's `Matchers`. -// Keep `jest-dom` in this file name: vite-plugin-solid only skips injecting -// `@testing-library/jest-dom/vitest` when a setup file path contains it. -expect.extend(jestDomMatchers) - -declare module 'vitest' { - // Type parameter names must match Vitest's declaration for the interfaces to merge. - // eslint-disable-next-line @typescript-eslint/naming-convention - interface Matchers extends TestingLibraryMatchers {} -} diff --git a/examples/solid/search-validator-adapters/tests/valibot.test.tsx b/examples/solid/search-validator-adapters/tests/valibot.test.tsx index 8594c1cb29..cd4545397c 100644 --- a/examples/solid/search-validator-adapters/tests/valibot.test.tsx +++ b/examples/solid/search-validator-adapters/tests/valibot.test.tsx @@ -8,6 +8,7 @@ import { createRouter, } from '@tanstack/solid-router' import * as v from 'valibot' +import '@testing-library/jest-dom/vitest' test('can navigate to the route', async () => { const rootRoute = createRootRoute() diff --git a/examples/solid/search-validator-adapters/vite.config.ts b/examples/solid/search-validator-adapters/vite.config.ts index 4e05d81e75..5b9dbebfef 100644 --- a/examples/solid/search-validator-adapters/vite.config.ts +++ b/examples/solid/search-validator-adapters/vite.config.ts @@ -11,7 +11,6 @@ export default defineConfig({ watch: false, environment: 'jsdom', typecheck: { enabled: true }, - setupFiles: ['./tests/jest-dom.setup.ts'], server: { deps: { inline: [/@solidjs/, /@tanstack\/solid-store/], diff --git a/examples/solid/start-basic-auth/README.md b/examples/solid/start-basic-auth/README.md index 313c930051..90cba4aac1 100644 --- a/examples/solid/start-basic-auth/README.md +++ b/examples/solid/start-basic-auth/README.md @@ -70,13 +70,3 @@ pnpm dev > [!WARNING] > You will need to update the `docs/config.json` file (in the project's repo) if you add a new doc page! - -## Session configuration - -This example uses [iron-session](https://github.com/vvo/iron-session) through Start's `getCookie` and `setCookie` helpers. Set `SESSION_PASSWORD` to a random secret of at least 32 characters before starting the app, for example: - -```sh -export SESSION_PASSWORD="$(openssl rand -base64 32)" -``` - -Keep the same secret across instances and deployments that must read the same sessions. The cookie requires HTTPS in production. Each handler reads its own session, then awaits `session.save()` before redirecting or returning. diff --git a/examples/solid/start-basic-auth/package.json b/examples/solid/start-basic-auth/package.json index d686fdf616..235e0958ea 100644 --- a/examples/solid/start-basic-auth/package.json +++ b/examples/solid/start-basic-auth/package.json @@ -14,11 +14,10 @@ "@libsql/client": "^0.15.15", "@prisma/adapter-libsql": "^7.0.0", "@prisma/client": "^7.0.0", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/solid-start": "^1.169.6", - "iron-session": "^9.0.1", - "redaxios": "^0.5.1", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-start": "^1.168.47", + "redaxios": "catalog:", "solid-js": "^1.9.10", "tailwind-merge": "^3.6.0" }, diff --git a/examples/solid/start-basic-auth/src/routes/__root.tsx b/examples/solid/start-basic-auth/src/routes/__root.tsx index 05ad0d298a..3aa0bfa18b 100644 --- a/examples/solid/start-basic-auth/src/routes/__root.tsx +++ b/examples/solid/start-basic-auth/src/routes/__root.tsx @@ -14,18 +14,18 @@ import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary.js' import { NotFound } from '~/components/NotFound.js' import appCss from '~/styles/app.css?url' import { seo } from '~/utils/seo.js' -import { getAppSession } from '~/utils/session.js' +import { useAppSession } from '~/utils/session.js' const fetchUser = createServerFn({ method: 'GET' }).handler(async () => { // We need to auth on the server so we have access to secure cookies - const session = await getAppSession() + const session = await useAppSession() - if (!session.userEmail) { + if (!session.data.userEmail) { return null } return { - email: session.userEmail, + email: session.data.userEmail, } }) diff --git a/examples/solid/start-basic-auth/src/routes/_authed.tsx b/examples/solid/start-basic-auth/src/routes/_authed.tsx index cded7ca880..60ad613e56 100644 --- a/examples/solid/start-basic-auth/src/routes/_authed.tsx +++ b/examples/solid/start-basic-auth/src/routes/_authed.tsx @@ -2,7 +2,7 @@ import { createFileRoute } from '@tanstack/solid-router' import { createServerFn } from '@tanstack/solid-start' import { hashPassword, prismaClient } from '~/utils/prisma' import { Login } from '~/components/Login' -import { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' export const loginFn = createServerFn({ method: 'POST' }) .validator((d: { email: string; password: string }) => d) @@ -33,10 +33,13 @@ export const loginFn = createServerFn({ method: 'POST' }) } } + // Create a session + const session = await useAppSession() + // Store the user's email in the session - const session = await getAppSession() - session.userEmail = user.email - await session.save() + await session.update({ + userEmail: user.email, + }) }) export const Route = createFileRoute('/_authed')({ diff --git a/examples/solid/start-basic-auth/src/routes/logout.tsx b/examples/solid/start-basic-auth/src/routes/logout.tsx index 56cd70cbc2..f7d624ff15 100644 --- a/examples/solid/start-basic-auth/src/routes/logout.tsx +++ b/examples/solid/start-basic-auth/src/routes/logout.tsx @@ -1,10 +1,11 @@ import { createFileRoute, redirect } from '@tanstack/solid-router' import { createServerFn } from '@tanstack/solid-start' -import { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' const logoutFn = createServerFn().handler(async () => { - const session = await getAppSession() - session.destroy() + const session = await useAppSession() + + session.clear() throw redirect({ href: '/', diff --git a/examples/solid/start-basic-auth/src/routes/signup.tsx b/examples/solid/start-basic-auth/src/routes/signup.tsx index b8d6bf89fa..7cb9ae7161 100644 --- a/examples/solid/start-basic-auth/src/routes/signup.tsx +++ b/examples/solid/start-basic-auth/src/routes/signup.tsx @@ -3,7 +3,7 @@ import { createServerFn, useServerFn } from '@tanstack/solid-start' import { hashPassword, prismaClient } from '~/utils/prisma' import { useMutation } from '~/hooks/useMutation' import { Auth } from '~/components/Auth' -import { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' export const signupFn = createServerFn({ method: 'POST' }) .validator( @@ -20,6 +20,9 @@ export const signupFn = createServerFn({ method: 'POST' }) // Encrypt the password using Sha256 into plaintext const password = await hashPassword(data.password) + // Create a session + const session = await useAppSession() + if (found) { if (found.password !== password) { return { @@ -30,9 +33,9 @@ export const signupFn = createServerFn({ method: 'POST' }) } // Store the user's email in the session - const session = await getAppSession() - session.userEmail = found.email - await session.save() + await session.update({ + userEmail: found.email, + }) // Redirect to the prev page stored in the "redirect" search param throw redirect({ @@ -49,9 +52,9 @@ export const signupFn = createServerFn({ method: 'POST' }) }) // Store the user's email in the session - const session = await getAppSession() - session.userEmail = user.email - await session.save() + await session.update({ + userEmail: user.email, + }) // Redirect to the prev page stored in the "redirect" search param throw redirect({ diff --git a/examples/solid/start-basic-auth/src/utils/session.ts b/examples/solid/start-basic-auth/src/utils/session.ts index 4577764d28..120a410b60 100644 --- a/examples/solid/start-basic-auth/src/utils/session.ts +++ b/examples/solid/start-basic-auth/src/utils/session.ts @@ -1,29 +1,13 @@ -import { getIronSession } from 'iron-session' -import { getCookie, setCookie } from '@tanstack/solid-start/server' +// src/services/session.server.ts +import { useSession } from '@tanstack/solid-start/server' import type { User } from '@prisma/client' type SessionUser = { userEmail: User['email'] } -export function getAppSession() { - const password = process.env.SESSION_PASSWORD - if (!password || password.length < 32) { - throw new Error('Set SESSION_PASSWORD to at least 32 characters') - } - - return getIronSession( - { read: getCookie, write: setCookie }, - { - cookieName: 'app-session', - password, - ttl: 7 * 24 * 60 * 60, - cookieOptions: { - httpOnly: true, - sameSite: 'lax', - secure: process.env.NODE_ENV === 'production', - path: '/', - }, - }, - ) +export function useAppSession() { + return useSession({ + password: 'ChangeThisBeforeShippingToProdOrYouWillBeFired', + }) } diff --git a/examples/solid/start-basic-authjs/package.json b/examples/solid/start-basic-authjs/package.json index 2c910663bd..c7846e6d88 100644 --- a/examples/solid/start-basic-authjs/package.json +++ b/examples/solid/start-basic-authjs/package.json @@ -11,9 +11,9 @@ }, "dependencies": { "@auth/core": "^0.41.1", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/solid-start": "^1.169.6", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-start": "^1.168.47", "solid-js": "^1.9.10", "start-authjs": "^1.0.0", "tailwind-merge": "^3.6.0" diff --git a/examples/solid/start-basic-cloudflare/package.json b/examples/solid/start-basic-cloudflare/package.json index 7ece143f61..b313d2e5d7 100644 --- a/examples/solid/start-basic-cloudflare/package.json +++ b/examples/solid/start-basic-cloudflare/package.json @@ -12,9 +12,9 @@ "postinstall": "WRANGLER_LOG=warn npm run --silent cf-typegen" }, "dependencies": { - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/solid-start": "^1.169.6", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-start": "^1.168.47", "solid-js": "^1.9.10" }, "devDependencies": { diff --git a/examples/solid/start-basic-netlify/package.json b/examples/solid/start-basic-netlify/package.json index 69299cdb79..f94007b553 100644 --- a/examples/solid/start-basic-netlify/package.json +++ b/examples/solid/start-basic-netlify/package.json @@ -9,13 +9,13 @@ "preview": "vite preview" }, "dependencies": { - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/solid-start": "^1.169.6", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-start": "^1.168.47", "solid-js": "^1.9.10" }, "devDependencies": { - "@netlify/vite-plugin-tanstack-start": "^1.3.19", + "@netlify/vite-plugin-tanstack-start": "^1.1.4", "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", "tailwindcss": "^4.2.2", diff --git a/examples/solid/start-basic-nitro/package.json b/examples/solid/start-basic-nitro/package.json index 2c0dc7dad6..c75682d7f0 100644 --- a/examples/solid/start-basic-nitro/package.json +++ b/examples/solid/start-basic-nitro/package.json @@ -9,15 +9,15 @@ "preview": "vite preview" }, "dependencies": { - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/solid-start": "^1.169.6", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-start": "^1.168.47", "solid-js": "^1.9.10" }, "devDependencies": { "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", - "nitro": "^3.0.260903-beta", + "nitro": "^3.0.260311-beta", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/examples/solid/start-basic-solid-query/package.json b/examples/solid/start-basic-solid-query/package.json index ddbb7d8764..31f53a2d22 100644 --- a/examples/solid/start-basic-solid-query/package.json +++ b/examples/solid/start-basic-solid-query/package.json @@ -12,11 +12,11 @@ "dependencies": { "@tanstack/solid-query": "^5.90.9", "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/solid-router-ssr-query": "^1.167.3", - "@tanstack/solid-start": "^1.169.6", - "redaxios": "^0.5.1", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-router-ssr-query": "^1.167.2", + "@tanstack/solid-start": "^1.168.47", + "redaxios": "catalog:", "solid-js": "^1.9.10", "tailwind-merge": "^3.6.0" }, diff --git a/examples/solid/start-basic-static/package.json b/examples/solid/start-basic-static/package.json index 8b639da68a..b258ba660d 100644 --- a/examples/solid/start-basic-static/package.json +++ b/examples/solid/start-basic-static/package.json @@ -10,11 +10,11 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/solid-start": "^1.169.6", - "@tanstack/start-static-server-functions": "^1.167.44", - "redaxios": "^0.5.1", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-start": "^1.168.47", + "@tanstack/start-static-server-functions": "^1.167.32", + "redaxios": "catalog:", "solid-js": "^1.9.10", "tailwind-merge": "^3.6.0" }, diff --git a/examples/solid/start-basic/package.json b/examples/solid/start-basic/package.json index 758815b669..e3f2a4ffea 100644 --- a/examples/solid/start-basic/package.json +++ b/examples/solid/start-basic/package.json @@ -10,17 +10,17 @@ "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/solid-start": "^1.169.6", - "redaxios": "^0.5.1", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-start": "^1.168.47", + "redaxios": "catalog:", "solid-js": "^1.9.10", "tailwind-merge": "^3.6.0" }, "devDependencies": { "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", - "nitro": "^3.0.260903-beta", + "nitro": "^3.0.260311-beta", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/examples/solid/start-bun/package.json b/examples/solid/start-bun/package.json index d1ad9a9563..7b2230725e 100644 --- a/examples/solid/start-bun/package.json +++ b/examples/solid/start-bun/package.json @@ -15,11 +15,11 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-devtools": "^0.7.0", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/solid-router-ssr-query": "^1.167.3", - "@tanstack/solid-start": "^1.169.6", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-router-ssr-query": "^1.167.2", + "@tanstack/solid-start": "^1.168.47", + "@tanstack/router-plugin": "^1.168.35", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2" }, @@ -35,7 +35,7 @@ "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", - "vitest": "^5.0.4", + "vitest": "catalog:", "web-vitals": "^5.1.0" } } diff --git a/examples/solid/start-convex-better-auth/package.json b/examples/solid/start-convex-better-auth/package.json index ea13a1c1e3..f069ea4d19 100644 --- a/examples/solid/start-convex-better-auth/package.json +++ b/examples/solid/start-convex-better-auth/package.json @@ -13,14 +13,14 @@ "dependencies": { "@convex-dev/better-auth": "^0.9.7", "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/solid-start": "^1.169.6", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-start": "^1.168.47", "better-auth": "^1.6.19", "clsx": "^2.1.1", "convex": "^1.28.2", "convex-solidjs": "^0.0.3", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "solid-js": "^1.9.10", "tailwind-merge": "^3.6.0", "tailwindcss": "^4.2.2", diff --git a/examples/solid/start-counter/package.json b/examples/solid/start-counter/package.json index 8b49c516bd..3864669681 100644 --- a/examples/solid/start-counter/package.json +++ b/examples/solid/start-counter/package.json @@ -10,10 +10,10 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/solid-start": "^1.169.6", - "redaxios": "^0.5.1", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-start": "^1.168.47", + "redaxios": "catalog:", "solid-js": "^1.9.10", "tailwind-merge": "^3.6.0", "zod": "^4.4.3" diff --git a/examples/solid/start-i18n-paraglide/package.json b/examples/solid/start-i18n-paraglide/package.json index 076c9b41dc..31a2ea82d6 100644 --- a/examples/solid/start-i18n-paraglide/package.json +++ b/examples/solid/start-i18n-paraglide/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tanstack/solid-devtools": "^0.7.0", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/solid-start": "^1.169.6", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-start": "^1.168.47", "solid-js": "^1.9.10" }, "devDependencies": { @@ -24,16 +24,5 @@ "@tailwindcss/vite": "^4.2.2", "tailwindcss": "^4.2.2", "@inlang/paraglide-js": "^2.4.0" - }, - "nx": { - "targets": { - "build": { - "outputs": [ - "...", - "{projectRoot}/src/paraglide", - "{projectRoot}/project.inlang/cache" - ] - } - } } } diff --git a/examples/solid/start-large/package.json b/examples/solid/start-large/package.json index 83f3589cc2..7bff363511 100644 --- a/examples/solid/start-large/package.json +++ b/examples/solid/start-large/package.json @@ -13,10 +13,10 @@ }, "dependencies": { "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/solid-start": "^1.169.6", - "redaxios": "^0.5.1", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-start": "^1.168.47", + "redaxios": "catalog:", "solid-js": "^1.9.10", "tailwind-merge": "^3.6.0", "valibot": "^1.0.0-beta.15" diff --git a/examples/solid/start-streaming-data-from-server-functions/package.json b/examples/solid/start-streaming-data-from-server-functions/package.json index 83e0719b39..77cb05c028 100644 --- a/examples/solid/start-streaming-data-from-server-functions/package.json +++ b/examples/solid/start-streaming-data-from-server-functions/package.json @@ -10,9 +10,9 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/solid-start": "^1.169.6", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-start": "^1.168.47", "solid-js": "^1.9.10", "zod": "^4.4.3" }, diff --git a/examples/solid/start-supabase-basic/package.json b/examples/solid/start-supabase-basic/package.json index 81ab5cd63c..2e3a3c27ad 100644 --- a/examples/solid/start-supabase-basic/package.json +++ b/examples/solid/start-supabase-basic/package.json @@ -14,11 +14,11 @@ "dependencies": { "@supabase/ssr": "^0.5.2", "@supabase/supabase-js": "^2.48.1", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/solid-start": "^1.169.6", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-start": "^1.168.47", "solid-js": "^1.9.9", - "redaxios": "^0.5.1" + "redaxios": "catalog:" }, "devDependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/examples/solid/start-tailwind-v4/package.json b/examples/solid/start-tailwind-v4/package.json index 94db6ac790..91b4a0202e 100644 --- a/examples/solid/start-tailwind-v4/package.json +++ b/examples/solid/start-tailwind-v4/package.json @@ -10,9 +10,9 @@ "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "@tanstack/solid-start": "^1.169.6", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-start": "^1.168.47", "solid-js": "^1.9.10", "tailwind-merge": "^3.6.0", "zod": "^4.4.3" diff --git a/examples/solid/view-transitions/package.json b/examples/solid/view-transitions/package.json index 2acb2432bf..7e7b3dff11 100644 --- a/examples/solid/view-transitions/package.json +++ b/examples/solid/view-transitions/package.json @@ -10,10 +10,10 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.169.0", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "redaxios": "^0.5.1", + "@tanstack/router-plugin": "^1.168.35", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "redaxios": "catalog:", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", "zod": "^4.4.3" diff --git a/examples/solid/with-framer-motion/package.json b/examples/solid/with-framer-motion/package.json index 449d8a3927..c633f6ad83 100644 --- a/examples/solid/with-framer-motion/package.json +++ b/examples/solid/with-framer-motion/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", - "redaxios": "^0.5.1", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", + "redaxios": "catalog:", "solid-js": "^1.9.10", "solid-motionone": "^1.0.4", "tailwindcss": "^4.2.2", diff --git a/examples/solid/with-trpc/package.json b/examples/solid/with-trpc/package.json index 46d33436db..f0c39079c9 100644 --- a/examples/solid/with-trpc/package.json +++ b/examples/solid/with-trpc/package.json @@ -11,13 +11,13 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.169.0", - "@tanstack/solid-router": "^1.170.43", - "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.168.35", + "@tanstack/solid-router": "^1.170.30", + "@tanstack/solid-router-devtools": "^1.167.1", "@trpc/client": "^11.4.3", "@trpc/server": "^11.4.3", "express": "^5.2.1", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", "zod": "^4.4.3" diff --git a/examples/vue/basic-file-based-jsx/package.json b/examples/vue/basic-file-based-jsx/package.json index 9cc36a6991..2213d9ac21 100644 --- a/examples/vue/basic-file-based-jsx/package.json +++ b/examples/vue/basic-file-based-jsx/package.json @@ -10,10 +10,10 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.169.0", - "@tanstack/vue-router": "^1.170.42", - "@tanstack/vue-router-devtools": "^1.167.3", - "redaxios": "^0.5.1", + "@tanstack/router-plugin": "^1.168.35", + "@tanstack/vue-router": "^1.170.29", + "@tanstack/vue-router-devtools": "^1.167.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "vue": "^3.5.16", "zod": "^4.4.3" diff --git a/examples/vue/basic-file-based-jsx/src/posts.tsx b/examples/vue/basic-file-based-jsx/src/posts.tsx index f7a1941605..1b4c92b41d 100644 --- a/examples/vue/basic-file-based-jsx/src/posts.tsx +++ b/examples/vue/basic-file-based-jsx/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/examples/vue/basic-file-based-jsx/src/routeTree.gen.ts b/examples/vue/basic-file-based-jsx/src/routeTree.gen.ts index 5922c5f7b1..3922025c82 100644 --- a/examples/vue/basic-file-based-jsx/src/routeTree.gen.ts +++ b/examples/vue/basic-file-based-jsx/src/routeTree.gen.ts @@ -364,7 +364,7 @@ declare module '@tanstack/vue-router' { '/(group)/_layout': { id: '/(group)/_layout' path: '' - fullPath: '/' + fullPath: '' preLoaderRoute: typeof groupLayoutRouteImport parentRoute: typeof rootRouteImport } diff --git a/examples/vue/basic-file-based-jsx/src/routes/(another-group)/onlyrouteinside.tsx b/examples/vue/basic-file-based-jsx/src/routes/(another-group)/onlyrouteinside.tsx index e475111e40..727c1b4d94 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/(another-group)/onlyrouteinside.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/(another-group)/onlyrouteinside.tsx @@ -1,32 +1,27 @@ import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' -import { defineComponent } from 'vue' import { z } from 'zod' -const OnlyRouteInsideComponent = defineComponent({ - setup() { - const searchViaHook = useSearch({ - from: '/(another-group)/onlyrouteinside', - }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return () => ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) - export const Route = createFileRoute('/(another-group)/onlyrouteinside')({ validateSearch: z.object({ hello: z.string().optional() }), component: OnlyRouteInsideComponent, }) const routeApi = getRouteApi('/(another-group)/onlyrouteinside') + +function OnlyRouteInsideComponent() { + const searchViaHook = useSearch({ from: '/(another-group)/onlyrouteinside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) +} diff --git a/examples/vue/basic-file-based-jsx/src/routes/(group)/_layout.insidelayout.tsx b/examples/vue/basic-file-based-jsx/src/routes/(group)/_layout.insidelayout.tsx index 869e536811..4b239f3ef4 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/(group)/_layout.insidelayout.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/(group)/_layout.insidelayout.tsx @@ -1,30 +1,27 @@ import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' -import { defineComponent } from 'vue' import { z } from 'zod' -const InsideLayoutComponent = defineComponent({ - setup() { - const searchViaHook = useSearch({ from: '/(group)/_layout/insidelayout' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return () => ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) - export const Route = createFileRoute('/(group)/_layout/insidelayout')({ validateSearch: z.object({ hello: z.string().optional() }), component: InsideLayoutComponent, }) const routeApi = getRouteApi('/(group)/_layout/insidelayout') + +function InsideLayoutComponent() { + const searchViaHook = useSearch({ from: '/(group)/_layout/insidelayout' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) +} diff --git a/examples/vue/basic-file-based-jsx/src/routes/(group)/inside.tsx b/examples/vue/basic-file-based-jsx/src/routes/(group)/inside.tsx index 4a0caa8f8d..f12ca517d3 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/(group)/inside.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/(group)/inside.tsx @@ -1,30 +1,27 @@ import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' -import { defineComponent } from 'vue' import { z } from 'zod' -const InsideComponent = defineComponent({ - setup() { - const searchViaHook = useSearch({ from: '/(group)/inside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return () => ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) - export const Route = createFileRoute('/(group)/inside')({ validateSearch: z.object({ hello: z.string().optional() }), component: InsideComponent, }) const routeApi = getRouteApi('/(group)/inside') + +function InsideComponent() { + const searchViaHook = useSearch({ from: '/(group)/inside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) +} diff --git a/examples/vue/basic-file-based-jsx/src/routes/(group)/lazyinside.tsx b/examples/vue/basic-file-based-jsx/src/routes/(group)/lazyinside.tsx index fdae632aee..05b34eb201 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/(group)/lazyinside.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/(group)/lazyinside.tsx @@ -1,30 +1,27 @@ import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' -import { defineComponent } from 'vue' import { z } from 'zod' -const LazyInsideComponent = defineComponent({ - setup() { - const searchViaHook = useSearch({ from: '/(group)/lazyinside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return () => ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) - export const Route = createFileRoute('/(group)/lazyinside')({ validateSearch: z.object({ hello: z.string().optional() }), component: LazyInsideComponent, }) const routeApi = getRouteApi('/(group)/lazyinside') + +function LazyInsideComponent() { + const searchViaHook = useSearch({ from: '/(group)/lazyinside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) +} diff --git a/examples/vue/basic-file-based-jsx/src/routes/(group)/subfolder/inside.tsx b/examples/vue/basic-file-based-jsx/src/routes/(group)/subfolder/inside.tsx index 8c7222ee70..317c766186 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/(group)/subfolder/inside.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/(group)/subfolder/inside.tsx @@ -1,30 +1,27 @@ import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' -import { defineComponent } from 'vue' import { z } from 'zod' -const SubfolderInsideComponent = defineComponent({ - setup() { - const searchViaHook = useSearch({ from: '/(group)/subfolder/inside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return () => ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) - }, -}) - export const Route = createFileRoute('/(group)/subfolder/inside')({ validateSearch: z.object({ hello: z.string().optional() }), component: SubfolderInsideComponent, }) const routeApi = getRouteApi('/(group)/subfolder/inside') + +function SubfolderInsideComponent() { + const searchViaHook = useSearch({ from: '/(group)/subfolder/inside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) +} diff --git a/examples/vue/basic-file-based-jsx/src/routes/__root.tsx b/examples/vue/basic-file-based-jsx/src/routes/__root.tsx index adcc3acbd7..59c9e6fa48 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/__root.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/__root.tsx @@ -8,100 +8,97 @@ import { useRouterState, } from '@tanstack/vue-router' import { TanStackRouterDevtools } from '@tanstack/vue-router-devtools' -import { defineComponent } from 'vue' import NotFoundComponent from '../components/NotFoundComponent.vue' -const RootComponent = defineComponent({ - setup() { - const router = useRouter() - const canGoBack = useCanGoBack() - // test useRouterState doesn't crash client side navigation - const _state = useRouterState() - - return () => ( - <> - -
- - - Home - - - Posts - - - Layout - - - Only Route Inside Group - - - Inside Group - - - Inside Subfolder Inside Group - - - Inside Group Inside Layout - - - Lazy Inside Group - - - unicode path - - - This Route Does Not Exist - -
-
- - - - ) - }, -}) - export const Route = createRootRoute({ component: RootComponent, notFoundComponent: NotFoundComponent, }) + +function RootComponent() { + const router = useRouter() + const canGoBack = useCanGoBack() + // test useRouterState doesn't crash client side navigation + const _state = useRouterState() + + return ( + <> + +
+ + + Home + + + Posts + + + Layout + + + Only Route Inside Group + + + Inside Group + + + Inside Subfolder Inside Group + + + Inside Group Inside Layout + + + Lazy Inside Group + + + unicode path + + + This Route Does Not Exist + +
+
+ + + + ) +} diff --git a/examples/vue/basic-file-based-jsx/src/routes/posts.$postId.tsx b/examples/vue/basic-file-based-jsx/src/routes/posts.$postId.tsx index bc1dbfbbd0..15d17387c8 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/posts.$postId.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/posts.$postId.tsx @@ -1,27 +1,24 @@ import { createFileRoute } from '@tanstack/vue-router' -import { defineComponent } from 'vue' import PostErrorComponent from '../components/PostErrorComponent.vue' import { fetchPost } from '../posts' import type { PostType } from '../posts' -const PostComponent = defineComponent({ - setup() { - const post = Route.useLoaderData() - - return () => ( -
-

- {(post.value as PostType).title} -

-
{(post.value as PostType).body}
-
- ) - }, -}) - export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost(postId), component: PostComponent, errorComponent: PostErrorComponent, notFoundComponent: () =>

Post not found

, }) + +function PostComponent() { + const post = Route.useLoaderData() + + return ( +
+

+ {(post.value as PostType).title} +

+
{(post.value as PostType).body}
+
+ ) +} diff --git a/examples/vue/basic-file-based-jsx/src/routes/posts.tsx b/examples/vue/basic-file-based-jsx/src/routes/posts.tsx index 522988e52b..ae580dfc02 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/posts.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/posts.tsx @@ -1,38 +1,7 @@ import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' -import { defineComponent } from 'vue' import { fetchPosts } from '../posts' import type { PostType } from '../posts' -const PostsComponent = defineComponent({ - setup() { - const posts = Route.useLoaderData() - - return () => ( -
-
    - {[ - ...(posts.value as Array), - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ))} -
-
- -
- ) - }, -}) - export const Route = createFileRoute('/posts')({ head: () => ({ meta: [ @@ -44,3 +13,31 @@ export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) + +function PostsComponent() { + const posts = Route.useLoaderData() + + return ( +
+
    + {[ + ...(posts.value as Array), + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ))} +
+
+ +
+ ) +} diff --git a/examples/vue/basic-file-based-jsx/src/routes/posts_.$postId.edit.tsx b/examples/vue/basic-file-based-jsx/src/routes/posts_.$postId.edit.tsx index ad20bcdf97..57963c6b64 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/posts_.$postId.edit.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/posts_.$postId.edit.tsx @@ -1,28 +1,23 @@ import { createFileRoute, getRouteApi, useParams } from '@tanstack/vue-router' -import { defineComponent } from 'vue' - -const PostEditComponent = defineComponent({ - setup() { - const paramsViaApi = api.useParams() - const paramsViaHook = useParams({ from: '/posts_/$postId/edit' }) - const paramsViaRouteHook = api.useParams() - - return () => ( -
-
{paramsViaHook.value.postId}
-
- {paramsViaRouteHook.value.postId} -
-
- {paramsViaApi.value.postId} -
-
- ) - }, -}) export const Route = createFileRoute('/posts_/$postId/edit')({ component: PostEditComponent, }) const api = getRouteApi('/posts_/$postId/edit') + +function PostEditComponent() { + const paramsViaApi = api.useParams() + const paramsViaHook = useParams({ from: '/posts_/$postId/edit' }) + const paramsViaRouteHook = api.useParams() + + return ( +
+
{paramsViaHook.value.postId}
+
+ {paramsViaRouteHook.value.postId} +
+
{paramsViaApi.value.postId}
+
+ ) +} diff --git a/examples/vue/basic-file-based-sfc/package.json b/examples/vue/basic-file-based-sfc/package.json index 87ab2c332b..5b0333c72b 100644 --- a/examples/vue/basic-file-based-sfc/package.json +++ b/examples/vue/basic-file-based-sfc/package.json @@ -10,10 +10,10 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.169.0", - "@tanstack/vue-router": "^1.170.42", - "@tanstack/vue-router-devtools": "^1.167.3", - "redaxios": "^0.5.1", + "@tanstack/router-plugin": "^1.168.35", + "@tanstack/vue-router": "^1.170.29", + "@tanstack/vue-router-devtools": "^1.167.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "vue": "^3.5.16", "zod": "^4.4.3" diff --git a/examples/vue/basic-file-based-sfc/src/posts.ts b/examples/vue/basic-file-based-sfc/src/posts.ts index f7a1941605..1b4c92b41d 100644 --- a/examples/vue/basic-file-based-sfc/src/posts.ts +++ b/examples/vue/basic-file-based-sfc/src/posts.ts @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/examples/vue/basic-file-based-sfc/src/routeTree.gen.ts b/examples/vue/basic-file-based-sfc/src/routeTree.gen.ts index 0bfdddab3d..09d62b0706 100644 --- a/examples/vue/basic-file-based-sfc/src/routeTree.gen.ts +++ b/examples/vue/basic-file-based-sfc/src/routeTree.gen.ts @@ -454,7 +454,7 @@ declare module '@tanstack/vue-router' { '/(group)/_layout': { id: '/(group)/_layout' path: '' - fullPath: '/' + fullPath: '' preLoaderRoute: typeof groupLayoutRouteImport parentRoute: typeof rootRouteImport } diff --git a/examples/vue/basic/package.json b/examples/vue/basic/package.json index af74afff3a..40863a9918 100644 --- a/examples/vue/basic/package.json +++ b/examples/vue/basic/package.json @@ -9,9 +9,9 @@ "start": "vite" }, "dependencies": { - "@tanstack/vue-router": "^1.170.42", - "@tanstack/vue-router-devtools": "^1.167.3", - "redaxios": "^0.5.1", + "@tanstack/vue-router": "^1.170.29", + "@tanstack/vue-router-devtools": "^1.167.1", + "redaxios": "catalog:", "vue": "^3.5.13", "tailwindcss": "4.1.18" }, diff --git a/examples/vue/basic/src/main.tsx b/examples/vue/basic/src/main.tsx index 09878913a8..dc12871db0 100644 --- a/examples/vue/basic/src/main.tsx +++ b/examples/vue/basic/src/main.tsx @@ -1,4 +1,4 @@ -import { createApp, defineComponent } from 'vue' +import { createApp } from 'vue' import { ErrorComponent, Link, @@ -102,20 +102,6 @@ function PostsIndexComponent() { return
Select a post.
} -const PostComponent = defineComponent({ - setup() { - const post = postRoute.useLoaderData() - - return () => ( -
-

{post.value.title}

-
-
{post.value.body}
-
- ) - }, -}) - const postRoute = createRoute({ getParentRoute: () => postsLayoutRoute, path: '$postId', @@ -132,6 +118,18 @@ function PostErrorComponent({ error }: ErrorComponentProps) { return } +function PostComponent() { + const post = postRoute.useLoaderData() + + return ( +
+

{post.value.title}

+
+
{post.value.body}
+
+ ) +} + const pathlessLayoutRoute = createRoute({ getParentRoute: () => rootRoute, id: '_pathlessLayout', diff --git a/examples/vue/basic/src/posts.lazy.tsx b/examples/vue/basic/src/posts.lazy.tsx index 8602de045f..1fd64723e5 100644 --- a/examples/vue/basic/src/posts.lazy.tsx +++ b/examples/vue/basic/src/posts.lazy.tsx @@ -1,39 +1,36 @@ import { Link, Outlet, createLazyRoute } from '@tanstack/vue-router' -import { defineComponent } from 'vue' - -const PostsLayoutComponent = defineComponent({ - setup() { - const posts = Route.useLoaderData() - - return () => ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
- -
- ) - }, -}) export const Route = createLazyRoute('/posts')({ component: PostsLayoutComponent, }) + +function PostsLayoutComponent() { + const posts = Route.useLoaderData() + + return ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+ +
+ ) +} diff --git a/labeler-config.yml b/labeler-config.yml index 9da92bf7ff..c1ad49328e 100644 --- a/labeler-config.yml +++ b/labeler-config.yml @@ -10,6 +10,9 @@ 'package: history': - changed-files: - any-glob-to-any-file: 'packages/history/**/*' +'package: nitro-v2-vite-plugin': + - changed-files: + - any-glob-to-any-file: 'packages/nitro-v2-vite-plugin/**/*' 'package: react-router': - changed-files: - any-glob-to-any-file: 'packages/react-router/**/*' diff --git a/nx.json b/nx.json index b7df8b2c09..e521988aec 100644 --- a/nx.json +++ b/nx.json @@ -1,7 +1,6 @@ { "$schema": "./node_modules/nx/schemas/nx-schema.json", "defaultBase": "main", - "bust": "nx24-exclusive-e2e-16-medium-baseline-2026-10-25-05", "nxCloudId": "6442f7de8226a6291646a813", "useInferencePlugins": false, "parallel": 5, @@ -11,10 +10,7 @@ "namedInputs": { "sharedGlobals": [ "{workspaceRoot}/.npmrc", - "{workspaceRoot}/nx.json", - "{workspaceRoot}/.github/workflows/pr.yml", - "{workspaceRoot}/.nx/ci-config.yaml", - "{workspaceRoot}/.nx/workflows/ultracache-config.yaml", + "{workspaceRoot}/.nx/workflows/sandboxing-config.yaml", "{workspaceRoot}/.nvmrc", "{workspaceRoot}/package.json", "{workspaceRoot}/tsconfig.json" @@ -25,11 +21,6 @@ "transitive": true } ], - "streamingSsrTests": [ - "{workspaceRoot}/e2e/streaming-ssr-assertions.ts", - "{workspaceRoot}/e2e/streaming-ssr-fixtures/**/*", - "{workspaceRoot}/e2e/streaming-ssr-specs/**/*" - ], "default": [ "sharedGlobals", "{projectRoot}/**/*", @@ -45,7 +36,7 @@ "targetDefaults": { "test:docs": { "cache": true, - "inputs": ["sharedGlobals", "{workspaceRoot}/docs/**/*"] + "inputs": ["{workspaceRoot}/docs/**/*"] }, "test:eslint": { "cache": true, @@ -71,27 +62,27 @@ "test:e2e": { "cache": true, "dependsOn": ["^build", "test:e2e--*"], - "inputs": ["buildProduction", "^production", "dependentTaskOutputs"], - "outputs": ["{projectRoot}/dist", "{projectRoot}/test-results"], - "parallelism": false + "inputs": ["default", "^production", "dependentTaskOutputs"], + "outputs": [ + "{projectRoot}/dist", + "{projectRoot}/port-*.txt", + "{projectRoot}/test-results" + ] }, "test:e2e:nitro": { "cache": true, "dependsOn": ["^build"], - "inputs": ["default", "^production"], - "parallelism": false + "inputs": ["default", "^production"] }, "test:e2e:basepath": { "cache": true, "dependsOn": ["^build"], - "inputs": ["default", "^production"], - "parallelism": false + "inputs": ["default", "^production"] }, "test:e2e:preview": { "cache": true, "dependsOn": ["^build"], - "inputs": ["default", "^production"], - "parallelism": false + "inputs": ["default", "^production"] }, "test:types": { "cache": true, @@ -103,21 +94,6 @@ "dependentTaskOutputs" ] }, - "test:types:client": { - "cache": true, - "inputs": [ - "default", - "^production", - "{workspaceRoot}/benchmarks/client-nav/*.{ts,json}", - "{workspaceRoot}/benchmarks/client-nav/scenarios/*.ts", - "{workspaceRoot}/benchmarks/client-nav/scenarios/*/*.ts", - "{workspaceRoot}/benchmarks/memory/*.ts", - "{workspaceRoot}/benchmarks/memory/client/*.{ts,json}", - "{workspaceRoot}/benchmarks/memory/client/scenarios/*/*.ts", - "{workspaceRoot}/benchmarks/cpu-simulation.ts", - "dependentTaskOutputs" - ] - }, "test:types:ssr": { "cache": true, "dependsOn": ["^build", "build"], @@ -126,10 +102,6 @@ "^production", "{workspaceRoot}/benchmarks/ssr/bench-utils.ts", "{workspaceRoot}/benchmarks/cpu-simulation.ts", - "{workspaceRoot}/benchmarks/ssr/scenarios/*/*.ts", - "{workspaceRoot}/benchmarks/memory/*.ts", - "{workspaceRoot}/benchmarks/memory/server/*.ts", - "{workspaceRoot}/benchmarks/memory/server/scenarios/*/*.ts", "dependentTaskOutputs" ] }, @@ -149,9 +121,6 @@ "cache": true, "dependsOn": ["build"], "inputs": ["buildProduction", "dependentTaskOutputs"] - }, - "test:e2e*": { - "parallelism": false } }, "plugins": [ diff --git a/package.json b/package.json index 3ef11b1969..a6dd44cdb4 100644 --- a/package.json +++ b/package.json @@ -5,24 +5,24 @@ "type": "git", "url": "git+https://github.com/TanStack/router.git" }, - "packageManager": "pnpm@12.18.0", + "packageManager": "pnpm@11.21.0", "engines": { - "pnpm": ">=12.18.0" + "pnpm": ">=11.21.0" }, "type": "module", "scripts": { "cleanNodeModules": "pnpm -r exec rm -rf node_modules", "clean": "pnpm --filter \"./packages/**\" run clean", "test": "pnpm run test:ci", - "test:pr": "nx affected --targets=test:eslint,test:unit,test:integration,test:e2e,test:types,test:build,build", - "test:ci": "nx run-many --targets=test:eslint,test:unit,test:integration,test:e2e,test:types,test:build,build", + "test:pr": "nx affected --targets=test:eslint,test:unit,test:e2e,test:types,test:build,build", + "test:ci": "nx run-many --targets=test:eslint,test:unit,test:e2e,test:types,test:build,build", "test:eslint": "nx affected --target=test:eslint --exclude=examples/**,e2e/**", "test:unit": "nx affected --target=test:unit --exclude=examples/**,e2e/**", "test:unit:dev": "pnpm run test:unit && nx watch --all -- pnpm run test:unit", "test:build": "nx affected --target=test:build --exclude=examples/**", "test:types": "nx affected --target=test:types --exclude=examples/**", "test:e2e": "nx run-many --target=test:e2e", - "benchmark:bundle-size": "node scripts/benchmarks/bundle-size/build.mjs", + "benchmark:bundle-size": "nx run @benchmarks/bundle-size:build", "benchmark:bundle-size:run": "node scripts/benchmarks/bundle-size/run.mjs", "benchmark:bundle-size:query": "node scripts/benchmarks/bundle-size/query.mjs", "benchmark:bundle-size:diff": "node scripts/benchmarks/bundle-size/diff.mjs", @@ -45,8 +45,7 @@ "format": "prettier --experimental-cli --ignore-unknown '**/*' --write", "changeset": "changeset", "changeset:publish": "changeset publish", - "changeset:version": "changeset version && pnpm run update:example-deps && pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile && pnpm format", - "update:example-deps": "node scripts/update-example-deps.mjs", + "changeset:version": "changeset version && node scripts/update-example-deps.mjs && pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile && pnpm format", "gpt-generate": "node gpt/generate.js", "set-ts-version": "node scripts/set-ts-version.js", "labeler-generate": "node scripts/generate-labeler-config.ts", @@ -65,7 +64,7 @@ "devDependencies": { "@changesets/changelog-github": "^0.7.0", "@changesets/cli": "^2.30.0", - "@nx/devkit": "24.0.0", + "@nx/devkit": "22.7.5", "@playwright/test": "catalog:", "@swc-node/register": "^1.11.1", "@tanstack/eslint-config": "0.4.0", @@ -73,7 +72,7 @@ "eslint": "catalog:", "eslint-plugin-unused-imports": "^4.1.4", "markdown-link-extractor": "^4.0.3", - "nx": "24.0.0", + "nx": "22.7.5", "prettier": "^3.8.0", "tinyglobby": "^0.2.15", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/packages/AGENTS.md b/packages/AGENTS.md deleted file mode 100644 index 0c63c3a15c..0000000000 --- a/packages/AGENTS.md +++ /dev/null @@ -1,16 +0,0 @@ -# Packages - -- Route generation/code splitting live in `router-generator`/`router-plugin`; Start build transforms live in `start-plugin-core`. - -## Router bindings - -- Navigation/render identity is more than href or route membership: same-href navigations can have different history keys, and suspended renders must acknowledge only their own match publication. Preserve those identity checks when optimizing stores or render notifications. -- In navigation params/search, an explicit `undefined` can clear an inherited value; an absent key can inherit it. Preserve that distinction when comparing or memoizing options; React's `useValueStable` uses `deepEqual` with `ignoreUndefined: false`. - -## Tests - -- Inspect test commands: several `test:unit` scripts immediately exit or only echo a message. For these packages, validate behavior in the shared core or consuming e2e app; a successful placeholder target provides no unit coverage. -- For `*-router-ssr-query` changes, run `router-ssr-query-core` unit tests and the affected framework's `e2e/-start/query-integration` tests. The framework wrapper unit targets currently exit without running tests. -- For single-command Vitest targets, append filters after `--`, e.g. `-- tests/link.test.tsx -t "preloading"`. -- `solid-router` and `router-generator` chain two Vitest commands in `test:unit`. Trailing file/name/update arguments reach only the final command. Run the full target for verification: Solid needs browser and server suites; the generator needs fixture generation followed by typechecking. -- For public type changes, add `*.test-d.*` inference regressions and run both unit and type targets. React/Solid Router's TypeScript compiler matrix checks `src`; Vitest runs their inference tests. For changes to inference cost, follow the [type-safety performance guidance](../docs/router/guide/type-safety.md#performance-recommendations); `test:perf` measures runtime, not compiler cost. diff --git a/packages/arktype-adapter/package.json b/packages/arktype-adapter/package.json index ceca3fad73..7418d5e1c5 100644 --- a/packages/arktype-adapter/package.json +++ b/packages/arktype-adapter/package.json @@ -66,8 +66,8 @@ "devDependencies": { "@tanstack/react-router": "workspace:*", "arktype": "^2.1.7", - "@testing-library/jest-dom": "catalog:", - "@testing-library/react": "catalog:", + "@testing-library/jest-dom": "^6.6.3", + "@testing-library/react": "^16.2.0", "react": "catalog:", "react-dom": "catalog:", "vite": "*", diff --git a/packages/arktype-adapter/tests/index.test.tsx b/packages/arktype-adapter/tests/index.test.tsx index ce6eb74756..a99ecda9c4 100644 --- a/packages/arktype-adapter/tests/index.test.tsx +++ b/packages/arktype-adapter/tests/index.test.tsx @@ -9,6 +9,7 @@ import { cleanup, fireEvent, render, screen } from '@testing-library/react' import { afterEach, expect, test, vi } from 'vitest' import { type } from 'arktype' import { arkTypeValidator } from '../src' +import '@testing-library/jest-dom/vitest' afterEach(() => { vi.resetAllMocks() diff --git a/packages/arktype-adapter/tests/jest-dom.setup.ts b/packages/arktype-adapter/tests/jest-dom.setup.ts deleted file mode 100644 index 8f7cbf15be..0000000000 --- a/packages/arktype-adapter/tests/jest-dom.setup.ts +++ /dev/null @@ -1,18 +0,0 @@ -import * as jestDomMatchers from '@testing-library/jest-dom/matchers' -import { expect } from 'vitest' -import type { TestingLibraryMatchers } from '@testing-library/jest-dom/matchers' - -// Workaround for Vitest 5: remove once testing-library/jest-dom#742 is merged -// and released, and go back to `import '@testing-library/jest-dom/vitest'`. -// That entry imports `vitest` from its own install location, which can resolve -// a different Vitest copy than the one running these tests, and its types -// augment Vitest 4's `Assertion` instead of Vitest 5's `Matchers`. -// Keep `jest-dom` in this file name: vite-plugin-solid only skips injecting -// `@testing-library/jest-dom/vitest` when a setup file path contains it. -expect.extend(jestDomMatchers) - -declare module 'vitest' { - // Type parameter names must match Vitest's declaration for the interfaces to merge. - // eslint-disable-next-line @typescript-eslint/naming-convention - interface Matchers extends TestingLibraryMatchers {} -} diff --git a/packages/arktype-adapter/vite.config.ts b/packages/arktype-adapter/vite.config.ts index 8d553e0a59..8c8c0c519f 100644 --- a/packages/arktype-adapter/vite.config.ts +++ b/packages/arktype-adapter/vite.config.ts @@ -9,7 +9,6 @@ const config = defineConfig({ watch: false, environment: 'jsdom', typecheck: { enabled: true }, - setupFiles: ['./tests/jest-dom.setup.ts'], }, }) diff --git a/packages/eslint-plugin-router/package.json b/packages/eslint-plugin-router/package.json index 9be54c220e..6490398d8c 100644 --- a/packages/eslint-plugin-router/package.json +++ b/packages/eslint-plugin-router/package.json @@ -56,7 +56,7 @@ }, "devDependencies": { "@typescript-eslint/rule-tester": "^8.23.0", - "combinate": "catalog:", + "combinate": "^1.1.11", "eslint": "^9.22.0", "vite": "*", "@tanstack/vite-config": "catalog:", @@ -67,15 +67,5 @@ }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0" - }, - "nx": { - "targets": { - "build": { - "inputs": [ - "...", - "{workspaceRoot}/eslint.config.js" - ] - } - } } } diff --git a/packages/eslint-plugin-start/package.json b/packages/eslint-plugin-start/package.json index 803264ed10..b90642f1c4 100644 --- a/packages/eslint-plugin-start/package.json +++ b/packages/eslint-plugin-start/package.json @@ -68,15 +68,5 @@ "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.7.0" - }, - "nx": { - "targets": { - "build": { - "inputs": [ - "...", - "{workspaceRoot}/eslint.config.js" - ] - } - } } } diff --git a/packages/history/AGENTS.md b/packages/history/AGENTS.md deleted file mode 100644 index 509da6a4ec..0000000000 --- a/packages/history/AGENTS.md +++ /dev/null @@ -1,3 +0,0 @@ -# History - -Accepted browser push/replace operations update the in-memory location immediately and batch native writes into a microtask. Preserve coalescing: the latest href/state wins, but any queued push wins over replaces. Use `history.flush()` when native browser state must be current; verify subsequent updates still flush afterward in `tests/createBrowserHistory.test.ts`. diff --git a/packages/history/CHANGELOG.md b/packages/history/CHANGELOG.md index ca3341088c..8d61013c84 100644 --- a/packages/history/CHANGELOG.md +++ b/packages/history/CHANGELOG.md @@ -1,57 +1,5 @@ # @tanstack/history -## 1.162.5 - -### Patch Changes - -- [#8605](https://github.com/TanStack/router/pull/8605) [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2) - Drop a duplicated current-location flag and a redundant `createHref` wrapper. - -- [#8605](https://github.com/TanStack/router/pull/8605) [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2) - Avoid temporary arrays when reading hash-history locations. - -- [#8605](https://github.com/TanStack/router/pull/8605) [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2) - Keep a leading query or fragment out of the parsed pathname, so hash-history URLs like `/#?x=1` no longer repeat the query in the router location. - -- [#8602](https://github.com/TanStack/router/pull/8602) [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb) - Fixed Link destinations that resolve to a route mask are now reused across navigations instead of being rebuilt every time. A mounted Link now follows changes to its `href` and `reloadDocument` props, and React Links no longer each subscribe to a hydration flag. - -- [#8605](https://github.com/TanStack/router/pull/8605) [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2) - Use `slice` instead of `substring` where the bounds are always ordered and non-negative. - -## 1.162.4 - -### Patch Changes - -- [#8359](https://github.com/TanStack/router/pull/8359) [`8fff7fa`](https://github.com/TanStack/router/commit/8fff7fa1f2e6f061916b0bf5e0ec486b2e732f94) - Normalize memory history hrefs consistently with browser and server history, including protocol-relative paths and control characters. - -- [#8352](https://github.com/TanStack/router/pull/8352) [`f021f6d`](https://github.com/TanStack/router/commit/f021f6d1c6dce6c9b54d70766f1d636d8fd9e184) - Avoid temporary arrays when replacing forward memory-history entries. - -- [#8349](https://github.com/TanStack/router/pull/8349) [`ae68535`](https://github.com/TanStack/router/commit/ae68535929043607d4ee9438f8ae401f3a064862) - Avoid generating unused history keys for locations with existing state. - -- [#8354](https://github.com/TanStack/router/pull/8354) [`9872d2a`](https://github.com/TanStack/router/commit/9872d2ac39fc05f4ef6566c0b421f71ceb115244) - Use lightweight request history for SSR and make server navigation a no-op. Use redirect() to issue HTTP redirects. Server hrefs use the same normalization as browser history to handle protocol-relative URLs and control characters. - -## 1.162.3 - -### Patch Changes - -- [#8308](https://github.com/TanStack/router/pull/8308) [`9c1871c`](https://github.com/TanStack/router/commit/9c1871ccc88bc1157186b8b460941a304ec740b8) - Validate navigation and redirect destinations, keep ambiguous relative URLs on the current origin, and constrain prerender requests and output paths. Prevent redirect headers from appearing in serialized server function response bodies. - - Preserve native form HTTP redirects, route error handling and masks for document redirects, and per-navigation destinations for shared loader redirects. Avoid redundant origin parsing and reduce link styling and server-rendering work. Configured origins must already be normalized. - - Keep blocked-link inactive props consistent during React hydration, honor explicit redirect Location headers before checking route options, and refresh Vue link state when destinations become internal. Reuse the protocol-relative URL check while parsing redirect schemes once. - - Reduce React link bundle size by sharing pathname comparisons, state-prop selection, and element creation. - - Share normalized pathname comparisons in Solid and Vue links to reduce bundle size. - -- [#8287](https://github.com/TanStack/router/pull/8287) [`0654c0a`](https://github.com/TanStack/router/commit/0654c0a1a427db24d9af13c1d6ad1217a588c0c9) - Use full-document navigation when an output rewrite produces a cross-origin destination, including the public URL of a route mask. - - Respect registered history blockers during document navigation, passing history locations and the requested push or replace action. - -## 1.162.2 - -### Patch Changes - -- [#8264](https://github.com/TanStack/router/pull/8264) [`9035abc`](https://github.com/TanStack/router/commit/9035abc41163d83409ef582f7743a3c7be57dd93) - Respect `ignoreBlocker` during `go()` navigation, including document unload warnings. Preserve beforeunload warnings during back and forward navigation unless `ignoreBlocker` is requested, and clear the bypass after same-document traversal so later document navigation still warns about unsaved changes. - - Restore the original browser history entry when forward or multi-entry navigation is blocked. - ## 1.162.1 ### Patch Changes diff --git a/packages/history/package.json b/packages/history/package.json index d09c710d2f..bbe5a589cf 100644 --- a/packages/history/package.json +++ b/packages/history/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/history", - "version": "1.162.5", + "version": "1.162.1", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", diff --git a/packages/history/src/index.ts b/packages/history/src/index.ts index d2f80581b9..063174c732 100644 --- a/packages/history/src/index.ts +++ b/packages/history/src/index.ts @@ -36,9 +36,7 @@ export interface RouterHistory { flush: () => void destroy: () => void notify: (action: SubscriberHistoryAction) => void - _getBlockers: () => Array _ignoreSubscribers?: boolean - _ignoreNextBeforeUnload?: (href: string) => void } export interface HistoryLocation extends ParsedPath { @@ -98,40 +96,12 @@ const stateIndexKey = '__TSR_index' const popStateEvent = 'popstate' const beforeUnloadEvent = 'beforeunload' -/** - * Turn protocol-relative inputs such as "//evil.example" into paths - * such as "/evil.example", keeping navigation on the current origin. - * - * For HTTP(S) URLs, WHATWG parsing ignores leading C0 controls and spaces, - * removes tabs/newlines, and treats backslashes as slashes, so inputs like - * "/\evil.example" also need normalization. This only allocates when those - * rules would make the input protocol-relative. - */ -// eslint-disable-next-line no-control-regex -const protocolRelativePrefix = /^[\x00-\x20]*(?:[\\/][\t\n\r]*){2,}/ - -export function normalizeProtocolRelative(url: string): string { - const match = protocolRelativePrefix.exec(url) - return match ? '/' + url.slice(match[0].length) : url -} - -function normalizeHref(href: string): string { - // eslint-disable-next-line no-control-regex - if (/[\x00-\x1f\x7f]/.test(href)) { - // eslint-disable-next-line no-control-regex - href = href.replace(/[\x00-\x1f\x7f]/g, (character) => - '\t\n\r'.includes(character) ? '' : encodeURIComponent(character), - ) - } - return normalizeProtocolRelative(href) -} - export function createHistory(opts: { getLocation: () => HistoryLocation getLength: () => number pushState: (path: string, state: any) => void replaceState: (path: string, state: any) => void - go: (n: number, ignoreBlocker: boolean) => void + go: (n: number) => void back: (ignoreBlocker: boolean) => void forward: (ignoreBlocker: boolean) => void createHref: (path: string) => string @@ -156,21 +126,27 @@ export function createHistory(opts: { else location = opts.getLocation() } - const tryNavigation = async (args: TryNavigateArgs) => { - const blockers = args.navigateOpts?.ignoreBlocker - ? undefined - : opts.getBlockers?.() - if ( - typeof document !== 'undefined' && - blockers?.length && - (args.type === 'PUSH' || args.type === 'REPLACE') - ) { + const tryNavigation = async ({ + task, + navigateOpts, + ...actionInfo + }: TryNavigateArgs) => { + const ignoreBlocker = navigateOpts?.ignoreBlocker ?? false + if (ignoreBlocker) { + task() + return + } + + const blockers = opts.getBlockers?.() ?? [] + const isPushOrReplace = + actionInfo.type === 'PUSH' || actionInfo.type === 'REPLACE' + if (typeof document !== 'undefined' && blockers.length && isPushOrReplace) { for (const blocker of blockers) { - const nextLocation = parseHref(args.path, args.state) + const nextLocation = parseHref(actionInfo.path, actionInfo.state) const isBlocked = await blocker.blockerFn({ currentLocation: location, nextLocation, - action: args.type, + action: actionInfo.type, }) if (isBlocked) { opts.onBlocked?.() @@ -179,7 +155,7 @@ export function createHistory(opts: { } } - args.task() + task() } return { @@ -228,7 +204,7 @@ export function createHistory(opts: { go: (index, navigateOpts) => { tryNavigation({ task: () => { - opts.go(index, navigateOpts?.ignoreBlocker ?? false) + opts.go(index) handleIndexChange({ type: 'GO', index }) }, navigateOpts, @@ -270,11 +246,13 @@ export function createHistory(opts: { flush: () => opts.flush?.(), destroy: () => opts.destroy?.(), notify, - _getBlockers: () => opts.getBlockers?.() ?? [], } } function assignKeyAndIndex(index: number, state: HistoryState | undefined) { + if (!state) { + state = {} + } const key = createRandomKey() return { ...state, @@ -317,8 +295,7 @@ export function createBrowserHistory(opts?: { const _setBlockers = (newBlockers: Array) => (blockers = newBlockers) - const createHref = (path: string) => - normalizeHref(opts?.createHref ? opts.createHref(path) : path) + const createHref = opts?.createHref ?? ((path) => path) const parseLocation = opts?.parseLocation ?? (() => @@ -345,9 +322,6 @@ export function createBrowserHistory(opts?: { let nextPopIsGo = false let ignoreNextPop = false - // TODO: An ignored traversal past a history boundary emits neither popstate - // nor beforeunload, leaving these bypasses active for a later navigation. - // The History API provides no completion signal for such no-op traversals. let skipBlockerNextPop = false let ignoreNextBeforeUnload = false @@ -394,24 +368,18 @@ export function createBrowserHistory(opts?: { destHref: string, state: any, ) => { - // A formatter changes the URL space and must receive the original input. - // Otherwise parseHref below already produces the browser destination. - const href = opts?.createHref ? createHref(destHref) : undefined + const href = createHref(destHref) const hasPendingAction = !!next if (!hasPendingAction) { rollbackLocation = currentLocation } - // Keep the optimistic location in the router's logical URL space. + // Update the location in memory currentLocation = parseHref(destHref, state) // Keep track of the next location we need to flush to the URL - next = [ - href ?? currentLocation.href, - state, - next?.[2 /* is push */] || isPush, - ] + next = [href, state, next?.[2 /* is push */] || isPush] if (!hasPendingAction) { // Schedule an update to the browser history @@ -426,10 +394,6 @@ export function createBrowserHistory(opts?: { } const onPushPopEvent = async () => { - // Same-document traversals do not fire beforeunload, so consume their - // exemption here instead of carrying it into a later document navigation. - ignoreNextBeforeUnload = false - if (ignoreNextPop) { ignoreNextPop = false return @@ -466,7 +430,7 @@ export function createBrowserHistory(opts?: { }) if (isBlocked) { ignoreNextPop = true - win.history.go(-delta) + win.history.go(1) history.notify(notify) return } @@ -519,28 +483,20 @@ export function createBrowserHistory(opts?: { pushState: (href, state) => queueHistoryAction(true, href, state), replaceState: (href, state) => queueHistoryAction(false, href, state), back: (ignoreBlocker) => { - if (ignoreBlocker) { - skipBlockerNextPop = true - ignoreNextBeforeUnload = true - } + if (ignoreBlocker) skipBlockerNextPop = true + ignoreNextBeforeUnload = true return win.history.back() }, forward: (ignoreBlocker) => { - if (ignoreBlocker) { - skipBlockerNextPop = true - ignoreNextBeforeUnload = true - } + if (ignoreBlocker) skipBlockerNextPop = true + ignoreNextBeforeUnload = true win.history.forward() }, - go: (n, ignoreBlocker) => { + go: (n) => { nextPopIsGo = true - if (ignoreBlocker) { - skipBlockerNextPop = true - ignoreNextBeforeUnload = true - } win.history.go(n) }, - createHref, + createHref: (href) => createHref(href), flush, destroy: () => { win.history.pushState = originalPushState @@ -562,21 +518,6 @@ export function createBrowserHistory(opts?: { notifyOnIndexChange: false, }) - history._ignoreNextBeforeUnload = (href) => { - ignoreNextBeforeUnload = false - try { - href = new URL(href, win.document.baseURI).href - // External handlers and same-document fragments may emit neither - // beforeunload nor popstate, leaving an exemption for a later departure. - ignoreNextBeforeUnload = - /^https?:/.test(href) && - (!href.includes('#') || - href.split('#')[0] !== win.location.href.split('#')[0]) - } catch { - // Invalid URLs cannot unload the document. - } - } - win.addEventListener(beforeUnloadEvent, onBeforeUnload, { capture: true }) win.addEventListener(popStateEvent, onPushPopEvent) @@ -607,17 +548,14 @@ export function createHashHistory(opts?: { window?: any }): RouterHistory { return createBrowserHistory({ window: win, parseLocation: () => { - // `#/path?query#fragment`: the router's own fragment starts at the - // second '#'. A non-empty `location.hash` always starts with '#'. - const hash = win.location.hash - let hashIndex = hash.indexOf('#', 1) - if (hashIndex < 0) { - hashIndex = hash.length - } - return parseHref( - `${hash ? hash.slice(1, hashIndex) : '/'}${win.location.search}${hash.slice(hashIndex)}`, - win.history.state, - ) + const hashSplit = win.location.hash.split('#').slice(1) + const pathPart = hashSplit[0] ?? '/' + const searchPart = win.location.search + const hashEntries = hashSplit.slice(1) + const hashPart = + hashEntries.length === 0 ? '' : `#${hashEntries.join('#')}` + const hashHref = `${pathPart}${searchPart}${hashPart}` + return parseHref(hashHref, win.history.state) }, createHref: (href) => `${win.location.pathname}${win.location.search}#${href}`, @@ -657,13 +595,13 @@ export function createMemoryHistory( getLength: () => entries.length, pushState: (path, state) => { // Removes all subsequent entries after the current index to start a new branch - index = index < entries.length - 1 ? index + 1 : entries.length - states[index] = state - entries[index] = path if (index < entries.length - 1) { - entries.length = index + 1 - states.length = index + 1 + entries.splice(index + 1) + states.splice(index + 1) } + states.push(state) + entries.push(path) + index = Math.max(entries.length - 1, 0) }, replaceState: (path, state) => { states[index] = state @@ -678,89 +616,54 @@ export function createMemoryHistory( go: (n) => { index = Math.min(Math.max(index + n, 0), entries.length - 1) }, - createHref: normalizeHref, + createHref: (path) => path, getBlockers: _getBlockers, setBlockers: _setBlockers, }) } -const noop = () => {} +/** + * Sanitize a path to prevent open redirect vulnerabilities. + * Removes control characters and collapses leading double slashes. + */ +function sanitizePath(path: string): string { + // Remove ASCII control characters (0x00-0x1F) and DEL (0x7F) + // These include CR (\r = 0x0D), LF (\n = 0x0A), and other potentially dangerous characters + // eslint-disable-next-line no-control-regex + let sanitized = path.replace(/[\x00-\x1f\x7f]/g, '') -class ServerHistory implements RouterHistory { - declare private _subscribers?: RouterHistory['subscribers'] - - constructor(public location: HistoryLocation) {} - - get length() { - return 1 + // Prevent open redirect via protocol-relative URLs (e.g. "//evil.com") + // Collapse leading double slashes to a single slash + if (sanitized.startsWith('//')) { + sanitized = '/' + sanitized.replace(/^\/+/, '') } - // Preserve the history interface without allocating a Set for each request. - get subscribers() { - return (this._subscribers ??= new Set()) - } - - subscribe() { - return noop - } - - push() {} - replace() {} - go() {} - back() {} - forward() {} - - canGoBack() { - return false - } - - createHref(href: string) { - return normalizeHref(href) - } - - block() { - return noop - } - - flush() {} - destroy() {} - notify() {} - - _getBlockers(): Array { - return [] - } -} - -/** A fixed request location; server navigation is a no-op. */ -export function createServerHistory(href: string): RouterHistory { - return new ServerHistory(parseHref(href, undefined)) + return sanitized } export function parseHref( href: string, state: ParsedHistoryState | undefined, ): HistoryLocation { - const sanitizedHref = normalizeHref(href) + const sanitizedHref = sanitizePath(href) const hashIndex = sanitizedHref.indexOf('#') const searchIndex = sanitizedHref.indexOf('?') - if (!state) { - const key = createRandomKey() - state = { [stateIndexKey]: 0, key, __TSR_key: key } - } + + const addedKey = createRandomKey() return { href: sanitizedHref, - pathname: sanitizedHref.slice( + pathname: sanitizedHref.substring( 0, - hashIndex > -1 - ? searchIndex > -1 + hashIndex > 0 + ? searchIndex > 0 ? Math.min(hashIndex, searchIndex) : hashIndex - : searchIndex > -1 + : searchIndex > 0 ? searchIndex : sanitizedHref.length, ), - hash: hashIndex > -1 ? sanitizedHref.slice(hashIndex) : '', + hash: hashIndex > -1 ? sanitizedHref.substring(hashIndex) : '', search: searchIndex > -1 ? sanitizedHref.slice( @@ -768,11 +671,11 @@ export function parseHref( hashIndex === -1 ? undefined : hashIndex, ) : '', - state, + state: state || { [stateIndexKey]: 0, key: addedKey, __TSR_key: addedKey }, } } // Thanks co-pilot! function createRandomKey() { - return (Math.random() + 1).toString(36).slice(7) + return (Math.random() + 1).toString(36).substring(7) } diff --git a/packages/history/tests/createBrowserHistory.test.ts b/packages/history/tests/createBrowserHistory.test.ts index 5b24744fb5..97b3c40ef3 100644 --- a/packages/history/tests/createBrowserHistory.test.ts +++ b/packages/history/tests/createBrowserHistory.test.ts @@ -1,8 +1,7 @@ import { describe, expect, test, vi } from 'vitest' import { createBrowserHistory } from '../src' -function createBrowserHistoryHarness(createHref?: (path: string) => string) { - const listeners = new Map any>() +function createBrowserHistoryHarness() { const location = { pathname: '/', search: '', @@ -22,64 +21,19 @@ function createBrowserHistoryHarness(createHref?: (path: string) => string) { const window = { location, history: nativeHistory, - addEventListener: vi.fn((type: string, listener: (event: any) => any) => { - listeners.set(type, listener) - }), - removeEventListener: vi.fn((type: string) => { - listeners.delete(type) - }), - dispatchEvent: (event: { type: string }) => - listeners.get(event.type)?.(event), + addEventListener: vi.fn(), + removeEventListener: vi.fn(), } - const history = createBrowserHistory({ window, createHref }) + const history = createBrowserHistory({ window }) return { history, pushState, replaceState, - window, } } describe('createBrowserHistory', () => { - test('passes the original destination to a custom formatter', () => { - const { history, pushState } = createBrowserHistoryHarness( - (href) => '/mapped?value=' + encodeURIComponent(href), - ) - history.push('/a\tb') - history.flush() - expect(pushState).toHaveBeenCalledWith( - expect.anything(), - '', - '/mapped?value=%2Fa%09b', - ) - expect(history.location.href).toBe('/ab') - history.destroy() - }) - - test.each(['/a\x00b?q=a\x01b#/\\section\x7f', '/a\tb?q=a\nb#/\\section\r'])( - 'preserves the browser interpretation of %j', - (href) => { - const originalHref = window.location.href - const expected = new URL(href, originalHref) - const history = createBrowserHistory() - try { - expect(new URL(history.createHref(href), originalHref).href).toBe( - expected.href, - ) - history.push(href) - history.flush() - expect(window.location.href).toBe(expected.href) - expect(new URL(history.location.href, originalHref).href).toBe( - expected.href, - ) - } finally { - history.destroy() - window.history.replaceState(null, '', originalHref) - } - }, - ) - test('coalesces consecutive replaces into the latest replace', async () => { const { history, pushState, replaceState } = createBrowserHistoryHarness() @@ -149,159 +103,4 @@ describe('createBrowserHistory', () => { ) history.destroy() }) - - test.each([ - '//evil.com/path', - '///evil.com/path', - '/\\evil.com/path', - '/\\\\evil.com/path', - '/\\/evil.com/path', - '\\/evil.com/path', - '\\\\evil.com/path', - ' /\\evil.com/path', - '\x01//evil.com/path', - '/\t/evil.com/path', - ])('sanitizes %j before calling the native History API', async (href) => { - const { history, pushState } = createBrowserHistoryHarness() - - history.push(href) - await Promise.resolve() - - expect(pushState).toHaveBeenCalledOnce() - const pushedHref = pushState.mock.calls[0]![2] - const serializedUrl = new URL(pushedHref, 'https://victim.example') - expect(serializedUrl.origin).toBe('https://victim.example') - expect(serializedUrl.pathname).toBe( - href === '\x01//evil.com/path' ? '/%01//evil.com/path' : '/evil.com/path', - ) - expect( - new URL(history.location.href, 'https://victim.example').origin, - ).toBe('https://victim.example') - history.destroy() - }) - - test('does not exempt a normal traversal from beforeunload blockers', () => { - const { history, window } = createBrowserHistoryHarness() - history.block({ blockerFn: vi.fn(), enableBeforeUnload: true }) - - history.back() - const event = { - type: 'beforeunload', - preventDefault: vi.fn(), - returnValue: undefined, - } - window.dispatchEvent(event) - - expect(event.preventDefault).toHaveBeenCalledOnce() - expect(event.returnValue).toBe('') - history.destroy() - }) - - test('exempts an ignored document traversal from beforeunload blockers', () => { - const { history, window } = createBrowserHistoryHarness() - history.block({ blockerFn: vi.fn(), enableBeforeUnload: true }) - - history.back({ ignoreBlocker: true }) - const event = { - type: 'beforeunload', - preventDefault: vi.fn(), - returnValue: undefined, - } - window.dispatchEvent(event) - - expect(event.preventDefault).not.toHaveBeenCalled() - expect(event.returnValue).toBeUndefined() - history.destroy() - }) - - test('passes the logical requested destination to blockers', async () => { - const { history } = createBrowserHistoryHarness( - () => '/mapped/../browser-destination', - ) - const blockerFn = vi.fn(() => true) - history.block({ blockerFn, enableBeforeUnload: false }) - - history.push('/logical/../destination?query=value#hash') - await Promise.resolve() - - expect(blockerFn).toHaveBeenCalledWith( - expect.objectContaining({ - action: 'PUSH', - nextLocation: expect.objectContaining({ - href: '/logical/../destination?query=value#hash', - pathname: '/logical/../destination', - search: '?query=value', - hash: '#hash', - }), - }), - ) - history.destroy() - }) - - test('normalizes the final result of a custom createHref', async () => { - const { history, pushState, replaceState } = createBrowserHistoryHarness( - () => ' \t/\\evil.example/path', - ) - - expect(history.createHref('/safe')).toBe('/evil.example/path') - - history.push('/safe') - await Promise.resolve() - history.replace('/safe') - await Promise.resolve() - - expect(pushState).toHaveBeenCalledWith( - expect.anything(), - '', - '/evil.example/path', - ) - expect(replaceState).toHaveBeenCalledWith( - expect.anything(), - '', - '/evil.example/path', - ) - expect(history.location.href).toBe('/safe') - history.destroy() - }) - - test('keeps the optimistic location in the logical URL space', async () => { - const { history, pushState } = createBrowserHistoryHarness( - () => '/mapped/../browser-destination', - ) - - history.push('/logical/../destination?query=value#hash') - await Promise.resolve() - - expect(history.location).toMatchObject({ - href: '/logical/../destination?query=value#hash', - pathname: '/logical/../destination', - search: '?query=value', - hash: '#hash', - }) - expect(pushState).toHaveBeenCalledWith( - expect.anything(), - '', - '/mapped/../browser-destination', - ) - history.destroy() - }) - - test('does not retain a beforeunload exemption after a same-document traversal', async () => { - const { history, window } = createBrowserHistoryHarness() - history.block({ blockerFn: vi.fn(), enableBeforeUnload: true }) - - history.back({ ignoreBlocker: true }) - await window.dispatchEvent({ type: 'popstate' }) - - const event = { - type: 'beforeunload', - preventDefault: vi.fn(), - returnValue: undefined, - } - window.dispatchEvent(event) - - expect(event.preventDefault).toHaveBeenCalledOnce() - expect(event.returnValue).toBe('') - history.destroy() - }) }) diff --git a/packages/history/tests/createHashHistory.test.ts b/packages/history/tests/createHashHistory.test.ts index e54b1a1ae1..4d68238249 100644 --- a/packages/history/tests/createHashHistory.test.ts +++ b/packages/history/tests/createHashHistory.test.ts @@ -1,162 +1,8 @@ -import { describe, expect, test, vi } from 'vitest' +import { describe, expect, test } from 'vitest' import { createHashHistory } from '../src' describe('createHashHistory', () => { - test.each(['\x00/route', '/route\x01', '/route?q=a\x1fb#c\x7fd'])( - 'keeps logical control data stable after reading the browser URL again: %j', - (href) => { - const originalHref = window.location.href - window.history.replaceState(null, '', '/shell') - const history = createHashHistory() - let reloaded: ReturnType | undefined - try { - history.push(href) - history.flush() - const location = history.location - history.destroy() - reloaded = createHashHistory() - expect(reloaded.location).toEqual(location) - } finally { - history.destroy() - reloaded?.destroy() - window.history.replaceState(null, '', originalHref) - } - }, - ) - - test('reads a hash route that starts with a query without leaking it into the pathname', () => { - const window = { - location: { pathname: '/', search: '', hash: '#?x=1' }, - history: { - state: { __TSR_index: 0, __TSR_key: 'initial' }, - length: 1, - pushState: vi.fn(), - replaceState: vi.fn(), - back: vi.fn(), - forward: vi.fn(), - go: vi.fn(), - }, - addEventListener: vi.fn(), - removeEventListener: vi.fn(), - } - const history = createHashHistory({ window }) - - expect(history.location).toMatchObject({ - href: '?x=1', - pathname: '', - search: '?x=1', - hash: '', - }) - history.destroy() - }) - - test('normalizes the final browser href without changing the logical hash location', async () => { - const pushState = vi.fn() - const window = { - location: { - pathname: '//nested/path', - search: '', - hash: '', - }, - history: { - state: { __TSR_index: 0, __TSR_key: 'initial' }, - length: 1, - pushState, - replaceState: vi.fn(), - back: vi.fn(), - forward: vi.fn(), - go: vi.fn(), - }, - addEventListener: vi.fn(), - removeEventListener: vi.fn(), - } - const history = createHashHistory({ window }) - - history.push('/logical') - await Promise.resolve() - - expect(pushState).toHaveBeenCalledWith( - expect.anything(), - '', - '/nested/path#/logical', - ) - expect(history.location.href).toBe('/logical') - history.destroy() - }) - - test.each([ - [ - '/?shell=1#/hello#section#tail', - { - href: '/hello?shell=1#section#tail', - pathname: '/hello', - search: '?shell=1', - hash: '#section#tail', - }, - ], - [ - '/?shell=1#/hello?route=2#section', - { - href: '/hello?route=2?shell=1#section', - pathname: '/hello', - search: '?route=2?shell=1', - hash: '#section', - }, - ], - [ - '/#/hello##tail#', - { - href: '/hello##tail#', - pathname: '/hello', - search: '', - hash: '##tail#', - }, - ], - [ - '/#/hello%23nested?value=%23#anchor%23tail', - { - href: '/hello%23nested?value=%23#anchor%23tail', - pathname: '/hello%23nested', - search: '?value=%23', - hash: '#anchor%23tail', - }, - ], - [ - '/?shell=1#//evil.example/path#fragment', - { - href: '/evil.example/path?shell=1#fragment', - pathname: '/evil.example/path', - search: '?shell=1', - hash: '#fragment', - }, - ], - [ - '/?shell=1#', - { - href: '/?shell=1', - pathname: '/', - search: '?shell=1', - hash: '', - }, - ], - ])('preserves the logical URL when reading %s', (href, expected) => { - const originalHref = window.location.href - const originalState = window.history.state - window.history.replaceState(null, '', href) - const history = createHashHistory() - - try { - expect(history.location).toMatchObject(expected) - window.history.replaceState(window.history.state, '', '/shell') - window.history.pushState(window.history.state, '', href) - expect(history.location).toMatchObject(expected) - } finally { - history.destroy() - window.history.replaceState(originalState, '', originalHref) - } - }) - describe('parseLocation', () => { describe.each([ ['/', { pathname: '/', search: '' }, 'neither search params nor hash'], diff --git a/packages/history/tests/createMemoryHistory.test.ts b/packages/history/tests/createMemoryHistory.test.ts index c0f565115e..1a27c04919 100644 --- a/packages/history/tests/createMemoryHistory.test.ts +++ b/packages/history/tests/createMemoryHistory.test.ts @@ -2,53 +2,6 @@ import { describe, expect, test, vi } from 'vitest' import { createMemoryHistory } from '../src' describe('createMemoryHistory', () => { - test.each([ - ['//example.com/path', '/example.com/path'], - ['/\\example.com/path', '/example.com/path'], - ['\\/example.com/path', '/example.com/path'], - ['\\\\example.com/path', '/example.com/path'], - [' \t/\r\\example.com/path', '/example.com/path'], - ['/\t/example.com/path', '/example.com/path'], - ['/a\tb?q=a\nb#section\r', '/ab?q=ab#section'], - ['/a\u0000b?q=a\u0001b#section\u007f', '/a%00b?q=a%01b#section%7F'], - ['/', '/'], - ['/posts/123?sort=new#comments', '/posts/123?sort=new#comments'], - ['/caf%C3%A9?q=%2F#//section', '/caf%C3%A9?q=%2F#//section'], - ['/a//b?q=//value#\\/section', '/a//b?q=//value#\\/section'], - ['/%2Fexample.com/path', '/%2Fexample.com/path'], - ])('creates href %j consistent with navigation', (href, expected) => { - const history = createMemoryHistory() - const location = history.location - const createdHref = history.createHref(href) - - expect(createdHref).toBe(expected) - expect(history.location).toBe(location) - expect(new URL(createdHref, 'https://app.example').origin).toBe( - 'https://app.example', - ) - - history.push(href) - expect(history.location.href).toBe(createdHref) - }) - - test('exposes the current blocker registry after registration and removal', () => { - const history = createMemoryHistory() - const first = { blockerFn: vi.fn(() => true) } - const second = { blockerFn: vi.fn(() => false) } - - expect(history._getBlockers()).toEqual([]) - - const removeFirst = history.block(first) - const removeSecond = history.block(second) - expect(history._getBlockers()).toEqual([first, second]) - - removeFirst() - expect(history._getBlockers()).toEqual([second]) - - removeSecond() - expect(history._getBlockers()).toEqual([]) - }) - test('back', () => { const initialEntry = '/initial' const history = createMemoryHistory({ initialEntries: [initialEntry] }) @@ -99,38 +52,6 @@ describe('createMemoryHistory', () => { expect(history.location.pathname).toBe('/b') }) - test('discards forward entries and their state when pushing a new branch', () => { - const initialEntries = ['/'] - const history = createMemoryHistory({ initialEntries }) - history.push('/kept', { marker: 'kept' }) - const keptState = history.location.state - history.push('/discarded-first', { marker: 'discarded-first' }) - history.push('/discarded-last', { marker: 'discarded-last' }) - history.go(-2) - history.push('/new', { marker: 'new' }) - - expect(initialEntries).toEqual(['/', '/kept', '/new']) - expect(history.length).toBe(3) - expect(history.location.pathname).toBe('/new') - expect(history.location.state).toMatchObject({ - __TSR_index: 2, - marker: 'new', - }) - const newState = history.location.state - - history.forward() - expect(history.location.pathname).toBe('/new') - expect(history.location.state).toBe(newState) - - history.back() - expect(history.location.pathname).toBe('/kept') - expect(history.location.state).toBe(keptState) - - history.forward() - expect(history.location.pathname).toBe('/new') - expect(history.location.state).toBe(newState) - }) - test('length', () => { const history = createMemoryHistory() expect(history.length).toBe(1) diff --git a/packages/history/tests/createServerHistory.test.ts b/packages/history/tests/createServerHistory.test.ts deleted file mode 100644 index c036cea185..0000000000 --- a/packages/history/tests/createServerHistory.test.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { describe, expect, test, vi } from 'vitest' -import { - createBrowserHistory, - createMemoryHistory, - createServerHistory, -} from '../src' - -describe('server history', () => { - test.each([ - '/', - '/posts/123?sort=new#comments', - '/caf%C3%A9?q=%2F#//section', - '//example.com/path', - '/\\example.com/path', - '/path\nname?value=\u0000', - ])('parses and sanitizes %j like memory history', (href) => { - const history = createServerHistory(href) - const memory = createMemoryHistory({ initialEntries: [href] }) - expect(history.location).toEqual({ - ...memory.location, - state: { - key: expect.any(String), - __TSR_key: expect.any(String), - __TSR_index: 0, - }, - }) - expect(history.location.state.key).toBe(history.location.state.__TSR_key) - }) - - test.each([ - '//evil.example/path', - '/\\evil.example/path', - '\\/evil.example/path', - '\\\\evil.example/path', - ' \t/\r\\evil.example/path', - '/\t/evil.example/path', - '/a\tb?q=a\nb#section\r', - '/a\u0000b?q=a\u0001b#section\u007f', - '/', - '/posts/123?sort=new#comments', - '/caf%C3%A9?q=%2F#//section', - '/a//b?q=//value#\\/section', - '/%2Fevil.example/path', - ])('normalizes href %j like browser history', (href) => { - const history = createServerHistory('/request') - const browser = createBrowserHistory() - try { - expect(history.createHref(href)).toBe(browser.createHref(href)) - expect(history.location.href).toBe('/request') - } finally { - browser.destroy() - } - }) - - test('ignores navigation, subscriptions, and blockers', () => { - const history = createServerHistory('/request?q=1') - const location = history.location - const subscriber = vi.fn() - const blockerFn = vi.fn(() => true) - const unsubscribe = history.subscribe(subscriber) - const unblock = history.block({ blockerFn }) - - history.push('/pushed', { value: 1 }) - history.replace('/replaced', { value: 2 }) - history.go(-1) - history.back() - history.forward() - history.notify({ type: 'PUSH' }) - history.flush() - history.destroy() - unsubscribe() - unblock() - - expect(history.location).toBe(location) - expect(history.length).toBe(1) - expect(history.canGoBack()).toBe(false) - expect(history.subscribers.size).toBe(0) - expect(history._getBlockers()).toEqual([]) - expect(subscriber).not.toHaveBeenCalled() - expect(blockerFn).not.toHaveBeenCalled() - }) - - test('isolates state and exposed collections between requests', () => { - const first = createServerHistory('/first') - const second = createServerHistory('/second') - first.location.state.__TSR_index = 10 - first.subscribers.add(vi.fn()) - first._getBlockers().push({ blockerFn: () => true }) - - expect(second.location.pathname).toBe('/second') - expect(second.location.state.__TSR_index).toBe(0) - expect(second.subscribers.size).toBe(0) - expect(second._getBlockers()).toEqual([]) - }) -}) diff --git a/packages/history/tests/parseHref.test.ts b/packages/history/tests/parseHref.test.ts index aa6882e6fc..e1b8db9c1a 100644 --- a/packages/history/tests/parseHref.test.ts +++ b/packages/history/tests/parseHref.test.ts @@ -1,19 +1,7 @@ import { describe, expect, test } from 'vitest' import { parseHref } from '../src' -const baseUrl = new URL('https://victim.example/base') - describe('parseHref', () => { - test.each(['\x00', '\x01', '\x1f', '\x7f', '\t', '\n', '\r'])( - 'preserves browser path, query, and fragment interpretation for %j', - (character) => { - const href = `/a${character}b?q=a${character}b#a${character}b` - expect(new URL(parseHref(href, undefined).href, baseUrl).href).toBe( - new URL(href, baseUrl).href, - ) - }, - ) - test('works', () => { const parsed = parseHref('/foo?bar=baz#qux', {} as any) expect(parsed.pathname).toEqual('/foo') @@ -21,42 +9,6 @@ describe('parseHref', () => { expect(parsed.hash).toEqual('#qux') }) - test.each([ - ['?x=1', { pathname: '', search: '?x=1', hash: '' }], - ['#top', { pathname: '', search: '', hash: '#top' }], - ['?x=1#top', { pathname: '', search: '?x=1', hash: '#top' }], - ['#top?x=1', { pathname: '', search: '', hash: '#top?x=1' }], - ])( - 'keeps a leading query or fragment out of the pathname: %j', - (href, expected) => { - expect(parseHref(href, undefined)).toMatchObject({ href, ...expected }) - }, - ) - - test.each([ - { __TSR_index: 2 }, - { __TSR_index: 2, key: 'legacy-key', __TSR_key: 'current-key' }, - ])('preserves supplied state %j', (state) => { - Object.freeze(state) - expect(parseHref('/foo', state).state).toBe(state) - }) - - test('creates independent initial states with matching history keys', () => { - const first = parseHref('/foo', undefined) - const second = parseHref('/bar', undefined) - - for (const location of [first, second]) { - expect(location.state).toEqual({ - __TSR_index: 0, - key: expect.any(String), - __TSR_key: location.state.key, - }) - } - - first.state.__TSR_index = 1 - expect(second.state.__TSR_index).toBe(0) - }) - describe('open redirect prevention', () => { test('strips CR characters to prevent open redirect', () => { // If \r (CR) is in the href, it should be stripped @@ -93,86 +45,6 @@ describe('parseHref', () => { expect(url.pathname).toBe('/evil.com/') }) - test.each([ - '//evil.com/path', - '///evil.com/path', - '/\\evil.com/path', - '/\\\\evil.com/path', - '/\\/evil.com/path', - '\\/evil.com/path', - '\\\\evil.com/path', - ' /\\evil.com/path', - '\x01//evil.com/path', - '/\t/evil.com/path', - ])('keeps protocol-relative input %j on the current origin', (href) => { - const parsed = parseHref(href, undefined) - const url = new URL(parsed.href, 'https://victim.example') - - expect(url.origin).toBe('https://victim.example') - }) - - test.each([ - 'h\x00ttps://evil.example', - 'java\x00script:alert(1)', - '/\x00/evil.example', - '\x7f//evil.example', - '/%5c/evil.example', - '/%2f/evil.example', - '?next=//evil.example', - '#//evil.example', - '//evil.example', - '', - ' ', - '\x00', - '\x00\t\n', - ])('does not make same-origin input %j cross-origin', (href) => { - expect(new URL(href, baseUrl).origin).toBe(baseUrl.origin) - - const parsed = parseHref(href, undefined) - - expect(new URL(parsed.href, baseUrl).origin).toBe(baseUrl.origin) - }) - - test('matches WHATWG parsing of protocol-relative prefixes', () => { - const alphabet = [ - '/', - '\\', - '\t', - '\n', - '\r', - '\x00', - '\x0b', - ' ', - '\x7f', - ] - - for (let length = 0; length <= 4; length++) { - const count = alphabet.length ** length - for (let value = 0; value < count; value++) { - let input = '' - let cursor = value - for (let index = 0; index < length; index++) { - input += alphabet[cursor % alphabet.length] - cursor = Math.floor(cursor / alphabet.length) - } - input += 'evil.example/path' - - try { - new URL(input, baseUrl) - } catch { - continue - } - - const parsed = parseHref(input, undefined) - - expect( - new URL(parsed.href, baseUrl).origin, - JSON.stringify(input), - ).toBe(baseUrl.origin) - } - } - }) - test('normal paths remain unchanged', () => { const parsed = parseHref('/users/profile?id=1#section', undefined) expect(parsed.href).toBe('/users/profile?id=1#section') diff --git a/packages/nitro-v2-vite-plugin/CHANGELOG.md b/packages/nitro-v2-vite-plugin/CHANGELOG.md new file mode 100644 index 0000000000..934532d11b --- /dev/null +++ b/packages/nitro-v2-vite-plugin/CHANGELOG.md @@ -0,0 +1,19 @@ +# @tanstack/nitro-v2-vite-plugin + +## 1.155.0 + +### Minor Changes + +- Clean minor bump, fresh start ([#7395](https://github.com/TanStack/router/pull/7395)) + +## 1.154.9 + +### Patch Changes + +- build: update to vite-config 5.x (rolldown) ([#6926](https://github.com/TanStack/router/pull/6926)) + +## 1.154.8 + +### Patch Changes + +- fix: build with @tanstack/vite-config 0.4.3 ([#6923](https://github.com/TanStack/router/pull/6923)) diff --git a/packages/nitro-v2-vite-plugin/README.md b/packages/nitro-v2-vite-plugin/README.md new file mode 100644 index 0000000000..5882e61120 --- /dev/null +++ b/packages/nitro-v2-vite-plugin/README.md @@ -0,0 +1 @@ +# Experimental Nitro v2 Vite Plugin diff --git a/packages/nitro-v2-vite-plugin/eslint.config.js b/packages/nitro-v2-vite-plugin/eslint.config.js new file mode 100644 index 0000000000..8ce6ad05fc --- /dev/null +++ b/packages/nitro-v2-vite-plugin/eslint.config.js @@ -0,0 +1,5 @@ +// @ts-check + +import rootConfig from '../../eslint.config.js' + +export default [...rootConfig] diff --git a/packages/nitro-v2-vite-plugin/package.json b/packages/nitro-v2-vite-plugin/package.json new file mode 100644 index 0000000000..b14ab9df76 --- /dev/null +++ b/packages/nitro-v2-vite-plugin/package.json @@ -0,0 +1,76 @@ +{ + "name": "@tanstack/nitro-v2-vite-plugin", + "version": "1.155.0", + "description": "Modern and scalable routing for React applications", + "author": "Tanner Linsley", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/TanStack/router.git", + "directory": "packages/nitro-v2-vite-plugin" + }, + "homepage": "https://tanstack.com/router", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "keywords": [ + "react", + "location", + "router", + "routing", + "async", + "async router", + "typescript" + ], + "scripts": { + "clean": "rimraf ./dist && rimraf ./coverage", + "test": "pnpm test:eslint && pnpm test:types && pnpm test:build && pnpm test:unit", + "test:unit": "echo 'No unit tests are needed here since we do them in @tanstack/router-plugin!'", + "test:eslint": "eslint ./src", + "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", + "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", + "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js", + "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js", + "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js", + "test:types:ts60": "tsc6", + "test:types:ts70": "tsc", + "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", + "build": "vite build" + }, + "type": "module", + "types": "dist/esm/index.d.ts", + "main": "dist/cjs/index.cjs", + "module": "dist/esm/index.js", + "exports": { + ".": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + } + }, + "./package.json": "./package.json" + }, + "sideEffects": false, + "files": [ + "dist", + "src" + ], + "engines": { + "node": ">=22.12" + }, + "dependencies": { + "nitropack": "^2.13.1", + "pathe": "^2.0.3" + }, + "peerDependencies": { + "vite": ">=7.0.0" + }, + "devDependencies": { + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" + } +} diff --git a/packages/nitro-v2-vite-plugin/src/index.ts b/packages/nitro-v2-vite-plugin/src/index.ts new file mode 100644 index 0000000000..9adf8d8577 --- /dev/null +++ b/packages/nitro-v2-vite-plugin/src/index.ts @@ -0,0 +1,188 @@ +import { build, copyPublicAssets, createNitro, prepare } from 'nitropack' +import { dirname, resolve } from 'pathe' + +import type { PluginOption, ResolvedConfig, Rollup } from 'vite' +import type { NitroConfig } from 'nitropack' + +let ssrBundle: Rollup.OutputBundle +let ssrEntryFile: string + +export function nitroV2Plugin(nitroConfig?: NitroConfig): Array { + let resolvedConfig: ResolvedConfig + return [ + { + name: 'tanstack-nitro-v2-vite-plugin', + + generateBundle: { + handler(_options, bundle) { + if (this.environment.name !== 'ssr') { + return + } + + // find entry point of ssr bundle + let entryFile: string | undefined + for (const [_name, file] of Object.entries(bundle)) { + if (file.type === 'chunk') { + if (file.isEntry) { + if (entryFile !== undefined) { + this.error( + `Multiple entry points found for service "${this.environment.name}". Only one entry point is allowed.`, + ) + } + entryFile = file.fileName + } + } + } + if (entryFile === undefined) { + this.error( + `No entry point found for service "${this.environment.name}".`, + ) + } + ssrEntryFile = entryFile! + ssrBundle = bundle + }, + }, + + configResolved(config) { + resolvedConfig = config + }, + config(_, env) { + if (env.command !== 'build') { + return + } + + return { + environments: { + ssr: { + consumer: 'server', + build: { + ssr: true, + // we don't write to the file system as the below 'capture-output' plugin will + // capture the output and write it to the virtual file system + write: false, + copyPublicDir: false, + commonjsOptions: { + include: [/node_modules/], + }, + }, + }, + }, + builder: { + sharedPlugins: true, + async buildApp(builder) { + const client = builder.environments.client + const server = builder.environments.ssr + + if (!client) { + throw new Error('Client environment not found') + } + + if (!server) { + throw new Error('SSR environment not found') + } + + await builder.build(client) + await builder.build(server) + + const virtualEntry = '#tanstack/start/entry' + const baseURL = !URL.canParse(resolvedConfig.base) + ? resolvedConfig.base + : undefined + const config: NitroConfig = { + baseURL, + publicAssets: [ + { + dir: client.config.build.outDir, + maxAge: 31536000, // 1 year + baseURL: '/', + }, + ], + ...nitroConfig, + esbuild: { + options: { + target: server.config.build.target || undefined, + ...nitroConfig?.esbuild?.options, + }, + }, + renderer: virtualEntry, + rollupConfig: { + ...nitroConfig?.rollupConfig, + plugins: [virtualBundlePlugin(ssrBundle) as any], + }, + virtual: { + ...nitroConfig?.virtual, + [virtualEntry]: `import { fromWebHandler } from 'h3' + import handler from '${ssrEntryFile}' + export default fromWebHandler(handler.fetch)`, + }, + } + + const nitro = await createNitro(config) + + await prepare(nitro) + await copyPublicAssets(nitro) + await build(nitro) + + await nitro.close() + }, + }, + } + }, + }, + ] +} + +function virtualBundlePlugin(bundle: Rollup.OutputBundle): Rollup.Plugin { + type VirtualModule = { code: string; map: string | null } + let _modules: Map | null = null + + // lazy initialize _modules since at the time of plugin creation, the bundles are not available yet + const getModules = () => { + if (_modules) { + return _modules + } + _modules = new Map() + // group chunks and source maps + for (const [fileName, content] of Object.entries(bundle)) { + if (content.type === 'chunk') { + const virtualModule: VirtualModule = { + code: content.code, + map: null, + } + const maybeMap = bundle[`${fileName}.map`] + if (maybeMap && maybeMap.type === 'asset') { + virtualModule.map = maybeMap.source as string + } + _modules.set(fileName, virtualModule) + _modules.set(resolve(fileName), virtualModule) + } + } + return _modules + } + + return { + name: 'virtual-bundle', + resolveId(id, importer) { + const modules = getModules() + if (modules.has(id)) { + return resolve(id) + } + + if (importer) { + const resolved = resolve(dirname(importer), id) + if (modules.has(resolved)) { + return resolved + } + } + return null + }, + load(id) { + const modules = getModules() + const m = modules.get(id) + if (!m) { + return null + } + return m + }, + } +} diff --git a/packages/nitro-v2-vite-plugin/tsconfig.build.json b/packages/nitro-v2-vite-plugin/tsconfig.build.json new file mode 100644 index 0000000000..92be18587f --- /dev/null +++ b/packages/nitro-v2-vite-plugin/tsconfig.build.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "rootDir": "./src" + }, + "include": ["src"] +} diff --git a/packages/nitro-v2-vite-plugin/tsconfig.json b/packages/nitro-v2-vite-plugin/tsconfig.json new file mode 100644 index 0000000000..bd398a8728 --- /dev/null +++ b/packages/nitro-v2-vite-plugin/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.json", + "include": ["src", "vite.config.ts", "tests"], + "exclude": ["tests/test-files/**", "tests/snapshots/**"], + "compilerOptions": { + "jsx": "react-jsx" + } +} diff --git a/packages/nitro-v2-vite-plugin/vite.config.ts b/packages/nitro-v2-vite-plugin/vite.config.ts new file mode 100644 index 0000000000..7401092b13 --- /dev/null +++ b/packages/nitro-v2-vite-plugin/vite.config.ts @@ -0,0 +1,14 @@ +import { defineConfig, mergeConfig } from 'vitest/config' +import { tanstackViteConfig } from '@tanstack/vite-config' + +const config = defineConfig({}) + +export default mergeConfig( + config, + tanstackViteConfig({ + tsconfigPath: './tsconfig.build.json', + entry: './src/index.ts', + srcDir: './src', + exclude: ['./src/tests/'], + }), +) diff --git a/packages/react-router-devtools/CHANGELOG.md b/packages/react-router-devtools/CHANGELOG.md index f74de5f187..7634f3d19e 100644 --- a/packages/react-router-devtools/CHANGELOG.md +++ b/packages/react-router-devtools/CHANGELOG.md @@ -1,21 +1,5 @@ # @tanstack/react-router-devtools -## 1.167.3 - -### Patch Changes - -- Updated dependencies [[`bbf9b75`](https://github.com/TanStack/router/commit/bbf9b75808d8eee497a6dd1663f0cf08426512e0)]: - - @tanstack/router-devtools-core@1.168.3 - -## 1.167.2 - -### Patch Changes - -- Updated dependencies [[`d76a332`](https://github.com/TanStack/router/commit/d76a33284bc0668f7af4c972a6d32bd0f42b22a6), [`b747fb8`](https://github.com/TanStack/router/commit/b747fb8891b3347b1ffdfe0fa81e7d15049cb776), [`6cfb1e8`](https://github.com/TanStack/router/commit/6cfb1e8b564be282584765352250bf61747895ed), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`6387d58`](https://github.com/TanStack/router/commit/6387d581eabc6e6a3acc87a0bc924e5a38d9c8b2), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`9b2adaf`](https://github.com/TanStack/router/commit/9b2adaf8c3fca905f156c42f6a4fe17a787afcc8), [`873c830`](https://github.com/TanStack/router/commit/873c830ccb2610a864ee697250e10fcc99772ffa), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`f151ab0`](https://github.com/TanStack/router/commit/f151ab018eede64ae849b77e68f3cdf31cb95cc5), [`bc57fa3`](https://github.com/TanStack/router/commit/bc57fa3f12450cf34c731450947c7c8f1ea05e58), [`6387d58`](https://github.com/TanStack/router/commit/6387d581eabc6e6a3acc87a0bc924e5a38d9c8b2), [`9872d2a`](https://github.com/TanStack/router/commit/9872d2ac39fc05f4ef6566c0b421f71ceb115244), [`d76a332`](https://github.com/TanStack/router/commit/d76a33284bc0668f7af4c972a6d32bd0f42b22a6), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`9448caa`](https://github.com/TanStack/router/commit/9448caa03a89076b9770631c356c0cc502802c09), [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef)]: - - @tanstack/router-core@1.171.30 - - @tanstack/react-router@1.170.36 - - @tanstack/router-devtools-core@1.168.2 - ## 1.167.1 ### Patch Changes diff --git a/packages/react-router-devtools/package.json b/packages/react-router-devtools/package.json index 969371a6a6..22306474a0 100644 --- a/packages/react-router-devtools/package.json +++ b/packages/react-router-devtools/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-router-devtools", - "version": "1.167.3", + "version": "1.167.1", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -65,7 +65,7 @@ "@tanstack/router-devtools-core": "workspace:*" }, "devDependencies": { - "@vitejs/plugin-react": "catalog:", + "@vitejs/plugin-react": "^4.3.4", "react": "catalog:", "react-dom": "catalog:", "vite": "*", diff --git a/packages/react-router-ssr-query/CHANGELOG.md b/packages/react-router-ssr-query/CHANGELOG.md index d0fc73ff50..082433df3d 100644 --- a/packages/react-router-ssr-query/CHANGELOG.md +++ b/packages/react-router-ssr-query/CHANGELOG.md @@ -1,32 +1,5 @@ # @tanstack/react-router-ssr-query -## 1.167.3 - -### Patch Changes - -- [#8204](https://github.com/TanStack/router/pull/8204) [`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26) - Stream large deferred SSR hydration payloads through a backpressure-aware router transport, fail known setup errors before response creation, and close cancelled or expired transforms safely. - - Start now cancels discarded middleware and HEAD response bodies, including plain streams and derived branches. - - Server-function raw streams share one ordered response. Arbitrary or sequential consumption can require potentially unbounded buffering of unread data on the client. Cancelling one raw stream discards it locally, while aborting the whole call cancels the response and server work. Consume streams concurrently, cancel unused streams promptly, or use separate calls when independent backpressure is required. A raw stream that exceeds its unread-byte limit now fails alone; sibling streams and the JSON result keep flowing. - - The JSON wire shape of a `RawStream` server-function argument changed. Clients and servers must run matching versions for requests that pass a `RawStream`. - - The frame-protocol constants (`FRAME_TYPE_*`, `MAX_FRAME_PAYLOAD_SIZE`, `MAX_FRAMED_STREAMS`) moved from the `@tanstack/start-client-core` root to the `@tanstack/start-client-core/client-rpc` subpath. - - Router requests whose `Accept` header allows neither `text/html` nor `*/*` now receive `406 Not Acceptable` instead of `500`. - - Framework adapters share the body `` composition (`getSsrBodyScriptParts`, `composeSsrBodyScripts`) and the eager HTML response wrapper (`renderSsrHtmlResponse`) from `@tanstack/router-core`. - - Solid SSR now emits one document type and renders late lazy errors through route boundaries. A Solid `` without a `fallback` no longer holds the streamed shell; it renders inside the nearest `` boundary like React and Vue, and now renders falsy resolved values. - - Static server functions decode cached `RawStream` values with the client deserializer plugins. - - SSR Query integrations now keep request cleanup and stream ownership aligned with the router lifecycle. - -- Updated dependencies [[`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26)]: - - @tanstack/router-ssr-query-core@1.169.3 - ## 1.167.2 ### Patch Changes diff --git a/packages/react-router-ssr-query/package.json b/packages/react-router-ssr-query/package.json index 7333146047..dba26ffbdf 100644 --- a/packages/react-router-ssr-query/package.json +++ b/packages/react-router-ssr-query/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-router-ssr-query", - "version": "1.167.3", + "version": "1.167.2", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -67,7 +67,7 @@ "@tanstack/router-ssr-query-core": "workspace:*" }, "devDependencies": { - "@vitejs/plugin-react": "catalog:", + "@vitejs/plugin-react": "^4.3.4", "react": "catalog:", "react-dom": "catalog:", "@tanstack/react-router": "workspace:*", @@ -88,7 +88,7 @@ "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0", "@tanstack/query-core": ">=5.102.0", - "@tanstack/react-router": ">=1.170.33", + "@tanstack/react-router": ">=1.127.0", "@tanstack/react-query": ">=5.102.0" } } diff --git a/packages/react-router/CHANGELOG.md b/packages/react-router/CHANGELOG.md index 7e1e2f1a62..cd54f70d03 100644 --- a/packages/react-router/CHANGELOG.md +++ b/packages/react-router/CHANGELOG.md @@ -1,201 +1,5 @@ # @tanstack/react-router -## 1.170.46 - -### Patch Changes - -- [#8670](https://github.com/TanStack/router/pull/8670) [`32a3360`](https://github.com/TanStack/router/commit/32a3360cba0e0f884b3215813a48c63467f5a53c) - Reference agent skills in other packages by their `intent load` identifier (`@tanstack/#`) instead of relative file links that break once packages are installed. - -- [#8671](https://github.com/TanStack/router/pull/8671) [`689a7c5`](https://github.com/TanStack/router/commit/689a7c5419de68bce0aaaef72b9a36f115ea1398) - Publish the `@tanstack/react-router` agent skills (`react-router`, `compositions/router-query`, `lifecycle/migrate-from-react-router`), which were missing from the package's `files` list. - -- Updated dependencies [[`32a3360`](https://github.com/TanStack/router/commit/32a3360cba0e0f884b3215813a48c63467f5a53c)]: - - @tanstack/router-core@1.171.39 - -## 1.170.45 - -### Patch Changes - -- Updated dependencies [[`18154b1`](https://github.com/TanStack/router/commit/18154b1c45454a70aa77e9d6d27c8a6e0733d031)]: - - @tanstack/router-core@1.171.38 - -## 1.170.44 - -### Patch Changes - -- Updated dependencies [[`d6ba115`](https://github.com/TanStack/router/commit/d6ba115d5751c75e20943f0062577cf17b446d82)]: - - @tanstack/router-core@1.171.37 - -## 1.170.43 - -### Patch Changes - -- Updated dependencies [[`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5)]: - - @tanstack/router-core@1.171.36 - -## 1.170.42 - -### Patch Changes - -- [#8594](https://github.com/TanStack/router/pull/8594) [`2413cc0`](https://github.com/TanStack/router/commit/2413cc009826fba4f97b166a35a8a50a4a8fe4bb) - reduce component nesting per route match - -- [#8602](https://github.com/TanStack/router/pull/8602) [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb) - Links of a route that the pending navigation leaves skip deriving the destination location, and clicks and preloads follow the href a Link displays. `buildLocation` now builds `mask` and `routeMasks` locations from the same `_fromLocation` as the destination. - -- [#8602](https://github.com/TanStack/router/pull/8602) [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb) - Fixed Link destinations that resolve to a route mask are now reused across navigations instead of being rebuilt every time. A mounted Link now follows changes to its `href` and `reloadDocument` props, and React Links no longer each subscribe to a hydration flag. - -- [#8579](https://github.com/TanStack/router/pull/8579) [`d35aab4`](https://github.com/TanStack/router/commit/d35aab425b07b46e222a507c0f0239644669757b) - Cancel pending link preload timers when starting navigation to avoid redundant preloading while the destination is loading. - -- Updated dependencies [[`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2), [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2), [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2), [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb), [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb), [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2), [`663282b`](https://github.com/TanStack/router/commit/663282b0ebbc494aee3595ed95867ee29d01938e)]: - - @tanstack/history@1.162.5 - - @tanstack/router-core@1.171.35 - -## 1.170.41 - -### Patch Changes - -- [#8529](https://github.com/TanStack/router/pull/8529) [`60b8ad1`](https://github.com/TanStack/router/commit/60b8ad1ad00812bf966a8eeee6be238c37ddad74) - Compose only enabled route boundaries instead of rendering inactive wrapper components. - -- [#8568](https://github.com/TanStack/router/pull/8568) [`614bc27`](https://github.com/TanStack/router/commit/614bc27034c8ec98747bf305ed41d4a619640949) - Update TanStack Store to 0.11.2 to prevent unrelated atom reads inside subscription observers from triggering extra notifications. - -- [#8530](https://github.com/TanStack/router/pull/8530) [`ff66a03`](https://github.com/TanStack/router/commit/ff66a03df4816f44a48a4a37189fc4021b1c8480) - Consolidate the root match context provider while preserving match context in the root shell. - -- [#8522](https://github.com/TanStack/router/pull/8522) [`863c8a7`](https://github.com/TanStack/router/commit/863c8a736b96746c56278a16c50554356f5523d1) - Reuse Link href classification and active/inactive results across location updates while preserving live history href formatting. - -- Updated dependencies [[`d521abd`](https://github.com/TanStack/router/commit/d521abd71c69f1ff010bb3def4d417cb5fa058cb)]: - - @tanstack/router-core@1.171.34 - -## 1.170.40 - -### Patch Changes - -- [#8436](https://github.com/TanStack/router/pull/8436) [`f5ffd38`](https://github.com/TanStack/router/commit/f5ffd3884ba26778a2a8ce53b379a5bded231676) - Skip unused Link preload cleanup when preloading is disabled and ignore queued viewport notifications after their effect has been cleaned up. - -- Updated dependencies [[`488d046`](https://github.com/TanStack/router/commit/488d046a907d330429e2c807ef95326dad87480f), [`0c1b5e3`](https://github.com/TanStack/router/commit/0c1b5e38de71b7e81bbf1fd81c73ee0cd68ffe47), [`3cdd1af`](https://github.com/TanStack/router/commit/3cdd1af04b3e2d6f777797ee7bddf285318dd9d2)]: - - @tanstack/router-core@1.171.33 - -## 1.170.39 - -### Patch Changes - -- [#8435](https://github.com/TanStack/router/pull/8435) [`73bfc15`](https://github.com/TanStack/router/commit/73bfc153eef460e9b670556215a5adb2b5cbf542) - Avoid hydration-triggered rerenders for links that do not compare URL hashes while preserving hash-sensitive active state and ClientOnly behavior. - -## 1.170.38 - -### Patch Changes - -- Updated dependencies [[`cecae54`](https://github.com/TanStack/router/commit/cecae5440b8edaea77c5448fe3d74bbd20fe10a4), [`0103578`](https://github.com/TanStack/router/commit/01035782e53af9b929c784b94ddd64b95efb89c7), [`ce10dcd`](https://github.com/TanStack/router/commit/ce10dcd4d9d3d23738744e453205aad5c6dbd716), [`84936cc`](https://github.com/TanStack/router/commit/84936cc04530bba11059c57b293a794922bbc5aa), [`bbd2336`](https://github.com/TanStack/router/commit/bbd2336b8446de3f7dd85070895e7cf43980183e)]: - - @tanstack/router-core@1.171.32 - -## 1.170.37 - -### Patch Changes - -- [#8418](https://github.com/TanStack/router/pull/8418) [`e561fa1`](https://github.com/TanStack/router/commit/e561fa1d7118e3d29267cc3b6ce1130d6581f387) - `deepEqual` now takes its flags as positional arguments — `deepEqual(a, b, partial?, explicitUndefined?)` — instead of an options object. The router's hot callers (Link option stabilization and active-state checks, `matchRoute`) no longer allocate an options object per comparison, and the comparator reads two booleans instead of a polymorphic object. `explicitUndefined` replaces `ignoreUndefined: false`. `deepEqual` is an internal helper; it stays exported for compatibility of two-argument calls. - -- [#8419](https://github.com/TanStack/router/pull/8419) [`a1c8d1a`](https://github.com/TanStack/router/commit/a1c8d1aa759c227eae9601a030321ac4c53c24bd) - `resolvePath` (internal helper) now takes positional arguments — `resolvePath(base, to, trailingSlash?, cache?)` — so `buildLocation` and `matchRoute` no longer allocate an options object per path resolution. - -- [#8204](https://github.com/TanStack/router/pull/8204) [`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26) - Stream large deferred SSR hydration payloads through a backpressure-aware router transport, fail known setup errors before response creation, and close cancelled or expired transforms safely. - - Start now cancels discarded middleware and HEAD response bodies, including plain streams and derived branches. - - Server-function raw streams share one ordered response. Arbitrary or sequential consumption can require potentially unbounded buffering of unread data on the client. Cancelling one raw stream discards it locally, while aborting the whole call cancels the response and server work. Consume streams concurrently, cancel unused streams promptly, or use separate calls when independent backpressure is required. A raw stream that exceeds its unread-byte limit now fails alone; sibling streams and the JSON result keep flowing. - - The JSON wire shape of a `RawStream` server-function argument changed. Clients and servers must run matching versions for requests that pass a `RawStream`. - - The frame-protocol constants (`FRAME_TYPE_*`, `MAX_FRAME_PAYLOAD_SIZE`, `MAX_FRAMED_STREAMS`) moved from the `@tanstack/start-client-core` root to the `@tanstack/start-client-core/client-rpc` subpath. - - Router requests whose `Accept` header allows neither `text/html` nor `*/*` now receive `406 Not Acceptable` instead of `500`. - - Framework adapters share the body `` composition (`getSsrBodyScriptParts`, `composeSsrBodyScripts`) and the eager HTML response wrapper (`renderSsrHtmlResponse`) from `@tanstack/router-core`. - - Solid SSR now emits one document type and renders late lazy errors through route boundaries. A Solid `` without a `fallback` no longer holds the streamed shell; it renders inside the nearest `` boundary like React and Vue, and now renders falsy resolved values. - - Static server functions decode cached `RawStream` values with the client deserializer plugins. - - SSR Query integrations now keep request cleanup and stream ownership aligned with the router lifecycle. - -- [#8420](https://github.com/TanStack/router/pull/8420) [`8e164d2`](https://github.com/TanStack/router/commit/8e164d28f9e9eb1a7301109230d7ece9817492a8) - `useLinkProps` no longer calls through an internal wrapper. The host element `Link` renders on is an `@internal` overload parameter that is stripped from the published declarations, so the public `useLinkProps(options, forwardedRef?)` signature is unchanged. - -- Updated dependencies [[`bc80866`](https://github.com/TanStack/router/commit/bc80866f6d6eb3e6f152ee3682eb783c96403e83), [`e561fa1`](https://github.com/TanStack/router/commit/e561fa1d7118e3d29267cc3b6ce1130d6581f387), [`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26), [`a1c8d1a`](https://github.com/TanStack/router/commit/a1c8d1aa759c227eae9601a030321ac4c53c24bd), [`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26), [`a0b2ad9`](https://github.com/TanStack/router/commit/a0b2ad99aee64af08d16b0e4ff26b3ba42a99f0a), [`1ca361b`](https://github.com/TanStack/router/commit/1ca361ba52a627d2f76ab33323bd83d1d0aa65a3)]: - - @tanstack/router-core@1.171.31 - -## 1.170.36 - -### Patch Changes - -- [#8390](https://github.com/TanStack/router/pull/8390) [`b747fb8`](https://github.com/TanStack/router/commit/b747fb8891b3347b1ffdfe0fa81e7d15049cb776) - Keep the Link location cache out of server bundles: `buildLocation` only creates, reads and writes it when `isServer` is false. Render React Links on the server without the extra prop copies and the forwarded-ref hook. Link SSR rendering is 20-40% faster in the Link benchmarks and the React Start SSR request loop about 7% faster. - - React `activeProps` and `inactiveProps` now follow one precedence rule on every link, including links whose destination is blocked for using a disallowed scheme: state props override element props, `ref` and event handlers, while `href`, `disabled` and `target` stay controlled by the router. Previously a blocked link ignored a `ref` or handler from its inactive props. - - React `Link` and `useLinkProps` split router options from element props with one key set on the client and the server. Element props pass through as given: external links forward them verbatim, falsy values included, and `useLinkProps` now returns `children` for router-controlled links as it already did for external ones. - -- [#8324](https://github.com/TanStack/router/pull/8324) [`6387d58`](https://github.com/TanStack/router/commit/6387d581eabc6e6a3acc87a0bc924e5a38d9c8b2) - Reuse hydration snapshot getters to avoid unnecessary store-instance effect updates when Links and other hydration-aware components rerender. - -- [#8318](https://github.com/TanStack/router/pull/8318) [`9b2adaf`](https://github.com/TanStack/router/commit/9b2adaf8c3fca905f156c42f6a4fe17a787afcc8) - Allow active and inactive Link props to override base element props in React and Solid while preserving class/style merging. Keep React's `href`, `target`, and `disabled` values controlled by routing options. Preserve Vue object and nested-array class bindings, including reactive updates and server rendering, without mutating cached bindings during VNode normalization. - -- [#8327](https://github.com/TanStack/router/pull/8327) [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef) - Make `pathParamsAllowedCharacters` initialization-only. Configure it when creating the router; changing allowed characters requires a new router instance. Remove decoder-update bookkeeping and decoder-change checks from route-owned path caches. - -- [#8370](https://github.com/TanStack/router/pull/8370) [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5) - Stop exporting the internal `isPlainObject` and `isPlainArray` helpers. - -- [#8324](https://github.com/TanStack/router/pull/8324) [`6387d58`](https://github.com/TanStack/router/commit/6387d581eabc6e6a3acc87a0bc924e5a38d9c8b2) - Avoid a redundant prop copy when rendering native Links while preserving custom-component props and the public hook result. - -- [#8252](https://github.com/TanStack/router/pull/8252) [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734) - Reduce the bundle cost of shared Link pathname interpolation while preserving its rendering performance. Reuse one interpolation pass for pathname and optional metadata, keep the bounded cache on the router, and simplify React Link active-state and prop merging. - -- [#8370](https://github.com/TanStack/router/pull/8370) [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5) - Reuse built locations for Links whose destination does not depend on the current location. `buildLocation` keeps the result per options object when the build never read the current location, and the React `Link` passes one stable options object per instance, so navigations resolve unchanged Links with a lookup instead of a full build. The per-route pathname interpolation cache this replaces is removed. Link `params`, `search` and `activeOptions` are compared by value on render, so inline object literals with unchanged contents keep reusing the Link's location. Pass a new object to change a destination; like any other React prop, an object mutated in place is not re-read. - -- Updated dependencies [[`d76a332`](https://github.com/TanStack/router/commit/d76a33284bc0668f7af4c972a6d32bd0f42b22a6), [`b747fb8`](https://github.com/TanStack/router/commit/b747fb8891b3347b1ffdfe0fa81e7d15049cb776), [`6cfb1e8`](https://github.com/TanStack/router/commit/6cfb1e8b564be282584765352250bf61747895ed), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`8fff7fa`](https://github.com/TanStack/router/commit/8fff7fa1f2e6f061916b0bf5e0ec486b2e732f94), [`f021f6d`](https://github.com/TanStack/router/commit/f021f6d1c6dce6c9b54d70766f1d636d8fd9e184), [`ae68535`](https://github.com/TanStack/router/commit/ae68535929043607d4ee9438f8ae401f3a064862), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`873c830`](https://github.com/TanStack/router/commit/873c830ccb2610a864ee697250e10fcc99772ffa), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`f151ab0`](https://github.com/TanStack/router/commit/f151ab018eede64ae849b77e68f3cdf31cb95cc5), [`bc57fa3`](https://github.com/TanStack/router/commit/bc57fa3f12450cf34c731450947c7c8f1ea05e58), [`9872d2a`](https://github.com/TanStack/router/commit/9872d2ac39fc05f4ef6566c0b421f71ceb115244), [`d76a332`](https://github.com/TanStack/router/commit/d76a33284bc0668f7af4c972a6d32bd0f42b22a6), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`9448caa`](https://github.com/TanStack/router/commit/9448caa03a89076b9770631c356c0cc502802c09), [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef)]: - - @tanstack/router-core@1.171.30 - - @tanstack/history@1.162.4 - -## 1.170.35 - -### Patch Changes - -- [#7824](https://github.com/TanStack/router/pull/7824) [`8c43c71`](https://github.com/TanStack/router/commit/8c43c712523fc63dc3a814f3a19617e270ce8ed1) - Upgrade TanStack Store to 0.11 and migrate router subscriptions to useSelector, preserving selector comparisons and Vue subscription cleanup. - -## 1.170.34 - -### Patch Changes - -- [#8279](https://github.com/TanStack/router/pull/8279) [`aee42c6`](https://github.com/TanStack/router/commit/aee42c6b641d8e919bfed9e0f04bb1b72092f3a6) - Avoid allocating event-handler arrays and wrapper functions for links without user-supplied event handlers. - -- [#8308](https://github.com/TanStack/router/pull/8308) [`9c1871c`](https://github.com/TanStack/router/commit/9c1871ccc88bc1157186b8b460941a304ec740b8) - Validate navigation and redirect destinations, keep ambiguous relative URLs on the current origin, and constrain prerender requests and output paths. Prevent redirect headers from appearing in serialized server function response bodies. - - Preserve native form HTTP redirects, route error handling and masks for document redirects, and per-navigation destinations for shared loader redirects. Avoid redundant origin parsing and reduce link styling and server-rendering work. Configured origins must already be normalized. - - Keep blocked-link inactive props consistent during React hydration, honor explicit redirect Location headers before checking route options, and refresh Vue link state when destinations become internal. Reuse the protocol-relative URL check while parsing redirect schemes once. - - Reduce React link bundle size by sharing pathname comparisons, state-prop selection, and element creation. - - Share normalized pathname comparisons in Solid and Vue links to reduce bundle size. - -- [#8311](https://github.com/TanStack/router/pull/8311) [`9aec5a7`](https://github.com/TanStack/router/commit/9aec5a7012c47e83ec23bb4763494b72a5e68bfc) - React Links resolve state props without temporary class-name arrays or unnecessary style copies. - -- Updated dependencies [[`f9836f1`](https://github.com/TanStack/router/commit/f9836f16f0e25b0a8495f5e01e3f303b1cbc8725), [`9c1871c`](https://github.com/TanStack/router/commit/9c1871ccc88bc1157186b8b460941a304ec740b8), [`9871c06`](https://github.com/TanStack/router/commit/9871c0625806001d6bf373524821a00303438a91), [`0654c0a`](https://github.com/TanStack/router/commit/0654c0a1a427db24d9af13c1d6ad1217a588c0c9)]: - - @tanstack/router-core@1.171.29 - - @tanstack/history@1.162.3 - -## 1.170.33 - -### Patch Changes - -- [#8165](https://github.com/TanStack/router/pull/8165) [`2f20c00`](https://github.com/TanStack/router/commit/2f20c00224c5ba63467551914e0c37012588c4c2) - Exclude structural descendants below error and not-found boundaries from route lifecycle callbacks. Preserve lifecycle membership through invalidation, hydration, background reloads, and superseded navigation publication. - -- [#8209](https://github.com/TanStack/router/pull/8209) [`28a5e45`](https://github.com/TanStack/router/commit/28a5e4504e4ea5cb1480667a4bea2588a53e110f) - Preserve falsy thrown values in React and Vue error boundaries. Type React and Vue boundary error components and `onCatch` callbacks as `unknown`. Solid boundary errors remain typed as `Error`; SSR now wraps non-`Error` loader errors to match Solid’s native boundary behavior, preserving the original value in `cause`. Router state and loader `onError` values are unchanged. - - When upgrading React or Vue, narrow boundary errors (for example, with `error instanceof Error`) before reading `message` or `stack`. `ErrorComponentProps` remains available for values narrowed to a specific error type. Route `onError` types are unchanged. - -- [#8161](https://github.com/TanStack/router/pull/8161) [`f0b5eda`](https://github.com/TanStack/router/commit/f0b5eda544606686a8a8d675a686ca1366428b96) - Retain successful not-found matches as terminal shared boundaries during client navigation, preserving route context while the destination loads. - -- [#8251](https://github.com/TanStack/router/pull/8251) [`0497cae`](https://github.com/TanStack/router/commit/0497caeef3ff7e1c1c6080eca38bca24e7ec320b) - Use URL.canParse for absolute URL checks in links, navigation, redirects, and build configuration. Preserve a URL constructor fallback for older browsers. - -- [#8169](https://github.com/TanStack/router/pull/8169) [`0caf6b9`](https://github.com/TanStack/router/commit/0caf6b9a2b7e14b0b146c74cc27cb05c19d700a5) - Fix route-scoped `useMatch`, `useSearch`, and `useParams` APIs to forward the `shouldThrow` option and preserve optional return types when `shouldThrow: false`. - -- [#8257](https://github.com/TanStack/router/pull/8257) [`cf166d1`](https://github.com/TanStack/router/commit/cf166d160e6397007a979bfc7065b45ff69ea543) - Fix repeated `innerHTML` writes for unchanged styles and data scripts during React re-renders. This prevents unnecessary CSS parsing and Trusted Types errors during client navigation. - -- Updated dependencies [[`edf0e16`](https://github.com/TanStack/router/commit/edf0e16ebfe82ec6e8f68f403a1fda8de9e28889), [`2f20c00`](https://github.com/TanStack/router/commit/2f20c00224c5ba63467551914e0c37012588c4c2), [`28a5e45`](https://github.com/TanStack/router/commit/28a5e4504e4ea5cb1480667a4bea2588a53e110f), [`08eff50`](https://github.com/TanStack/router/commit/08eff50c447a154a3373909009e9e4375cea17ce), [`216c0c4`](https://github.com/TanStack/router/commit/216c0c48036fd1a33163b70dcabfed2b893808b0), [`2f91503`](https://github.com/TanStack/router/commit/2f9150309bc472f4a75cbe98adcdb50c76b12c7a), [`f0b5eda`](https://github.com/TanStack/router/commit/f0b5eda544606686a8a8d675a686ca1366428b96), [`50eafca`](https://github.com/TanStack/router/commit/50eafcaebbbedb6fde3b2816de7a0ace8cde4832), [`0497cae`](https://github.com/TanStack/router/commit/0497caeef3ff7e1c1c6080eca38bca24e7ec320b), [`ee28348`](https://github.com/TanStack/router/commit/ee283480dfa51150a2e0b096a6eff94a89ff8b3f), [`9035abc`](https://github.com/TanStack/router/commit/9035abc41163d83409ef582f7743a3c7be57dd93), [`c18e690`](https://github.com/TanStack/router/commit/c18e69081475a7c98f9d40bd0fe6da78ccb84598)]: - - @tanstack/router-core@1.171.28 - - @tanstack/history@1.162.2 - ## 1.170.32 ### Patch Changes diff --git a/packages/react-router/package.json b/packages/react-router/package.json index 9a61d5af25..afa0d4fbc8 100644 --- a/packages/react-router/package.json +++ b/packages/react-router/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-router", - "version": "1.170.46", + "version": "1.170.32", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -86,30 +86,28 @@ "sideEffects": false, "files": [ "dist", - "src", - "skills", - "!skills/_artifacts" + "src" ], "engines": { "node": ">=20.19" }, "dependencies": { "@tanstack/history": "workspace:*", - "@tanstack/react-store": "^0.11.2", + "@tanstack/react-store": "^0.9.3", "@tanstack/router-core": "workspace:*", - "isbot": "catalog:" + "isbot": "^5.1.22" }, "devDependencies": { - "@testing-library/jest-dom": "catalog:", - "@testing-library/react": "catalog:", + "@testing-library/jest-dom": "^6.6.3", + "@testing-library/react": "^16.2.0", "@tanstack/react-query": "catalog:", "@types/node": ">=20", - "@vitejs/plugin-react": "catalog:", - "combinate": "catalog:", + "@vitejs/plugin-react": "^4.3.4", + "combinate": "^1.1.11", "react": "catalog:", "react-dom": "catalog:", "vite": "*", - "zod": "catalog:", + "zod": "^4.4.3", "@tanstack/vite-config": "catalog:", "vitest": "catalog:", "jsdom": "catalog:", diff --git a/packages/react-router/skills/compositions/router-query/SKILL.md b/packages/react-router/skills/compositions/router-query/SKILL.md index 4fdd74fc30..9bda851b1c 100644 --- a/packages/react-router/skills/compositions/router-query/SKILL.md +++ b/packages/react-router/skills/compositions/router-query/SKILL.md @@ -2,7 +2,7 @@ name: router-query description: >- Integrating TanStack Router with TanStack Query: queryClient - in router context, static queries and fire-and-forget queries in loaders, + in router context, ensureQueryData/prefetchQuery in loaders, useSuspenseQuery in components, defaultPreloadStaleTime: 0, setupRouterSsrQueryIntegration for SSR dehydration/hydration and streaming, per-request QueryClient isolation. @@ -21,7 +21,7 @@ sources: # TanStack Router + TanStack Query Integration -This skill requires familiarity with both TanStack Router and TanStack Query. Read `@tanstack/router-core#router-core` and [react-router](../../react-router/SKILL.md) first. +This skill requires familiarity with both TanStack Router and TanStack Query. Read [router-core](../../../../router-core/skills/router-core/SKILL.md) and [react-router](../../react-router/SKILL.md) first. This skill covers coordinating TanStack Query as an external data cache with TanStack Router's loader system. The router acts as a **coordinator** — it triggers data fetching during navigation, while Query manages caching, background refetching, and data lifecycle. @@ -182,9 +182,9 @@ export function createAppRouter() { } ``` -## Core Pattern: Static `query` in Loader + `useSuspenseQuery` in Component +## Core Pattern: `ensureQueryData` in Loader + `useSuspenseQuery` in Component -This is the recommended pattern. The loader queries data before render (no loading flash), using `staleTime: 'static'` to reuse cached data without a stale refetch. The component subscribes to the cache for updates. +This is the recommended pattern. The loader ensures data is in the cache before render (no loading flash). The component subscribes to the cache for updates. ```tsx // src/routes/posts.tsx @@ -204,12 +204,9 @@ const postsQueryOptions = queryOptions({ export const Route = createFileRoute('/posts')({ loader: ({ context }) => { - // query returns cached data when available and fetches when it is missing - // Keep this query static so a stale refetch does not block navigation - return context.queryClient.query({ - ...postsQueryOptions, - staleTime: 'static', - }) + // ensureQueryData returns cached data if available, fetches if not in cache + // To also refetch stale data, pass revalidateIfStale: true + return context.queryClient.ensureQueryData(postsQueryOptions) }, component: PostsPage, }) @@ -249,10 +246,7 @@ const postQueryOptions = (postId: string) => export const Route = createFileRoute('/posts/$postId')({ loader: ({ context, params }) => { - return context.queryClient.query({ - ...postQueryOptions(params.postId), - staleTime: 'static', - }) + return context.queryClient.ensureQueryData(postQueryOptions(params.postId)) }, component: PostPage, }) @@ -265,23 +259,20 @@ function PostPage() { } ``` -## Streaming Pattern: Fire-and-Forget `query` (Not Awaited) +## Streaming Pattern: `prefetchQuery` (Not Awaited) -For non-critical data, start a query without blocking navigation. Handle its rejection with `noop` so a background failure does not become an unhandled rejection: +For non-critical data, start the fetch without blocking navigation: ```tsx -import { noop, useQuery, useSuspenseQuery } from '@tanstack/react-query' +import { useQuery, useSuspenseQuery } from '@tanstack/react-query' export const Route = createFileRoute('/dashboard')({ loader: ({ context }) => { // Await critical data - const user = context.queryClient.query({ - ...userQueryOptions, - staleTime: 'static', - }) + const user = context.queryClient.ensureQueryData(userQueryOptions) - // Start non-critical query without awaiting — streams during SSR - void context.queryClient.query({ ...analyticsQueryOptions }).catch(noop) + // Start non-critical fetch without awaiting — streams during SSR + context.queryClient.prefetchQuery(analyticsQueryOptions) return user }, @@ -313,10 +304,7 @@ import { useRouter } from '@tanstack/react-router' export const Route = createFileRoute('/posts')({ loader: ({ context }) => - context.queryClient.query({ - ...postsQueryOptions, - staleTime: 'static', - }), + context.queryClient.ensureQueryData(postsQueryOptions), errorComponent: PostsErrorComponent, component: PostsPage, }) @@ -385,29 +373,24 @@ export function createAppRouter() { } ``` -### 3. MEDIUM: Awaiting a fire-and-forget query in a loader blocks rendering +### 3. MEDIUM: Awaiting `prefetchQuery` in loader blocks rendering -A query used for streaming should start in the background and handle errors with `catch(noop)`. Awaiting it blocks the navigation transition until the data resolves, defeating the purpose of streaming. +`prefetchQuery` is designed to fire-and-forget. Awaiting it blocks the navigation transition until the data resolves, defeating the purpose of streaming. ```tsx -import { noop } from '@tanstack/react-query' - // WRONG — blocks navigation, no streaming benefit loader: async ({ context }) => { - await context.queryClient.query({ ...analyticsQueryOptions }).catch(noop) + await context.queryClient.prefetchQuery(analyticsQueryOptions) } -// CORRECT — fire and forget for streaming, with handled rejection +// CORRECT — fire and forget for streaming loader: ({ context }) => { - void context.queryClient.query({ ...analyticsQueryOptions }).catch(noop) + context.queryClient.prefetchQuery(analyticsQueryOptions) } -// If you need to block (critical data), use a static query instead: +// If you need to block (critical data), use ensureQueryData instead: loader: ({ context }) => { - return context.queryClient.query({ - ...criticalQueryOptions, - staleTime: 'static', - }) + return context.queryClient.ensureQueryData(criticalQueryOptions) } ``` @@ -432,10 +415,10 @@ const rootRoute = createRootRouteWithContext<{ queryClient: QueryClient }>()({ TanStack Router has its own SWR cache (`staleTime`, `gcTime`, `defaultPreloadStaleTime`). When using Query as an external cache: - Set `defaultPreloadStaleTime: 0` to prevent Router's cache from short-circuiting Query's freshness logic -- Router's `staleTime`/`gcTime` still apply to the loader return value. For pure Query patterns, return nothing from the loader (just a static `query` for the side effect) and read data exclusively from `useSuspenseQuery` -- `router.invalidate()` re-runs loaders (which call `query` with `staleTime: 'static'`), so the cached Query data remains the freshness authority +- Router's `staleTime`/`gcTime` still apply to the loader return value. For pure Query patterns, return nothing from the loader (just `ensureQueryData` for the side effect) and read data exclusively from `useSuspenseQuery` +- `router.invalidate()` re-runs loaders (which call `ensureQueryData`), but Query decides whether to actually refetch based on its own `staleTime` ## Cross-References -- `@tanstack/router-core#router-core/data-loading` — built-in loader caching fundamentals -- `@tanstack/router-core#router-core/ssr` — SSR setup for dehydration/hydration +- [router-core/data-loading](../../../../router-core/skills/router-core/data-loading/SKILL.md) — built-in loader caching fundamentals +- [router-core/ssr](../../../../router-core/skills/router-core/ssr/SKILL.md) — SSR setup for dehydration/hydration diff --git a/packages/react-router/skills/react-router/SKILL.md b/packages/react-router/skills/react-router/SKILL.md index f8df76df02..ba628f7003 100644 --- a/packages/react-router/skills/react-router/SKILL.md +++ b/packages/react-router/skills/react-router/SKILL.md @@ -23,7 +23,7 @@ sources: # React Router (`@tanstack/react-router`) -This skill builds on router-core. Read `@tanstack/router-core#router-core` first for foundational concepts. +This skill builds on router-core. Read [router-core](../../../router-core/skills/router-core/SKILL.md) first for foundational concepts. > **CRITICAL**: TanStack Router types are FULLY INFERRED. Never cast, never annotate inferred values. > **CRITICAL**: TanStack Router is CLIENT-FIRST. Loaders run on the client by default, not on the server. @@ -495,4 +495,4 @@ function App() { ## Cross-References -- `@tanstack/router-core#router-core` — all sub-skills for domain-specific patterns (search params, data loading, navigation, auth, SSR, etc.) +- [router-core/SKILL.md](../../../router-core/skills/router-core/SKILL.md) — all sub-skills for domain-specific patterns (search params, data loading, navigation, auth, SSR, etc.) diff --git a/packages/react-router/src/Asset.tsx b/packages/react-router/src/Asset.tsx index 04cbac9064..5e4f159f52 100644 --- a/packages/react-router/src/Asset.tsx +++ b/packages/react-router/src/Asset.tsx @@ -42,11 +42,6 @@ export function Asset( }, ): React.ReactElement | null { const { attrs, children, nonce, preventScriptHoist } = asset - // React 19 compares this object by reference before assigning innerHTML. - const innerHTML = React.useMemo( - () => (children === undefined ? undefined : { __html: children }), - [children], - ) switch (asset.tag) { case 'title': @@ -83,7 +78,11 @@ export function Asset( } return ( -

+ TanStack Logo +

+ Next.js TanStack Start +

+
+ Docs + +