diff --git a/.changeset/rsbuild-manifest-module-chunks-once.md b/.changeset/rsbuild-manifest-module-chunks-once.md new file mode 100644 index 0000000000..02febd9d84 --- /dev/null +++ b/.changeset/rsbuild-manifest-module-chunks-once.md @@ -0,0 +1,5 @@ +--- +'@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 new file mode 100644 index 0000000000..04e8e29928 --- /dev/null +++ b/.changeset/rsbuild-manifest-own-chunks.md @@ -0,0 +1,5 @@ +--- +'@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 new file mode 100644 index 0000000000..a84a054fbd --- /dev/null +++ b/.changeset/rsbuild-rule-use-falsy-loaders.md @@ -0,0 +1,5 @@ +--- +'@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 new file mode 100644 index 0000000000..01a0c5ee6e --- /dev/null +++ b/.changeset/rsbuild-virtual-modules-build.md @@ -0,0 +1,5 @@ +--- +'@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 new file mode 100644 index 0000000000..427043a712 --- /dev/null +++ b/.changeset/rsbuild-virtual-modules-root.md @@ -0,0 +1,5 @@ +--- +'@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 new file mode 100644 index 0000000000..9c828f13b3 --- /dev/null +++ b/.changeset/rsc-security-floor.md @@ -0,0 +1,8 @@ +--- +'@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/start-server-fn-custom-id-check.md b/.changeset/start-server-fn-custom-id-check.md new file mode 100644 index 0000000000..384f0ade06 --- /dev/null +++ b/.changeset/start-server-fn-custom-id-check.md @@ -0,0 +1,7 @@ +--- +'@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 new file mode 100644 index 0000000000..d4e8221c59 --- /dev/null +++ b/.changeset/start-vite-root-library-discovery.md @@ -0,0 +1,5 @@ +--- +'@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/warm-routes-rest.md b/.changeset/warm-routes-rest.md deleted file mode 100644 index 37e759c41e..0000000000 --- a/.changeset/warm-routes-rest.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -'@tanstack/solid-router': patch -'@tanstack/vue-router': patch ---- - -Keep active route components mounted by default when route params change. diff --git a/.coderabbit.yaml b/.coderabbit.yaml new file mode 100644 index 0000000000..21d884dbeb --- /dev/null +++ b/.coderabbit.yaml @@ -0,0 +1,12 @@ +# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json + +reviews: + request_changes_workflow: false + slop_detection: + enabled: true + +knowledge_base: + code_guidelines: + enabled: true + filePatterns: + - 'CONTRIBUTING.md' diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index a33150af03..9dd0def7bd 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -4,6 +4,14 @@ 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 new file mode 100644 index 0000000000..a5ef10f1ff --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,22 @@ +## 🎯 Changes + + + +## ✅ Checklist + +- [ ] I have followed the steps in the [Contributing guide](https://github.com/TanStack/router/blob/main/CONTRIBUTING.md). +- [ ] I have tested code changes locally with the relevant test commands, or tests do not apply to this pull request. +- [ ] I fully understand the code in this pull request, including any code generated with AI assistance. + +## 🚀 Release Impact + +- [ ] 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 01be1ce5c2..6fd5aa1c86 100644 --- a/.github/renovate.json +++ b/.github/renovate.json @@ -21,7 +21,6 @@ "@types/node", "@types/react", "@types/react-dom", - "h3", "node", "react", "react-dom", diff --git a/.github/workflows/client-nav-benchmarks.yml b/.github/workflows/benchmarks.yml similarity index 88% rename from .github/workflows/client-nav-benchmarks.yml rename to .github/workflows/benchmarks.yml index 8715312d36..bbc3a1fa24 100644 --- a/.github/workflows/client-nav-benchmarks.yml +++ b/.github/workflows/benchmarks.yml @@ -18,9 +18,18 @@ on: pull_request: paths: - 'packages/**' + - '!packages/**/tests/**' + - '!packages/**/__tests__/**' + - '!packages/**/*.test.*' - 'benchmarks/**' + - '.nvmrc' workflow_dispatch: +concurrency: + group: benchmarks-${{ github.ref }} + cancel-in-progress: false + queue: single + permissions: contents: read # required for actions/checkout id-token: write # required for OIDC authentication with CodSpeed @@ -72,7 +81,8 @@ jobs: @benchmarks/${{ matrix.benchmark }}:build:${{ matrix.framework }} - name: Run ${{ matrix.benchmark }}:${{ matrix.framework }} CodSpeed benchmark - uses: CodSpeedHQ/action@4296e51e7041e24dadb86d1d6e8b9320d223dbe8 # v5.0.3 + uses: CodSpeedHQ/action@373d6868929f444bc08d901fd0eb0ad52a8875ea # v5.2.1 + timeout-minutes: 20 with: mode: ${{ matrix.mode }} run: >- diff --git a/.github/workflows/bundle-size.yml b/.github/workflows/bundle-size.yml index 23c354e06e..51ffa28e4c 100644 --- a/.github/workflows/bundle-size.yml +++ b/.github/workflows/bundle-size.yml @@ -9,12 +9,18 @@ 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: @@ -45,7 +51,7 @@ jobs: uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main - name: Measure Bundle Size - run: pnpm nx run @benchmarks/bundle-size:build --outputStyle=stream --skipRemoteCache + run: pnpm benchmark:bundle-size --outputStyle=stream --skipRemoteCache - name: Capture Benchmark Outputs id: capture @@ -103,6 +109,8 @@ 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: | @@ -112,7 +120,7 @@ jobs: benchmark-main: name: Publish Bundle Size History - if: github.event_name == 'push' && github.ref == 'refs/heads/main' && github.repository_owner == 'TanStack' + if: (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && github.ref == 'refs/heads/main' && github.repository_owner == 'TanStack' runs-on: ubuntu-latest permissions: contents: write @@ -127,7 +135,7 @@ jobs: uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main - name: Measure Bundle Size - run: pnpm nx run @benchmarks/bundle-size:build --outputStyle=stream --skipRemoteCache + run: pnpm benchmark:bundle-size --outputStyle=stream --skipRemoteCache - name: Publish Benchmark Dashboard uses: benchmark-action/github-action-benchmark@52576c92bccf6ac60c8223ec7eb2565637cae9ba # v1.22.1 with: diff --git a/.github/workflows/compiler-platforms.yml b/.github/workflows/compiler-platforms.yml new file mode 100644 index 0000000000..ad70e39bb6 --- /dev/null +++ b/.github/workflows/compiler-platforms.yml @@ -0,0 +1,101 @@ +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 d8c779b170..fde1100409 100644 --- a/.github/workflows/labeler.yml +++ b/.github/workflows/labeler.yml @@ -9,6 +9,8 @@ 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 71026a0a92..ae19b4f0d2 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -10,6 +10,13 @@ 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 @@ -26,8 +33,8 @@ jobs: with: fetch-depth: 0 persist-credentials: false - - name: Start Nx Agents - run: npx nx-cloud start-ci-run --distribute-on=".nx/workflows/dynamic-changesets.yaml" + - name: Start Nx Workers + run: npx nx-cloud start-workers - name: Setup Tools uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main - name: Get base and head commits for `nx affected` @@ -36,9 +43,9 @@ jobs: main-branch-name: main - name: Run Checks run: pnpm run test:pr --parallel=3 - - name: Stop Nx Agents + - name: Stop Nx Workers if: ${{ always() }} - run: npx nx-cloud stop-all-agents + run: npx nx-cloud stop-all-workers preview: name: Preview runs-on: ubuntu-latest diff --git a/.gitignore b/.gitignore index 1699592784..70028b2860 100644 --- a/.gitignore +++ b/.gitignore @@ -66,6 +66,7 @@ nx-cloud.env .nx/workspace-data .nx/polygraph .nx/self-healing +.nx/migrate-runs gpt/db.json diff --git a/.nvmrc b/.nvmrc index b404027604..63f87c20ef 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -24.8.0 +26.12.1 diff --git a/.nx/ci-config.yaml b/.nx/ci-config.yaml new file mode 100644 index 0000000000..2f0783feb4 --- /dev/null +++ b/.nx/ci-config.yaml @@ -0,0 +1,5 @@ +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 deleted file mode 100644 index 39d858d5b2..0000000000 --- a/.nx/workflows/dynamic-changesets.yaml +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index 4fa2634bc3..0000000000 --- a/.nx/workflows/sandboxing-config.yaml +++ /dev/null @@ -1,9 +0,0 @@ -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 new file mode 100644 index 0000000000..b3ed223621 --- /dev/null +++ b/.nx/workflows/ultracache-config.yaml @@ -0,0 +1,124 @@ +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 65991e1964..de501452ad 100644 --- a/.prettierignore +++ b/.prettierignore @@ -17,4 +17,7 @@ node_modules /.nx/workspace-data **/src/routeTree.gen.ts packages/router-plugin/tests/**/test-files/** -.nx/self-healing \ No newline at end of file +.nx/self-healing + +# Preserve the pinned upstream URL fixtures byte for byte. +packages/router-core/tests/fixtures/wpt-url/urltestdata*.json diff --git a/AGENTS.md b/AGENTS.md index 490cb691d4..f47b5103e1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,177 +1,41 @@ # AGENTS.md -## Project overview +## Scope -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: +- 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`. -- **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 +## Work and validation -## Setup commands +- 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. -- 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` +```sh +CI=1 NX_DAEMON=false pnpm nx run-many -p -t --skipRemoteCache +``` -## Code style +- 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`. -- 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`. +## Runtime rules -## Dev environment tips +- 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. -- 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. +## Performance and final bundle pass -## 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 +- 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. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e9e793926f..4b6e808af1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -33,7 +33,17 @@ TanStack Router is a community project. Contributions to both TanStack Router an ## Before you start -PRs that require API changes must first be proposed as an issue and receive maintainer sign-off before implementation begins. +- Search the [open and closed issues](https://github.com/TanStack/router/issues?q=is%3Aissue) before reporting a bug. If it has not already been reported, use the [bug report template](https://github.com/TanStack/router/issues/new?template=bug_report.yml). +- Search the [open and closed pull requests](https://github.com/TanStack/router/pulls?q=is%3Apr) before starting work to avoid duplicating an existing contribution. +- Pull requests that require API changes must first be proposed as an issue and receive maintainer sign-off before implementation begins. + +## Pull request guidelines + +Every pull request must follow the [TanStack Router pull request template](.github/pull_request_template.md). Complete its description and checklist without removing or bypassing the required sections. + +- Keep each pull request focused on one change or topic. Pull requests that combine unrelated changes will be closed with a request to split them into separately reviewable contributions. +- Write a concise description that clearly explains what changed and why. Follow the sections in the pull request template; a long, unstructured description makes a contribution harder to review. +- Every change that affects a published package must include a changeset. Create it with `pnpm changeset`; documentation, CI, examples, and development-only changes do not require one. ## Development @@ -132,10 +142,19 @@ 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. 2. **Keep ownership of technical decisions**. Understand every change, verify its behavior with the appropriate tests and documentation, and be ready to explain it during review. 3. **Do not paste LLM output verbatim into the codebase or a contribution**. Treat generated text and code as a draft: check its claims, adapt it to the repository, and remove anything you cannot justify. Issues or pull requests that appear to contain unreviewed LLM output may be closed without further review. +4. **Do not mass-submit unrelated or low-quality AI-generated pull requests**. We treat that behavior as spam and may close the pull requests, block the contributor, and report the GitHub account. AI-assisted contributions follow the same standards for correctness, testing, documentation, and review as every other contribution. diff --git a/_artifacts/domain_map.yaml b/_artifacts/domain_map.yaml index 4b5d6f8386..0b2672f0c6 100644 --- a/_artifacts/domain_map.yaml +++ b/_artifacts/domain_map.yaml @@ -147,13 +147,15 @@ skills: context types to not flow into loader. wrong_pattern: | createFileRoute('/posts')({ - loader: ({ context }) => context.queryClient.ensureQueryData(postsQuery), + loader: ({ context }) => + context.queryClient.query({ ...postsQuery, staleTime: 'static' }), beforeLoad: ({ context }) => ({ queryClient: context.queryClient }), }) correct_pattern: | createFileRoute('/posts')({ beforeLoad: ({ context }) => ({ queryClient: context.queryClient }), - loader: ({ context }) => context.queryClient.ensureQueryData(postsQuery), + loader: ({ context }) => + context.queryClient.query({ ...postsQuery, staleTime: 'static' }), }) source: 'docs/router/eslint/create-route-property-order.md' priority: HIGH @@ -536,7 +538,7 @@ skills: - '@tanstack/react-router-ssr-query' covers: - External cache coordination pattern - - queryClient.ensureQueryData in loader + - "queryClient.query with staleTime: 'static' in loader" - useSuspenseQuery in components - setupRouterSsrQueryIntegration - defaultPreloadStaleTime @@ -579,11 +581,11 @@ skills: priority: HIGH status: active - - mistake: 'Awaiting prefetchQuery in loader blocks rendering' + - mistake: 'Awaiting a fire-and-forget query in loader blocks rendering' mechanism: >- - 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. + 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. source: 'docs/router/integrations/query.md' priority: MEDIUM status: active diff --git a/_artifacts/skill_spec.md b/_artifacts/skill_spec.md index 4503afb48a..7eb9554a42 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 prefetchQuery 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 a fire-and-forget query 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 ec38a04bdd..6f7c4c8742 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, ensureQueryData/prefetchQuery in loaders, + in router context, static queries and fire-and-forget queries 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 new file mode 100644 index 0000000000..9d56a2411a --- /dev/null +++ b/benchmarks/AGENTS.md @@ -0,0 +1,15 @@ +# 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 new file mode 100644 index 0000000000..94d2f31802 --- /dev/null +++ b/benchmarks/README.md @@ -0,0 +1,88 @@ +# CPU simulation benchmarks + +`client-nav` measures navigation, mounting, and React/Solid hydration in +Node/jsdom; `ssr` measures server requests. +Both suites run through the CodSpeed Vitest integration in CPU simulation mode. + +## Worker runtime + +Every CPU benchmark project includes `cpuSimulationExecArgv()` from +[`cpu-simulation.ts`](./cpu-simulation.ts). It augments CodSpeed's worker flags +only during CPU simulation, including the legacy `instrumentation` mode. + +The pinned CodSpeed integration supplies `--no-opt`. In Node 24 this is an alias +for `--no-turbofan`, so Maglev can still optimize and inline hot functions. The +additional `--no-maglev` keeps the optimizing compiler out of the simulation. +`--always-sparkplug` compiles baseline code on first use, so warmup does not leave +functions approaching a later tier-up or batch-compilation threshold. The worker +regression test checks that even a once-called function receives baseline code. +The integration also omits the old `--no-scavenge-task` flag on Node 20 and +newer, where V8 renamed it to `--no-minor-gc-task`. Supplying the renamed flag +keeps minor GC tied to allocation pressure instead of scheduled foreground +tasks. Both flags follow the fixes in +[CodSpeed's Node 24 support](https://github.com/CodSpeedHQ/codspeed-node/commit/e3224e7872). + +`--initial-old-space-size=512` fixes the initial/minimum old-generation +allocation budget at 512 MiB. Removing only this override after worker isolation +left two Vue SSR scenarios with same-commit spreads above 2% in five full-suite +repetitions. The paired default-heap comparison with stock incremental-marking +tasks also exceeded 2%. Runtime comparisons and tested alternatives are recorded in +[PR #8248](https://github.com/TanStack/router/pull/8248). + +This is a GC-policy tradeoff. Minor collections and allocation work remain +measured, and CodSpeed still explicitly collects before measurement. However, +V8 can skip automatic full collections below this old-generation budget, so the +benchmark can omit some eventual full-GC CPU cost from increased object +retention. Repeatability does not establish representative production GC +frequency. The flag does not preallocate 512 MiB; the existing 4096 MiB maximum +remains. See [V8's initial/minimum heap configuration](https://github.com/nodejs/node/blob/v24.8.0/deps/v8/src/heap/heap.cc#L5071). + +The configuration preserves CodSpeed's incremental-marking task settings; the +additional `--no-incremental-marking-task` from the initial stabilization proposal +has been removed. + +The flags are intentionally absent from ordinary Vitest timing and walltime runs. + +Changing simulation compiler settings changes the measurement baseline. Compare +repeatability within each configuration before interpreting performance changes +between configurations as router improvements or regressions. + +## Worker isolation + +Keep one SSR workload in each `speed*.bench.ts` file. These projects explicitly +enable Vitest isolation; CodSpeed uses the forks pool, so every file receives a +fresh worker. Multiple workloads in one file share the worker's runtime state, +even though CodSpeed collects before each measurement. Later control cases +remained noisy after the runtime flag corrections. Running the React plain +dehydration and linked-CSS controls alone reduced their observed three-run spreads +to 0.09% and 0.02% respectively. + +Variant files keep their workload names, request counts, concurrency, payloads +and assertions. CodSpeed includes the file path in a benchmark's identity, so +moved variants start a new history. The first workload keeps `speed.bench.ts`; +the additional variants have descriptive file names alongside it. Type-check +includes cover all of these files. + +## Streaming workload + +Deferred payloads in the SSR streaming scenario resolve after two task turns on +Node. A real 1 ms timer lets elapsed host time decide which concurrent requests +resolve together. Counted turns preserve the initial loading render and deferred +payloads; the existing HTML assertions check both. These benchmarks execute in +Node and use `setImmediate` directly. + +## Repeatability checks + +Dispatch the existing `Benchmarks` workflow against an unchanged branch: + +```sh +gh workflow run 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. +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/.gitignore b/benchmarks/bundle-size/.gitignore index d5ced39aa3..bd05a98cee 100644 --- a/benchmarks/bundle-size/.gitignore +++ b/benchmarks/bundle-size/.gitignore @@ -6,4 +6,6 @@ scenarios/*/src/routeTree.gen.ts results/*.json results/*.md results/*.js +results/*.log +results/runs/ !results/.gitkeep diff --git a/benchmarks/bundle-size/README.md b/benchmarks/bundle-size/README.md index 4d4d3dc2d3..2185d6b43f 100644 --- a/benchmarks/bundle-size/README.md +++ b/benchmarks/bundle-size/README.md @@ -29,29 +29,102 @@ Each package has `minimal` and `full` scenarios: ## Local Run ```bash -pnpm nx run @benchmarks/bundle-size:build +pnpm benchmark:bundle-size:run ``` Run one or more scenarios during local optimization: ```bash -pnpm nx run @benchmarks/bundle-size:build -- --scenario react-router.minimal -pnpm nx run @benchmarks/bundle-size:build -- --scenario react-router.minimal,react-router.full +pnpm benchmark:bundle-size:run --scenario react-router.minimal +pnpm benchmark:bundle-size:run --scenario react-router.minimal,react-router.full ``` -Filtered runs build only the package projects needed by selected scenarios. Full runs build all package projects needed by all scenarios. If the required packages are already built and unchanged, skip that step: +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`. + +If the required packages are already built and unchanged, skip that step: ```bash -pnpm nx run @benchmarks/bundle-size:build -- --scenario react-router.minimal --skip-package-builds +pnpm benchmark:bundle-size:run --scenario react-router.minimal --skip-package-builds ``` 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` `current.json` includes run status, selected package build projects, per-scenario totals, per-file sizes, and the emitted JS files used for measurement. Dist paths use `scenarioDir`/`outDir`, e.g. `react-router.minimal` maps to `benchmarks/bundle-size/dist/react-router-minimal/`. +The runner sets `CI=1` and `NX_DAEMON=false`. Successful runs print log locations and the existing `query` or `diff` summary. +If a step fails, the runner stops with a nonzero exit code. It prints the last 40 log lines, limited to 8,000 characters. +Full stdout and stderr stay in the log files. A positive bundle-size delta does not cause failure. + +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: + +```bash +pnpm benchmark:bundle-size:run --name baseline --scenario react-router.minimal,react-router.full +``` + +After you change the implementation, compare a candidate against that baseline: + +```bash +pnpm benchmark:bundle-size:run --name candidate --baseline baseline \ + --scenario react-router.minimal,react-router.full \ + --test-projects @tanstack/router-core,@tanstack/react-router \ + -- tests/path.test.ts tests/link.test.tsx +``` + +`--test-projects` runs the selected Nx unit-test targets before measurement. Arguments after `--` go only to those tests. +Tests and measurement run sequentially. Failed tests stop the runner before measurement, so old results cannot produce a misleading diff. +Without `--test-projects`, the runner only measures bundles. Type tests, performance benchmarks, and e2e tests remain separate commands. + +Named runs store their metrics and logs in `benchmarks/bundle-size/results/runs//`. Existing named results cannot be overwritten. +Without `--name`, runs replace `current.json` and the logs for the steps they run. +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. + +For command reference, run: + +```bash +pnpm benchmark:bundle-size:run --help +``` + ## Local Query Tools ```bash @@ -60,18 +133,22 @@ 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 -pnpm nx run @benchmarks/bundle-size:build -- --scenario react-router.minimal --analysis +pnpm benchmark:bundle-size:run --scenario react-router.minimal --analysis pnpm benchmark:bundle-size:analyze --id react-router.minimal --top-sources 30 ``` +For a named run, pass `--current benchmarks/bundle-size/results/runs//current.json` to `query`, `diff`, or `analyze`. + ## CI Reporting - PR workflow generates a sticky comment with: - - current gzip values - - baseline delta + - current gzip, initial gzip, raw, and Brotli values + - per-metric deltas from the `main` baseline - inline sparkline trend - Pushes to `main` publish historical chart data to GitHub Pages via `benchmark-action/github-action-benchmark`. diff --git a/benchmarks/bundle-size/package.json b/benchmarks/bundle-size/package.json index 500cf9b8f2..ca34cd6cd7 100644 --- a/benchmarks/bundle-size/package.json +++ b/benchmarks/bundle-size/package.json @@ -3,17 +3,35 @@ "private": true, "type": "module", "scripts": { - "build": "node ../../scripts/benchmarks/bundle-size/measure.mjs --skip-package-builds", - "test:unit": "node --test ../../scripts/benchmarks/bundle-size/pr-report.test.mjs" + "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" }, "nx": { "targets": { - "build": { - "cache": false, + "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" + ], "dependsOn": [ { "projects": [ "@tanstack/react-router", + "@tanstack/react-router-ssr-query", "@tanstack/react-start", "@tanstack/router-plugin", "@tanstack/solid-router", @@ -26,29 +44,31 @@ ] }, "test:unit": { + "dependsOn": [], "inputs": [ "default", "^production", - "{workspaceRoot}/scripts/benchmarks/bundle-size/pr-report.mjs", - "{workspaceRoot}/scripts/benchmarks/bundle-size/pr-report.test.mjs" + "{workspaceRoot}/scripts/benchmarks/bundle-size/*.mjs" ] } } }, "dependencies": { "@tanstack/react-router": "workspace:^", + "@tanstack/react-router-ssr-query": "workspace:^", "@tanstack/solid-router": "workspace:^", "@tanstack/vue-router": "workspace:^", "@tanstack/react-start": "workspace:^", "@tanstack/solid-start": "workspace:^", "@tanstack/vue-start": "workspace:^", + "@tanstack/react-query": "catalog:", "react": "^19.0.0", "react-dom": "^19.0.0", "solid-js": "^1.9.10", "vue": "^3.5.16" }, "devDependencies": { - "@rsbuild/core": "^2.1.0", + "@rsbuild/core": "^2.3.1", "@rsbuild/plugin-react": "^2.0.0", "@tanstack/router-plugin": "workspace:^", "@types/react": "^19.0.8", diff --git a/benchmarks/bundle-size/scenarios/react-start-full/rsbuild.config.ts b/benchmarks/bundle-size/scenarios/react-start-full/rsbuild.config.ts index 641de56234..349e11bec1 100644 --- a/benchmarks/bundle-size/scenarios/react-start-full/rsbuild.config.ts +++ b/benchmarks/bundle-size/scenarios/react-start-full/rsbuild.config.ts @@ -6,7 +6,7 @@ const outDir = process.env.BUNDLE_SIZE_DIST_DIR ?? 'dist-rsbuild' export default defineConfig({ logLevel: 'silent', - plugins: [pluginReact({ splitChunks: false }), tanstackStart()], + plugins: [pluginReact(), tanstackStart()], output: { distPath: { root: outDir, diff --git a/benchmarks/bundle-size/scenarios/react-start-minimal/rsbuild.config.ts b/benchmarks/bundle-size/scenarios/react-start-minimal/rsbuild.config.ts index 78752d0190..7d27421d4d 100644 --- a/benchmarks/bundle-size/scenarios/react-start-minimal/rsbuild.config.ts +++ b/benchmarks/bundle-size/scenarios/react-start-minimal/rsbuild.config.ts @@ -16,7 +16,7 @@ const startOptions = clientOutput export default defineConfig({ logLevel: 'silent', - plugins: [pluginReact({ splitChunks: false }), tanstackStart(startOptions)], + plugins: [pluginReact(), tanstackStart(startOptions)], output: { distPath: { root: outDir, diff --git a/benchmarks/bundle-size/scenarios/react-start-query-integration/src/router.tsx b/benchmarks/bundle-size/scenarios/react-start-query-integration/src/router.tsx new file mode 100644 index 0000000000..93b95f3148 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-start-query-integration/src/router.tsx @@ -0,0 +1,17 @@ +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() + const router = createRouter({ + routeTree, + context: { queryClient }, + scrollRestoration: true, + }) + + setupRouterSsrQueryIntegration({ router, queryClient }) + + return router +} diff --git a/benchmarks/bundle-size/scenarios/react-start-query-integration/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/react-start-query-integration/src/routes/__root.tsx new file mode 100644 index 0000000000..ff1da4c304 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-start-query-integration/src/routes/__root.tsx @@ -0,0 +1,24 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/bundle-size/scenarios/react-start-query-integration/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/react-start-query-integration/src/routes/index.tsx new file mode 100644 index 0000000000..76fb363538 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-start-query-integration/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
hello world
+} diff --git a/benchmarks/bundle-size/scenarios/react-start-query-integration/vite.config.ts b/benchmarks/bundle-size/scenarios/react-start-query-integration/vite.config.ts new file mode 100644 index 0000000000..d4e4cd980d --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-start-query-integration/vite.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from 'vite' +import viteReact from '@vitejs/plugin-react' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' + +export default defineConfig({ + plugins: [tanstackStart(), viteReact()], +}) 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 d696063083..0ff40aebfc 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,3 +1,4 @@ +import { defineComponent } from 'vue' import { Asset, Await, @@ -45,143 +46,151 @@ 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 aa0539fa1a..8e8870a2ce 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,3 +1,4 @@ +import { defineComponent } from 'vue' import { Asset, Await, @@ -68,151 +69,159 @@ 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 6179c7f0b8..ec34ecc0c1 100644 --- a/benchmarks/client-nav/README.md +++ b/benchmarks/client-nav/README.md @@ -9,10 +9,11 @@ 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 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`. +> **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`. ## Layout @@ -38,7 +39,7 @@ scenarios/// routes/ ``` -Scenario apps use file-based routing (`@tanstack/router-plugin`) with a +Navigation 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 @@ -57,9 +58,11 @@ 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. The only scenario measuring router creation. | +| `mount` | Cold start: `createRouter` (route-tree processing) + first render + initial `router.load()` + unmount, with a fresh router per mount. | | `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). | @@ -68,10 +71,14 @@ 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). @@ -96,7 +103,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 --config ./scenarios///vite.config.ts +cd benchmarks/client-nav && NODE_ENV=production vitest bench --mode benchmark --config ./scenarios///vite.config.ts ``` Run framework-specific flame benchmarks (10 second loop, profiled with `@platformatic/flame`, forced to `NODE_ENV=production`): @@ -115,3 +122,186 @@ 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 new file mode 100644 index 0000000000..a25eac563b --- /dev/null +++ b/benchmarks/client-nav/link-performance/cases.ts @@ -0,0 +1,360 @@ +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 new file mode 100644 index 0000000000..f819fab52b --- /dev/null +++ b/benchmarks/client-nav/link-performance/client.bench.ts @@ -0,0 +1,30 @@ +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 new file mode 100644 index 0000000000..1a468a3169 --- /dev/null +++ b/benchmarks/client-nav/link-performance/config.test.ts @@ -0,0 +1,42 @@ +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 new file mode 100644 index 0000000000..416b027057 --- /dev/null +++ b/benchmarks/client-nav/link-performance/config.ts @@ -0,0 +1,69 @@ +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 new file mode 100644 index 0000000000..fd1751c081 --- /dev/null +++ b/benchmarks/client-nav/link-performance/project.json @@ -0,0 +1,103 @@ +{ + "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 new file mode 100644 index 0000000000..f1a3fb6df7 --- /dev/null +++ b/benchmarks/client-nav/link-performance/scenario.ts @@ -0,0 +1,114 @@ +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 new file mode 100644 index 0000000000..a187ee8c15 --- /dev/null +++ b/benchmarks/client-nav/link-performance/src/client.tsx @@ -0,0 +1,29 @@ +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 new file mode 100644 index 0000000000..491191b1f9 --- /dev/null +++ b/benchmarks/client-nav/link-performance/src/ssr.tsx @@ -0,0 +1,29 @@ +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 new file mode 100644 index 0000000000..8315b85b8b --- /dev/null +++ b/benchmarks/client-nav/link-performance/src/workload.tsx @@ -0,0 +1,506 @@ +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 new file mode 100644 index 0000000000..c30084e510 --- /dev/null +++ b/benchmarks/client-nav/link-performance/ssr.bench.ts @@ -0,0 +1,30 @@ +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 new file mode 100644 index 0000000000..59ccfa3cb4 --- /dev/null +++ b/benchmarks/client-nav/link-performance/stable-runner.ts @@ -0,0 +1,269 @@ +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 new file mode 100644 index 0000000000..087b32414a --- /dev/null +++ b/benchmarks/client-nav/link-performance/stable-worker.test.ts @@ -0,0 +1,60 @@ +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 new file mode 100644 index 0000000000..d98679dc15 --- /dev/null +++ b/benchmarks/client-nav/link-performance/stable-worker.ts @@ -0,0 +1,112 @@ +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 new file mode 100644 index 0000000000..ac07d34c29 --- /dev/null +++ b/benchmarks/client-nav/link-performance/staging.ts @@ -0,0 +1,10 @@ +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 new file mode 100644 index 0000000000..8f5f37413b --- /dev/null +++ b/benchmarks/client-nav/link-performance/statistics.test.ts @@ -0,0 +1,36 @@ +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 new file mode 100644 index 0000000000..469bdaf65a --- /dev/null +++ b/benchmarks/client-nav/link-performance/statistics.ts @@ -0,0 +1,57 @@ +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 new file mode 100644 index 0000000000..fbf230c977 --- /dev/null +++ b/benchmarks/client-nav/link-performance/tsconfig.json @@ -0,0 +1,15 @@ +{ + "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 new file mode 100644 index 0000000000..1cd45fc45e --- /dev/null +++ b/benchmarks/client-nav/link-performance/vite.client.config.ts @@ -0,0 +1,3 @@ +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 new file mode 100644 index 0000000000..f59148eaf6 --- /dev/null +++ b/benchmarks/client-nav/link-performance/vite.ssr.config.ts @@ -0,0 +1,3 @@ +import { createLinkPerformanceConfig } from './config' + +export default createLinkPerformanceConfig('ssr') diff --git a/benchmarks/client-nav/link-performance/vitest.config.ts b/benchmarks/client-nav/link-performance/vitest.config.ts new file mode 100644 index 0000000000..f8454c819d --- /dev/null +++ b/benchmarks/client-nav/link-performance/vitest.config.ts @@ -0,0 +1,11 @@ +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', + include: ['*.test.ts'], + }, +}) diff --git a/benchmarks/client-nav/link-performance/worker-protocol.ts b/benchmarks/client-nav/link-performance/worker-protocol.ts new file mode 100644 index 0000000000..474858a529 --- /dev/null +++ b/benchmarks/client-nav/link-performance/worker-protocol.ts @@ -0,0 +1,28 @@ +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 5b1262c31d..1f878adc67 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 --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: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: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,19 +31,21 @@ }, "devDependencies": { "@platformatic/flame": "^1.6.0", - "@codspeed/vitest-plugin": "^5.5.0", + "@codspeed/vitest-plugin": "^6.0.1", "@tanstack/router-plugin": "workspace:^", "@testing-library/react": "^16.2.0", "@vitejs/plugin-react": "^6.0.1", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "@types/jsdom": "28.0.0", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", "@typescript/native": "npm:typescript@^7.0.2", "jsdom": "^29.1.1", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11", - "vitest": "^4.1.4" + "vitest": "catalog:" }, "nx": { "targets": { @@ -62,6 +64,8 @@ "@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", @@ -90,6 +94,8 @@ "@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", @@ -118,6 +124,7 @@ "@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", @@ -176,7 +183,13 @@ ] }, "test:types": { - "cache": false, + "inputs": [ + "default", + "^production", + "{workspaceRoot}/eslint.config.js", + "{workspaceRoot}/benchmarks/cpu-simulation.ts", + "dependentTaskOutputs" + ], "dependsOn": [ "^build", { @@ -193,8 +206,13 @@ "@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 fcc15b5fbc..944f182734 100644 --- a/benchmarks/client-nav/react/speed.bench.ts +++ b/benchmarks/client-nav/react/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' import { setup } from './setup' -describe('client-nav', () => { - const test = setup() +test('client-nav', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-side navigation loop (react)', + { beforeAll: scenario.before, afterAll: scenario.after }, async () => { for (let i = 0; i < 10; i++) { - await test.tick() + await scenario.tick() } }, - { - warmupIterations: 100, - time: 10_000, - setup: test.before, - teardown: test.after, - }, - ) + ).run({ + warmupIterations: 100, + time: 10_000, + }) }) diff --git a/benchmarks/client-nav/react/vite.config.ts b/benchmarks/client-nav/react/vite.config.ts index adc31ddd64..7df3f80e71 100644 --- a/benchmarks/client-nav/react/vite.config.ts +++ b/benchmarks/client-nav/react/vite.config.ts @@ -2,6 +2,7 @@ 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' // Anchor the project root to the package directory so this config resolves // identically when run directly and as part of an aggregate `projects` config. @@ -28,9 +29,11 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav (react)', 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 c3f4c5231c..65dab0781e 100644 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-async-pipeline', () => { - const test = setup() +test('client-async-pipeline', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-async-pipeline navigation loop (react)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/vite.config.ts b/benchmarks/client-nav/scenarios/async-pipeline/react/vite.config.ts index 7161c9a13d..e36a5244b1 100644 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/vite.config.ts +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/vite.config.ts @@ -3,6 +3,7 @@ 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)) @@ -32,6 +33,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav async-pipeline (react)', watch: false, environment: 'jsdom', 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 96082e9963..acef710469 100644 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-async-pipeline', () => { - const test = setup() +test('client-async-pipeline', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-async-pipeline navigation loop (solid)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) 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 7c15baf4e9..27b9498b11 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 NestedRouteImport } from './routes/nested' 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 NestedRouteImport } from './routes/nested' import { Route as CtxIdRouteImport } from './routes/ctx.$id' +import { Route as NestedIdRouteImport } from './routes/nested.$id' +import { Route as SlowIdRouteImport } from './routes/slow.$id' -const NestedRoute = NestedRouteImport.update({ - id: '/nested', - path: '/nested', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const SlowIdRoute = SlowIdRouteImport.update({ - id: '/slow/$id', - path: '/slow/$id', +const NestedRoute = NestedRouteImport.update({ + id: '/nested', + path: '/nested', + getParentRoute: () => rootRouteImport, +} as any) +const CtxIdRoute = CtxIdRouteImport.update({ + id: '/ctx/$id', + path: '/ctx/$id', getParentRoute: () => rootRouteImport, } as any) const NestedIdRoute = NestedIdRouteImport.update({ @@ -35,9 +35,9 @@ const NestedIdRoute = NestedIdRouteImport.update({ path: '/$id', getParentRoute: () => NestedRoute, } as any) -const CtxIdRoute = CtxIdRouteImport.update({ - id: '/ctx/$id', - path: '/ctx/$id', +const SlowIdRoute = SlowIdRouteImport.update({ + id: '/slow/$id', + path: '/slow/$id', getParentRoute: () => rootRouteImport, } as any) @@ -80,13 +80,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/nested': { - id: '/nested' - path: '/nested' - fullPath: '/nested' - preLoaderRoute: typeof NestedRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -94,11 +87,18 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/slow/$id': { - id: '/slow/$id' - path: '/slow/$id' - fullPath: '/slow/$id' - preLoaderRoute: typeof SlowIdRouteImport + '/nested': { + id: '/nested' + path: '/nested' + fullPath: '/nested' + preLoaderRoute: typeof NestedRouteImport + parentRoute: typeof rootRouteImport + } + '/ctx/$id': { + id: '/ctx/$id' + path: '/ctx/$id' + fullPath: '/ctx/$id' + preLoaderRoute: typeof CtxIdRouteImport parentRoute: typeof rootRouteImport } '/nested/$id': { @@ -108,11 +108,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof NestedIdRouteImport parentRoute: typeof NestedRoute } - '/ctx/$id': { - id: '/ctx/$id' - path: '/ctx/$id' - fullPath: '/ctx/$id' - preLoaderRoute: typeof CtxIdRouteImport + '/slow/$id': { + id: '/slow/$id' + path: '/slow/$id' + fullPath: '/slow/$id' + preLoaderRoute: typeof SlowIdRouteImport parentRoute: typeof rootRouteImport } } diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/vite.config.ts b/benchmarks/client-nav/scenarios/async-pipeline/solid/vite.config.ts index 5107c1f056..214da8042e 100644 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/vite.config.ts +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/vite.config.ts @@ -3,6 +3,7 @@ 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)) @@ -35,6 +36,7 @@ export default defineConfig({ conditions: ['solid', 'browser'], }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav async-pipeline (solid)', watch: false, environment: 'jsdom', 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 193a3837df..f0fd3e58df 100644 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-async-pipeline', () => { - const test = setup() +test('client-async-pipeline', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-async-pipeline navigation loop (vue)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) 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 ce26dc62d1..66b9efd7aa 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 NestedRouteImport } from './routes/nested' 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 NestedRouteImport } from './routes/nested' import { Route as CtxIdRouteImport } from './routes/ctx.$id' +import { Route as NestedIdRouteImport } from './routes/nested.$id' +import { Route as SlowIdRouteImport } from './routes/slow.$id' -const NestedRoute = NestedRouteImport.update({ - id: '/nested', - path: '/nested', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const SlowIdRoute = SlowIdRouteImport.update({ - id: '/slow/$id', - path: '/slow/$id', +const NestedRoute = NestedRouteImport.update({ + id: '/nested', + path: '/nested', + getParentRoute: () => rootRouteImport, +} as any) +const CtxIdRoute = CtxIdRouteImport.update({ + id: '/ctx/$id', + path: '/ctx/$id', getParentRoute: () => rootRouteImport, } as any) const NestedIdRoute = NestedIdRouteImport.update({ @@ -35,9 +35,9 @@ const NestedIdRoute = NestedIdRouteImport.update({ path: '/$id', getParentRoute: () => NestedRoute, } as any) -const CtxIdRoute = CtxIdRouteImport.update({ - id: '/ctx/$id', - path: '/ctx/$id', +const SlowIdRoute = SlowIdRouteImport.update({ + id: '/slow/$id', + path: '/slow/$id', getParentRoute: () => rootRouteImport, } as any) @@ -80,13 +80,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/nested': { - id: '/nested' - path: '/nested' - fullPath: '/nested' - preLoaderRoute: typeof NestedRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -94,11 +87,18 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/slow/$id': { - id: '/slow/$id' - path: '/slow/$id' - fullPath: '/slow/$id' - preLoaderRoute: typeof SlowIdRouteImport + '/nested': { + id: '/nested' + path: '/nested' + fullPath: '/nested' + preLoaderRoute: typeof NestedRouteImport + parentRoute: typeof rootRouteImport + } + '/ctx/$id': { + id: '/ctx/$id' + path: '/ctx/$id' + fullPath: '/ctx/$id' + preLoaderRoute: typeof CtxIdRouteImport parentRoute: typeof rootRouteImport } '/nested/$id': { @@ -108,11 +108,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof NestedIdRouteImport parentRoute: typeof NestedRoute } - '/ctx/$id': { - id: '/ctx/$id' - path: '/ctx/$id' - fullPath: '/ctx/$id' - preLoaderRoute: typeof CtxIdRouteImport + '/slow/$id': { + id: '/slow/$id' + path: '/slow/$id' + fullPath: '/slow/$id' + preLoaderRoute: typeof SlowIdRouteImport parentRoute: typeof rootRouteImport } } diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/vite.config.ts b/benchmarks/client-nav/scenarios/async-pipeline/vue/vite.config.ts index e16a8ee828..ce4fa7318a 100644 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/vite.config.ts +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/vite.config.ts @@ -4,6 +4,7 @@ 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)) @@ -34,6 +35,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav async-pipeline (vue)', watch: false, environment: 'jsdom', 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 7f1153021f..d6f2190be7 100644 --- a/benchmarks/client-nav/scenarios/control-flow/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/control-flow/react/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-control-flow', () => { - const test = setup() +test('client-control-flow', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-control-flow navigation loop (react)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/broken.tsx b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/broken.tsx index 2dc4a26486..b11bb845bc 100644 --- a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/broken.tsx +++ b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/broken.tsx @@ -12,5 +12,9 @@ export const Route = createFileRoute('/broken')({ }) function BrokenError(props: ErrorComponentProps) { - return
{props.error.message}
+ return ( +
+ {props.error instanceof Error ? props.error.message : String(props.error)} +
+ ) } diff --git a/benchmarks/client-nav/scenarios/control-flow/react/vite.config.ts b/benchmarks/client-nav/scenarios/control-flow/react/vite.config.ts index 1aa2c1fa35..1eefca0fc3 100644 --- a/benchmarks/client-nav/scenarios/control-flow/react/vite.config.ts +++ b/benchmarks/client-nav/scenarios/control-flow/react/vite.config.ts @@ -3,6 +3,7 @@ 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)) @@ -32,6 +33,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav control-flow (react)', watch: false, environment: 'jsdom', 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 a88093ca52..d803d2a313 100644 --- a/benchmarks/client-nav/scenarios/control-flow/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/control-flow/solid/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-control-flow', () => { - const test = setup() +test('client-control-flow', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-control-flow navigation loop (solid)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) 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 44d88e9f8d..cd84f99d5d 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 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 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 MissingIdRouteImport } from './routes/missing.$id' -const TargetRoute = TargetRouteImport.update({ - id: '/target', - path: '/target', - getParentRoute: () => rootRouteImport, -} as any) -const Hop2Route = Hop2RouteImport.update({ - id: '/hop2', - path: '/hop2', - getParentRoute: () => rootRouteImport, -} as any) -const Hop1Route = Hop1RouteImport.update({ - id: '/hop1', - path: '/hop1', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const BrokenRoute = BrokenRouteImport.update({ @@ -36,9 +26,19 @@ const BrokenRoute = BrokenRouteImport.update({ path: '/broken', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const Hop1Route = Hop1RouteImport.update({ + id: '/hop1', + path: '/hop1', + getParentRoute: () => rootRouteImport, +} as any) +const Hop2Route = Hop2RouteImport.update({ + id: '/hop2', + path: '/hop2', + getParentRoute: () => rootRouteImport, +} as any) +const TargetRoute = TargetRouteImport.update({ + id: '/target', + path: '/target', getParentRoute: () => rootRouteImport, } as any) const MissingIdRoute = MissingIdRouteImport.update({ @@ -98,25 +98,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/target': { - id: '/target' - path: '/target' - fullPath: '/target' - preLoaderRoute: typeof TargetRouteImport - parentRoute: typeof rootRouteImport - } - '/hop2': { - id: '/hop2' - path: '/hop2' - fullPath: '/hop2' - preLoaderRoute: typeof Hop2RouteImport - parentRoute: typeof rootRouteImport - } - '/hop1': { - id: '/hop1' - path: '/hop1' - fullPath: '/hop1' - preLoaderRoute: typeof Hop1RouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/broken': { @@ -126,11 +112,25 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof BrokenRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/hop1': { + id: '/hop1' + path: '/hop1' + fullPath: '/hop1' + preLoaderRoute: typeof Hop1RouteImport + parentRoute: typeof rootRouteImport + } + '/hop2': { + id: '/hop2' + path: '/hop2' + fullPath: '/hop2' + preLoaderRoute: typeof Hop2RouteImport + parentRoute: typeof rootRouteImport + } + '/target': { + id: '/target' + path: '/target' + fullPath: '/target' + preLoaderRoute: typeof TargetRouteImport parentRoute: typeof rootRouteImport } '/missing/$id': { diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/vite.config.ts b/benchmarks/client-nav/scenarios/control-flow/solid/vite.config.ts index 1c6244d3d1..f4fa916154 100644 --- a/benchmarks/client-nav/scenarios/control-flow/solid/vite.config.ts +++ b/benchmarks/client-nav/scenarios/control-flow/solid/vite.config.ts @@ -3,6 +3,7 @@ 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)) @@ -35,6 +36,7 @@ export default defineConfig({ conditions: ['solid', 'browser'], }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav control-flow (solid)', watch: false, environment: 'jsdom', 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 9a335cfb87..8a019945c7 100644 --- a/benchmarks/client-nav/scenarios/control-flow/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/control-flow/vue/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-control-flow', () => { - const test = setup() +test('client-control-flow', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-control-flow navigation loop (vue)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) 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 60fc846f89..6b53a6a203 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 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 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 MissingIdRouteImport } from './routes/missing.$id' -const TargetRoute = TargetRouteImport.update({ - id: '/target', - path: '/target', - getParentRoute: () => rootRouteImport, -} as any) -const Hop2Route = Hop2RouteImport.update({ - id: '/hop2', - path: '/hop2', - getParentRoute: () => rootRouteImport, -} as any) -const Hop1Route = Hop1RouteImport.update({ - id: '/hop1', - path: '/hop1', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const BrokenRoute = BrokenRouteImport.update({ @@ -36,9 +26,19 @@ const BrokenRoute = BrokenRouteImport.update({ path: '/broken', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const Hop1Route = Hop1RouteImport.update({ + id: '/hop1', + path: '/hop1', + getParentRoute: () => rootRouteImport, +} as any) +const Hop2Route = Hop2RouteImport.update({ + id: '/hop2', + path: '/hop2', + getParentRoute: () => rootRouteImport, +} as any) +const TargetRoute = TargetRouteImport.update({ + id: '/target', + path: '/target', getParentRoute: () => rootRouteImport, } as any) const MissingIdRoute = MissingIdRouteImport.update({ @@ -98,25 +98,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/target': { - id: '/target' - path: '/target' - fullPath: '/target' - preLoaderRoute: typeof TargetRouteImport - parentRoute: typeof rootRouteImport - } - '/hop2': { - id: '/hop2' - path: '/hop2' - fullPath: '/hop2' - preLoaderRoute: typeof Hop2RouteImport - parentRoute: typeof rootRouteImport - } - '/hop1': { - id: '/hop1' - path: '/hop1' - fullPath: '/hop1' - preLoaderRoute: typeof Hop1RouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/broken': { @@ -126,11 +112,25 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof BrokenRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/hop1': { + id: '/hop1' + path: '/hop1' + fullPath: '/hop1' + preLoaderRoute: typeof Hop1RouteImport + parentRoute: typeof rootRouteImport + } + '/hop2': { + id: '/hop2' + path: '/hop2' + fullPath: '/hop2' + preLoaderRoute: typeof Hop2RouteImport + parentRoute: typeof rootRouteImport + } + '/target': { + id: '/target' + path: '/target' + fullPath: '/target' + preLoaderRoute: typeof TargetRouteImport parentRoute: typeof rootRouteImport } '/missing/$id': { diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/vite.config.ts b/benchmarks/client-nav/scenarios/control-flow/vue/vite.config.ts index 4694cf69c8..3c2750d2a6 100644 --- a/benchmarks/client-nav/scenarios/control-flow/vue/vite.config.ts +++ b/benchmarks/client-nav/scenarios/control-flow/vue/vite.config.ts @@ -4,6 +4,7 @@ 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)) @@ -34,6 +35,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav control-flow (vue)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/head/react/speed.bench.ts b/benchmarks/client-nav/scenarios/head/react/speed.bench.ts index 97c76a1a11..d0d731a09f 100644 --- a/benchmarks/client-nav/scenarios/head/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/head/react/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-head', () => { - const test = setup() +test('client-head', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-head navigation loop (react)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/head/react/vite.config.ts b/benchmarks/client-nav/scenarios/head/react/vite.config.ts index 086bd60bb4..7c8d6d4c15 100644 --- a/benchmarks/client-nav/scenarios/head/react/vite.config.ts +++ b/benchmarks/client-nav/scenarios/head/react/vite.config.ts @@ -3,6 +3,7 @@ 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)) @@ -32,6 +33,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav head (react)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/head/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/head/solid/speed.bench.ts index 075e7673de..ca156c950b 100644 --- a/benchmarks/client-nav/scenarios/head/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/head/solid/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-head', () => { - const test = setup() +test('client-head', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-head navigation loop (solid)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) 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 ead6a4436a..b6f217e527 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 SettingsRouteImport } from './routes/settings' -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 DocsRouteImport } from './routes/docs' +import { Route as SettingsRouteImport } from './routes/settings' import { Route as ArticlesIdRouteImport } from './routes/articles.$id' +import { Route as DocsSectionRouteImport } from './routes/docs.$section' -const SettingsRoute = SettingsRouteImport.update({ - id: '/settings', - path: '/settings', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const DocsRoute = DocsRouteImport.update({ @@ -25,9 +25,14 @@ const DocsRoute = DocsRouteImport.update({ path: '/docs', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const SettingsRoute = SettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => rootRouteImport, +} as any) +const ArticlesIdRoute = ArticlesIdRouteImport.update({ + id: '/articles/$id', + path: '/articles/$id', getParentRoute: () => rootRouteImport, } as any) const DocsSectionRoute = DocsSectionRouteImport.update({ @@ -35,11 +40,6 @@ 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 { - '/settings': { - id: '/settings' - path: '/settings' - fullPath: '/settings' - preLoaderRoute: typeof SettingsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/docs': { @@ -100,11 +100,18 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DocsRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/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 parentRoute: typeof rootRouteImport } '/docs/$section': { @@ -114,13 +121,6 @@ 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/solid/vite.config.ts b/benchmarks/client-nav/scenarios/head/solid/vite.config.ts index 7b5a1e22b4..986b2de2b0 100644 --- a/benchmarks/client-nav/scenarios/head/solid/vite.config.ts +++ b/benchmarks/client-nav/scenarios/head/solid/vite.config.ts @@ -3,6 +3,7 @@ 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)) @@ -35,6 +36,7 @@ export default defineConfig({ conditions: ['solid', 'browser'], }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav head (solid)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/head/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/head/vue/speed.bench.ts index 7080b4ea7d..d188a9dd7a 100644 --- a/benchmarks/client-nav/scenarios/head/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/head/vue/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-head', () => { - const test = setup() +test('client-head', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-head navigation loop (vue)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) 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 b115854c26..161f99a65c 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 SettingsRouteImport } from './routes/settings' -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 DocsRouteImport } from './routes/docs' +import { Route as SettingsRouteImport } from './routes/settings' import { Route as ArticlesIdRouteImport } from './routes/articles.$id' +import { Route as DocsSectionRouteImport } from './routes/docs.$section' -const SettingsRoute = SettingsRouteImport.update({ - id: '/settings', - path: '/settings', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const DocsRoute = DocsRouteImport.update({ @@ -25,9 +25,14 @@ const DocsRoute = DocsRouteImport.update({ path: '/docs', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const SettingsRoute = SettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => rootRouteImport, +} as any) +const ArticlesIdRoute = ArticlesIdRouteImport.update({ + id: '/articles/$id', + path: '/articles/$id', getParentRoute: () => rootRouteImport, } as any) const DocsSectionRoute = DocsSectionRouteImport.update({ @@ -35,11 +40,6 @@ 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 { - '/settings': { - id: '/settings' - path: '/settings' - fullPath: '/settings' - preLoaderRoute: typeof SettingsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/docs': { @@ -100,11 +100,18 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof DocsRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/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 parentRoute: typeof rootRouteImport } '/docs/$section': { @@ -114,13 +121,6 @@ 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/head/vue/vite.config.ts b/benchmarks/client-nav/scenarios/head/vue/vite.config.ts index 0ad2067925..bb1126d85f 100644 --- a/benchmarks/client-nav/scenarios/head/vue/vite.config.ts +++ b/benchmarks/client-nav/scenarios/head/vue/vite.config.ts @@ -4,6 +4,7 @@ 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)) @@ -34,6 +35,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav head (vue)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/history/react/speed.bench.ts b/benchmarks/client-nav/scenarios/history/react/speed.bench.ts index 9192258b66..6ec7031857 100644 --- a/benchmarks/client-nav/scenarios/history/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/history/react/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-history', () => { - const test = setup() +test('client-history', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-history navigation loop (react)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/history/react/vite.config.ts b/benchmarks/client-nav/scenarios/history/react/vite.config.ts index 61a1b2feef..bdbde9c668 100644 --- a/benchmarks/client-nav/scenarios/history/react/vite.config.ts +++ b/benchmarks/client-nav/scenarios/history/react/vite.config.ts @@ -3,6 +3,7 @@ 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)) @@ -32,6 +33,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav history (react)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/history/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/history/solid/speed.bench.ts index d7f4fd898d..56af035b2b 100644 --- a/benchmarks/client-nav/scenarios/history/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/history/solid/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-history', () => { - const test = setup() +test('client-history', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-history navigation loop (solid)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) 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 a6ab2a4fc8..af253f4a15 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 GalleryRouteImport } from './routes/gallery' import { Route as IndexRouteImport } from './routes/index' -import { Route as PhotosPhotoIdRouteImport } from './routes/photos.$photoId' +import { Route as GalleryRouteImport } from './routes/gallery' import { Route as PagesNRouteImport } from './routes/pages.$n' +import { Route as PhotosPhotoIdRouteImport } from './routes/photos.$photoId' -const GalleryRoute = GalleryRouteImport.update({ - id: '/gallery', - path: '/gallery', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const PhotosPhotoIdRoute = PhotosPhotoIdRouteImport.update({ - id: '/photos/$photoId', - path: '/photos/$photoId', +const GalleryRoute = GalleryRouteImport.update({ + id: '/gallery', + path: '/gallery', getParentRoute: () => rootRouteImport, } as any) const PagesNRoute = PagesNRouteImport.update({ @@ -34,6 +29,11 @@ const PagesNRoute = PagesNRouteImport.update({ path: '/pages/$n', getParentRoute: () => rootRouteImport, } as any) +const PhotosPhotoIdRoute = PhotosPhotoIdRouteImport.update({ + id: '/photos/$photoId', + path: '/photos/$photoId', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -71,13 +71,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/gallery': { - id: '/gallery' - path: '/gallery' - fullPath: '/gallery' - preLoaderRoute: typeof GalleryRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -85,11 +78,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/photos/$photoId': { - id: '/photos/$photoId' - path: '/photos/$photoId' - fullPath: '/photos/$photoId' - preLoaderRoute: typeof PhotosPhotoIdRouteImport + '/gallery': { + id: '/gallery' + path: '/gallery' + fullPath: '/gallery' + preLoaderRoute: typeof GalleryRouteImport parentRoute: typeof rootRouteImport } '/pages/$n': { @@ -99,6 +92,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PagesNRouteImport parentRoute: typeof rootRouteImport } + '/photos/$photoId': { + id: '/photos/$photoId' + path: '/photos/$photoId' + fullPath: '/photos/$photoId' + preLoaderRoute: typeof PhotosPhotoIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/client-nav/scenarios/history/solid/vite.config.ts b/benchmarks/client-nav/scenarios/history/solid/vite.config.ts index de0eda543c..4da589ff0e 100644 --- a/benchmarks/client-nav/scenarios/history/solid/vite.config.ts +++ b/benchmarks/client-nav/scenarios/history/solid/vite.config.ts @@ -3,6 +3,7 @@ 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)) @@ -35,6 +36,7 @@ export default defineConfig({ conditions: ['solid', 'browser'], }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav history (solid)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/history/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/history/vue/speed.bench.ts index a378e45ac5..3d36ac4cfa 100644 --- a/benchmarks/client-nav/scenarios/history/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/history/vue/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-history', () => { - const test = setup() +test('client-history', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-history navigation loop (vue)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) 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 cee1b68870..519aef7c8f 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 GalleryRouteImport } from './routes/gallery' import { Route as IndexRouteImport } from './routes/index' -import { Route as PhotosPhotoIdRouteImport } from './routes/photos.$photoId' +import { Route as GalleryRouteImport } from './routes/gallery' import { Route as PagesNRouteImport } from './routes/pages.$n' +import { Route as PhotosPhotoIdRouteImport } from './routes/photos.$photoId' -const GalleryRoute = GalleryRouteImport.update({ - id: '/gallery', - path: '/gallery', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const PhotosPhotoIdRoute = PhotosPhotoIdRouteImport.update({ - id: '/photos/$photoId', - path: '/photos/$photoId', +const GalleryRoute = GalleryRouteImport.update({ + id: '/gallery', + path: '/gallery', getParentRoute: () => rootRouteImport, } as any) const PagesNRoute = PagesNRouteImport.update({ @@ -34,6 +29,11 @@ const PagesNRoute = PagesNRouteImport.update({ path: '/pages/$n', getParentRoute: () => rootRouteImport, } as any) +const PhotosPhotoIdRoute = PhotosPhotoIdRouteImport.update({ + id: '/photos/$photoId', + path: '/photos/$photoId', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -71,13 +71,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/gallery': { - id: '/gallery' - path: '/gallery' - fullPath: '/gallery' - preLoaderRoute: typeof GalleryRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -85,11 +78,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/photos/$photoId': { - id: '/photos/$photoId' - path: '/photos/$photoId' - fullPath: '/photos/$photoId' - preLoaderRoute: typeof PhotosPhotoIdRouteImport + '/gallery': { + id: '/gallery' + path: '/gallery' + fullPath: '/gallery' + preLoaderRoute: typeof GalleryRouteImport parentRoute: typeof rootRouteImport } '/pages/$n': { @@ -99,6 +92,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PagesNRouteImport parentRoute: typeof rootRouteImport } + '/photos/$photoId': { + id: '/photos/$photoId' + path: '/photos/$photoId' + fullPath: '/photos/$photoId' + preLoaderRoute: typeof PhotosPhotoIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/client-nav/scenarios/history/vue/vite.config.ts b/benchmarks/client-nav/scenarios/history/vue/vite.config.ts index 58986d6526..c5f1ca9807 100644 --- a/benchmarks/client-nav/scenarios/history/vue/vite.config.ts +++ b/benchmarks/client-nav/scenarios/history/vue/vite.config.ts @@ -4,6 +4,7 @@ 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)) @@ -34,6 +35,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav history (vue)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/hydration/react/fixture.ts b/benchmarks/client-nav/scenarios/hydration/react/fixture.ts new file mode 100644 index 0000000000..950c870a1c --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/fixture.ts @@ -0,0 +1,31 @@ +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 new file mode 100644 index 0000000000..fbc67c5a08 --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/generate-fixture.mjs @@ -0,0 +1,23 @@ +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 new file mode 100644 index 0000000000..7e466cbaed --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/hydration.test.ts @@ -0,0 +1,93 @@ +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 new file mode 100644 index 0000000000..ca23838c0f --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/project.json @@ -0,0 +1,40 @@ +{ + "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 new file mode 100644 index 0000000000..cc4c09a72d --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/settle.ts @@ -0,0 +1,35 @@ +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 new file mode 100644 index 0000000000..7c588af3fd --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/setup.ts @@ -0,0 +1,316 @@ +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 new file mode 100644 index 0000000000..643877760e --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/speed.bench.ts @@ -0,0 +1,19 @@ +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 new file mode 100644 index 0000000000..e9797f71fa --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/src/app.tsx @@ -0,0 +1,216 @@ +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 new file mode 100644 index 0000000000..42c5a5104e --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/src/client.tsx @@ -0,0 +1,83 @@ +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 new file mode 100644 index 0000000000..713b0a77f2 --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/src/server.tsx @@ -0,0 +1,29 @@ +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 new file mode 100644 index 0000000000..23dd08de8b --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/tsconfig.json @@ -0,0 +1,10 @@ +{ + "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 new file mode 100644 index 0000000000..62ab87115b --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/vite.config.ts @@ -0,0 +1,36 @@ +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 new file mode 100644 index 0000000000..fbf6a149b9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/vite.server.config.ts @@ -0,0 +1,26 @@ +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 new file mode 100644 index 0000000000..4c86d0e2f4 --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/solid/fixture.ts @@ -0,0 +1,35 @@ +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 new file mode 100644 index 0000000000..63647e1be7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/solid/generate-fixture.mjs @@ -0,0 +1,30 @@ +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 new file mode 100644 index 0000000000..4e5f3208ca --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/solid/hydration.test.ts @@ -0,0 +1,81 @@ +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 new file mode 100644 index 0000000000..1fa162771b --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/solid/project.json @@ -0,0 +1,40 @@ +{ + "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 new file mode 100644 index 0000000000..ebdbc8e9b2 --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/solid/setup.ts @@ -0,0 +1,326 @@ +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 new file mode 100644 index 0000000000..b386cb8215 --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/solid/speed.bench.ts @@ -0,0 +1,19 @@ +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 new file mode 100644 index 0000000000..cb772d6b5b --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/solid/src/app.tsx @@ -0,0 +1,213 @@ +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 new file mode 100644 index 0000000000..ef0f5268d6 --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/solid/src/client.tsx @@ -0,0 +1,91 @@ +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 new file mode 100644 index 0000000000..6052c48eac --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/solid/src/server.tsx @@ -0,0 +1,40 @@ +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 new file mode 100644 index 0000000000..daf27ddf12 --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/solid/tsconfig.json @@ -0,0 +1,10 @@ +{ + "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 new file mode 100644 index 0000000000..16e5ff95aa --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/solid/vite.config.ts @@ -0,0 +1,38 @@ +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 new file mode 100644 index 0000000000..9787cbb4e2 --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/solid/vite.server.config.ts @@ -0,0 +1,29 @@ +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 new file mode 100644 index 0000000000..1606b2c456 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/react/project.json @@ -0,0 +1,40 @@ +{ + "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 new file mode 100644 index 0000000000..59221603da --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/react/setup.ts @@ -0,0 +1,18 @@ +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 new file mode 100644 index 0000000000..ca0b370528 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/react/speed.bench.ts @@ -0,0 +1,19 @@ +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 new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/react/speed.flame.ts @@ -0,0 +1,18 @@ +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 new file mode 100644 index 0000000000..5febd6f795 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/react/src/main.tsx @@ -0,0 +1,37 @@ +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 new file mode 100644 index 0000000000..4535430b61 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/react/src/routeTree.gen.ts @@ -0,0 +1,121 @@ +/* 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 new file mode 100644 index 0000000000..199cf1ff73 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/react/src/routes/__root.tsx @@ -0,0 +1,39 @@ +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 new file mode 100644 index 0000000000..143cb39a7a --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/react/src/routes/hub.detail.$id.tsx @@ -0,0 +1,21 @@ +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 new file mode 100644 index 0000000000..5aa37b20a7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/react/src/routes/hub.list.tsx @@ -0,0 +1,65 @@ +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 new file mode 100644 index 0000000000..ac12eae2da --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/react/src/routes/hub.tsx @@ -0,0 +1,64 @@ +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 new file mode 100644 index 0000000000..1f146b789f --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/react/src/routes/other.tsx @@ -0,0 +1,14 @@ +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 new file mode 100644 index 0000000000..1d59cbb450 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/react/tsconfig.json @@ -0,0 +1,21 @@ +{ + "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 new file mode 100644 index 0000000000..344974ebf9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/react/vite.config.ts @@ -0,0 +1,42 @@ +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 new file mode 100644 index 0000000000..d936af35cc --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/shared.ts @@ -0,0 +1,178 @@ +/** + * 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 new file mode 100644 index 0000000000..4e46143b32 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/solid/project.json @@ -0,0 +1,40 @@ +{ + "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 new file mode 100644 index 0000000000..a2a024341d --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/solid/setup.ts @@ -0,0 +1,18 @@ +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 new file mode 100644 index 0000000000..80c4aaa6fd --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/solid/speed.bench.ts @@ -0,0 +1,19 @@ +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 new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/solid/speed.flame.ts @@ -0,0 +1,18 @@ +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 new file mode 100644 index 0000000000..fa9d239418 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/solid/src/main.tsx @@ -0,0 +1,34 @@ +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 new file mode 100644 index 0000000000..e3cb546963 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/solid/src/routeTree.gen.ts @@ -0,0 +1,121 @@ +/* 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 new file mode 100644 index 0000000000..a9de4ea356 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/__root.tsx @@ -0,0 +1,39 @@ +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 new file mode 100644 index 0000000000..7aca4a9935 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/hub.detail.$id.tsx @@ -0,0 +1,24 @@ +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 new file mode 100644 index 0000000000..5796a50b02 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/hub.list.tsx @@ -0,0 +1,68 @@ +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 new file mode 100644 index 0000000000..4682f85aae --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/hub.tsx @@ -0,0 +1,67 @@ +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 new file mode 100644 index 0000000000..2606089113 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/other.tsx @@ -0,0 +1,14 @@ +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 new file mode 100644 index 0000000000..98d76ad6b8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/solid/tsconfig.json @@ -0,0 +1,21 @@ +{ + "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 new file mode 100644 index 0000000000..37718a2d6a --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/solid/vite.config.ts @@ -0,0 +1,50 @@ +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 new file mode 100644 index 0000000000..fb890ddfb8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/vue/project.json @@ -0,0 +1,40 @@ +{ + "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 new file mode 100644 index 0000000000..95cacb9ea8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/vue/setup.ts @@ -0,0 +1,18 @@ +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 new file mode 100644 index 0000000000..dea511c24c --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/vue/speed.bench.ts @@ -0,0 +1,19 @@ +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 new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/vue/speed.flame.ts @@ -0,0 +1,18 @@ +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 new file mode 100644 index 0000000000..cae9b54f1d --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/vue/src/main.tsx @@ -0,0 +1,41 @@ +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 new file mode 100644 index 0000000000..9327bbc01d --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/vue/src/routeTree.gen.ts @@ -0,0 +1,121 @@ +/* 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 new file mode 100644 index 0000000000..a4f7985c5a --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/__root.tsx @@ -0,0 +1,46 @@ +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 new file mode 100644 index 0000000000..4701ab44eb --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/hub.detail.$id.tsx @@ -0,0 +1,27 @@ +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 new file mode 100644 index 0000000000..02abd6db1b --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/hub.list.tsx @@ -0,0 +1,74 @@ +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 new file mode 100644 index 0000000000..5be17f3350 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/hub.tsx @@ -0,0 +1,69 @@ +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 new file mode 100644 index 0000000000..08dec586fa --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/other.tsx @@ -0,0 +1,17 @@ +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 new file mode 100644 index 0000000000..7786fc3da9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/vue/tsconfig.json @@ -0,0 +1,21 @@ +{ + "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 new file mode 100644 index 0000000000..8f56734e04 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/vue/vite.config.ts @@ -0,0 +1,44 @@ +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 0892308901..75f5f725d4 100644 --- a/benchmarks/client-nav/scenarios/links/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/links/react/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-links', () => { - const test = setup() +test('client-links', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-links navigation loop (react)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/links/react/vite.config.ts b/benchmarks/client-nav/scenarios/links/react/vite.config.ts index 9e9cd48895..69de10b5b7 100644 --- a/benchmarks/client-nav/scenarios/links/react/vite.config.ts +++ b/benchmarks/client-nav/scenarios/links/react/vite.config.ts @@ -3,6 +3,7 @@ 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)) @@ -32,6 +33,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav links (react)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/links/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/links/solid/speed.bench.ts index a3d690b423..fc7f3e71e7 100644 --- a/benchmarks/client-nav/scenarios/links/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/links/solid/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-links', () => { - const test = setup() +test('client-links', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-links navigation loop (solid)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) 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 b61431e40d..0da70513e8 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 AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' import { Route as ItemsIdRouteImport } from './routes/items.$id' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + 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 { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -75,6 +68,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } '/items/$id': { id: '/items/$id' path: '/items/$id' diff --git a/benchmarks/client-nav/scenarios/links/solid/vite.config.ts b/benchmarks/client-nav/scenarios/links/solid/vite.config.ts index 9a5b3d138b..e37342ffc3 100644 --- a/benchmarks/client-nav/scenarios/links/solid/vite.config.ts +++ b/benchmarks/client-nav/scenarios/links/solid/vite.config.ts @@ -3,6 +3,7 @@ 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)) @@ -35,6 +36,7 @@ export default defineConfig({ conditions: ['solid', 'browser'], }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav links (solid)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/links/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/links/vue/speed.bench.ts index e2d3f7c47a..2ace7a8409 100644 --- a/benchmarks/client-nav/scenarios/links/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/links/vue/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-links', () => { - const test = setup() +test('client-links', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-links navigation loop (vue)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) 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 cee64be43c..7d2b1e9bbb 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 AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' import { Route as ItemsIdRouteImport } from './routes/items.$id' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + 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 { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -75,6 +68,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } '/items/$id': { id: '/items/$id' path: '/items/$id' diff --git a/benchmarks/client-nav/scenarios/links/vue/vite.config.ts b/benchmarks/client-nav/scenarios/links/vue/vite.config.ts index d1cf9f561d..ad89a49d70 100644 --- a/benchmarks/client-nav/scenarios/links/vue/vite.config.ts +++ b/benchmarks/client-nav/scenarios/links/vue/vite.config.ts @@ -4,6 +4,7 @@ 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)) @@ -34,6 +35,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav links (vue)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/loaders/react/speed.bench.ts b/benchmarks/client-nav/scenarios/loaders/react/speed.bench.ts index f5a51b29be..8bcc53b88e 100644 --- a/benchmarks/client-nav/scenarios/loaders/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/loaders/react/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-loaders', () => { - const test = setup() +test('client-loaders', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-loaders navigation loop (react)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/loaders/react/vite.config.ts b/benchmarks/client-nav/scenarios/loaders/react/vite.config.ts index 6fa28bcd35..818b224130 100644 --- a/benchmarks/client-nav/scenarios/loaders/react/vite.config.ts +++ b/benchmarks/client-nav/scenarios/loaders/react/vite.config.ts @@ -3,6 +3,7 @@ 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)) @@ -32,6 +33,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav loaders (react)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/loaders/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/loaders/solid/speed.bench.ts index 9f3bd397db..953a17b31a 100644 --- a/benchmarks/client-nav/scenarios/loaders/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/loaders/solid/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-loaders', () => { - const test = setup() +test('client-loaders', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-loaders navigation loop (solid)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) 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 bdec400237..fa5d032141 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 DepsRouteImport } from './routes/deps' import { Route as IndexRouteImport } from './routes/index' -import { Route as FreshIdRouteImport } from './routes/fresh.$id' +import { Route as DepsRouteImport } from './routes/deps' import { Route as CachedIdRouteImport } from './routes/cached.$id' +import { Route as FreshIdRouteImport } from './routes/fresh.$id' -const DepsRoute = DepsRouteImport.update({ - id: '/deps', - path: '/deps', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const FreshIdRoute = FreshIdRouteImport.update({ - id: '/fresh/$id', - path: '/fresh/$id', +const DepsRoute = DepsRouteImport.update({ + id: '/deps', + path: '/deps', getParentRoute: () => rootRouteImport, } as any) const CachedIdRoute = CachedIdRouteImport.update({ @@ -34,6 +29,11 @@ const CachedIdRoute = CachedIdRouteImport.update({ path: '/cached/$id', getParentRoute: () => rootRouteImport, } as any) +const FreshIdRoute = FreshIdRouteImport.update({ + id: '/fresh/$id', + path: '/fresh/$id', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -71,13 +71,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/deps': { - id: '/deps' - path: '/deps' - fullPath: '/deps' - preLoaderRoute: typeof DepsRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -85,11 +78,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/fresh/$id': { - id: '/fresh/$id' - path: '/fresh/$id' - fullPath: '/fresh/$id' - preLoaderRoute: typeof FreshIdRouteImport + '/deps': { + id: '/deps' + path: '/deps' + fullPath: '/deps' + preLoaderRoute: typeof DepsRouteImport parentRoute: typeof rootRouteImport } '/cached/$id': { @@ -99,6 +92,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof CachedIdRouteImport parentRoute: typeof rootRouteImport } + '/fresh/$id': { + id: '/fresh/$id' + path: '/fresh/$id' + fullPath: '/fresh/$id' + preLoaderRoute: typeof FreshIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/client-nav/scenarios/loaders/solid/vite.config.ts b/benchmarks/client-nav/scenarios/loaders/solid/vite.config.ts index ea913ac578..90584d3b7e 100644 --- a/benchmarks/client-nav/scenarios/loaders/solid/vite.config.ts +++ b/benchmarks/client-nav/scenarios/loaders/solid/vite.config.ts @@ -3,6 +3,7 @@ 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)) @@ -35,6 +36,7 @@ export default defineConfig({ conditions: ['solid', 'browser'], }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav loaders (solid)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/loaders/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/loaders/vue/speed.bench.ts index 819fe020b0..1ae2f89a56 100644 --- a/benchmarks/client-nav/scenarios/loaders/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/loaders/vue/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-loaders', () => { - const test = setup() +test('client-loaders', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-loaders navigation loop (vue)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) 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 25a82df477..10cb8f2aca 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 DepsRouteImport } from './routes/deps' import { Route as IndexRouteImport } from './routes/index' -import { Route as FreshIdRouteImport } from './routes/fresh.$id' +import { Route as DepsRouteImport } from './routes/deps' import { Route as CachedIdRouteImport } from './routes/cached.$id' +import { Route as FreshIdRouteImport } from './routes/fresh.$id' -const DepsRoute = DepsRouteImport.update({ - id: '/deps', - path: '/deps', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const FreshIdRoute = FreshIdRouteImport.update({ - id: '/fresh/$id', - path: '/fresh/$id', +const DepsRoute = DepsRouteImport.update({ + id: '/deps', + path: '/deps', getParentRoute: () => rootRouteImport, } as any) const CachedIdRoute = CachedIdRouteImport.update({ @@ -34,6 +29,11 @@ const CachedIdRoute = CachedIdRouteImport.update({ path: '/cached/$id', getParentRoute: () => rootRouteImport, } as any) +const FreshIdRoute = FreshIdRouteImport.update({ + id: '/fresh/$id', + path: '/fresh/$id', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -71,13 +71,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/deps': { - id: '/deps' - path: '/deps' - fullPath: '/deps' - preLoaderRoute: typeof DepsRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -85,11 +78,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/fresh/$id': { - id: '/fresh/$id' - path: '/fresh/$id' - fullPath: '/fresh/$id' - preLoaderRoute: typeof FreshIdRouteImport + '/deps': { + id: '/deps' + path: '/deps' + fullPath: '/deps' + preLoaderRoute: typeof DepsRouteImport parentRoute: typeof rootRouteImport } '/cached/$id': { @@ -99,6 +92,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof CachedIdRouteImport parentRoute: typeof rootRouteImport } + '/fresh/$id': { + id: '/fresh/$id' + path: '/fresh/$id' + fullPath: '/fresh/$id' + preLoaderRoute: typeof FreshIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/client-nav/scenarios/loaders/vue/vite.config.ts b/benchmarks/client-nav/scenarios/loaders/vue/vite.config.ts index 350fadf387..ecf4cce139 100644 --- a/benchmarks/client-nav/scenarios/loaders/vue/vite.config.ts +++ b/benchmarks/client-nav/scenarios/loaders/vue/vite.config.ts @@ -4,6 +4,7 @@ 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)) @@ -34,6 +35,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav loaders (vue)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/mount/react/speed.bench.ts b/benchmarks/client-nav/scenarios/mount/react/speed.bench.ts index 2d675ff259..6c3a64b026 100644 --- a/benchmarks/client-nav/scenarios/mount/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/mount/react/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-mount', () => { - const test = setup() +test('client-mount', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-mount loop (react)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/mount/react/vite.config.ts b/benchmarks/client-nav/scenarios/mount/react/vite.config.ts index 68ee46738a..e197d33a9e 100644 --- a/benchmarks/client-nav/scenarios/mount/react/vite.config.ts +++ b/benchmarks/client-nav/scenarios/mount/react/vite.config.ts @@ -3,6 +3,7 @@ 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)) @@ -32,6 +33,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav mount (react)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/mount/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/mount/solid/speed.bench.ts index eaf7f1ed34..236f875f57 100644 --- a/benchmarks/client-nav/scenarios/mount/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/mount/solid/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-mount', () => { - const test = setup() +test('client-mount', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-mount loop (solid)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) 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 dc0acc183d..30247636dd 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 ShopRouteImport } from './routes/shop' -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 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 ShopProductIdRouteImport } from './routes/shop.$productId' import { Route as BlogSlugRouteImport } from './routes/blog.$slug' +import { Route as ShopIndexRouteImport } from './routes/shop.index' +import { Route as ShopProductIdRouteImport } from './routes/shop.$productId' -const ShopRoute = ShopRouteImport.update({ - id: '/shop', - path: '/shop', - getParentRoute: () => rootRouteImport, -} as any) -const SettingsRoute = SettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => rootRouteImport, -} as any) -const SearchRoute = SearchRouteImport.update({ - id: '/search', - path: '/search', - getParentRoute: () => rootRouteImport, -} as any) -const BlogRoute = BlogRouteImport.update({ - id: '/blog', - path: '/blog', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AboutRoute = AboutRouteImport.update({ @@ -45,31 +30,46 @@ const AboutRoute = AboutRouteImport.update({ path: '/about', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const BlogRoute = BlogRouteImport.update({ + id: '/blog', + path: '/blog', getParentRoute: () => rootRouteImport, } as any) -const ShopIndexRoute = ShopIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => ShopRoute, +const SearchRoute = SearchRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => rootRouteImport, +} as any) +const SettingsRoute = SettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => rootRouteImport, +} as any) +const ShopRoute = ShopRouteImport.update({ + id: '/shop', + path: '/shop', + getParentRoute: () => rootRouteImport, } 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) +const ShopIndexRoute = ShopIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => ShopRoute, +} as any) +const ShopProductIdRoute = ShopProductIdRouteImport.update({ + id: '/$productId', + path: '/$productId', + getParentRoute: () => ShopRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -154,32 +154,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/shop': { - id: '/shop' - path: '/shop' - fullPath: '/shop' - preLoaderRoute: typeof ShopRouteImport - parentRoute: typeof rootRouteImport - } - '/settings': { - id: '/settings' - path: '/settings' - fullPath: '/settings' - preLoaderRoute: typeof SettingsRouteImport - parentRoute: typeof rootRouteImport - } - '/search': { - id: '/search' - path: '/search' - fullPath: '/search' - preLoaderRoute: typeof SearchRouteImport - parentRoute: typeof rootRouteImport - } - '/blog': { - id: '/blog' - path: '/blog' - fullPath: '/blog' - preLoaderRoute: typeof BlogRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/about': { @@ -189,19 +168,33 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/blog': { + id: '/blog' + path: '/blog' + fullPath: '/blog' + preLoaderRoute: typeof BlogRouteImport parentRoute: typeof rootRouteImport } - '/shop/': { - id: '/shop/' - path: '/' - fullPath: '/shop/' - preLoaderRoute: typeof ShopIndexRouteImport - parentRoute: typeof ShopRoute + '/search': { + id: '/search' + path: '/search' + fullPath: '/search' + preLoaderRoute: typeof SearchRouteImport + parentRoute: typeof rootRouteImport + } + '/settings': { + id: '/settings' + path: '/settings' + fullPath: '/settings' + preLoaderRoute: typeof SettingsRouteImport + parentRoute: typeof rootRouteImport + } + '/shop': { + id: '/shop' + path: '/shop' + fullPath: '/shop' + preLoaderRoute: typeof ShopRouteImport + parentRoute: typeof rootRouteImport } '/blog/': { id: '/blog/' @@ -210,13 +203,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof BlogIndexRouteImport parentRoute: typeof BlogRoute } - '/shop/$productId': { - id: '/shop/$productId' - path: '/$productId' - fullPath: '/shop/$productId' - preLoaderRoute: typeof ShopProductIdRouteImport - parentRoute: typeof ShopRoute - } '/blog/$slug': { id: '/blog/$slug' path: '/$slug' @@ -224,6 +210,20 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof BlogSlugRouteImport parentRoute: typeof BlogRoute } + '/shop/': { + id: '/shop/' + path: '/' + fullPath: '/shop/' + preLoaderRoute: typeof ShopIndexRouteImport + parentRoute: typeof ShopRoute + } + '/shop/$productId': { + id: '/shop/$productId' + path: '/$productId' + fullPath: '/shop/$productId' + preLoaderRoute: typeof ShopProductIdRouteImport + parentRoute: typeof ShopRoute + } } } diff --git a/benchmarks/client-nav/scenarios/mount/solid/vite.config.ts b/benchmarks/client-nav/scenarios/mount/solid/vite.config.ts index 910d332f9c..5b586dd128 100644 --- a/benchmarks/client-nav/scenarios/mount/solid/vite.config.ts +++ b/benchmarks/client-nav/scenarios/mount/solid/vite.config.ts @@ -3,6 +3,7 @@ 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)) @@ -35,6 +36,7 @@ export default defineConfig({ conditions: ['solid', 'browser'], }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav mount (solid)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/mount/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/mount/vue/speed.bench.ts index f5538dd49c..d9268ba91b 100644 --- a/benchmarks/client-nav/scenarios/mount/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/mount/vue/speed.bench.ts @@ -1,32 +1,15 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-mount', () => { - const test = setup() +test('client-mount', async ({ bench }) => { + const scenario = setup() - /** - * 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, - }, - ) + await bench('client-mount 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/mount/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/mount/vue/src/routeTree.gen.ts index 98643d63c9..cd27c917e1 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 ShopRouteImport } from './routes/shop' -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 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 ShopProductIdRouteImport } from './routes/shop.$productId' import { Route as BlogSlugRouteImport } from './routes/blog.$slug' +import { Route as ShopIndexRouteImport } from './routes/shop.index' +import { Route as ShopProductIdRouteImport } from './routes/shop.$productId' -const ShopRoute = ShopRouteImport.update({ - id: '/shop', - path: '/shop', - getParentRoute: () => rootRouteImport, -} as any) -const SettingsRoute = SettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => rootRouteImport, -} as any) -const SearchRoute = SearchRouteImport.update({ - id: '/search', - path: '/search', - getParentRoute: () => rootRouteImport, -} as any) -const BlogRoute = BlogRouteImport.update({ - id: '/blog', - path: '/blog', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AboutRoute = AboutRouteImport.update({ @@ -45,31 +30,46 @@ const AboutRoute = AboutRouteImport.update({ path: '/about', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const BlogRoute = BlogRouteImport.update({ + id: '/blog', + path: '/blog', getParentRoute: () => rootRouteImport, } as any) -const ShopIndexRoute = ShopIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => ShopRoute, +const SearchRoute = SearchRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => rootRouteImport, +} as any) +const SettingsRoute = SettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => rootRouteImport, +} as any) +const ShopRoute = ShopRouteImport.update({ + id: '/shop', + path: '/shop', + getParentRoute: () => rootRouteImport, } 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) +const ShopIndexRoute = ShopIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => ShopRoute, +} as any) +const ShopProductIdRoute = ShopProductIdRouteImport.update({ + id: '/$productId', + path: '/$productId', + getParentRoute: () => ShopRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -154,32 +154,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/shop': { - id: '/shop' - path: '/shop' - fullPath: '/shop' - preLoaderRoute: typeof ShopRouteImport - parentRoute: typeof rootRouteImport - } - '/settings': { - id: '/settings' - path: '/settings' - fullPath: '/settings' - preLoaderRoute: typeof SettingsRouteImport - parentRoute: typeof rootRouteImport - } - '/search': { - id: '/search' - path: '/search' - fullPath: '/search' - preLoaderRoute: typeof SearchRouteImport - parentRoute: typeof rootRouteImport - } - '/blog': { - id: '/blog' - path: '/blog' - fullPath: '/blog' - preLoaderRoute: typeof BlogRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/about': { @@ -189,19 +168,33 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/blog': { + id: '/blog' + path: '/blog' + fullPath: '/blog' + preLoaderRoute: typeof BlogRouteImport parentRoute: typeof rootRouteImport } - '/shop/': { - id: '/shop/' - path: '/' - fullPath: '/shop/' - preLoaderRoute: typeof ShopIndexRouteImport - parentRoute: typeof ShopRoute + '/search': { + id: '/search' + path: '/search' + fullPath: '/search' + preLoaderRoute: typeof SearchRouteImport + parentRoute: typeof rootRouteImport + } + '/settings': { + id: '/settings' + path: '/settings' + fullPath: '/settings' + preLoaderRoute: typeof SettingsRouteImport + parentRoute: typeof rootRouteImport + } + '/shop': { + id: '/shop' + path: '/shop' + fullPath: '/shop' + preLoaderRoute: typeof ShopRouteImport + parentRoute: typeof rootRouteImport } '/blog/': { id: '/blog/' @@ -210,13 +203,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof BlogIndexRouteImport parentRoute: typeof BlogRoute } - '/shop/$productId': { - id: '/shop/$productId' - path: '/$productId' - fullPath: '/shop/$productId' - preLoaderRoute: typeof ShopProductIdRouteImport - parentRoute: typeof ShopRoute - } '/blog/$slug': { id: '/blog/$slug' path: '/$slug' @@ -224,6 +210,20 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof BlogSlugRouteImport parentRoute: typeof BlogRoute } + '/shop/': { + id: '/shop/' + path: '/' + fullPath: '/shop/' + preLoaderRoute: typeof ShopIndexRouteImport + parentRoute: typeof ShopRoute + } + '/shop/$productId': { + id: '/shop/$productId' + path: '/$productId' + fullPath: '/shop/$productId' + preLoaderRoute: typeof ShopProductIdRouteImport + parentRoute: typeof ShopRoute + } } } diff --git a/benchmarks/client-nav/scenarios/mount/vue/vite.config.ts b/benchmarks/client-nav/scenarios/mount/vue/vite.config.ts index 107e1037b6..8d4005f339 100644 --- a/benchmarks/client-nav/scenarios/mount/vue/vite.config.ts +++ b/benchmarks/client-nav/scenarios/mount/vue/vite.config.ts @@ -4,6 +4,7 @@ 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)) @@ -34,6 +35,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav mount (vue)', watch: false, environment: 'jsdom', 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 3dfe93c117..fa5809c1fd 100644 --- a/benchmarks/client-nav/scenarios/nested-params/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/nested-params/react/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-nested-params', () => { - const test = setup() +test('client-nested-params', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-nested-params navigation loop (react)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/nested-params/react/vite.config.ts b/benchmarks/client-nav/scenarios/nested-params/react/vite.config.ts index 672b1850ff..a99060bf1c 100644 --- a/benchmarks/client-nav/scenarios/nested-params/react/vite.config.ts +++ b/benchmarks/client-nav/scenarios/nested-params/react/vite.config.ts @@ -3,6 +3,7 @@ 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)) @@ -32,6 +33,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav nested-params (react)', watch: false, environment: 'jsdom', 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 dc7ec11f6b..2c64d9a221 100644 --- a/benchmarks/client-nav/scenarios/nested-params/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/nested-params/solid/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-nested-params', () => { - const test = setup() +test('client-nested-params', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-nested-params navigation loop (solid)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/vite.config.ts b/benchmarks/client-nav/scenarios/nested-params/solid/vite.config.ts index f5c9e13c0f..9897e2c199 100644 --- a/benchmarks/client-nav/scenarios/nested-params/solid/vite.config.ts +++ b/benchmarks/client-nav/scenarios/nested-params/solid/vite.config.ts @@ -3,6 +3,7 @@ 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)) @@ -35,6 +36,7 @@ export default defineConfig({ conditions: ['solid', 'browser'], }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav nested-params (solid)', watch: false, environment: 'jsdom', 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 fcb336d1db..bd3e82e070 100644 --- a/benchmarks/client-nav/scenarios/nested-params/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/nested-params/vue/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-nested-params', () => { - const test = setup() +test('client-nested-params', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-nested-params navigation loop (vue)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/vite.config.ts b/benchmarks/client-nav/scenarios/nested-params/vue/vite.config.ts index 59a4af48ef..0d74eb7a7c 100644 --- a/benchmarks/client-nav/scenarios/nested-params/vue/vite.config.ts +++ b/benchmarks/client-nav/scenarios/nested-params/vue/vite.config.ts @@ -4,6 +4,7 @@ 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)) @@ -34,6 +35,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav nested-params (vue)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/preload/react/speed.bench.ts b/benchmarks/client-nav/scenarios/preload/react/speed.bench.ts index 5b188a0a0b..5c210b2fd7 100644 --- a/benchmarks/client-nav/scenarios/preload/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/preload/react/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-preload', () => { - const test = setup() +test('client-preload', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-preload interaction loop (react)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/preload/react/vite.config.ts b/benchmarks/client-nav/scenarios/preload/react/vite.config.ts index ff51686959..8a41fc8707 100644 --- a/benchmarks/client-nav/scenarios/preload/react/vite.config.ts +++ b/benchmarks/client-nav/scenarios/preload/react/vite.config.ts @@ -3,6 +3,7 @@ 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)) @@ -32,6 +33,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav preload (react)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/preload/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/preload/solid/speed.bench.ts index 267c9fd41d..f835b4a7b9 100644 --- a/benchmarks/client-nav/scenarios/preload/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/preload/solid/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-preload', () => { - const test = setup() +test('client-preload', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-preload interaction loop (solid)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) 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 645d925238..97e215b6da 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 DocsRouteImport } from './routes/docs' import { Route as IndexRouteImport } from './routes/index' +import { Route as DocsRouteImport } from './routes/docs' import { Route as SectionsSectionRouteImport } from './routes/sections.$section' -const DocsRoute = DocsRouteImport.update({ - id: '/docs', - path: '/docs', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const DocsRoute = DocsRouteImport.update({ + id: '/docs', + path: '/docs', + 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 { - '/docs': { - id: '/docs' - path: '/docs' - fullPath: '/docs' - preLoaderRoute: typeof DocsRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -75,6 +68,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/docs': { + id: '/docs' + path: '/docs' + fullPath: '/docs' + preLoaderRoute: typeof DocsRouteImport + parentRoute: typeof rootRouteImport + } '/sections/$section': { id: '/sections/$section' path: '/sections/$section' diff --git a/benchmarks/client-nav/scenarios/preload/solid/vite.config.ts b/benchmarks/client-nav/scenarios/preload/solid/vite.config.ts index b542834469..07014e6124 100644 --- a/benchmarks/client-nav/scenarios/preload/solid/vite.config.ts +++ b/benchmarks/client-nav/scenarios/preload/solid/vite.config.ts @@ -3,6 +3,7 @@ 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)) @@ -35,6 +36,7 @@ export default defineConfig({ conditions: ['solid', 'browser'], }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav preload (solid)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/preload/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/preload/vue/speed.bench.ts index 38a2e9e664..e0ec83619b 100644 --- a/benchmarks/client-nav/scenarios/preload/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/preload/vue/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-preload', () => { - const test = setup() +test('client-preload', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-preload interaction loop (vue)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) 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 05a751060b..5f95d09da0 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 DocsRouteImport } from './routes/docs' import { Route as IndexRouteImport } from './routes/index' +import { Route as DocsRouteImport } from './routes/docs' import { Route as SectionsSectionRouteImport } from './routes/sections.$section' -const DocsRoute = DocsRouteImport.update({ - id: '/docs', - path: '/docs', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const DocsRoute = DocsRouteImport.update({ + id: '/docs', + path: '/docs', + 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 { - '/docs': { - id: '/docs' - path: '/docs' - fullPath: '/docs' - preLoaderRoute: typeof DocsRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -75,6 +68,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/docs': { + id: '/docs' + path: '/docs' + fullPath: '/docs' + preLoaderRoute: typeof DocsRouteImport + parentRoute: typeof rootRouteImport + } '/sections/$section': { id: '/sections/$section' path: '/sections/$section' diff --git a/benchmarks/client-nav/scenarios/preload/vue/vite.config.ts b/benchmarks/client-nav/scenarios/preload/vue/vite.config.ts index 25e64b5bef..8d00e66378 100644 --- a/benchmarks/client-nav/scenarios/preload/vue/vite.config.ts +++ b/benchmarks/client-nav/scenarios/preload/vue/vite.config.ts @@ -4,6 +4,7 @@ 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)) @@ -34,6 +35,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav preload (vue)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/rewrites/react/speed.bench.ts b/benchmarks/client-nav/scenarios/rewrites/react/speed.bench.ts index 8e79c6db7e..dd1b6f3686 100644 --- a/benchmarks/client-nav/scenarios/rewrites/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/rewrites/react/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-rewrites', () => { - const test = setup() +test('client-rewrites', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-rewrites navigation loop (react)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/rewrites/react/vite.config.ts b/benchmarks/client-nav/scenarios/rewrites/react/vite.config.ts index 8c07cff4fb..e79e8522e9 100644 --- a/benchmarks/client-nav/scenarios/rewrites/react/vite.config.ts +++ b/benchmarks/client-nav/scenarios/rewrites/react/vite.config.ts @@ -3,6 +3,7 @@ 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)) @@ -32,6 +33,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav rewrites (react)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/rewrites/solid/speed.bench.ts index cf70bcaa40..9c4313e2ff 100644 --- a/benchmarks/client-nav/scenarios/rewrites/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/rewrites/solid/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-rewrites', () => { - const test = setup() +test('client-rewrites', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-rewrites navigation loop (solid)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/vite.config.ts b/benchmarks/client-nav/scenarios/rewrites/solid/vite.config.ts index 41613c2ad4..c9e99b7d60 100644 --- a/benchmarks/client-nav/scenarios/rewrites/solid/vite.config.ts +++ b/benchmarks/client-nav/scenarios/rewrites/solid/vite.config.ts @@ -3,6 +3,7 @@ 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)) @@ -35,6 +36,7 @@ export default defineConfig({ conditions: ['solid', 'browser'], }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav rewrites (solid)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/rewrites/vue/speed.bench.ts index 2dc9eb2679..e96aff39eb 100644 --- a/benchmarks/client-nav/scenarios/rewrites/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/rewrites/vue/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-rewrites', () => { - const test = setup() +test('client-rewrites', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-rewrites navigation loop (vue)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/vite.config.ts b/benchmarks/client-nav/scenarios/rewrites/vue/vite.config.ts index 39e22b6c3e..1a795a4e1d 100644 --- a/benchmarks/client-nav/scenarios/rewrites/vue/vite.config.ts +++ b/benchmarks/client-nav/scenarios/rewrites/vue/vite.config.ts @@ -4,6 +4,7 @@ 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)) @@ -34,6 +35,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav rewrites (vue)', watch: false, environment: 'jsdom', 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 337ba35b73..6f4b448775 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,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-route-tree-scale', () => { - const test = setup() +test('client-route-tree-scale', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-route-tree-scale navigation loop (react)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/vite.config.ts b/benchmarks/client-nav/scenarios/route-tree-scale/react/vite.config.ts index 686907a506..0f588fda53 100644 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/vite.config.ts +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/vite.config.ts @@ -3,6 +3,7 @@ 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)) @@ -35,6 +36,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav route-tree-scale (react)', watch: false, environment: 'jsdom', 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 545b501617..9244ef1350 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,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-route-tree-scale', () => { - const test = setup() +test('client-route-tree-scale', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-route-tree-scale navigation loop (solid)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) 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 20b4af6146..e6f3596562 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,68 +9,52 @@ // 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 SecFRouteImport } from './routes/sec-f' -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 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 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 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 SecFSettingsRouteImport } from './routes/sec-f.settings' -const SecFRoute = SecFRouteImport.update({ - id: '/sec-f', - path: '/sec-f', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const SecERoute = SecERouteImport.update({ - id: '/sec-e', - path: '/sec-e', - getParentRoute: () => rootRouteImport, -} as any) -const SecDRoute = SecDRouteImport.update({ - id: '/sec-d', - path: '/sec-d', - getParentRoute: () => rootRouteImport, -} as any) -const SecCRoute = SecCRouteImport.update({ - id: '/sec-c', - path: '/sec-c', - getParentRoute: () => rootRouteImport, -} as any) -const SecBRoute = SecBRouteImport.update({ - id: '/sec-b', - path: '/sec-b', +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', getParentRoute: () => rootRouteImport, } as any) const SecARoute = SecARouteImport.update({ @@ -78,134 +62,55 @@ const SecARoute = SecARouteImport.update({ path: '/sec-a', getParentRoute: () => rootRouteImport, } as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', +const SecBRoute = SecBRouteImport.update({ + id: '/sec-b', + path: '/sec-b', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const SecCRoute = SecCRouteImport.update({ + id: '/sec-c', + path: '/sec-c', getParentRoute: () => rootRouteImport, } as any) -const SecFIndexRoute = SecFIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecFRoute, +const SecDRoute = SecDRouteImport.update({ + id: '/sec-d', + path: '/sec-d', + getParentRoute: () => rootRouteImport, } as any) -const SecEIndexRoute = SecEIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecERoute, +const SecERoute = SecERouteImport.update({ + id: '/sec-e', + path: '/sec-e', + getParentRoute: () => rootRouteImport, } as any) -const SecDIndexRoute = SecDIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecDRoute, +const SecFRoute = SecFRouteImport.update({ + id: '/sec-f', + path: '/sec-f', + getParentRoute: () => rootRouteImport, } as any) -const SecCIndexRoute = SecCIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecCRoute, +const marketingPricingRoute = marketingPricingRouteImport.update({ + id: '/(marketing)/pricing', + path: '/pricing', + getParentRoute: () => rootRouteImport, } as any) -const SecBIndexRoute = SecBIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecBRoute, +const marketingPromoRoute = marketingPromoRouteImport.update({ + id: '/(marketing)/promo', + path: '/promo', + getParentRoute: () => rootRouteImport, } as any) -const SecAIndexRoute = SecAIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecARoute, +const LayoutAlphaRoute = LayoutAlphaRouteImport.update({ + id: '/alpha', + path: '/alpha', + getParentRoute: () => LayoutRoute, } as any) -const SecFSettingsRoute = SecFSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecFRoute, +const LayoutBetaRoute = LayoutBetaRouteImport.update({ + id: '/beta', + path: '/beta', + getParentRoute: () => LayoutRoute, } as any) -const SecFAboutRoute = SecFAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecFRoute, -} as any) -const SecFIdRoute = SecFIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecFRoute, -} as any) -const SecESettingsRoute = SecESettingsRouteImport.update({ - id: '/settings', - path: '/settings', - 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, +const FilesSplatRoute = FilesSplatRouteImport.update({ + id: '/files/$', + path: '/files/$', + getParentRoute: () => rootRouteImport, } as any) const ReleaseVChar123versionChar125Route = ReleaseVChar123versionChar125RouteImport.update({ @@ -213,30 +118,125 @@ const ReleaseVChar123versionChar125Route = path: '/release/v{$version}', getParentRoute: () => rootRouteImport, } as any) -const FilesSplatRoute = FilesSplatRouteImport.update({ - id: '/files/$', - path: '/files/$', - getParentRoute: () => rootRouteImport, +const SecAIndexRoute = SecAIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecARoute, } as any) -const LayoutBetaRoute = LayoutBetaRouteImport.update({ - id: '/beta', - path: '/beta', - getParentRoute: () => LayoutRoute, +const SecAIdRoute = SecAIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecARoute, } as any) -const LayoutAlphaRoute = LayoutAlphaRouteImport.update({ - id: '/alpha', - path: '/alpha', - getParentRoute: () => LayoutRoute, +const SecAAboutRoute = SecAAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecARoute, } as any) -const marketingPromoRoute = marketingPromoRouteImport.update({ - id: '/(marketing)/promo', - path: '/promo', - getParentRoute: () => rootRouteImport, +const SecASettingsRoute = SecASettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecARoute, } as any) -const marketingPricingRoute = marketingPricingRouteImport.update({ - id: '/(marketing)/pricing', - path: '/pricing', - getParentRoute: () => rootRouteImport, +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, +} as any) +const SecFIndexRoute = SecFIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecFRoute, +} as any) +const SecFIdRoute = SecFIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecFRoute, +} as any) +const SecFAboutRoute = SecFAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecFRoute, +} as any) +const SecFSettingsRoute = SecFSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecFRoute, } as any) export interface FileRoutesByFullPath { @@ -484,46 +484,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/sec-f': { - id: '/sec-f' - path: '/sec-f' - fullPath: '/sec-f' - preLoaderRoute: typeof SecFRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-e': { - id: '/sec-e' - path: '/sec-e' - fullPath: '/sec-e' - preLoaderRoute: typeof SecERouteImport - parentRoute: typeof rootRouteImport - } - '/sec-d': { - id: '/sec-d' - path: '/sec-d' - fullPath: '/sec-d' - preLoaderRoute: typeof SecDRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-c': { - id: '/sec-c' - path: '/sec-c' - fullPath: '/sec-c' - preLoaderRoute: typeof SecCRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-b': { - id: '/sec-b' - path: '/sec-b' - fullPath: '/sec-b' - preLoaderRoute: typeof SecBRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-a': { - id: '/sec-a' - path: '/sec-a' - fullPath: '/sec-a' - preLoaderRoute: typeof SecARouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_layout': { @@ -533,47 +498,89 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/sec-a': { + id: '/sec-a' + path: '/sec-a' + fullPath: '/sec-a' + preLoaderRoute: typeof SecARouteImport parentRoute: typeof rootRouteImport } - '/sec-f/': { - id: '/sec-f/' - path: '/' - fullPath: '/sec-f/' - preLoaderRoute: typeof SecFIndexRouteImport - parentRoute: typeof SecFRoute + '/sec-b': { + id: '/sec-b' + path: '/sec-b' + fullPath: '/sec-b' + preLoaderRoute: typeof SecBRouteImport + parentRoute: typeof rootRouteImport } - '/sec-e/': { - id: '/sec-e/' - path: '/' - fullPath: '/sec-e/' - preLoaderRoute: typeof SecEIndexRouteImport - parentRoute: typeof SecERoute + '/sec-c': { + id: '/sec-c' + path: '/sec-c' + fullPath: '/sec-c' + preLoaderRoute: typeof SecCRouteImport + parentRoute: typeof rootRouteImport } - '/sec-d/': { - id: '/sec-d/' - path: '/' - fullPath: '/sec-d/' - preLoaderRoute: typeof SecDIndexRouteImport - parentRoute: typeof SecDRoute + '/sec-d': { + id: '/sec-d' + path: '/sec-d' + fullPath: '/sec-d' + preLoaderRoute: typeof SecDRouteImport + parentRoute: typeof rootRouteImport } - '/sec-c/': { - id: '/sec-c/' - path: '/' - fullPath: '/sec-c/' - preLoaderRoute: typeof SecCIndexRouteImport - parentRoute: typeof SecCRoute + '/sec-e': { + id: '/sec-e' + path: '/sec-e' + fullPath: '/sec-e' + preLoaderRoute: typeof SecERouteImport + parentRoute: typeof rootRouteImport } - '/sec-b/': { - id: '/sec-b/' - path: '/' - fullPath: '/sec-b/' - preLoaderRoute: typeof SecBIndexRouteImport - parentRoute: typeof SecBRoute + '/sec-f': { + id: '/sec-f' + path: '/sec-f' + fullPath: '/sec-f' + preLoaderRoute: typeof SecFRouteImport + parentRoute: typeof rootRouteImport + } + '/(marketing)/pricing': { + id: '/(marketing)/pricing' + path: '/pricing' + fullPath: '/pricing' + preLoaderRoute: typeof marketingPricingRouteImport + parentRoute: typeof rootRouteImport + } + '/(marketing)/promo': { + id: '/(marketing)/promo' + path: '/promo' + fullPath: '/promo' + preLoaderRoute: typeof marketingPromoRouteImport + 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 + parentRoute: typeof rootRouteImport + } + '/release/v{$version}': { + id: '/release/v{$version}' + path: '/release/v{$version}' + fullPath: '/release/v{$version}' + preLoaderRoute: typeof ReleaseVChar123versionChar125RouteImport + parentRoute: typeof rootRouteImport } '/sec-a/': { id: '/sec-a/' @@ -582,125 +589,6 @@ declare module '@tanstack/solid-router' { 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': { - id: '/sec-f/about' - path: '/about' - fullPath: '/sec-f/about' - preLoaderRoute: typeof SecFAboutRouteImport - parentRoute: typeof SecFRoute - } - '/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' @@ -708,47 +596,159 @@ declare module '@tanstack/solid-router' { 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 + '/sec-a/about': { + id: '/sec-a/about' + path: '/about' + fullPath: '/sec-a/about' + preLoaderRoute: typeof SecAAboutRouteImport + parentRoute: typeof SecARoute } - '/files/$': { - id: '/files/$' - path: '/files/$' - fullPath: '/files/$' - preLoaderRoute: typeof FilesSplatRouteImport - parentRoute: typeof rootRouteImport + '/sec-a/settings': { + id: '/sec-a/settings' + path: '/settings' + fullPath: '/sec-a/settings' + preLoaderRoute: typeof SecASettingsRouteImport + parentRoute: typeof SecARoute } - '/_layout/beta': { - id: '/_layout/beta' - path: '/beta' - fullPath: '/beta' - preLoaderRoute: typeof LayoutBetaRouteImport - parentRoute: typeof LayoutRoute + '/sec-b/': { + id: '/sec-b/' + path: '/' + fullPath: '/sec-b/' + preLoaderRoute: typeof SecBIndexRouteImport + parentRoute: typeof SecBRoute } - '/_layout/alpha': { - id: '/_layout/alpha' - path: '/alpha' - fullPath: '/alpha' - preLoaderRoute: typeof LayoutAlphaRouteImport - parentRoute: typeof LayoutRoute + '/sec-b/$id': { + id: '/sec-b/$id' + path: '/$id' + fullPath: '/sec-b/$id' + preLoaderRoute: typeof SecBIdRouteImport + parentRoute: typeof SecBRoute } - '/(marketing)/promo': { - id: '/(marketing)/promo' - path: '/promo' - fullPath: '/promo' - preLoaderRoute: typeof marketingPromoRouteImport - parentRoute: typeof rootRouteImport + '/sec-b/about': { + id: '/sec-b/about' + path: '/about' + fullPath: '/sec-b/about' + preLoaderRoute: typeof SecBAboutRouteImport + parentRoute: typeof SecBRoute } - '/(marketing)/pricing': { - id: '/(marketing)/pricing' - path: '/pricing' - fullPath: '/pricing' - preLoaderRoute: typeof marketingPricingRouteImport - parentRoute: typeof rootRouteImport + '/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 + } + '/sec-f/': { + id: '/sec-f/' + path: '/' + fullPath: '/sec-f/' + preLoaderRoute: typeof SecFIndexRouteImport + parentRoute: typeof SecFRoute + } + '/sec-f/$id': { + id: '/sec-f/$id' + path: '/$id' + fullPath: '/sec-f/$id' + preLoaderRoute: typeof SecFIdRouteImport + parentRoute: typeof SecFRoute + } + '/sec-f/about': { + id: '/sec-f/about' + path: '/about' + fullPath: '/sec-f/about' + preLoaderRoute: typeof SecFAboutRouteImport + parentRoute: typeof SecFRoute + } + '/sec-f/settings': { + id: '/sec-f/settings' + path: '/settings' + fullPath: '/sec-f/settings' + preLoaderRoute: typeof SecFSettingsRouteImport + parentRoute: typeof SecFRoute } } } diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/vite.config.ts b/benchmarks/client-nav/scenarios/route-tree-scale/solid/vite.config.ts index dd0bd234e0..542ede131b 100644 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/vite.config.ts +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/vite.config.ts @@ -3,6 +3,7 @@ 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)) @@ -38,6 +39,7 @@ export default defineConfig({ conditions: ['solid', 'browser'], }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav route-tree-scale (solid)', watch: false, environment: 'jsdom', 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 9365231579..331e8e008f 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,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-route-tree-scale', () => { - const test = setup() +test('client-route-tree-scale', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-route-tree-scale navigation loop (vue)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) 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 a03c051a79..a12f981bb4 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,68 +9,52 @@ // 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 SecFRouteImport } from './routes/sec-f' -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 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 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 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 SecFSettingsRouteImport } from './routes/sec-f.settings' -const SecFRoute = SecFRouteImport.update({ - id: '/sec-f', - path: '/sec-f', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const SecERoute = SecERouteImport.update({ - id: '/sec-e', - path: '/sec-e', - getParentRoute: () => rootRouteImport, -} as any) -const SecDRoute = SecDRouteImport.update({ - id: '/sec-d', - path: '/sec-d', - getParentRoute: () => rootRouteImport, -} as any) -const SecCRoute = SecCRouteImport.update({ - id: '/sec-c', - path: '/sec-c', - getParentRoute: () => rootRouteImport, -} as any) -const SecBRoute = SecBRouteImport.update({ - id: '/sec-b', - path: '/sec-b', +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', getParentRoute: () => rootRouteImport, } as any) const SecARoute = SecARouteImport.update({ @@ -78,134 +62,55 @@ const SecARoute = SecARouteImport.update({ path: '/sec-a', getParentRoute: () => rootRouteImport, } as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', +const SecBRoute = SecBRouteImport.update({ + id: '/sec-b', + path: '/sec-b', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const SecCRoute = SecCRouteImport.update({ + id: '/sec-c', + path: '/sec-c', getParentRoute: () => rootRouteImport, } as any) -const SecFIndexRoute = SecFIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecFRoute, +const SecDRoute = SecDRouteImport.update({ + id: '/sec-d', + path: '/sec-d', + getParentRoute: () => rootRouteImport, } as any) -const SecEIndexRoute = SecEIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecERoute, +const SecERoute = SecERouteImport.update({ + id: '/sec-e', + path: '/sec-e', + getParentRoute: () => rootRouteImport, } as any) -const SecDIndexRoute = SecDIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecDRoute, +const SecFRoute = SecFRouteImport.update({ + id: '/sec-f', + path: '/sec-f', + getParentRoute: () => rootRouteImport, } as any) -const SecCIndexRoute = SecCIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecCRoute, +const marketingPricingRoute = marketingPricingRouteImport.update({ + id: '/(marketing)/pricing', + path: '/pricing', + getParentRoute: () => rootRouteImport, } as any) -const SecBIndexRoute = SecBIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecBRoute, +const marketingPromoRoute = marketingPromoRouteImport.update({ + id: '/(marketing)/promo', + path: '/promo', + getParentRoute: () => rootRouteImport, } as any) -const SecAIndexRoute = SecAIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecARoute, +const LayoutAlphaRoute = LayoutAlphaRouteImport.update({ + id: '/alpha', + path: '/alpha', + getParentRoute: () => LayoutRoute, } as any) -const SecFSettingsRoute = SecFSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecFRoute, +const LayoutBetaRoute = LayoutBetaRouteImport.update({ + id: '/beta', + path: '/beta', + getParentRoute: () => LayoutRoute, } as any) -const SecFAboutRoute = SecFAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecFRoute, -} as any) -const SecFIdRoute = SecFIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecFRoute, -} as any) -const SecESettingsRoute = SecESettingsRouteImport.update({ - id: '/settings', - path: '/settings', - 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, +const FilesSplatRoute = FilesSplatRouteImport.update({ + id: '/files/$', + path: '/files/$', + getParentRoute: () => rootRouteImport, } as any) const ReleaseVChar123versionChar125Route = ReleaseVChar123versionChar125RouteImport.update({ @@ -213,30 +118,125 @@ const ReleaseVChar123versionChar125Route = path: '/release/v{$version}', getParentRoute: () => rootRouteImport, } as any) -const FilesSplatRoute = FilesSplatRouteImport.update({ - id: '/files/$', - path: '/files/$', - getParentRoute: () => rootRouteImport, +const SecAIndexRoute = SecAIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecARoute, } as any) -const LayoutBetaRoute = LayoutBetaRouteImport.update({ - id: '/beta', - path: '/beta', - getParentRoute: () => LayoutRoute, +const SecAIdRoute = SecAIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecARoute, } as any) -const LayoutAlphaRoute = LayoutAlphaRouteImport.update({ - id: '/alpha', - path: '/alpha', - getParentRoute: () => LayoutRoute, +const SecAAboutRoute = SecAAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecARoute, } as any) -const marketingPromoRoute = marketingPromoRouteImport.update({ - id: '/(marketing)/promo', - path: '/promo', - getParentRoute: () => rootRouteImport, +const SecASettingsRoute = SecASettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecARoute, } as any) -const marketingPricingRoute = marketingPricingRouteImport.update({ - id: '/(marketing)/pricing', - path: '/pricing', - getParentRoute: () => rootRouteImport, +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, +} as any) +const SecFIndexRoute = SecFIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecFRoute, +} as any) +const SecFIdRoute = SecFIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecFRoute, +} as any) +const SecFAboutRoute = SecFAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecFRoute, +} as any) +const SecFSettingsRoute = SecFSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecFRoute, } as any) export interface FileRoutesByFullPath { @@ -484,46 +484,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/sec-f': { - id: '/sec-f' - path: '/sec-f' - fullPath: '/sec-f' - preLoaderRoute: typeof SecFRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-e': { - id: '/sec-e' - path: '/sec-e' - fullPath: '/sec-e' - preLoaderRoute: typeof SecERouteImport - parentRoute: typeof rootRouteImport - } - '/sec-d': { - id: '/sec-d' - path: '/sec-d' - fullPath: '/sec-d' - preLoaderRoute: typeof SecDRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-c': { - id: '/sec-c' - path: '/sec-c' - fullPath: '/sec-c' - preLoaderRoute: typeof SecCRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-b': { - id: '/sec-b' - path: '/sec-b' - fullPath: '/sec-b' - preLoaderRoute: typeof SecBRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-a': { - id: '/sec-a' - path: '/sec-a' - fullPath: '/sec-a' - preLoaderRoute: typeof SecARouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_layout': { @@ -533,47 +498,89 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/sec-a': { + id: '/sec-a' + path: '/sec-a' + fullPath: '/sec-a' + preLoaderRoute: typeof SecARouteImport parentRoute: typeof rootRouteImport } - '/sec-f/': { - id: '/sec-f/' - path: '/' - fullPath: '/sec-f/' - preLoaderRoute: typeof SecFIndexRouteImport - parentRoute: typeof SecFRoute + '/sec-b': { + id: '/sec-b' + path: '/sec-b' + fullPath: '/sec-b' + preLoaderRoute: typeof SecBRouteImport + parentRoute: typeof rootRouteImport } - '/sec-e/': { - id: '/sec-e/' - path: '/' - fullPath: '/sec-e/' - preLoaderRoute: typeof SecEIndexRouteImport - parentRoute: typeof SecERoute + '/sec-c': { + id: '/sec-c' + path: '/sec-c' + fullPath: '/sec-c' + preLoaderRoute: typeof SecCRouteImport + parentRoute: typeof rootRouteImport } - '/sec-d/': { - id: '/sec-d/' - path: '/' - fullPath: '/sec-d/' - preLoaderRoute: typeof SecDIndexRouteImport - parentRoute: typeof SecDRoute + '/sec-d': { + id: '/sec-d' + path: '/sec-d' + fullPath: '/sec-d' + preLoaderRoute: typeof SecDRouteImport + parentRoute: typeof rootRouteImport } - '/sec-c/': { - id: '/sec-c/' - path: '/' - fullPath: '/sec-c/' - preLoaderRoute: typeof SecCIndexRouteImport - parentRoute: typeof SecCRoute + '/sec-e': { + id: '/sec-e' + path: '/sec-e' + fullPath: '/sec-e' + preLoaderRoute: typeof SecERouteImport + parentRoute: typeof rootRouteImport } - '/sec-b/': { - id: '/sec-b/' - path: '/' - fullPath: '/sec-b/' - preLoaderRoute: typeof SecBIndexRouteImport - parentRoute: typeof SecBRoute + '/sec-f': { + id: '/sec-f' + path: '/sec-f' + fullPath: '/sec-f' + preLoaderRoute: typeof SecFRouteImport + parentRoute: typeof rootRouteImport + } + '/(marketing)/pricing': { + id: '/(marketing)/pricing' + path: '/pricing' + fullPath: '/pricing' + preLoaderRoute: typeof marketingPricingRouteImport + parentRoute: typeof rootRouteImport + } + '/(marketing)/promo': { + id: '/(marketing)/promo' + path: '/promo' + fullPath: '/promo' + preLoaderRoute: typeof marketingPromoRouteImport + 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 + parentRoute: typeof rootRouteImport + } + '/release/v{$version}': { + id: '/release/v{$version}' + path: '/release/v{$version}' + fullPath: '/release/v{$version}' + preLoaderRoute: typeof ReleaseVChar123versionChar125RouteImport + parentRoute: typeof rootRouteImport } '/sec-a/': { id: '/sec-a/' @@ -582,125 +589,6 @@ declare module '@tanstack/vue-router' { 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': { - id: '/sec-f/about' - path: '/about' - fullPath: '/sec-f/about' - preLoaderRoute: typeof SecFAboutRouteImport - parentRoute: typeof SecFRoute - } - '/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' @@ -708,47 +596,159 @@ declare module '@tanstack/vue-router' { 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 + '/sec-a/about': { + id: '/sec-a/about' + path: '/about' + fullPath: '/sec-a/about' + preLoaderRoute: typeof SecAAboutRouteImport + parentRoute: typeof SecARoute } - '/files/$': { - id: '/files/$' - path: '/files/$' - fullPath: '/files/$' - preLoaderRoute: typeof FilesSplatRouteImport - parentRoute: typeof rootRouteImport + '/sec-a/settings': { + id: '/sec-a/settings' + path: '/settings' + fullPath: '/sec-a/settings' + preLoaderRoute: typeof SecASettingsRouteImport + parentRoute: typeof SecARoute } - '/_layout/beta': { - id: '/_layout/beta' - path: '/beta' - fullPath: '/beta' - preLoaderRoute: typeof LayoutBetaRouteImport - parentRoute: typeof LayoutRoute + '/sec-b/': { + id: '/sec-b/' + path: '/' + fullPath: '/sec-b/' + preLoaderRoute: typeof SecBIndexRouteImport + parentRoute: typeof SecBRoute } - '/_layout/alpha': { - id: '/_layout/alpha' - path: '/alpha' - fullPath: '/alpha' - preLoaderRoute: typeof LayoutAlphaRouteImport - parentRoute: typeof LayoutRoute + '/sec-b/$id': { + id: '/sec-b/$id' + path: '/$id' + fullPath: '/sec-b/$id' + preLoaderRoute: typeof SecBIdRouteImport + parentRoute: typeof SecBRoute } - '/(marketing)/promo': { - id: '/(marketing)/promo' - path: '/promo' - fullPath: '/promo' - preLoaderRoute: typeof marketingPromoRouteImport - parentRoute: typeof rootRouteImport + '/sec-b/about': { + id: '/sec-b/about' + path: '/about' + fullPath: '/sec-b/about' + preLoaderRoute: typeof SecBAboutRouteImport + parentRoute: typeof SecBRoute } - '/(marketing)/pricing': { - id: '/(marketing)/pricing' - path: '/pricing' - fullPath: '/pricing' - preLoaderRoute: typeof marketingPricingRouteImport - parentRoute: typeof rootRouteImport + '/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 + } + '/sec-f/': { + id: '/sec-f/' + path: '/' + fullPath: '/sec-f/' + preLoaderRoute: typeof SecFIndexRouteImport + parentRoute: typeof SecFRoute + } + '/sec-f/$id': { + id: '/sec-f/$id' + path: '/$id' + fullPath: '/sec-f/$id' + preLoaderRoute: typeof SecFIdRouteImport + parentRoute: typeof SecFRoute + } + '/sec-f/about': { + id: '/sec-f/about' + path: '/about' + fullPath: '/sec-f/about' + preLoaderRoute: typeof SecFAboutRouteImport + parentRoute: typeof SecFRoute + } + '/sec-f/settings': { + id: '/sec-f/settings' + path: '/settings' + fullPath: '/sec-f/settings' + preLoaderRoute: typeof SecFSettingsRouteImport + parentRoute: typeof SecFRoute } } } diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/vite.config.ts b/benchmarks/client-nav/scenarios/route-tree-scale/vue/vite.config.ts index a547406198..189ba1de99 100644 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/vite.config.ts +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/vite.config.ts @@ -4,6 +4,7 @@ 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)) @@ -37,6 +38,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav route-tree-scale (vue)', watch: false, environment: 'jsdom', 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 5bdd994e32..0b38f7bddb 100644 --- a/benchmarks/client-nav/scenarios/search-params/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/search-params/react/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-search-params', () => { - const test = setup() +test('client-search-params', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-search-params navigation loop (react)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/search-params/react/vite.config.ts b/benchmarks/client-nav/scenarios/search-params/react/vite.config.ts index b220ae7d0d..0318a10815 100644 --- a/benchmarks/client-nav/scenarios/search-params/react/vite.config.ts +++ b/benchmarks/client-nav/scenarios/search-params/react/vite.config.ts @@ -3,6 +3,7 @@ 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)) @@ -32,6 +33,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav search-params (react)', watch: false, environment: 'jsdom', 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 ea0baa1098..caa626c596 100644 --- a/benchmarks/client-nav/scenarios/search-params/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/search-params/solid/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-search-params', () => { - const test = setup() +test('client-search-params', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-search-params navigation loop (solid)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) 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 96d211d64c..b15beed09b 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 ProductsRouteImport } from './routes/products' -import { Route as CatalogRouteImport } from './routes/catalog' import { Route as IndexRouteImport } from './routes/index' +import { Route as CatalogRouteImport } from './routes/catalog' +import { Route as ProductsRouteImport } from './routes/products' -const ProductsRoute = ProductsRouteImport.update({ - id: '/products', - path: '/products', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const CatalogRoute = CatalogRouteImport.update({ @@ -23,9 +23,9 @@ const CatalogRoute = CatalogRouteImport.update({ path: '/catalog', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const ProductsRoute = ProductsRouteImport.update({ + id: '/products', + path: '/products', getParentRoute: () => rootRouteImport, } as any) @@ -61,11 +61,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/products': { - id: '/products' - path: '/products' - fullPath: '/products' - preLoaderRoute: typeof ProductsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/catalog': { @@ -75,11 +75,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof CatalogRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/products': { + id: '/products' + path: '/products' + fullPath: '/products' + preLoaderRoute: typeof ProductsRouteImport parentRoute: typeof rootRouteImport } } diff --git a/benchmarks/client-nav/scenarios/search-params/solid/vite.config.ts b/benchmarks/client-nav/scenarios/search-params/solid/vite.config.ts index c2f4b32806..511fd49466 100644 --- a/benchmarks/client-nav/scenarios/search-params/solid/vite.config.ts +++ b/benchmarks/client-nav/scenarios/search-params/solid/vite.config.ts @@ -3,6 +3,7 @@ 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)) @@ -35,6 +36,7 @@ export default defineConfig({ conditions: ['solid', 'browser'], }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav search-params (solid)', watch: false, environment: 'jsdom', 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 c82efd49c9..728d2779e8 100644 --- a/benchmarks/client-nav/scenarios/search-params/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/search-params/vue/speed.bench.ts @@ -1,32 +1,19 @@ -import { afterEach, beforeEach, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-search-params', () => { - const test = setup() +test('client-search-params', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-search-params navigation loop (vue)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } - await test.finishBatch() + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) 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 b95b667803..f73b84ebe7 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 ProductsRouteImport } from './routes/products' -import { Route as CatalogRouteImport } from './routes/catalog' import { Route as IndexRouteImport } from './routes/index' +import { Route as CatalogRouteImport } from './routes/catalog' +import { Route as ProductsRouteImport } from './routes/products' -const ProductsRoute = ProductsRouteImport.update({ - id: '/products', - path: '/products', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const CatalogRoute = CatalogRouteImport.update({ @@ -23,9 +23,9 @@ const CatalogRoute = CatalogRouteImport.update({ path: '/catalog', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const ProductsRoute = ProductsRouteImport.update({ + id: '/products', + path: '/products', getParentRoute: () => rootRouteImport, } as any) @@ -61,11 +61,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/products': { - id: '/products' - path: '/products' - fullPath: '/products' - preLoaderRoute: typeof ProductsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/catalog': { @@ -75,11 +75,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof CatalogRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/products': { + id: '/products' + path: '/products' + fullPath: '/products' + preLoaderRoute: typeof ProductsRouteImport parentRoute: typeof rootRouteImport } } diff --git a/benchmarks/client-nav/scenarios/search-params/vue/vite.config.ts b/benchmarks/client-nav/scenarios/search-params/vue/vite.config.ts index 9a3b82d066..27490b276a 100644 --- a/benchmarks/client-nav/scenarios/search-params/vue/vite.config.ts +++ b/benchmarks/client-nav/scenarios/search-params/vue/vite.config.ts @@ -4,6 +4,7 @@ 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)) @@ -34,6 +35,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav search-params (vue)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/solid/speed.bench.ts b/benchmarks/client-nav/solid/speed.bench.ts index 34791180ce..d629da17a8 100644 --- a/benchmarks/client-nav/solid/speed.bench.ts +++ b/benchmarks/client-nav/solid/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' import { setup } from './setup' -describe('client-nav', () => { - const test = setup() +test('client-nav', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-side navigation loop (solid)', + { beforeAll: scenario.before, afterAll: scenario.after }, async () => { for (let i = 0; i < 10; i++) { - await test.tick() + await scenario.tick() } }, - { - warmupIterations: 100, - time: 10_000, - setup: test.before, - teardown: test.after, - }, - ) + ).run({ + warmupIterations: 100, + time: 10_000, + }) }) diff --git a/benchmarks/client-nav/solid/vite.config.ts b/benchmarks/client-nav/solid/vite.config.ts index bd11fe8de9..0c26b32f5f 100644 --- a/benchmarks/client-nav/solid/vite.config.ts +++ b/benchmarks/client-nav/solid/vite.config.ts @@ -2,6 +2,7 @@ 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' // Anchor the project root to the package directory so this config resolves // identically when run directly and as part of an aggregate `projects` config. @@ -31,10 +32,12 @@ export default defineConfig({ conditions: ['solid', 'browser'], }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav (solid)', 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 f9e532f5ba..503e91e7b7 100644 --- a/benchmarks/client-nav/vue/speed.bench.ts +++ b/benchmarks/client-nav/vue/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' import { setup } from './setup' -describe('client-nav', () => { - const test = setup() +test('client-nav', async ({ bench }) => { + const scenario = setup() - /** - * 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( + await bench( 'client-side navigation loop (vue)', + { beforeAll: scenario.before, afterAll: scenario.after }, async () => { for (let i = 0; i < 10; i++) { - await test.tick() + await scenario.tick() } }, - { - warmupIterations: 100, - time: 10_000, - setup: test.before, - teardown: test.after, - }, - ) + ).run({ + warmupIterations: 100, + time: 10_000, + }) }) diff --git a/benchmarks/client-nav/vue/vite.config.ts b/benchmarks/client-nav/vue/vite.config.ts index 4c44c09fdd..78d8ae5638 100644 --- a/benchmarks/client-nav/vue/vite.config.ts +++ b/benchmarks/client-nav/vue/vite.config.ts @@ -3,6 +3,7 @@ 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 { cpuSimulationExecArgv } from '../../cpu-simulation' // Anchor the project root to the package directory so this config resolves // identically when run directly and as part of an aggregate `projects` config. @@ -30,9 +31,11 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav (vue)', 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 new file mode 100644 index 0000000000..9b8859f74d --- /dev/null +++ b/benchmarks/cpu-simulation.ts @@ -0,0 +1,53 @@ +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() + 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. + // Compile baseline code on first use, so warmup does not leave functions + // near Sparkplug's later tier-up/batch-compilation thresholds. + // V8 renamed --scavenge-task in Node 20; CodSpeed's old flag is omitted. + // Keep minor GC tied to allocations instead of scheduled foreground tasks. + // Fix the initial/minimum old-generation allocation budget. This can skip + // automatic full collections below the budget; minor GC remains enabled. + return [ + '--no-maglev', + '--always-sparkplug', + '--no-minor-gc-task', + '--initial-old-space-size=512', + ] + } + 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 cf871f3439..18b68768f9 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/client-nav-benchmarks.yml`). The workflow runs on every +`.github/workflows/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 `bench(...)` directly, and `memory.flame.ts` runs the -same workload through the Flame profiler. +`memory.bench.ts` registers it with Vitest's `bench` test fixture, and +`memory.flame.ts` runs the same workload through the Flame profiler. ## How the memory instrument executes a bench @@ -43,40 +43,98 @@ same workload through the Flame profiler. 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 **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. + 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. - 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 (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. +- **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. ## Scenarios ### Server -| Scenario | Shape | Guards against | +| Scenario | Shape | Exercises | | ----------------------- | ----- | --------------------------------------------------------- | | `request-churn` | churn | cross-request retention in document SSR (unique URLs) | | `server-fn-churn` | churn | retention in the server-function RPC path | @@ -88,7 +146,7 @@ same workload through the Flame profiler. ### Client -| Scenario | Shape | Guards against | +| Scenario | Shape | Exercises | | ------------------------- | ----- | -------------------------------------------------------- | | `navigation-churn` | churn | per-navigation retention at steady state | | `unique-location-churn` | churn | unbounded href/search-keyed caches (never-repeated URLs) | @@ -103,14 +161,10 @@ same workload through the Flame profiler. 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`; 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. +- 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. - 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 @@ -184,7 +238,7 @@ pnpm --filter @benchmarks/memory-client clean:profiles ``` Client memory benches are useful for regression tracking of router/React/jsdom -integration behavior, especially retained route/cache data. They are not pure +integration behavior and native allocation activity. They are not pure browser-memory measurements, and local Flame attribution can include jsdom, React DOM, and profiler shutdown frames. @@ -200,3 +254,20 @@ 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 0cbaedbd71..785e8fac7f 100644 --- a/benchmarks/memory/client/bench-utils.ts +++ b/benchmarks/memory/client/bench-utils.ts @@ -1,3 +1,5 @@ +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 8b877b0740..463047f4d9 100644 --- a/benchmarks/memory/client/benchmark.ts +++ b/benchmarks/memory/client/benchmark.ts @@ -1,6 +1,10 @@ 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 d4c9f732c7..4dc6246183 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": "^5.5.0", + "@codspeed/vitest-plugin": "^6.0.1", "@datadog/pprof": "^5.13.2", "@platformatic/flame": "^1.6.0", "@testing-library/react": "^16.2.0", @@ -30,12 +30,14 @@ "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "@types/jsdom": "28.0.0", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", "jsdom": "29.1.1", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11", - "vitest": "^4.1.4" + "vitest": "catalog:" }, "nx": { "targets": { @@ -200,7 +202,7 @@ "build:react" ], "options": { - "command": "NODE_ENV=production vitest bench --config ./vitest.react.config.ts", + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.react.config.ts", "cwd": "benchmarks/memory/client" } }, @@ -212,7 +214,7 @@ "build:solid" ], "options": { - "command": "NODE_ENV=production vitest bench --config ./vitest.solid.config.ts", + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.solid.config.ts", "cwd": "benchmarks/memory/client" } }, @@ -224,12 +226,12 @@ "build:vue" ], "options": { - "command": "NODE_ENV=production vitest bench --config ./vitest.vue.config.ts", + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.vue.config.ts", "cwd": "benchmarks/memory/client" } }, "test:types": { - "executor": "nx:noop", + "executor": "nx:run-commands", "dependsOn": [ { "projects": [ @@ -254,6 +256,17 @@ ], "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 e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/react/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -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) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).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 048a9cc833..0f05cedf40 100644 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/vite.config.ts +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/react/vite.config.ts @@ -2,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -26,9 +27,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), 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 e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -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) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).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 e710e0fd12..26ff0b5c8c 100644 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/vite.config.ts +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/vite.config.ts @@ -2,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -26,9 +27,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), 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 e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -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) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).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 3bd820bd07..f6dc9ac3bd 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,6 +1,19 @@ +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, @@ -9,13 +22,3 @@ 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 68885fb918..3b5bb75ede 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,6 +1,19 @@ +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) @@ -9,13 +22,3 @@ 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 b2912ce9d1..02574908d2 100644 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/vite.config.ts +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/vite.config.ts @@ -3,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -28,9 +29,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), 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 e645ab38f1..43ab822de3 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,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -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) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).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 555e5f5612..8630417936 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,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -26,9 +27,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), 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 e645ab38f1..43ab822de3 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,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -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) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).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 58d6b77acc..5dfd5b53fe 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,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -26,9 +27,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), 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 e645ab38f1..43ab822de3 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,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -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) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).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 9f4b3c4470..38f1d2614c 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,22 +1,25 @@ +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 bbf2fd02d8..006636eaa0 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,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -28,9 +29,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), 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 e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/mount-unmount/react/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/mount-unmount/react/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -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) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).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 bb0f3c2e0a..a08352a837 100644 --- a/benchmarks/memory/client/scenarios/mount-unmount/react/vite.config.ts +++ b/benchmarks/memory/client/scenarios/mount-unmount/react/vite.config.ts @@ -2,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -26,9 +27,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), 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 e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/mount-unmount/solid/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/mount-unmount/solid/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -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) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).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 5f0ab26252..33699639de 100644 --- a/benchmarks/memory/client/scenarios/mount-unmount/solid/vite.config.ts +++ b/benchmarks/memory/client/scenarios/mount-unmount/solid/vite.config.ts @@ -2,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -26,9 +27,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), 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 e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/mount-unmount/vue/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -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) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).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 cbcd543ce5..0dd650e1dd 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,12 +1,15 @@ +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 0f7573a408..a3f0eeaa8c 100644 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/vite.config.ts +++ b/benchmarks/memory/client/scenarios/mount-unmount/vue/vite.config.ts @@ -3,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -28,9 +29,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), 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 e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/navigation-churn/react/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -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) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).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 b05b999297..eef60a658e 100644 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/vite.config.ts +++ b/benchmarks/memory/client/scenarios/navigation-churn/react/vite.config.ts @@ -2,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -26,9 +27,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), 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 e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/navigation-churn/solid/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -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) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).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 6b6735891a..7dfb186b2e 100644 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/vite.config.ts +++ b/benchmarks/memory/client/scenarios/navigation-churn/solid/vite.config.ts @@ -2,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -26,9 +27,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), 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 e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/navigation-churn/vue/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -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) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).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 183228e748..c1a9cfb244 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,16 +1,19 @@ +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 3a18ec97a9..3a20799f3b 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,16 +1,19 @@ +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 d26ce23d07..b3bdd39dd2 100644 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/vite.config.ts +++ b/benchmarks/memory/client/scenarios/navigation-churn/vue/vite.config.ts @@ -3,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -28,9 +29,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), 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 e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/preload-churn/react/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/preload-churn/react/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -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) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).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 f9c426656b..c12995f68e 100644 --- a/benchmarks/memory/client/scenarios/preload-churn/react/vite.config.ts +++ b/benchmarks/memory/client/scenarios/preload-churn/react/vite.config.ts @@ -2,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -26,9 +27,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), 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 8cea4aca81..68fdfedd3f 100644 --- a/benchmarks/memory/client/scenarios/preload-churn/shared.ts +++ b/benchmarks/memory/client/scenarios/preload-churn/shared.ts @@ -35,18 +35,14 @@ type PreloadRouter = { subscribe: (event: 'onRendered', listener: () => void) => () => void } -// 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. +// Reuse one navigation target while evicting the distinct preloaded routes. 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. Interleaving a navigation every few preloads is -// what makes the flat floor assert "eviction releases preloaded payloads". +// during a preload-only loop. Interleave navigation to exercise eviction. const preloadsPerEvictionNavigation = 10 -// 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. +// Keep generated URLs unique across warmup and measured invocations. 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 e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/preload-churn/solid/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -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) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).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 c86a6fcbb3..efc75d2b93 100644 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/vite.config.ts +++ b/benchmarks/memory/client/scenarios/preload-churn/solid/vite.config.ts @@ -2,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -26,9 +27,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), 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 e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/preload-churn/vue/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -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) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).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 2a29245926..08254e173e 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,6 +1,19 @@ +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) @@ -8,13 +21,3 @@ 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 ea7ed7b695..3d56089ba7 100644 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/vite.config.ts +++ b/benchmarks/memory/client/scenarios/preload-churn/vue/vite.config.ts @@ -3,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -28,9 +29,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), 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 e645ab38f1..43ab822de3 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,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -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) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).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 f424c57cef..7ee67bfe30 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,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -26,9 +27,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), 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 e645ab38f1..43ab822de3 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,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -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) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).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 d4acf0019a..4db90da2d2 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,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -26,9 +27,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), 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 e645ab38f1..43ab822de3 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,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -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) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).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 1854367142..e796ee14d1 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,9 +1,22 @@ +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 : '', @@ -22,13 +35,3 @@ 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 423126019b..d074d571b9 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,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -28,9 +29,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), 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 9280d5c42f..eefc5c581e 100644 --- a/benchmarks/memory/client/tsconfig.json +++ b/benchmarks/memory/client/tsconfig.json @@ -3,5 +3,10 @@ "compilerOptions": { "types": ["node", "vite/client", "vitest/globals"] }, - "include": ["bench-utils.ts", "lifecycle.ts", "vitest.setup.ts"] + "include": [ + "bench-utils.ts", + "lifecycle.ts", + "vitest.setup.ts", + "scenarios/*/shared.ts" + ] } diff --git a/benchmarks/memory/runtime.ts b/benchmarks/memory/runtime.ts new file mode 100644 index 0000000000..010149b4df --- /dev/null +++ b/benchmarks/memory/runtime.ts @@ -0,0 +1,36 @@ +import { fileURLToPath } from 'node:url' +import { isMemoryInstrumented } from './turn' + +/** Worker settings for the CodSpeed memory instrument. */ +export function memoryExecArgv() { + if (!isMemoryInstrumented()) { + 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. + return [ + '--no-maglev', + '--no-flush-bytecode', + '--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.ts b/benchmarks/memory/server/bench-utils.ts index b8a09fdd8e..9caaf63384 100644 --- a/benchmarks/memory/server/bench-utils.ts +++ b/benchmarks/memory/server/bench-utils.ts @@ -1,3 +1,5 @@ +export { memoryBenchHooks } from '../turn' + export interface StartRequestHandler { fetch: (request: Request) => Promise | Response } @@ -17,24 +19,6 @@ export type RunSequentialRequestLoopOptions = iterations?: number buildRequest: (random: () => number, index: number) => Request validateResponse?: (response: Response, request: Request) => void - // Whether V8 collects iteration i's garbage before iteration i+1 - // allocates its payload is not reproducible run to run — the measured - // peak flips by a whole payload depending on GC timing, which shifts - // with runner hardware. Forcing a collection between iterations pins - // the GC points so peak deterministically measures the largest - // single-iteration footprint plus any reachable accumulation. - // Accumulation signals stay visible: leaked or cached objects are - // still referenced, so a forced collection cannot reclaim them — it - // only removes floating garbage, whose collection timing is the - // dominant cross-run noise source. - pinGcBetweenIterations?: boolean - // For peak-shape scenarios ONLY (flat inter-iteration heap floor): - // verify each pinned collection actually returned the heap to the - // floor, extending the barrier when a runner's late teardown holds the - // payload past the fixed window. Churn/abort scenarios must not set - // this: their floor legitimately drifts, so the verification caps out - // chronically and the extra collections it fires destabilize the peak. - verifyGcFloor?: boolean } export const memoryBenchOptions = { @@ -66,7 +50,7 @@ export async function drainResponse(response: Response) { } try { - while (true) { + for (;;) { const result = await reader.read() if (result.done) { @@ -82,13 +66,7 @@ export async function runSequentialRequestLoop( handler: StartRequestHandler, options: RunSequentialRequestLoopOptions, ) { - const { - iterations = 10, - buildRequest, - validateResponse, - pinGcBetweenIterations = false, - verifyGcFloor = false, - } = options + const { iterations = 10, buildRequest, validateResponse } = options const random = options.seed !== undefined ? createDeterministicRandom(options.seed) @@ -103,8 +81,6 @@ export async function runSequentialRequestLoop( } }) - const gcPinState = verifyGcFloor ? createGcPinState() : undefined - for (let index = 0; index < iterations; index++) { const request = buildRequest(random, index) const response = await handler.fetch(request) @@ -112,89 +88,12 @@ export async function runSequentialRequestLoop( validate(response, request) await drainResponse(response) - - if (pinGcBetweenIterations) { - await settleAndPinGc(gcPinState) - } } } -// Renderer/stream teardown spans several event-loop turns (React and Vue -// need more than the two turns the original barrier allowed for), and a -// too-short settle window leaks a whole payload of garbage past the -// collection point, flipping the measured peak bimodally between runs. -// The settle length is a fixed count on purpose: an adaptive exit (collect -// until the post-GC heap size stops moving) makes the collection points -// land at data-dependent turns, which re-introduces exactly the run-to-run -// variance this barrier exists to remove — heap-size readings never fully -// stabilize under the instrumented CI environment, so the exit point (and -// with it every subsequent GC point) shifted between identical runs. -const settleTurnsBeforeGc = 16 -const maxSettleTurns = 64 -// Below every scenario's payload size, above normal inter-iteration jitter. -const settledHeapSlackBytes = 256 * 1024 - -// Tracks the smallest post-collection heap size seen in a workload run: -// the inter-iteration floor the heap must return to before the next -// iteration may start. -export interface GcPinState { - floorHeapUsed: number -} - -export function createGcPinState(): GcPinState { - return { floorHeapUsed: Infinity } -} - -// Settle trailing renderer/stream teardown with a fixed number of 0ms timer -// hops (one full event-loop turn each, microtasks flushing between hops), -// then pin a collection point. The second collection one turn later picks -// up whatever the first collection's finalizers released. gc() is present -// under CodSpeed (--expose-gc); in plain smoke runs there is nothing to -// pin, so only the settle hops run. -// -// The collection is then verified against the inter-iteration heap floor: -// on some runners the response teardown holds the payload past the fixed -// settle window (released only by a later internal timer), and that one -// still-reachable payload survives the collection and bleeds into the next -// iteration's measured peak. When the post-collection heap has not returned -// to the floor, keep hopping and collecting — bounded — until the payload -// is actually released, so the barrier self-heals in exactly the case where -// the fixed-count barrier fails. A workload that genuinely accumulates -// reachable memory raises the floor as it goes (the floor is the minimum -// seen), so accumulation still measures; it only pays the turn cap. -export async function settleAndPinGc(state?: GcPinState) { - for (let turn = 0; turn < settleTurnsBeforeGc; turn++) { +// Cancellation can leave deferred loaders and renderer teardown queued. +export async function settle() { + for (let turn = 0; turn < 16; turn++) { await new Promise((resolve) => setTimeout(resolve, 0)) } - - const gc = (globalThis as { gc?: () => void }).gc - - if (!gc) { - return - } - - gc() - await new Promise((resolve) => setTimeout(resolve, 0)) - gc() - - if (!state) { - return - } - - let heapUsed = process.memoryUsage().heapUsed - - for ( - let turn = settleTurnsBeforeGc; - turn < maxSettleTurns && - heapUsed > state.floorHeapUsed + settledHeapSlackBytes; - turn++ - ) { - await new Promise((resolve) => setTimeout(resolve, 0)) - gc() - heapUsed = process.memoryUsage().heapUsed - } - - if (heapUsed < state.floorHeapUsed) { - state.floorHeapUsed = heapUsed - } } diff --git a/benchmarks/memory/server/benchmark.ts b/benchmarks/memory/server/benchmark.ts index 301a9f956d..9b8dc2c76f 100644 --- a/benchmarks/memory/server/benchmark.ts +++ b/benchmarks/memory/server/benchmark.ts @@ -1,5 +1,9 @@ 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 ae09eb8511..d09343c7b6 100644 --- a/benchmarks/memory/server/package.json +++ b/benchmarks/memory/server/package.json @@ -23,16 +23,18 @@ "vue": "^3.5.16" }, "devDependencies": { - "@codspeed/vitest-plugin": "^5.5.0", + "@codspeed/vitest-plugin": "^6.0.1", "@datadog/pprof": "^5.13.2", "@platformatic/flame": "^1.6.0", "@vitejs/plugin-react": "^6.0.1", "@vitejs/plugin-vue-jsx": "^5.1.5", + "@types/react": "catalog:", "@typescript/native": "npm:typescript@^7.0.2", + "jsdom": "29.1.1", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11", - "vitest": "^4.1.4" + "vitest": "catalog:" }, "nx": { "targets": { @@ -206,7 +208,7 @@ "build:react" ], "options": { - "command": "NODE_ENV=production vitest bench --config ./vitest.react.config.ts", + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.react.config.ts", "cwd": "benchmarks/memory/server" } }, @@ -218,7 +220,7 @@ "build:solid" ], "options": { - "command": "NODE_ENV=production vitest bench --config ./vitest.solid.config.ts", + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.solid.config.ts", "cwd": "benchmarks/memory/server" } }, @@ -230,12 +232,12 @@ "build:vue" ], "options": { - "command": "NODE_ENV=production vitest bench --config ./vitest.vue.config.ts", + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.vue.config.ts", "cwd": "benchmarks/memory/server" } }, "test:types": { - "executor": "nx:noop", + "executor": "nx:run-commands", "dependsOn": [ { "projects": [ @@ -263,6 +265,17 @@ ], "target": "test:types:ssr" } + ], + "options": { + "command": "tsc -p ./tsconfig.json --noEmit", + "cwd": "benchmarks/memory/server" + }, + "inputs": [ + "default", + "^production", + "{workspaceRoot}/eslint.config.js", + "dependentTaskOutputs", + "{workspaceRoot}/benchmarks/memory/*.ts" ] } } diff --git a/benchmarks/memory/server/scenarios/aborted-requests/deferred-records.ts b/benchmarks/memory/server/scenarios/aborted-requests/deferred-records.ts index 4886e3ee80..7a1cd6d254 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/deferred-records.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/deferred-records.ts @@ -16,3 +16,42 @@ 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 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/react/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/react/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).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 2ce925e406..eff0d0e043 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/react/vite.config.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/react/vite.config.ts @@ -3,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // 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: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), 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 c98f462538..29eca99e00 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/shared.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/shared.ts @@ -1,4 +1,4 @@ -import { settleAndPinGc } from '#memory-server/bench-utils' +import { settle } from '#memory-server/bench-utils' import type { StartRequestHandler } from '#memory-server/bench-utils' export type { StartRequestHandler } @@ -6,13 +6,6 @@ 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"' @@ -24,19 +17,10 @@ const betaFirstRecord = (id: string) => `deferred-beta-${id}-0` const betaLastRecord = (id: string) => `deferred-beta-${id}-19` const textDecoder = new TextDecoder() -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 abortedRequestModes: Record = { + react: 'first-chunk', + solid: 'first-chunk', + vue: 'shell-before-deferred', } const documentRequestInit = { @@ -96,7 +80,7 @@ async function readShellBeforeDeferred( const reader = response.body.getReader() let text = '' - while (true) { + for (;;) { const result = await reader.read() const value = result.value @@ -137,10 +121,10 @@ async function readShellBeforeDeferred( async function readSanityStream( response: Response, request: Request, - mode: AbortedRequestMode, + mode: AbortedRequestReadMode, id: string, ) { - if (mode.readMode === 'shell-before-deferred') { + if (mode === 'shell-before-deferred') { return readShellBeforeDeferred(response, request, id) } @@ -165,36 +149,19 @@ function readLoopStream( return readFirstChunk(response, request) } -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 - } +async function cancelReader(reader: ReadableStreamDefaultReader) { + try { + await reader.cancel() + } catch (error) { + if (!(error instanceof DOMException && error.name === 'AbortError')) { + throw error } - - return } - - await reader.cancel() -} - -// Post-abort settlement barrier. Settles renderer teardown across a fixed -// number of event-loop turns, then (under CodSpeed) pins a collection point -// after every aborted request, so the measured peak cannot drift with how -// much floating garbage the previous iterations happened to leave behind. -async function drainCancellation() { - await settleAndPinGc() } async function assertAbortedRequestsSanity( handler: StartRequestHandler, - mode: AbortedRequestMode, + mode: AbortedRequestReadMode, ) { const fullId = 'sanity-full' const fullRequest = buildStreamRequest(fullId) @@ -227,13 +194,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, mode.cancelMode) - await drainCancellation() + await cancelReader(reader) + await settle() } async function runAbortedRequestLoop( handler: StartRequestHandler, - mode: AbortedRequestMode, + mode: AbortedRequestReadMode, ) { for (let index = 0; index < abortedRequestIterations; index++) { const controller = new AbortController() @@ -242,15 +209,10 @@ async function runAbortedRequestLoop( const response = await handler.fetch(request) validateDocumentResponse(response, request) - const { reader } = await readLoopStream( - mode.readMode, - response, - request, - id, - ) + const { reader } = await readLoopStream(mode, response, request, id) controller.abort() - await cancelReader(reader, mode.cancelMode) - await drainCancellation() + await cancelReader(reader) + await settle() } } @@ -259,7 +221,7 @@ export function createWorkloadGroup( handler: StartRequestHandler, ) { const mode = abortedRequestModes[framework] - const run = () => runAbortedRequestLoop(handler, mode) + const run = async () => 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 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/solid/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).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 b47f25a405..bf6af17f31 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,90 +1,17 @@ +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 { - makeAbortedRequestRecords, - type DeferredRecord, - type RecordGroup, -} from '../../../deferred-records' +import { makeDeferredRecords } from '../../../deferred-records' +import type { DeferredRecord } from '../../../deferred-records' -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), - () => [], - ) -} +const getRequestSignal = createServerOnlyFn(() => getRequest().signal) export const Route = createFileRoute('/stream/$id')({ - loader: ({ params, abortController }) => ({ + loader: ({ params }) => ({ eager: `eager-${params.id}`, - alpha: makeDeferredRecords(params.id, 'alpha', abortController.signal), - beta: makeDeferredRecords(params.id, 'beta', abortController.signal), + alpha: makeDeferredRecords(params.id, 'alpha', getRequestSignal()), + beta: makeDeferredRecords(params.id, 'beta', getRequestSignal()), }), 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 5ee4e152af..d7fd3459ee 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/vite.config.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/solid/vite.config.ts @@ -3,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // 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: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), 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 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/vue/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).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 b723c7f69e..e41af03c16 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,136 +1,65 @@ +import { createServerOnlyFn } from '@tanstack/vue-start' +import { getRequest } from '@tanstack/vue-start/server' import { Await, createFileRoute } from '@tanstack/vue-router' -import { Suspense } from 'vue' -import { - makeAbortedRequestRecords, - type DeferredRecord, - type RecordGroup, -} from '../../../deferred-records' +import { Suspense, defineComponent } from 'vue' +import { makeDeferredRecords } from '../../../deferred-records' +import type { DeferredRecord } from '../../../deferred-records' -const alphaResolveTicks = 4 -const betaResolveTicks = 6 -const abortProbeAlphaResolveTicks = 40 -const abortProbeBetaResolveTicks = 60 +const getRequestSignal = createServerOnlyFn(() => getRequest().signal) -function isAbortProbeId(id: string) { - return id === 'sanity-mid-stream' || id.startsWith('abort-') -} +const StreamComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() -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), - () => [], - ) -} + return () => ( +
+

{data.value.eager}

+

loading-alpha

+

loading-beta

+ + {{ + default: () => ( + ) => ( +
    + {records.map((record) => ( +
  • {record.label}
  • + ))} +
+ )} + /> + ), + fallback: () => null, + }} +
+ + {{ + default: () => ( + ) => ( +
    + {records.map((record) => ( +
  • {record.label}
  • + ))} +
+ )} + /> + ), + fallback: () => null, + }} +
+
+ ) + }, +}) export const Route = createFileRoute('/stream/$id')({ - loader: ({ params, abortController }) => ({ + loader: ({ params }) => ({ eager: `eager-${params.id}`, - alpha: makeDeferredRecords(params.id, 'alpha', abortController.signal), - beta: makeDeferredRecords(params.id, 'beta', abortController.signal), + alpha: makeDeferredRecords(params.id, 'alpha', getRequestSignal()), + beta: makeDeferredRecords(params.id, 'beta', getRequestSignal()), }), 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 5ccc9f5d1d..e4e1eb66d4 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/vite.config.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/vue/vite.config.ts @@ -3,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // 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: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), 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 9a5c211fee..a6f07b97be 100644 --- a/benchmarks/memory/server/scenarios/error-paths/react/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/error-paths/react/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { - for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) - } +const workload = workloadGroup.workloads[0]! + +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(), workload.run).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 new file mode 100644 index 0000000000..89071137c3 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/react/memory.error.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + 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, + ) +}) 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 new file mode 100644 index 0000000000..fa6a6693ed --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/react/memory.not-found.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + 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, + ) +}) 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 new file mode 100644 index 0000000000..b2c3d24200 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/react/memory.unmatched.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + 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, + ) +}) diff --git a/benchmarks/memory/server/scenarios/error-paths/react/tsconfig.json b/benchmarks/memory/server/scenarios/error-paths/react/tsconfig.json index 11ddcce4ea..2dba47fc99 100644 --- a/benchmarks/memory/server/scenarios/error-paths/react/tsconfig.json +++ b/benchmarks/memory/server/scenarios/error-paths/react/tsconfig.json @@ -7,7 +7,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "memory.bench.ts", + "memory*.bench.ts", "memory.flame.ts", "setup.ts", "vite.config.ts", 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 bc67b1cfc7..c00de7727a 100644 --- a/benchmarks/memory/server/scenarios/error-paths/react/vite.config.ts +++ b/benchmarks/memory/server/scenarios/error-paths/react/vite.config.ts @@ -3,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,8 @@ export default defineConfig({ minify: false, }, test: { - // 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: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + isolate: true, + ...memoryConfig('server'), 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 57e229b7e3..11ed293d22 100644 --- a/benchmarks/memory/server/scenarios/error-paths/shared.ts +++ b/benchmarks/memory/server/scenarios/error-paths/shared.ts @@ -9,8 +9,6 @@ export type { StartRequestHandler } type Framework = 'react' | 'solid' | 'vue' -// Sized to sit just above the 2s measured-run floor on CI (per-iteration -// cost with the pinned collection is ~0.13-0.19s across frameworks). const errorPathsIterations = 18 const redirectSeed = 0xdecafbad const notFoundSeed = 0xdecafb0d @@ -138,40 +136,36 @@ export function createWorkloadGroup( framework: Framework, handler: StartRequestHandler, ) { - const runRedirect = () => + const runRedirect = async () => runSequentialRequestLoop(handler, { random: redirectRandom, iterations: errorPathsIterations, buildRequest: buildRedirectRequest, validateResponse: validateRedirectResponse, - pinGcBetweenIterations: true, }) - const runNotFound = () => + const runNotFound = async () => runSequentialRequestLoop(handler, { random: notFoundRandom, iterations: errorPathsIterations, buildRequest: buildNotFoundRequest, validateResponse: validateNotFoundResponse, - pinGcBetweenIterations: true, }) - const runError = () => + const runError = async () => runSequentialRequestLoop(handler, { random: errorRandom, iterations: errorPathsIterations, buildRequest: buildErrorRequest, validateResponse: validateErrorResponse, - pinGcBetweenIterations: true, }) - const runUnmatched = () => + const runUnmatched = async () => runSequentialRequestLoop(handler, { random: unmatchedRandom, iterations: errorPathsIterations, buildRequest: buildUnmatchedRequest, validateResponse: validateNotFoundResponse, - pinGcBetweenIterations: true, }) return { 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 9a5c211fee..a6f07b97be 100644 --- a/benchmarks/memory/server/scenarios/error-paths/solid/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/error-paths/solid/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { - for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) - } +const workload = workloadGroup.workloads[0]! + +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(), workload.run).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 new file mode 100644 index 0000000000..89071137c3 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/solid/memory.error.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + 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, + ) +}) 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 new file mode 100644 index 0000000000..fa6a6693ed --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/solid/memory.not-found.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + 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, + ) +}) 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 new file mode 100644 index 0000000000..b2c3d24200 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/solid/memory.unmatched.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + 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, + ) +}) diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/tsconfig.json b/benchmarks/memory/server/scenarios/error-paths/solid/tsconfig.json index 4b61264e11..1e8103127a 100644 --- a/benchmarks/memory/server/scenarios/error-paths/solid/tsconfig.json +++ b/benchmarks/memory/server/scenarios/error-paths/solid/tsconfig.json @@ -7,7 +7,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "memory.bench.ts", + "memory*.bench.ts", "memory.flame.ts", "setup.ts", "vite.config.ts", 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 401d1e5f25..d7a0bb51b0 100644 --- a/benchmarks/memory/server/scenarios/error-paths/solid/vite.config.ts +++ b/benchmarks/memory/server/scenarios/error-paths/solid/vite.config.ts @@ -3,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,8 @@ export default defineConfig({ minify: false, }, test: { - // 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: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + isolate: true, + ...memoryConfig('server'), 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 9a5c211fee..a6f07b97be 100644 --- a/benchmarks/memory/server/scenarios/error-paths/vue/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/error-paths/vue/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { - for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) - } +const workload = workloadGroup.workloads[0]! + +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(), workload.run).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 new file mode 100644 index 0000000000..89071137c3 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/vue/memory.error.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + 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, + ) +}) 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 new file mode 100644 index 0000000000..fa6a6693ed --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/vue/memory.not-found.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + 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, + ) +}) 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 new file mode 100644 index 0000000000..b2c3d24200 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/vue/memory.unmatched.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + 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, + ) +}) 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 17ade6bf5b..0bbf4a3dc6 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,11 +1,14 @@ +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/tsconfig.json b/benchmarks/memory/server/scenarios/error-paths/vue/tsconfig.json index 9ad6481342..af8b83005c 100644 --- a/benchmarks/memory/server/scenarios/error-paths/vue/tsconfig.json +++ b/benchmarks/memory/server/scenarios/error-paths/vue/tsconfig.json @@ -7,7 +7,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "memory.bench.ts", + "memory*.bench.ts", "memory.flame.ts", "setup.ts", "vite.config.ts", 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 9a0ca28a25..3dc0762aa0 100644 --- a/benchmarks/memory/server/scenarios/error-paths/vue/vite.config.ts +++ b/benchmarks/memory/server/scenarios/error-paths/vue/vite.config.ts @@ -3,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,8 @@ export default defineConfig({ minify: false, }, test: { - // 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: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + isolate: true, + ...memoryConfig('server'), 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 9a5c211fee..8b5f16ad63 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,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).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 adaacda86e..dcfcf1f92b 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,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // 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: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), 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 578fc9c5a2..085e576244 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/shared.ts +++ b/benchmarks/memory/server/scenarios/peak-large-page/shared.ts @@ -6,7 +6,7 @@ export type { StartRequestHandler } type Framework = 'react' | 'solid' | 'vue' const benchmarkSeed = 0x5eed_0005 -const peakLargePageIterations = 20 +const peakLargePageIterations = 1 const peakLargePageUrl = 'http://localhost/l1/l2/l3/l4/l5/l6/l7/l8' const levelEightMarker = 'data-bench="peak-large-page-level-8"' @@ -48,14 +48,12 @@ export function createWorkloadGroup( framework: Framework, handler: StartRequestHandler, ) { - const run = () => + const run = async () => runSequentialRequestLoop(handler, { seed: benchmarkSeed, iterations: peakLargePageIterations, buildRequest: buildPeakLargePageRequest, validateResponse: validatePeakLargePageResponse, - pinGcBetweenIterations: true, - verifyGcFloor: true, }) return { 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 9a5c211fee..8b5f16ad63 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,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).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 27d4dd65f7..15b8c3a571 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,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // 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: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), 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 9a5c211fee..8b5f16ad63 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,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).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 bd079aa1a0..7f7a42d645 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,28 +1,34 @@ +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 7f69f6f438..a99c56e529 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,29 +1,35 @@ +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 75a7c717e3..3de3f03427 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,29 +1,35 @@ +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 f390ae3db3..5d936f83b5 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,29 +1,35 @@ +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 6b30bd50dc..8e10331f2d 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,29 +1,35 @@ +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 6ec6f32fea..d69529c50c 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,29 +1,35 @@ +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 e5b4cf0de1..d04bc7f827 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,29 +1,35 @@ +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 a29e465cd4..a95ae7f9b0 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,29 +1,35 @@ +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 0f238bd7f7..3fab2aff9e 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,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // 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: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), 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 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/request-churn/react/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/request-churn/react/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).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 1e956958ec..35adf6a249 100644 --- a/benchmarks/memory/server/scenarios/request-churn/react/vite.config.ts +++ b/benchmarks/memory/server/scenarios/request-churn/react/vite.config.ts @@ -3,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // 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: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), 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 a196eec8b5..b200c96ed6 100644 --- a/benchmarks/memory/server/scenarios/request-churn/shared.ts +++ b/benchmarks/memory/server/scenarios/request-churn/shared.ts @@ -62,13 +62,12 @@ export function createWorkloadGroup( return new Request(`http://localhost/items/${id}?q=${q}`, requestInit) } - const run = () => + const run = async () => runSequentialRequestLoop(handler, { random: benchmarkRandom, iterations: requestChurnIterations, buildRequest: buildItemRequest, validateResponse: validateItemResponse, - pinGcBetweenIterations: true, }) return { 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 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/request-churn/solid/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/request-churn/solid/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).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 fbf8df9491..6601309a74 100644 --- a/benchmarks/memory/server/scenarios/request-churn/solid/vite.config.ts +++ b/benchmarks/memory/server/scenarios/request-churn/solid/vite.config.ts @@ -3,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // 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: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), 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 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/request-churn/vue/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/request-churn/vue/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).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 a98d036565..570561f2a8 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,3 +1,4 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' const itemIndexes = Array.from({ length: 5 }, (_, index) => index) @@ -6,6 +7,24 @@ 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 : '', @@ -22,19 +41,3 @@ 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 a551a96e2f..7f15c5c7af 100644 --- a/benchmarks/memory/server/scenarios/request-churn/vue/vite.config.ts +++ b/benchmarks/memory/server/scenarios/request-churn/vue/vite.config.ts @@ -3,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // 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: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), 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 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/serialization-payload/react/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/serialization-payload/react/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).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 de5549de3b..1ed3bcc335 100644 --- a/benchmarks/memory/server/scenarios/serialization-payload/react/vite.config.ts +++ b/benchmarks/memory/server/scenarios/serialization-payload/react/vite.config.ts @@ -3,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // 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: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), 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 ce095b5e10..14ec8f7e0a 100644 --- a/benchmarks/memory/server/scenarios/serialization-payload/shared.ts +++ b/benchmarks/memory/server/scenarios/serialization-payload/shared.ts @@ -9,7 +9,7 @@ export type { StartRequestHandler } type Framework = 'react' | 'solid' | 'vue' const benchmarkSeed = 0x51eaa11 -const serializationPayloadIterations = 12 +const serializationPayloadIterations = 1 const payloadPageMarker = 'data-bench="serialization-payload"' const requestInit = { @@ -55,14 +55,12 @@ export function createWorkloadGroup( framework: Framework, handler: StartRequestHandler, ) { - const run = () => + const run = async () => runSequentialRequestLoop(handler, { seed: benchmarkSeed, iterations: serializationPayloadIterations, buildRequest: buildPayloadRequest, validateResponse: validatePayloadResponse, - pinGcBetweenIterations: true, - verifyGcFloor: true, }) return { 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 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/serialization-payload/solid/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/serialization-payload/solid/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).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 926646ee12..a2d04b986c 100644 --- a/benchmarks/memory/server/scenarios/serialization-payload/solid/vite.config.ts +++ b/benchmarks/memory/server/scenarios/serialization-payload/solid/vite.config.ts @@ -3,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // 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: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), 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 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/serialization-payload/vue/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/serialization-payload/vue/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).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 e6b4cfadfb..37b1a590e4 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,17 +1,20 @@ +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 41a5596adf..b63a561228 100644 --- a/benchmarks/memory/server/scenarios/serialization-payload/vue/vite.config.ts +++ b/benchmarks/memory/server/scenarios/serialization-payload/vue/vite.config.ts @@ -3,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // 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: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), 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 9a5c211fee..8b5f16ad63 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,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).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 68d9ed839b..f72cc53d6f 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,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // 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: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), 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 6e2959e757..167b24d3b6 100644 --- a/benchmarks/memory/server/scenarios/server-fn-churn/shared.ts +++ b/benchmarks/memory/server/scenarios/server-fn-churn/shared.ts @@ -38,8 +38,6 @@ 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' @@ -204,11 +202,10 @@ export async function createWorkloadGroup( handler: StartRequestHandler, ) { const urls = await discoverUrls(handler) - const run = () => + const run = async () => runSequentialRequestLoop(handler, { seed: benchmarkSeed, iterations: serverFnChurnIterations, - pinGcBetweenIterations: true, buildRequest: (_random, index) => { const fixtureIndex = Math.floor(index / 2) % fixtureCount 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 9a5c211fee..8b5f16ad63 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,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).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 8d6d226e97..4fba196bd2 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,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // 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: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), 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 9a5c211fee..8b5f16ad63 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,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).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 0e249b9f3b..5ab5ec37e3 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,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // 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: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), 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 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/streaming-peak/react/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).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 5af0f0d138..5d555441b6 100644 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/vite.config.ts +++ b/benchmarks/memory/server/scenarios/streaming-peak/react/vite.config.ts @@ -3,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // 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: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), 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 6b45470329..c027047408 100644 --- a/benchmarks/memory/server/scenarios/streaming-peak/shared.ts +++ b/benchmarks/memory/server/scenarios/streaming-peak/shared.ts @@ -9,7 +9,7 @@ export type { StartRequestHandler } type Framework = 'react' | 'solid' | 'vue' const benchmarkSeed = 0xdecafbad -const streamingPeakIterations = 20 +const streamingPeakIterations = 1 const fallbackMarker = 'streaming-peak-fallback-0' const requestInit = { @@ -50,7 +50,7 @@ async function readStreamingBody(response: Response) { let body = '' let chunkCount = 0 - while (true) { + for (;;) { const result = await reader.read() if (result.done) { @@ -92,18 +92,21 @@ export function createWorkloadGroup( framework: Framework, handler: StartRequestHandler, ) { - const run = () => + const run = async () => runSequentialRequestLoop(handler, { seed: benchmarkSeed, iterations: streamingPeakIterations, buildRequest: buildStreamingRequest, validateResponse: validateStreamingResponse, - pinGcBetweenIterations: true, - verifyGcFloor: true, }) return { - sanity: () => assertStreamingPeakSanity(handler), + 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) + }, 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 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/streaming-peak/solid/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).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 18bf5b2d04..5fbdb48c23 100644 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/vite.config.ts +++ b/benchmarks/memory/server/scenarios/streaming-peak/solid/vite.config.ts @@ -3,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // 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: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), 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 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/streaming-peak/vue/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).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 0c71a8d3a0..750d1cb47d 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 } from 'vue' +import { Suspense, defineComponent } from 'vue' import { makeDeferredSectionPayload, type DeferredSectionPayload, @@ -7,6 +7,47 @@ 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}`, @@ -48,42 +89,6 @@ 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 7cd481da0b..cd848584a5 100644 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/vite.config.ts +++ b/benchmarks/memory/server/scenarios/streaming-peak/vue/vite.config.ts @@ -3,6 +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' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // 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: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), 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 5d5dcbf825..86d36f047a 100644 --- a/benchmarks/memory/server/tsconfig.json +++ b/benchmarks/memory/server/tsconfig.json @@ -3,5 +3,10 @@ "compilerOptions": { "types": ["node", "vite/client", "vitest/globals"] }, - "include": ["bench-utils.ts"] + "include": [ + "bench-utils.ts", + "scenarios/*/shared.ts", + "../runtime.ts", + "vitest.setup.ts" + ] } diff --git a/benchmarks/memory/tsconfig.json b/benchmarks/memory/tsconfig.json new file mode 100644 index 0000000000..5a325f3b6c --- /dev/null +++ b/benchmarks/memory/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "types": ["node"] + }, + "include": ["runtime.ts"] +} diff --git a/benchmarks/memory/turn.ts b/benchmarks/memory/turn.ts new file mode 100644 index 0000000000..08729685fe --- /dev/null +++ b/benchmarks/memory/turn.ts @@ -0,0 +1,34 @@ +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 625e1006c5..3d90af1598 100644 --- a/benchmarks/ssr/README.md +++ b/benchmarks/ssr/README.md @@ -98,3 +98,18 @@ 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 c5721ec7a0..20c1837468 100644 --- a/benchmarks/ssr/package.json +++ b/benchmarks/ssr/package.json @@ -15,15 +15,17 @@ "vue": "^3.5.16" }, "devDependencies": { - "@codspeed/vitest-plugin": "^5.5.0", + "@codspeed/vitest-plugin": "^6.0.1", "@vitejs/plugin-react": "^6.0.1", "@vitejs/plugin-vue-jsx": "^5.1.5", - "seroval": "^1.6.2", + "@types/react": "catalog:", + "seroval": "^1.6.7", "@typescript/native": "npm:typescript@^7.0.2", + "jsdom": "29.1.1", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11", - "vitest": "^4.1.4" + "vitest": "catalog:" }, "nx": { "targets": { @@ -114,7 +116,7 @@ "build:vue" ], "options": { - "command": "NODE_ENV=production vitest bench", + "command": "NODE_ENV=production vitest bench --mode benchmark", "cwd": "benchmarks/ssr" } }, @@ -132,7 +134,7 @@ "build:react" ], "options": { - "command": "NODE_ENV=production vitest bench --config ./vitest.react.config.ts", + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.react.config.ts", "cwd": "benchmarks/ssr" } }, @@ -143,7 +145,7 @@ "build:solid" ], "options": { - "command": "NODE_ENV=production vitest bench --config ./vitest.solid.config.ts", + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.solid.config.ts", "cwd": "benchmarks/ssr" } }, @@ -154,7 +156,7 @@ "build:vue" ], "options": { - "command": "NODE_ENV=production vitest bench --config ./vitest.vue.config.ts", + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.vue.config.ts", "cwd": "benchmarks/ssr" } }, @@ -215,6 +217,13 @@ ], "target": "test:types:ssr" } + ], + "inputs": [ + "default", + "^production", + "{workspaceRoot}/eslint.config.js", + "{workspaceRoot}/benchmarks/cpu-simulation.ts", + "dependentTaskOutputs" ] } } diff --git a/benchmarks/ssr/react/speed.bench.ts b/benchmarks/ssr/react/speed.bench.ts index 419b1ccb36..6825a7ddfb 100644 --- a/benchmarks/ssr/react/speed.bench.ts +++ b/benchmarks/ssr/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { runSsrRequestLoop } from '../bench-utils' import type { StartRequestHandler } from '../bench-utils' @@ -11,14 +11,12 @@ const { default: handler } = (await import( default: StartRequestHandler } -describe('ssr', () => { - bench( - 'ssr request loop (react)', - () => runSsrRequestLoop(handler, { seed: benchmarkSeed }), - { - warmupIterations: 100, - time: 10_000, - throws: true, - }, - ) +test('ssr', async ({ bench }) => { + await bench('ssr request loop (react)', async () => + runSsrRequestLoop(handler, { seed: benchmarkSeed }), + ).run({ + warmupIterations: 100, + time: 10_000, + throws: true, + }) }) diff --git a/benchmarks/ssr/react/vite.config.ts b/benchmarks/ssr/react/vite.config.ts index 04f15c3959..e607db366b 100644 --- a/benchmarks/ssr/react/vite.config.ts +++ b/benchmarks/ssr/react/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr (react)', watch: false, environment: 'node', 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 new file mode 100644 index 0000000000..0496613afb --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/react/speed.assets-linked-css-control.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertAssetsScenario, + assetsBenchOptions, + runAssetsLinkedControlLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertAssetsScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr assets linked-css control (react)', async () => + runAssetsLinkedControlLoop(handler), + ).run(assetsBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/assets/react/speed.bench.ts b/benchmarks/ssr/scenarios/assets/react/speed.bench.ts index a54042cd86..7dc57d89f1 100644 --- a/benchmarks/ssr/scenarios/assets/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/assets/react/speed.bench.ts @@ -1,11 +1,10 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertAssetsScenario, assetsBenchOptions, runAssetsInlineLoop, - runAssetsLinkedControlLoop, - type StartRequestHandler, } from '../shared' +import type { StartRequestHandler } from '../shared' const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href @@ -17,15 +16,8 @@ const { default: handler } = (await import( await assertAssetsScenario(handler) -describe('ssr', () => { - bench( - 'ssr assets inline-css cdn (react)', - () => runAssetsInlineLoop(handler), - assetsBenchOptions, - ) - bench( - 'ssr assets linked-css control (react)', - () => runAssetsLinkedControlLoop(handler), - assetsBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr assets inline-css cdn (react)', async () => + runAssetsInlineLoop(handler), + ).run(assetsBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/assets/react/tsconfig.json b/benchmarks/ssr/scenarios/assets/react/tsconfig.json index 91027bfc88..cf14e1d440 100644 --- a/benchmarks/ssr/scenarios/assets/react/tsconfig.json +++ b/benchmarks/ssr/scenarios/assets/react/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "./src/**/*" diff --git a/benchmarks/ssr/scenarios/assets/react/vite.config.ts b/benchmarks/ssr/scenarios/assets/react/vite.config.ts index 91534d3de8..5990bba6d3 100644 --- a/benchmarks/ssr/scenarios/assets/react/vite.config.ts +++ b/benchmarks/ssr/scenarios/assets/react/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -27,6 +28,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr assets (react)', watch: false, environment: 'node', 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 new file mode 100644 index 0000000000..d159124a04 --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/solid/speed.assets-linked-css-control.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertAssetsScenario, + assetsBenchOptions, + runAssetsLinkedControlLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertAssetsScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr assets linked-css control (solid)', async () => + runAssetsLinkedControlLoop(handler), + ).run(assetsBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/assets/solid/speed.bench.ts b/benchmarks/ssr/scenarios/assets/solid/speed.bench.ts index 49d7722163..47f483df11 100644 --- a/benchmarks/ssr/scenarios/assets/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/assets/solid/speed.bench.ts @@ -1,11 +1,10 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertAssetsScenario, assetsBenchOptions, runAssetsInlineLoop, - runAssetsLinkedControlLoop, - type StartRequestHandler, } from '../shared' +import type { StartRequestHandler } from '../shared' const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href @@ -17,15 +16,8 @@ const { default: handler } = (await import( await assertAssetsScenario(handler) -describe('ssr', () => { - bench( - 'ssr assets inline-css cdn (solid)', - () => runAssetsInlineLoop(handler), - assetsBenchOptions, - ) - bench( - 'ssr assets linked-css control (solid)', - () => runAssetsLinkedControlLoop(handler), - assetsBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr assets inline-css cdn (solid)', async () => + runAssetsInlineLoop(handler), + ).run(assetsBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/assets/solid/tsconfig.json b/benchmarks/ssr/scenarios/assets/solid/tsconfig.json index b1806caa67..42c3a2160f 100644 --- a/benchmarks/ssr/scenarios/assets/solid/tsconfig.json +++ b/benchmarks/ssr/scenarios/assets/solid/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "./src/**/*" diff --git a/benchmarks/ssr/scenarios/assets/solid/vite.config.ts b/benchmarks/ssr/scenarios/assets/solid/vite.config.ts index 788ac1f5b8..3ee54e5ae2 100644 --- a/benchmarks/ssr/scenarios/assets/solid/vite.config.ts +++ b/benchmarks/ssr/scenarios/assets/solid/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -27,6 +28,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr assets (solid)', watch: false, environment: 'node', 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 new file mode 100644 index 0000000000..e56d41df6b --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/vue/speed.assets-linked-css-control.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertAssetsScenario, + assetsBenchOptions, + runAssetsLinkedControlLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertAssetsScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr assets linked-css control (vue)', async () => + runAssetsLinkedControlLoop(handler), + ).run(assetsBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/assets/vue/speed.bench.ts b/benchmarks/ssr/scenarios/assets/vue/speed.bench.ts index 01eb3b9d5a..3f77a0dcc1 100644 --- a/benchmarks/ssr/scenarios/assets/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/assets/vue/speed.bench.ts @@ -1,11 +1,10 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertAssetsScenario, assetsBenchOptions, runAssetsInlineLoop, - runAssetsLinkedControlLoop, - type StartRequestHandler, } from '../shared' +import type { StartRequestHandler } from '../shared' const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href @@ -17,15 +16,8 @@ const { default: handler } = (await import( await assertAssetsScenario(handler) -describe('ssr', () => { - bench( - 'ssr assets inline-css cdn (vue)', - () => runAssetsInlineLoop(handler), - assetsBenchOptions, - ) - bench( - 'ssr assets linked-css control (vue)', - () => runAssetsLinkedControlLoop(handler), - assetsBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr assets inline-css cdn (vue)', async () => + runAssetsInlineLoop(handler), + ).run(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 a20e292938..a29fe59f22 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,6 +1,21 @@ +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}` }], @@ -12,15 +27,3 @@ 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 f8038f6f28..e1fe0418e4 100644 --- a/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.tsx +++ b/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.tsx @@ -1,6 +1,20 @@ +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}` }], @@ -12,14 +26,3 @@ 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/assets/vue/tsconfig.json b/benchmarks/ssr/scenarios/assets/vue/tsconfig.json index 4fe3ccecb1..08c94853f4 100644 --- a/benchmarks/ssr/scenarios/assets/vue/tsconfig.json +++ b/benchmarks/ssr/scenarios/assets/vue/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "./src/**/*" diff --git a/benchmarks/ssr/scenarios/assets/vue/vite.config.ts b/benchmarks/ssr/scenarios/assets/vue/vite.config.ts index 8beb38c972..e664b9b02b 100644 --- a/benchmarks/ssr/scenarios/assets/vue/vite.config.ts +++ b/benchmarks/ssr/scenarios/assets/vue/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -27,6 +28,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr assets (vue)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/before-load/react/speed.bench.ts b/benchmarks/ssr/scenarios/before-load/react/speed.bench.ts index 09073687c0..8a4355a168 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 { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertBeforeLoadScenario, beforeLoadBenchOptions, @@ -16,10 +16,8 @@ const { default: handler } = (await import( await assertBeforeLoadScenario(handler) -describe('ssr', () => { - bench( - 'ssr before-load chain (react)', - () => runBeforeLoadLoop(handler), - beforeLoadBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr before-load chain (react)', async () => + runBeforeLoadLoop(handler), + ).run(beforeLoadBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/before-load/react/vite.config.ts b/benchmarks/ssr/scenarios/before-load/react/vite.config.ts index 2767b85787..3fd72c5f1d 100644 --- a/benchmarks/ssr/scenarios/before-load/react/vite.config.ts +++ b/benchmarks/ssr/scenarios/before-load/react/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr before-load (react)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/before-load/solid/speed.bench.ts b/benchmarks/ssr/scenarios/before-load/solid/speed.bench.ts index 5f6e8baf8a..27e0d3a64c 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 { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertBeforeLoadScenario, beforeLoadBenchOptions, @@ -16,10 +16,8 @@ const { default: handler } = (await import( await assertBeforeLoadScenario(handler) -describe('ssr', () => { - bench( - 'ssr before-load chain (solid)', - () => runBeforeLoadLoop(handler), - beforeLoadBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr before-load chain (solid)', async () => + runBeforeLoadLoop(handler), + ).run(beforeLoadBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/before-load/solid/vite.config.ts b/benchmarks/ssr/scenarios/before-load/solid/vite.config.ts index ea0177e059..a20e32742e 100644 --- a/benchmarks/ssr/scenarios/before-load/solid/vite.config.ts +++ b/benchmarks/ssr/scenarios/before-load/solid/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr before-load (solid)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/before-load/vue/speed.bench.ts b/benchmarks/ssr/scenarios/before-load/vue/speed.bench.ts index d2cfd6814b..8684c159eb 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 { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertBeforeLoadScenario, beforeLoadBenchOptions, @@ -16,10 +16,8 @@ const { default: handler } = (await import( await assertBeforeLoadScenario(handler) -describe('ssr', () => { - bench( - 'ssr before-load chain (vue)', - () => runBeforeLoadLoop(handler), - beforeLoadBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr before-load chain (vue)', async () => + runBeforeLoadLoop(handler), + ).run(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 118e16553b..178d4071eb 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,6 +1,15 @@ +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 @@ -15,9 +24,3 @@ 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/before-load/vue/vite.config.ts b/benchmarks/ssr/scenarios/before-load/vue/vite.config.ts index 181200a004..093776869f 100644 --- a/benchmarks/ssr/scenarios/before-load/vue/vite.config.ts +++ b/benchmarks/ssr/scenarios/before-load/vue/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr before-load (vue)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/control-flow/react/speed.bench.ts b/benchmarks/ssr/scenarios/control-flow/react/speed.bench.ts index 4fca8eb477..899f400799 100644 --- a/benchmarks/ssr/scenarios/control-flow/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/control-flow/react/speed.bench.ts @@ -1,12 +1,8 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, - runErrorLoop, - runNotFoundLoop, runRedirectLoop, - runRouteHeadersLoop, - runUnmatchedLoop, } from '../shared' import type { StartRequestHandler } from '../shared' @@ -20,34 +16,8 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -describe('ssr', () => { - bench( - 'ssr redirect (react)', - () => runRedirectLoop(handler), - controlFlowBenchOptions, - ) - - bench( - 'ssr not-found (react)', - () => runNotFoundLoop(handler), - controlFlowBenchOptions, - ) - - bench( - 'ssr control-flow error 500 (react)', - () => runErrorLoop(handler), - controlFlowBenchOptions, - ) - - bench( - 'ssr control-flow unmatched 404 (react)', - () => runUnmatchedLoop(handler), - controlFlowBenchOptions, - ) - - bench( - 'ssr control-flow route headers (react)', - () => runRouteHeadersLoop(handler), +test('ssr', async ({ bench }) => { + await bench('ssr redirect (react)', async () => runRedirectLoop(handler)).run( 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 new file mode 100644 index 0000000000..0a93c5eac3 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-error-500.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runErrorLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr control-flow error 500 (react)', async () => + runErrorLoop(handler), + ).run(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 new file mode 100644 index 0000000000..53e09fd34e --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-route-headers.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runRouteHeadersLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr control-flow route headers (react)', async () => + runRouteHeadersLoop(handler), + ).run(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 new file mode 100644 index 0000000000..1cd7c1044c --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-unmatched-404.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runUnmatchedLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr control-flow unmatched 404 (react)', async () => + runUnmatchedLoop(handler), + ).run(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 new file mode 100644 index 0000000000..1e8abfd318 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/react/speed.not-found.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runNotFoundLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr not-found (react)', async () => + runNotFoundLoop(handler), + ).run(controlFlowBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/control-flow/react/tsconfig.json b/benchmarks/ssr/scenarios/control-flow/react/tsconfig.json index 91027bfc88..cf14e1d440 100644 --- a/benchmarks/ssr/scenarios/control-flow/react/tsconfig.json +++ b/benchmarks/ssr/scenarios/control-flow/react/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "./src/**/*" diff --git a/benchmarks/ssr/scenarios/control-flow/react/vite.config.ts b/benchmarks/ssr/scenarios/control-flow/react/vite.config.ts index b15f7bc530..273d7d9d80 100644 --- a/benchmarks/ssr/scenarios/control-flow/react/vite.config.ts +++ b/benchmarks/ssr/scenarios/control-flow/react/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr control-flow (react)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/control-flow/solid/speed.bench.ts b/benchmarks/ssr/scenarios/control-flow/solid/speed.bench.ts index ed23ed45d7..904b693e25 100644 --- a/benchmarks/ssr/scenarios/control-flow/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/control-flow/solid/speed.bench.ts @@ -1,12 +1,8 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, - runErrorLoop, - runNotFoundLoop, runRedirectLoop, - runRouteHeadersLoop, - runUnmatchedLoop, } from '../shared' import type { StartRequestHandler } from '../shared' @@ -20,34 +16,8 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -describe('ssr', () => { - bench( - 'ssr redirect (solid)', - () => runRedirectLoop(handler), - controlFlowBenchOptions, - ) - - bench( - 'ssr not-found (solid)', - () => runNotFoundLoop(handler), - controlFlowBenchOptions, - ) - - bench( - 'ssr control-flow error 500 (solid)', - () => runErrorLoop(handler), - controlFlowBenchOptions, - ) - - bench( - 'ssr control-flow unmatched 404 (solid)', - () => runUnmatchedLoop(handler), - controlFlowBenchOptions, - ) - - bench( - 'ssr control-flow route headers (solid)', - () => runRouteHeadersLoop(handler), +test('ssr', async ({ bench }) => { + await bench('ssr redirect (solid)', async () => runRedirectLoop(handler)).run( 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 new file mode 100644 index 0000000000..57a2f0fbe9 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-error-500.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runErrorLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr control-flow error 500 (solid)', async () => + runErrorLoop(handler), + ).run(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 new file mode 100644 index 0000000000..6581e92b39 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-route-headers.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runRouteHeadersLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr control-flow route headers (solid)', async () => + runRouteHeadersLoop(handler), + ).run(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 new file mode 100644 index 0000000000..40f1679320 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-unmatched-404.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runUnmatchedLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr control-flow unmatched 404 (solid)', async () => + runUnmatchedLoop(handler), + ).run(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 new file mode 100644 index 0000000000..efcb7cc229 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/solid/speed.not-found.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runNotFoundLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr not-found (solid)', async () => + runNotFoundLoop(handler), + ).run(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 5e7342c172..3cec17d9c8 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 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' +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' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const TargetIdRoute = TargetIdRouteImport.update({ - id: '/target/$id', - path: '/target/$id', - getParentRoute: () => rootRouteImport, -} as any) -const MissingIdRoute = MissingIdRouteImport.update({ - id: '/missing/$id', - path: '/missing/$id', - getParentRoute: () => rootRouteImport, -} as any) -const HeadersIdRoute = HeadersIdRouteImport.update({ - id: '/headers/$id', - path: '/headers/$id', +const BoomIdRoute = BoomIdRouteImport.update({ + id: '/boom/$id', + path: '/boom/$id', getParentRoute: () => rootRouteImport, } as any) const FromIdRoute = FromIdRouteImport.update({ @@ -41,9 +31,19 @@ const FromIdRoute = FromIdRouteImport.update({ path: '/from/$id', getParentRoute: () => rootRouteImport, } as any) -const BoomIdRoute = BoomIdRouteImport.update({ - id: '/boom/$id', - path: '/boom/$id', +const HeadersIdRoute = HeadersIdRouteImport.update({ + id: '/headers/$id', + path: '/headers/$id', + getParentRoute: () => rootRouteImport, +} as any) +const MissingIdRoute = MissingIdRouteImport.update({ + id: '/missing/$id', + path: '/missing/$id', + getParentRoute: () => rootRouteImport, +} as any) +const TargetIdRoute = TargetIdRouteImport.update({ + id: '/target/$id', + path: '/target/$id', getParentRoute: () => rootRouteImport, } as any) @@ -117,25 +117,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/target/$id': { - id: '/target/$id' - path: '/target/$id' - fullPath: '/target/$id' - preLoaderRoute: typeof TargetIdRouteImport - parentRoute: typeof rootRouteImport - } - '/missing/$id': { - id: '/missing/$id' - path: '/missing/$id' - fullPath: '/missing/$id' - preLoaderRoute: typeof MissingIdRouteImport - parentRoute: typeof rootRouteImport - } - '/headers/$id': { - id: '/headers/$id' - path: '/headers/$id' - fullPath: '/headers/$id' - preLoaderRoute: typeof HeadersIdRouteImport + '/boom/$id': { + id: '/boom/$id' + path: '/boom/$id' + fullPath: '/boom/$id' + preLoaderRoute: typeof BoomIdRouteImport parentRoute: typeof rootRouteImport } '/from/$id': { @@ -145,11 +131,25 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof FromIdRouteImport parentRoute: typeof rootRouteImport } - '/boom/$id': { - id: '/boom/$id' - path: '/boom/$id' - fullPath: '/boom/$id' - preLoaderRoute: typeof BoomIdRouteImport + '/headers/$id': { + id: '/headers/$id' + path: '/headers/$id' + fullPath: '/headers/$id' + preLoaderRoute: typeof HeadersIdRouteImport + parentRoute: typeof rootRouteImport + } + '/missing/$id': { + id: '/missing/$id' + path: '/missing/$id' + fullPath: '/missing/$id' + preLoaderRoute: typeof MissingIdRouteImport + parentRoute: typeof rootRouteImport + } + '/target/$id': { + id: '/target/$id' + path: '/target/$id' + fullPath: '/target/$id' + preLoaderRoute: typeof TargetIdRouteImport parentRoute: typeof rootRouteImport } } diff --git a/benchmarks/ssr/scenarios/control-flow/solid/tsconfig.json b/benchmarks/ssr/scenarios/control-flow/solid/tsconfig.json index b1806caa67..42c3a2160f 100644 --- a/benchmarks/ssr/scenarios/control-flow/solid/tsconfig.json +++ b/benchmarks/ssr/scenarios/control-flow/solid/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "./src/**/*" diff --git a/benchmarks/ssr/scenarios/control-flow/solid/vite.config.ts b/benchmarks/ssr/scenarios/control-flow/solid/vite.config.ts index 0bcd175f60..c75c957466 100644 --- a/benchmarks/ssr/scenarios/control-flow/solid/vite.config.ts +++ b/benchmarks/ssr/scenarios/control-flow/solid/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr control-flow (solid)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/control-flow/vue/speed.bench.ts b/benchmarks/ssr/scenarios/control-flow/vue/speed.bench.ts index 99bb46dfb3..0b95f426f2 100644 --- a/benchmarks/ssr/scenarios/control-flow/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/control-flow/vue/speed.bench.ts @@ -1,12 +1,8 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, - runErrorLoop, - runNotFoundLoop, runRedirectLoop, - runRouteHeadersLoop, - runUnmatchedLoop, } from '../shared' import type { StartRequestHandler } from '../shared' @@ -20,34 +16,8 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -describe('ssr', () => { - bench( - 'ssr redirect (vue)', - () => runRedirectLoop(handler), - controlFlowBenchOptions, - ) - - bench( - 'ssr not-found (vue)', - () => runNotFoundLoop(handler), - controlFlowBenchOptions, - ) - - bench( - 'ssr control-flow error 500 (vue)', - () => runErrorLoop(handler), - controlFlowBenchOptions, - ) - - bench( - 'ssr control-flow unmatched 404 (vue)', - () => runUnmatchedLoop(handler), - controlFlowBenchOptions, - ) - - bench( - 'ssr control-flow route headers (vue)', - () => runRouteHeadersLoop(handler), +test('ssr', async ({ bench }) => { + await bench('ssr redirect (vue)', async () => runRedirectLoop(handler)).run( 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 new file mode 100644 index 0000000000..262ca951af --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-error-500.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runErrorLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr control-flow error 500 (vue)', async () => + runErrorLoop(handler), + ).run(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 new file mode 100644 index 0000000000..bf8c90a8a1 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-route-headers.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runRouteHeadersLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr control-flow route headers (vue)', async () => + runRouteHeadersLoop(handler), + ).run(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 new file mode 100644 index 0000000000..d7f8ebeb9e --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-unmatched-404.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runUnmatchedLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr control-flow unmatched 404 (vue)', async () => + runUnmatchedLoop(handler), + ).run(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 new file mode 100644 index 0000000000..4b84fb594c --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/vue/speed.not-found.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runNotFoundLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr not-found (vue)', async () => runNotFoundLoop(handler)).run( + 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 f5063d1c09..6dcf0d095e 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 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' +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' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const TargetIdRoute = TargetIdRouteImport.update({ - id: '/target/$id', - path: '/target/$id', - getParentRoute: () => rootRouteImport, -} as any) -const MissingIdRoute = MissingIdRouteImport.update({ - id: '/missing/$id', - path: '/missing/$id', - getParentRoute: () => rootRouteImport, -} as any) -const HeadersIdRoute = HeadersIdRouteImport.update({ - id: '/headers/$id', - path: '/headers/$id', +const BoomIdRoute = BoomIdRouteImport.update({ + id: '/boom/$id', + path: '/boom/$id', getParentRoute: () => rootRouteImport, } as any) const FromIdRoute = FromIdRouteImport.update({ @@ -41,9 +31,19 @@ const FromIdRoute = FromIdRouteImport.update({ path: '/from/$id', getParentRoute: () => rootRouteImport, } as any) -const BoomIdRoute = BoomIdRouteImport.update({ - id: '/boom/$id', - path: '/boom/$id', +const HeadersIdRoute = HeadersIdRouteImport.update({ + id: '/headers/$id', + path: '/headers/$id', + getParentRoute: () => rootRouteImport, +} as any) +const MissingIdRoute = MissingIdRouteImport.update({ + id: '/missing/$id', + path: '/missing/$id', + getParentRoute: () => rootRouteImport, +} as any) +const TargetIdRoute = TargetIdRouteImport.update({ + id: '/target/$id', + path: '/target/$id', getParentRoute: () => rootRouteImport, } as any) @@ -117,25 +117,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/target/$id': { - id: '/target/$id' - path: '/target/$id' - fullPath: '/target/$id' - preLoaderRoute: typeof TargetIdRouteImport - parentRoute: typeof rootRouteImport - } - '/missing/$id': { - id: '/missing/$id' - path: '/missing/$id' - fullPath: '/missing/$id' - preLoaderRoute: typeof MissingIdRouteImport - parentRoute: typeof rootRouteImport - } - '/headers/$id': { - id: '/headers/$id' - path: '/headers/$id' - fullPath: '/headers/$id' - preLoaderRoute: typeof HeadersIdRouteImport + '/boom/$id': { + id: '/boom/$id' + path: '/boom/$id' + fullPath: '/boom/$id' + preLoaderRoute: typeof BoomIdRouteImport parentRoute: typeof rootRouteImport } '/from/$id': { @@ -145,11 +131,25 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof FromIdRouteImport parentRoute: typeof rootRouteImport } - '/boom/$id': { - id: '/boom/$id' - path: '/boom/$id' - fullPath: '/boom/$id' - preLoaderRoute: typeof BoomIdRouteImport + '/headers/$id': { + id: '/headers/$id' + path: '/headers/$id' + fullPath: '/headers/$id' + preLoaderRoute: typeof HeadersIdRouteImport + parentRoute: typeof rootRouteImport + } + '/missing/$id': { + id: '/missing/$id' + path: '/missing/$id' + fullPath: '/missing/$id' + preLoaderRoute: typeof MissingIdRouteImport + parentRoute: typeof rootRouteImport + } + '/target/$id': { + id: '/target/$id' + path: '/target/$id' + fullPath: '/target/$id' + preLoaderRoute: typeof TargetIdRouteImport 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 ac2ec01b52..20c1bbe5ac 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,5 +1,14 @@ +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}`, @@ -7,9 +16,3 @@ 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 17ade6bf5b..0bbf4a3dc6 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,11 +1,14 @@ +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/control-flow/vue/tsconfig.json b/benchmarks/ssr/scenarios/control-flow/vue/tsconfig.json index 4fe3ccecb1..08c94853f4 100644 --- a/benchmarks/ssr/scenarios/control-flow/vue/tsconfig.json +++ b/benchmarks/ssr/scenarios/control-flow/vue/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "./src/**/*" diff --git a/benchmarks/ssr/scenarios/control-flow/vue/vite.config.ts b/benchmarks/ssr/scenarios/control-flow/vue/vite.config.ts index 2c978a7a71..1b77968d96 100644 --- a/benchmarks/ssr/scenarios/control-flow/vue/vite.config.ts +++ b/benchmarks/ssr/scenarios/control-flow/vue/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr control-flow (vue)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/global-middleware/bench.ts b/benchmarks/ssr/scenarios/global-middleware/bench.ts index a89d03cabb..d2784aed38 100644 --- a/benchmarks/ssr/scenarios/global-middleware/bench.ts +++ b/benchmarks/ssr/scenarios/global-middleware/bench.ts @@ -7,10 +7,13 @@ 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 } @@ -140,6 +143,7 @@ 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) @@ -154,6 +158,7 @@ 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), @@ -175,7 +180,11 @@ async function assertDocumentResponse(handler: StartRequestHandler) { } } -async function assertServerRouteResponse(handler: StartRequestHandler) { +async function assertServerRouteResponseForCount( + handler: StartRequestHandler, + count: RequestMiddlewareCount, +) { + setRequestMiddlewareCount(count) const id = 'route-sanity' const response = await handler.fetch( new Request(`${origin}/api/ping/${id}`, apiRequestInit), @@ -199,10 +208,8 @@ async function assertServerRouteResponse(handler: StartRequestHandler) { marker?: string requestTotal?: number } - const expectedMarker = makeServerRouteMarker(id, { - requestTrace: 'req.r1.r2.r3', - requestTotal: expectedRequestTotal, - }) + const expectedContext = getExpectedRequestContext(count) + const expectedMarker = makeServerRouteMarker(id, expectedContext) if (body.marker !== expectedMarker) { throw new Error( @@ -210,9 +217,9 @@ async function assertServerRouteResponse(handler: StartRequestHandler) { ) } - if (body.requestTotal !== expectedRequestTotal) { + if (body.requestTotal !== expectedContext.requestTotal) { throw new Error( - `Expected server route requestTotal ${expectedRequestTotal}, received ${body.requestTotal}`, + `Expected server route requestTotal ${expectedContext.requestTotal}, received ${body.requestTotal}`, ) } } @@ -221,6 +228,7 @@ async function assertServerFnResponse( handler: StartRequestHandler, context: GlobalMiddlewareBenchContext, ) { + setRequestMiddlewareCount(3) const response = await handler.fetch( buildPostRequest(context.urls, context.bodies, 0), ) @@ -257,10 +265,14 @@ export async function assertGlobalMiddlewareScenario( ) { await assertDocumentResponse(handler) await assertServerFnResponse(handler, context) - await assertServerRouteResponse(handler) + for (const count of [0, 1, 2, 3] as const) { + await assertServerRouteResponseForCount(handler, count) + } + setRequestMiddlewareCount(3) } export function runGlobalMiddlewareDocumentLoop(handler: StartRequestHandler) { + setRequestMiddlewareCount(3) return runRequestLoop(handler, { seed: benchmarkSeed, concurrency: 16, @@ -273,6 +285,7 @@ export function runGlobalMiddlewareServerFnLoop( handler: StartRequestHandler, context: GlobalMiddlewareBenchContext, ) { + setRequestMiddlewareCount(3) return runRequestLoop(handler, { seed: benchmarkSeed, concurrency: 16, @@ -284,7 +297,9 @@ 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 8288322e70..cb3f9f427c 100644 --- a/benchmarks/ssr/scenarios/global-middleware/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/global-middleware/react/speed.bench.ts @@ -1,10 +1,8 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertGlobalMiddlewareScenario, globalMiddlewareBenchOptions, runGlobalMiddlewareDocumentLoop, - runGlobalMiddlewareServerFnLoop, - runGlobalMiddlewareServerRouteLoop, setupGlobalMiddlewareBench, } from '../bench' import type { StartRequestHandler } from '../bench' @@ -16,27 +14,12 @@ const { default: handler } = (await import( )) as { default: StartRequestHandler } - const context = await setupGlobalMiddlewareBench(handler) await assertGlobalMiddlewareScenario(handler, context) -describe('ssr', () => { - bench( - 'ssr global-mw document (react)', - () => runGlobalMiddlewareDocumentLoop(handler), - globalMiddlewareBenchOptions, - ) - - bench( - 'ssr global-mw server-fn (react)', - () => runGlobalMiddlewareServerFnLoop(handler, context), - globalMiddlewareBenchOptions, - ) - - bench( - 'ssr global-mw server-route (react)', - () => runGlobalMiddlewareServerRouteLoop(handler), - globalMiddlewareBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr global-mw document (react)', async () => + runGlobalMiddlewareDocumentLoop(handler), + ).run(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 new file mode 100644 index 0000000000..48c444de77 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-fn.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerFnLoop, + 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-fn (react)', async () => + runGlobalMiddlewareServerFnLoop(handler, context), + ).run(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 new file mode 100644 index 0000000000..22f53883ee --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-0-middleware.bench.ts @@ -0,0 +1,25 @@ +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 new file mode 100644 index 0000000000..f01b48d66e --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-1-middleware.bench.ts @@ -0,0 +1,25 @@ +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 new file mode 100644 index 0000000000..b01957f806 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-2-middleware.bench.ts @@ -0,0 +1,25 @@ +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 new file mode 100644 index 0000000000..08d97fcaf6 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route.bench.ts @@ -0,0 +1,25 @@ +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 3 middlewares (react)', async () => + runGlobalMiddlewareServerRouteLoop(handler, 3), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/src/start.ts b/benchmarks/ssr/scenarios/global-middleware/react/src/start.ts index 6b59e8035b..8dfb2dd3c4 100644 --- a/benchmarks/ssr/scenarios/global-middleware/react/src/start.ts +++ b/benchmarks/ssr/scenarios/global-middleware/react/src/start.ts @@ -1,4 +1,5 @@ import { createMiddleware, createStart } from '@tanstack/react-start' +import { getRequestMiddlewareCount } from '../../shared' import type { GlobalMiddlewareContext } from '../../shared' function appendTrace( @@ -48,6 +49,13 @@ 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 @@ -75,10 +83,6 @@ const functionMiddlewareB = createMiddleware({ type: 'function' }).server( ) export const startInstance = createStart(() => ({ - requestMiddleware: [ - requestMiddlewareA, - requestMiddlewareB, - requestMiddlewareC, - ], + requestMiddleware: requestMiddlewareSets[getRequestMiddlewareCount()], functionMiddleware: [functionMiddlewareA, functionMiddlewareB], })) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/tsconfig.json b/benchmarks/ssr/scenarios/global-middleware/react/tsconfig.json index 0c0192daaa..de4a3204b9 100644 --- a/benchmarks/ssr/scenarios/global-middleware/react/tsconfig.json +++ b/benchmarks/ssr/scenarios/global-middleware/react/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "../shared.ts", diff --git a/benchmarks/ssr/scenarios/global-middleware/react/vite.config.ts b/benchmarks/ssr/scenarios/global-middleware/react/vite.config.ts index 71c8ff3719..968a8a24e9 100644 --- a/benchmarks/ssr/scenarios/global-middleware/react/vite.config.ts +++ b/benchmarks/ssr/scenarios/global-middleware/react/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr global-middleware (react)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/global-middleware/shared.ts b/benchmarks/ssr/scenarios/global-middleware/shared.ts index f90fa9b233..8fbe788911 100644 --- a/benchmarks/ssr/scenarios/global-middleware/shared.ts +++ b/benchmarks/ssr/scenarios/global-middleware/shared.ts @@ -10,11 +10,41 @@ 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 019735eb40..0e5f504090 100644 --- a/benchmarks/ssr/scenarios/global-middleware/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/global-middleware/solid/speed.bench.ts @@ -1,10 +1,8 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertGlobalMiddlewareScenario, globalMiddlewareBenchOptions, runGlobalMiddlewareDocumentLoop, - runGlobalMiddlewareServerFnLoop, - runGlobalMiddlewareServerRouteLoop, setupGlobalMiddlewareBench, } from '../bench' import type { StartRequestHandler } from '../bench' @@ -16,27 +14,12 @@ const { default: handler } = (await import( )) as { default: StartRequestHandler } - const context = await setupGlobalMiddlewareBench(handler) await assertGlobalMiddlewareScenario(handler, context) -describe('ssr', () => { - bench( - 'ssr global-mw document (solid)', - () => runGlobalMiddlewareDocumentLoop(handler), - globalMiddlewareBenchOptions, - ) - - bench( - 'ssr global-mw server-fn (solid)', - () => runGlobalMiddlewareServerFnLoop(handler, context), - globalMiddlewareBenchOptions, - ) - - bench( - 'ssr global-mw server-route (solid)', - () => runGlobalMiddlewareServerRouteLoop(handler), - globalMiddlewareBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr global-mw document (solid)', async () => + runGlobalMiddlewareDocumentLoop(handler), + ).run(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 new file mode 100644 index 0000000000..915507ef9f --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-fn.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerFnLoop, + 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-fn (solid)', async () => + runGlobalMiddlewareServerFnLoop(handler, context), + ).run(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 new file mode 100644 index 0000000000..a791145935 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-0-middleware.bench.ts @@ -0,0 +1,25 @@ +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 new file mode 100644 index 0000000000..1baab0f344 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-1-middleware.bench.ts @@ -0,0 +1,25 @@ +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 new file mode 100644 index 0000000000..d6fde20764 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-2-middleware.bench.ts @@ -0,0 +1,25 @@ +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 new file mode 100644 index 0000000000..558ebeb9a4 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route.bench.ts @@ -0,0 +1,25 @@ +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 3 middlewares (solid)', async () => + runGlobalMiddlewareServerRouteLoop(handler, 3), + ).run(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 28d816525e..65f7fa5848 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 PageIdRouteImport } from './routes/page.$id' import { Route as ApiFnUrlsRouteImport } from './routes/api.fn-urls' +import { Route as PageIdRouteImport } from './routes/page.$id' 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 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 PageIdRoute = PageIdRouteImport.update({ + id: '/page/$id', + path: '/page/$id', + 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 } - '/page/$id': { - id: '/page/$id' - path: '/page/$id' - fullPath: '/page/$id' - preLoaderRoute: typeof PageIdRouteImport - parentRoute: typeof rootRouteImport - } '/api/fn-urls': { id: '/api/fn-urls' path: '/api/fn-urls' @@ -92,6 +85,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ApiFnUrlsRouteImport parentRoute: typeof rootRouteImport } + '/page/$id': { + id: '/page/$id' + path: '/page/$id' + fullPath: '/page/$id' + preLoaderRoute: typeof PageIdRouteImport + 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 8c4168d574..a6f6214b82 100644 --- a/benchmarks/ssr/scenarios/global-middleware/solid/src/start.ts +++ b/benchmarks/ssr/scenarios/global-middleware/solid/src/start.ts @@ -1,4 +1,5 @@ import { createMiddleware, createStart } from '@tanstack/solid-start' +import { getRequestMiddlewareCount } from '../../shared' import type { GlobalMiddlewareContext } from '../../shared' function appendTrace( @@ -48,6 +49,13 @@ 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 @@ -75,10 +83,6 @@ const functionMiddlewareB = createMiddleware({ type: 'function' }).server( ) export const startInstance = createStart(() => ({ - requestMiddleware: [ - requestMiddlewareA, - requestMiddlewareB, - requestMiddlewareC, - ], + requestMiddleware: requestMiddlewareSets[getRequestMiddlewareCount()], functionMiddleware: [functionMiddlewareA, functionMiddlewareB], })) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/tsconfig.json b/benchmarks/ssr/scenarios/global-middleware/solid/tsconfig.json index 5ad8f505b6..dce3ceae30 100644 --- a/benchmarks/ssr/scenarios/global-middleware/solid/tsconfig.json +++ b/benchmarks/ssr/scenarios/global-middleware/solid/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "../shared.ts", diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/vite.config.ts b/benchmarks/ssr/scenarios/global-middleware/solid/vite.config.ts index e8af6933ed..f3597b25d5 100644 --- a/benchmarks/ssr/scenarios/global-middleware/solid/vite.config.ts +++ b/benchmarks/ssr/scenarios/global-middleware/solid/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr global-middleware (solid)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/speed.bench.ts b/benchmarks/ssr/scenarios/global-middleware/vue/speed.bench.ts index 0b3ed9dd7a..9660f29d07 100644 --- a/benchmarks/ssr/scenarios/global-middleware/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/global-middleware/vue/speed.bench.ts @@ -1,10 +1,8 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertGlobalMiddlewareScenario, globalMiddlewareBenchOptions, runGlobalMiddlewareDocumentLoop, - runGlobalMiddlewareServerFnLoop, - runGlobalMiddlewareServerRouteLoop, setupGlobalMiddlewareBench, } from '../bench' import type { StartRequestHandler } from '../bench' @@ -16,27 +14,12 @@ const { default: handler } = (await import( )) as { default: StartRequestHandler } - const context = await setupGlobalMiddlewareBench(handler) await assertGlobalMiddlewareScenario(handler, context) -describe('ssr', () => { - bench( - 'ssr global-mw document (vue)', - () => runGlobalMiddlewareDocumentLoop(handler), - globalMiddlewareBenchOptions, - ) - - bench( - 'ssr global-mw server-fn (vue)', - () => runGlobalMiddlewareServerFnLoop(handler, context), - globalMiddlewareBenchOptions, - ) - - bench( - 'ssr global-mw server-route (vue)', - () => runGlobalMiddlewareServerRouteLoop(handler), - globalMiddlewareBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr global-mw document (vue)', async () => + runGlobalMiddlewareDocumentLoop(handler), + ).run(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 new file mode 100644 index 0000000000..297e8cee7b --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-fn.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerFnLoop, + 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-fn (vue)', async () => + runGlobalMiddlewareServerFnLoop(handler, context), + ).run(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 new file mode 100644 index 0000000000..d023dd458a --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-0-middleware.bench.ts @@ -0,0 +1,25 @@ +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 new file mode 100644 index 0000000000..5018163631 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-1-middleware.bench.ts @@ -0,0 +1,25 @@ +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 new file mode 100644 index 0000000000..f9abd8eb60 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-2-middleware.bench.ts @@ -0,0 +1,25 @@ +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 new file mode 100644 index 0000000000..adcec3019f --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route.bench.ts @@ -0,0 +1,25 @@ +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 3 middlewares (vue)', async () => + runGlobalMiddlewareServerRouteLoop(handler, 3), + ).run(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 aae3329420..3118848e4d 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 PageIdRouteImport } from './routes/page.$id' import { Route as ApiFnUrlsRouteImport } from './routes/api.fn-urls' +import { Route as PageIdRouteImport } from './routes/page.$id' 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 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 PageIdRoute = PageIdRouteImport.update({ + id: '/page/$id', + path: '/page/$id', + 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 } - '/page/$id': { - id: '/page/$id' - path: '/page/$id' - fullPath: '/page/$id' - preLoaderRoute: typeof PageIdRouteImport - parentRoute: typeof rootRouteImport - } '/api/fn-urls': { id: '/api/fn-urls' path: '/api/fn-urls' @@ -92,6 +85,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ApiFnUrlsRouteImport parentRoute: typeof rootRouteImport } + '/page/$id': { + id: '/page/$id' + path: '/page/$id' + fullPath: '/page/$id' + preLoaderRoute: typeof PageIdRouteImport + 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 2010d0cd2a..6e837ef0a0 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,3 +1,4 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { getGlobalMiddlewareContext, @@ -5,6 +6,14 @@ 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, @@ -14,9 +23,3 @@ 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 dc3f142e27..6e4eb2c5ef 100644 --- a/benchmarks/ssr/scenarios/global-middleware/vue/src/start.ts +++ b/benchmarks/ssr/scenarios/global-middleware/vue/src/start.ts @@ -1,4 +1,5 @@ import { createMiddleware, createStart } from '@tanstack/vue-start' +import { getRequestMiddlewareCount } from '../../shared' import type { GlobalMiddlewareContext } from '../../shared' function appendTrace( @@ -48,6 +49,13 @@ 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 @@ -75,10 +83,6 @@ const functionMiddlewareB = createMiddleware({ type: 'function' }).server( ) export const startInstance = createStart(() => ({ - requestMiddleware: [ - requestMiddlewareA, - requestMiddlewareB, - requestMiddlewareC, - ], + requestMiddleware: requestMiddlewareSets[getRequestMiddlewareCount()], functionMiddleware: [functionMiddlewareA, functionMiddlewareB], })) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/tsconfig.json b/benchmarks/ssr/scenarios/global-middleware/vue/tsconfig.json index 70d62162e6..56800fd29e 100644 --- a/benchmarks/ssr/scenarios/global-middleware/vue/tsconfig.json +++ b/benchmarks/ssr/scenarios/global-middleware/vue/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "../shared.ts", diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/vite.config.ts b/benchmarks/ssr/scenarios/global-middleware/vue/vite.config.ts index 6dd55adab3..8e29c5ee98 100644 --- a/benchmarks/ssr/scenarios/global-middleware/vue/vite.config.ts +++ b/benchmarks/ssr/scenarios/global-middleware/vue/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr global-middleware (vue)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/head/react/speed.bench.ts b/benchmarks/ssr/scenarios/head/react/speed.bench.ts index 19158b32a9..f75008506e 100644 --- a/benchmarks/ssr/scenarios/head/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/head/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertHeadSanity, headBenchOptions, runHeadLoop } from '../shared' import type { StartRequestHandler } from '../shared' @@ -12,6 +12,8 @@ const { default: handler } = (await import( await assertHeadSanity(handler) -describe('ssr', () => { - bench('ssr head (react)', () => runHeadLoop(handler), headBenchOptions) +test('ssr', async ({ bench }) => { + await bench('ssr head (react)', async () => runHeadLoop(handler)).run( + headBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/head/react/vite.config.ts b/benchmarks/ssr/scenarios/head/react/vite.config.ts index 56d69443ac..d24fc850a1 100644 --- a/benchmarks/ssr/scenarios/head/react/vite.config.ts +++ b/benchmarks/ssr/scenarios/head/react/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr head (react)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/head/solid/speed.bench.ts b/benchmarks/ssr/scenarios/head/solid/speed.bench.ts index ad5bf52809..333e2f091b 100644 --- a/benchmarks/ssr/scenarios/head/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/head/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertHeadSanity, headBenchOptions, runHeadLoop } from '../shared' import type { StartRequestHandler } from '../shared' @@ -12,6 +12,8 @@ const { default: handler } = (await import( await assertHeadSanity(handler) -describe('ssr', () => { - bench('ssr head (solid)', () => runHeadLoop(handler), headBenchOptions) +test('ssr', async ({ bench }) => { + await bench('ssr head (solid)', async () => runHeadLoop(handler)).run( + headBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/head/solid/vite.config.ts b/benchmarks/ssr/scenarios/head/solid/vite.config.ts index f7b97a44d1..7a870bbd77 100644 --- a/benchmarks/ssr/scenarios/head/solid/vite.config.ts +++ b/benchmarks/ssr/scenarios/head/solid/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr head (solid)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/head/vue/speed.bench.ts b/benchmarks/ssr/scenarios/head/vue/speed.bench.ts index 5d8243b588..936735a909 100644 --- a/benchmarks/ssr/scenarios/head/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/head/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertHeadSanity, headBenchOptions, runHeadLoop } from '../shared' import type { StartRequestHandler } from '../shared' @@ -12,6 +12,8 @@ const { default: handler } = (await import( await assertHeadSanity(handler) -describe('ssr', () => { - bench('ssr head (vue)', () => runHeadLoop(handler), headBenchOptions) +test('ssr', async ({ bench }) => { + await bench('ssr head (vue)', async () => runHeadLoop(handler)).run( + headBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/head/vue/vite.config.ts b/benchmarks/ssr/scenarios/head/vue/vite.config.ts index e020012560..1434d26069 100644 --- a/benchmarks/ssr/scenarios/head/vue/vite.config.ts +++ b/benchmarks/ssr/scenarios/head/vue/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr head (vue)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/loaders/react/speed.bench.ts b/benchmarks/ssr/scenarios/loaders/react/speed.bench.ts index a5eecfc648..7acd43c635 100644 --- a/benchmarks/ssr/scenarios/loaders/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/loaders/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertLoadersSanity, benchOptions, @@ -16,6 +16,8 @@ const { default: handler } = (await import( await assertLoadersSanity(handler) -describe('ssr', () => { - bench('ssr loaders (react)', () => runLoadersLoop(handler), benchOptions) +test('ssr', async ({ bench }) => { + await bench('ssr loaders (react)', async () => runLoadersLoop(handler)).run( + benchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/loaders/react/vite.config.ts b/benchmarks/ssr/scenarios/loaders/react/vite.config.ts index 5c4dcaa40d..e761426c84 100644 --- a/benchmarks/ssr/scenarios/loaders/react/vite.config.ts +++ b/benchmarks/ssr/scenarios/loaders/react/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr loaders (react)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/loaders/solid/speed.bench.ts b/benchmarks/ssr/scenarios/loaders/solid/speed.bench.ts index 7b3f6247ea..7fc8d88389 100644 --- a/benchmarks/ssr/scenarios/loaders/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/loaders/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertLoadersSanity, benchOptions, @@ -16,6 +16,8 @@ const { default: handler } = (await import( await assertLoadersSanity(handler) -describe('ssr', () => { - bench('ssr loaders (solid)', () => runLoadersLoop(handler), benchOptions) +test('ssr', async ({ bench }) => { + await bench('ssr loaders (solid)', async () => runLoadersLoop(handler)).run( + benchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/loaders/solid/vite.config.ts b/benchmarks/ssr/scenarios/loaders/solid/vite.config.ts index 527ca977c5..64f52159c3 100644 --- a/benchmarks/ssr/scenarios/loaders/solid/vite.config.ts +++ b/benchmarks/ssr/scenarios/loaders/solid/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr loaders (solid)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/loaders/vue/speed.bench.ts b/benchmarks/ssr/scenarios/loaders/vue/speed.bench.ts index fb39e0652c..321350d98c 100644 --- a/benchmarks/ssr/scenarios/loaders/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/loaders/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertLoadersSanity, benchOptions, @@ -16,6 +16,8 @@ const { default: handler } = (await import( await assertLoadersSanity(handler) -describe('ssr', () => { - bench('ssr loaders (vue)', () => runLoadersLoop(handler), benchOptions) +test('ssr', async ({ bench }) => { + await bench('ssr loaders (vue)', async () => runLoadersLoop(handler)).run( + 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 de927a8092..0a52b9c542 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,6 +1,24 @@ +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 @@ -15,18 +33,3 @@ 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 e1a5f52ae2..f3943d58e7 100644 --- a/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.tsx +++ b/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.tsx @@ -1,6 +1,25 @@ +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 @@ -15,19 +34,3 @@ 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 b197a8edf1..63bb36949f 100644 --- a/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.tsx +++ b/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.tsx @@ -1,6 +1,25 @@ +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 @@ -15,19 +34,3 @@ 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/loaders/vue/vite.config.ts b/benchmarks/ssr/scenarios/loaders/vue/vite.config.ts index b7a4d1b48b..92bf3e60f0 100644 --- a/benchmarks/ssr/scenarios/loaders/vue/vite.config.ts +++ b/benchmarks/ssr/scenarios/loaders/vue/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr loaders (vue)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/rewrites/react/speed.bench.ts b/benchmarks/ssr/scenarios/rewrites/react/speed.bench.ts index d7025ce0f9..920186c5db 100644 --- a/benchmarks/ssr/scenarios/rewrites/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/rewrites/react/speed.bench.ts @@ -1,11 +1,10 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertRewriteScenario, rewriteBenchOptions, runRewriteLocalizedLoop, - runRewritePassthroughLoop, - type StartRequestHandler, } from '../shared' +import type { StartRequestHandler } from '../shared' const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href @@ -17,15 +16,8 @@ const { default: handler } = (await import( await assertRewriteScenario(handler) -describe('ssr', () => { - bench( - 'ssr rewrite localized (react)', - () => runRewriteLocalizedLoop(handler), - rewriteBenchOptions, - ) - bench( - 'ssr rewrite passthrough (react)', - () => runRewritePassthroughLoop(handler), - rewriteBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr rewrite localized (react)', async () => + runRewriteLocalizedLoop(handler), + ).run(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 new file mode 100644 index 0000000000..f5d09089a6 --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/react/speed.rewrite-passthrough.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertRewriteScenario, + rewriteBenchOptions, + runRewritePassthroughLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertRewriteScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr rewrite passthrough (react)', async () => + runRewritePassthroughLoop(handler), + ).run(rewriteBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/rewrites/react/tsconfig.json b/benchmarks/ssr/scenarios/rewrites/react/tsconfig.json index 91027bfc88..cf14e1d440 100644 --- a/benchmarks/ssr/scenarios/rewrites/react/tsconfig.json +++ b/benchmarks/ssr/scenarios/rewrites/react/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "./src/**/*" diff --git a/benchmarks/ssr/scenarios/rewrites/react/vite.config.ts b/benchmarks/ssr/scenarios/rewrites/react/vite.config.ts index 5bf098275b..7b20340ec6 100644 --- a/benchmarks/ssr/scenarios/rewrites/react/vite.config.ts +++ b/benchmarks/ssr/scenarios/rewrites/react/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -25,6 +26,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr rewrites (react)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/rewrites/solid/speed.bench.ts b/benchmarks/ssr/scenarios/rewrites/solid/speed.bench.ts index 7aa4bd0b18..488fb2ca52 100644 --- a/benchmarks/ssr/scenarios/rewrites/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/rewrites/solid/speed.bench.ts @@ -1,11 +1,10 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertRewriteScenario, rewriteBenchOptions, runRewriteLocalizedLoop, - runRewritePassthroughLoop, - type StartRequestHandler, } from '../shared' +import type { StartRequestHandler } from '../shared' const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href @@ -17,15 +16,8 @@ const { default: handler } = (await import( await assertRewriteScenario(handler) -describe('ssr', () => { - bench( - 'ssr rewrite localized (solid)', - () => runRewriteLocalizedLoop(handler), - rewriteBenchOptions, - ) - bench( - 'ssr rewrite passthrough (solid)', - () => runRewritePassthroughLoop(handler), - rewriteBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr rewrite localized (solid)', async () => + runRewriteLocalizedLoop(handler), + ).run(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 new file mode 100644 index 0000000000..7b86e2ba11 --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/solid/speed.rewrite-passthrough.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertRewriteScenario, + rewriteBenchOptions, + runRewritePassthroughLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertRewriteScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr rewrite passthrough (solid)', async () => + runRewritePassthroughLoop(handler), + ).run(rewriteBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/rewrites/solid/tsconfig.json b/benchmarks/ssr/scenarios/rewrites/solid/tsconfig.json index b1806caa67..42c3a2160f 100644 --- a/benchmarks/ssr/scenarios/rewrites/solid/tsconfig.json +++ b/benchmarks/ssr/scenarios/rewrites/solid/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "./src/**/*" diff --git a/benchmarks/ssr/scenarios/rewrites/solid/vite.config.ts b/benchmarks/ssr/scenarios/rewrites/solid/vite.config.ts index ae9f925cb7..963fe7132b 100644 --- a/benchmarks/ssr/scenarios/rewrites/solid/vite.config.ts +++ b/benchmarks/ssr/scenarios/rewrites/solid/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -25,6 +26,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr rewrites (solid)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/rewrites/vue/speed.bench.ts b/benchmarks/ssr/scenarios/rewrites/vue/speed.bench.ts index 0bbd896d71..5fd4da9d3e 100644 --- a/benchmarks/ssr/scenarios/rewrites/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/rewrites/vue/speed.bench.ts @@ -1,11 +1,10 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertRewriteScenario, rewriteBenchOptions, runRewriteLocalizedLoop, - runRewritePassthroughLoop, - type StartRequestHandler, } from '../shared' +import type { StartRequestHandler } from '../shared' const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href @@ -17,15 +16,8 @@ const { default: handler } = (await import( await assertRewriteScenario(handler) -describe('ssr', () => { - bench( - 'ssr rewrite localized (vue)', - () => runRewriteLocalizedLoop(handler), - rewriteBenchOptions, - ) - bench( - 'ssr rewrite passthrough (vue)', - () => runRewritePassthroughLoop(handler), - rewriteBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr rewrite localized (vue)', async () => + runRewriteLocalizedLoop(handler), + ).run(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 new file mode 100644 index 0000000000..f3664b5f21 --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/vue/speed.rewrite-passthrough.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertRewriteScenario, + rewriteBenchOptions, + runRewritePassthroughLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertRewriteScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr rewrite passthrough (vue)', async () => + runRewritePassthroughLoop(handler), + ).run(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 3fdb7014f4..3c9de1806e 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,5 +1,41 @@ +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, @@ -8,32 +44,3 @@ 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 acb74aabbd..9702ebedd7 100644 --- a/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.tsx +++ b/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.tsx @@ -1,5 +1,26 @@ +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, @@ -7,21 +28,3 @@ 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/rewrites/vue/tsconfig.json b/benchmarks/ssr/scenarios/rewrites/vue/tsconfig.json index 4fe3ccecb1..08c94853f4 100644 --- a/benchmarks/ssr/scenarios/rewrites/vue/tsconfig.json +++ b/benchmarks/ssr/scenarios/rewrites/vue/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "./src/**/*" diff --git a/benchmarks/ssr/scenarios/rewrites/vue/vite.config.ts b/benchmarks/ssr/scenarios/rewrites/vue/vite.config.ts index f3b69dfe20..22399ec6b2 100644 --- a/benchmarks/ssr/scenarios/rewrites/vue/vite.config.ts +++ b/benchmarks/ssr/scenarios/rewrites/vue/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -25,6 +26,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr rewrites (vue)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/selective-ssr/react/speed.bench.ts b/benchmarks/ssr/scenarios/selective-ssr/react/speed.bench.ts index e0e8a0e3c4..ba6bd4a61d 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 { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertSelectiveSanity, benchOptions, @@ -16,6 +16,8 @@ const { default: handler } = (await import( await assertSelectiveSanity(handler) -describe('ssr', () => { - bench('ssr selective (react)', () => runSelectiveLoop(handler), benchOptions) +test('ssr', async ({ bench }) => { + await bench('ssr selective (react)', async () => + runSelectiveLoop(handler), + ).run(benchOptions) }) diff --git a/benchmarks/ssr/scenarios/selective-ssr/react/vite.config.ts b/benchmarks/ssr/scenarios/selective-ssr/react/vite.config.ts index 03ff77aa7b..70c67cff81 100644 --- a/benchmarks/ssr/scenarios/selective-ssr/react/vite.config.ts +++ b/benchmarks/ssr/scenarios/selective-ssr/react/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr selective-ssr (react)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/selective-ssr/solid/speed.bench.ts b/benchmarks/ssr/scenarios/selective-ssr/solid/speed.bench.ts index 6a2803d45f..76265397ab 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 { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertSelectiveSanity, benchOptions, @@ -16,6 +16,8 @@ const { default: handler } = (await import( await assertSelectiveSanity(handler) -describe('ssr', () => { - bench('ssr selective (solid)', () => runSelectiveLoop(handler), benchOptions) +test('ssr', async ({ bench }) => { + await bench('ssr selective (solid)', async () => + runSelectiveLoop(handler), + ).run(benchOptions) }) diff --git a/benchmarks/ssr/scenarios/selective-ssr/solid/vite.config.ts b/benchmarks/ssr/scenarios/selective-ssr/solid/vite.config.ts index 09b42f00e6..2c0042c1ed 100644 --- a/benchmarks/ssr/scenarios/selective-ssr/solid/vite.config.ts +++ b/benchmarks/ssr/scenarios/selective-ssr/solid/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr selective-ssr (solid)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/selective-ssr/vue/speed.bench.ts b/benchmarks/ssr/scenarios/selective-ssr/vue/speed.bench.ts index f3082a102d..ff60341b27 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 { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertSelectiveSanity, benchOptions, @@ -16,6 +16,8 @@ const { default: handler } = (await import( await assertSelectiveSanity(handler) -describe('ssr', () => { - bench('ssr selective (vue)', () => runSelectiveLoop(handler), benchOptions) +test('ssr', async ({ bench }) => { + await bench('ssr selective (vue)', async () => runSelectiveLoop(handler)).run( + 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 46d7541c2b..8ae7d468f1 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,6 +1,21 @@ +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 }) => { @@ -11,15 +26,3 @@ 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 bc685478cc..c10751489e 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,6 +1,22 @@ +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 }) => { @@ -11,16 +27,3 @@ 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 8ab4c7d54d..c96165c6d6 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,6 +1,22 @@ +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 }) => { @@ -8,16 +24,3 @@ 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/selective-ssr/vue/vite.config.ts b/benchmarks/ssr/scenarios/selective-ssr/vue/vite.config.ts index 76299a67fd..09bb36cb0b 100644 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/vite.config.ts +++ b/benchmarks/ssr/scenarios/selective-ssr/vue/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr selective-ssr (vue)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/serialization/react/speed.bench.ts b/benchmarks/ssr/scenarios/serialization/react/speed.bench.ts index 95c91f4529..8be07d2643 100644 --- a/benchmarks/ssr/scenarios/serialization/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/serialization/react/speed.bench.ts @@ -1,11 +1,10 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertSerializationScenario, - runPlainSerializationLoop, runRichSerializationLoop, serializationBenchOptions, - type StartRequestHandler, } from '../shared-bench' +import type { StartRequestHandler } from '../shared-bench' const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href @@ -17,16 +16,8 @@ const { default: handler } = (await import( await assertSerializationScenario(handler) -describe('ssr', () => { - bench( - 'ssr dehydrate rich types (react)', - () => runRichSerializationLoop(handler), - serializationBenchOptions, - ) - - bench( - 'ssr dehydrate plain control (react)', - () => runPlainSerializationLoop(handler), - serializationBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr dehydrate rich types (react)', async () => + runRichSerializationLoop(handler), + ).run(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 new file mode 100644 index 0000000000..c70fddc6c4 --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/react/speed.dehydrate-plain-control.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertSerializationScenario, + runPlainSerializationLoop, + serializationBenchOptions, +} from '../shared-bench' +import type { StartRequestHandler } from '../shared-bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertSerializationScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr dehydrate plain control (react)', async () => + runPlainSerializationLoop(handler), + ).run(serializationBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/serialization/react/tsconfig.json b/benchmarks/ssr/scenarios/serialization/react/tsconfig.json index 9bfd9bcf62..59499356d6 100644 --- a/benchmarks/ssr/scenarios/serialization/react/tsconfig.json +++ b/benchmarks/ssr/scenarios/serialization/react/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "../shared-bench.ts", diff --git a/benchmarks/ssr/scenarios/serialization/react/vite.config.ts b/benchmarks/ssr/scenarios/serialization/react/vite.config.ts index 6280d87579..64568ccb7e 100644 --- a/benchmarks/ssr/scenarios/serialization/react/vite.config.ts +++ b/benchmarks/ssr/scenarios/serialization/react/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr serialization (react)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/serialization/solid/speed.bench.ts b/benchmarks/ssr/scenarios/serialization/solid/speed.bench.ts index a939cae51f..70bda8c7af 100644 --- a/benchmarks/ssr/scenarios/serialization/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/serialization/solid/speed.bench.ts @@ -1,11 +1,10 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertSerializationScenario, - runPlainSerializationLoop, runRichSerializationLoop, serializationBenchOptions, - type StartRequestHandler, } from '../shared-bench' +import type { StartRequestHandler } from '../shared-bench' const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href @@ -17,16 +16,8 @@ const { default: handler } = (await import( await assertSerializationScenario(handler) -describe('ssr', () => { - bench( - 'ssr dehydrate rich types (solid)', - () => runRichSerializationLoop(handler), - serializationBenchOptions, - ) - - bench( - 'ssr dehydrate plain control (solid)', - () => runPlainSerializationLoop(handler), - serializationBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr dehydrate rich types (solid)', async () => + runRichSerializationLoop(handler), + ).run(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 new file mode 100644 index 0000000000..d7ccb16f6f --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/solid/speed.dehydrate-plain-control.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertSerializationScenario, + runPlainSerializationLoop, + serializationBenchOptions, +} from '../shared-bench' +import type { StartRequestHandler } from '../shared-bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertSerializationScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr dehydrate plain control (solid)', async () => + runPlainSerializationLoop(handler), + ).run(serializationBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/serialization/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/serialization/solid/src/routeTree.gen.ts index 69b63cffe9..b9e25f918e 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 RichIdRouteImport } from './routes/rich.$id' import { Route as PlainIdRouteImport } from './routes/plain.$id' +import { Route as RichIdRouteImport } from './routes/rich.$id' -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) +const RichIdRoute = RichIdRouteImport.update({ + id: '/rich/$id', + path: '/rich/$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 { - '/rich/$id': { - id: '/rich/$id' - path: '/rich/$id' - fullPath: '/rich/$id' - preLoaderRoute: typeof RichIdRouteImport - parentRoute: typeof rootRouteImport - } '/plain/$id': { id: '/plain/$id' path: '/plain/$id' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PlainIdRouteImport parentRoute: typeof rootRouteImport } + '/rich/$id': { + id: '/rich/$id' + path: '/rich/$id' + fullPath: '/rich/$id' + preLoaderRoute: typeof RichIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/ssr/scenarios/serialization/solid/tsconfig.json b/benchmarks/ssr/scenarios/serialization/solid/tsconfig.json index d7feff5f61..3ea91b977f 100644 --- a/benchmarks/ssr/scenarios/serialization/solid/tsconfig.json +++ b/benchmarks/ssr/scenarios/serialization/solid/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "../shared-bench.ts", diff --git a/benchmarks/ssr/scenarios/serialization/solid/vite.config.ts b/benchmarks/ssr/scenarios/serialization/solid/vite.config.ts index 67df3299e1..db81e2ab74 100644 --- a/benchmarks/ssr/scenarios/serialization/solid/vite.config.ts +++ b/benchmarks/ssr/scenarios/serialization/solid/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr serialization (solid)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/serialization/vue/speed.bench.ts b/benchmarks/ssr/scenarios/serialization/vue/speed.bench.ts index ee1e072286..7f733dd601 100644 --- a/benchmarks/ssr/scenarios/serialization/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/serialization/vue/speed.bench.ts @@ -1,11 +1,10 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertSerializationScenario, - runPlainSerializationLoop, runRichSerializationLoop, serializationBenchOptions, - type StartRequestHandler, } from '../shared-bench' +import type { StartRequestHandler } from '../shared-bench' const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href @@ -17,16 +16,8 @@ const { default: handler } = (await import( await assertSerializationScenario(handler) -describe('ssr', () => { - bench( - 'ssr dehydrate rich types (vue)', - () => runRichSerializationLoop(handler), - serializationBenchOptions, - ) - - bench( - 'ssr dehydrate plain control (vue)', - () => runPlainSerializationLoop(handler), - serializationBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr dehydrate rich types (vue)', async () => + runRichSerializationLoop(handler), + ).run(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 new file mode 100644 index 0000000000..8efdeb6c79 --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/vue/speed.dehydrate-plain-control.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertSerializationScenario, + runPlainSerializationLoop, + serializationBenchOptions, +} from '../shared-bench' +import type { StartRequestHandler } from '../shared-bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertSerializationScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr dehydrate plain control (vue)', async () => + runPlainSerializationLoop(handler), + ).run(serializationBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/serialization/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/serialization/vue/src/routeTree.gen.ts index 02268c2c3c..cd7b0b449b 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 RichIdRouteImport } from './routes/rich.$id' import { Route as PlainIdRouteImport } from './routes/plain.$id' +import { Route as RichIdRouteImport } from './routes/rich.$id' -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) +const RichIdRoute = RichIdRouteImport.update({ + id: '/rich/$id', + path: '/rich/$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 { - '/rich/$id': { - id: '/rich/$id' - path: '/rich/$id' - fullPath: '/rich/$id' - preLoaderRoute: typeof RichIdRouteImport - parentRoute: typeof rootRouteImport - } '/plain/$id': { id: '/plain/$id' path: '/plain/$id' @@ -65,6 +58,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PlainIdRouteImport parentRoute: typeof rootRouteImport } + '/rich/$id': { + id: '/rich/$id' + path: '/rich/$id' + fullPath: '/rich/$id' + preLoaderRoute: typeof RichIdRouteImport + 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 d41d123f1f..47fdeb971f 100644 --- a/benchmarks/ssr/scenarios/serialization/vue/src/routes/plain.$id.tsx +++ b/benchmarks/ssr/scenarios/serialization/vue/src/routes/plain.$id.tsx @@ -1,24 +1,27 @@ +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 d50a3f292d..1ee86cefd3 100644 --- a/benchmarks/ssr/scenarios/serialization/vue/src/routes/rich.$id.tsx +++ b/benchmarks/ssr/scenarios/serialization/vue/src/routes/rich.$id.tsx @@ -1,24 +1,27 @@ +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/serialization/vue/tsconfig.json b/benchmarks/ssr/scenarios/serialization/vue/tsconfig.json index 4a7f0ef092..5d8c7b5b62 100644 --- a/benchmarks/ssr/scenarios/serialization/vue/tsconfig.json +++ b/benchmarks/ssr/scenarios/serialization/vue/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "../shared-bench.ts", diff --git a/benchmarks/ssr/scenarios/serialization/vue/vite.config.ts b/benchmarks/ssr/scenarios/serialization/vue/vite.config.ts index 76f99750c3..b89537fa18 100644 --- a/benchmarks/ssr/scenarios/serialization/vue/vite.config.ts +++ b/benchmarks/ssr/scenarios/serialization/vue/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr serialization (vue)', watch: false, environment: 'node', 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 c168f6e61c..fa80cdb690 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-fn-transport/react/speed.bench.ts @@ -1,9 +1,7 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertServerFnTransportScenario, runServerFnMultipartRequestLoop, - runServerFnRawResponseRequestLoop, - runServerFnRawStreamRequestLoop, serverFnTransportBenchOptions, setupServerFnTransportBench, } from '../bench' @@ -14,27 +12,12 @@ const { default: handler } = (await import( )) as { default: StartRequestHandler } - const context = await setupServerFnTransportBench(handler) await assertServerFnTransportScenario(handler, context) -describe('ssr', () => { - bench( - 'ssr server-fn multipart (react)', - () => runServerFnMultipartRequestLoop(handler, context), - serverFnTransportBenchOptions, - ) - - bench( - 'ssr server-fn raw-response (react)', - () => runServerFnRawResponseRequestLoop(handler, context), - serverFnTransportBenchOptions, - ) - - bench( - 'ssr server-fn raw-stream (react)', - () => runServerFnRawStreamRequestLoop(handler, context), - serverFnTransportBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr server-fn multipart (react)', async () => + runServerFnMultipartRequestLoop(handler, context), + ).run(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 new file mode 100644 index 0000000000..fd535ee313 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/react/speed.server-fn-raw-response.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnTransportScenario, + runServerFnRawResponseRequestLoop, + serverFnTransportBenchOptions, + setupServerFnTransportBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +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) +}) 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 new file mode 100644 index 0000000000..8fbce405dd --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/react/speed.server-fn-raw-stream.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnTransportScenario, + runServerFnRawStreamRequestLoop, + serverFnTransportBenchOptions, + setupServerFnTransportBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +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) +}) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/react/tsconfig.json b/benchmarks/ssr/scenarios/server-fn-transport/react/tsconfig.json index 08c349fd49..4f3cc314af 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/tsconfig.json +++ b/benchmarks/ssr/scenarios/server-fn-transport/react/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "../bench.ts", diff --git a/benchmarks/ssr/scenarios/server-fn-transport/react/vite.config.ts b/benchmarks/ssr/scenarios/server-fn-transport/react/vite.config.ts index 4c6293d5d7..c37fde0c4b 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/vite.config.ts +++ b/benchmarks/ssr/scenarios/server-fn-transport/react/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr server-fn-transport (react)', watch: false, environment: 'node', 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 b93d7d79a9..adac07cb22 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.bench.ts @@ -1,9 +1,7 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertServerFnTransportScenario, runServerFnMultipartRequestLoop, - runServerFnRawResponseRequestLoop, - runServerFnRawStreamRequestLoop, serverFnTransportBenchOptions, setupServerFnTransportBench, } from '../bench' @@ -14,27 +12,12 @@ const { default: handler } = (await import( )) as { default: StartRequestHandler } - const context = await setupServerFnTransportBench(handler) await assertServerFnTransportScenario(handler, context) -describe('ssr', () => { - bench( - 'ssr server-fn multipart (solid)', - () => runServerFnMultipartRequestLoop(handler, context), - serverFnTransportBenchOptions, - ) - - bench( - 'ssr server-fn raw-response (solid)', - () => runServerFnRawResponseRequestLoop(handler, context), - serverFnTransportBenchOptions, - ) - - bench( - 'ssr server-fn raw-stream (solid)', - () => runServerFnRawStreamRequestLoop(handler, context), - serverFnTransportBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr server-fn multipart (solid)', async () => + runServerFnMultipartRequestLoop(handler, context), + ).run(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 new file mode 100644 index 0000000000..843a4c97ce --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.server-fn-raw-response.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnTransportScenario, + runServerFnRawResponseRequestLoop, + serverFnTransportBenchOptions, + setupServerFnTransportBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +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) +}) 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 new file mode 100644 index 0000000000..aa24d55e79 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.server-fn-raw-stream.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnTransportScenario, + runServerFnRawStreamRequestLoop, + serverFnTransportBenchOptions, + setupServerFnTransportBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +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) +}) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/solid/tsconfig.json b/benchmarks/ssr/scenarios/server-fn-transport/solid/tsconfig.json index 54a0e49d93..0af78df33d 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/tsconfig.json +++ b/benchmarks/ssr/scenarios/server-fn-transport/solid/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "../bench.ts", diff --git a/benchmarks/ssr/scenarios/server-fn-transport/solid/vite.config.ts b/benchmarks/ssr/scenarios/server-fn-transport/solid/vite.config.ts index b71d03009b..a8af4a6b50 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/vite.config.ts +++ b/benchmarks/ssr/scenarios/server-fn-transport/solid/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr server-fn-transport (solid)', watch: false, environment: 'node', 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 6f803d1665..24305cf1bc 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.bench.ts @@ -1,9 +1,7 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertServerFnTransportScenario, runServerFnMultipartRequestLoop, - runServerFnRawResponseRequestLoop, - runServerFnRawStreamRequestLoop, serverFnTransportBenchOptions, setupServerFnTransportBench, } from '../bench' @@ -14,27 +12,12 @@ const { default: handler } = (await import( )) as { default: StartRequestHandler } - const context = await setupServerFnTransportBench(handler) await assertServerFnTransportScenario(handler, context) -describe('ssr', () => { - bench( - 'ssr server-fn multipart (vue)', - () => runServerFnMultipartRequestLoop(handler, context), - serverFnTransportBenchOptions, - ) - - bench( - 'ssr server-fn raw-response (vue)', - () => runServerFnRawResponseRequestLoop(handler, context), - serverFnTransportBenchOptions, - ) - - bench( - 'ssr server-fn raw-stream (vue)', - () => runServerFnRawStreamRequestLoop(handler, context), - serverFnTransportBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr server-fn multipart (vue)', async () => + runServerFnMultipartRequestLoop(handler, context), + ).run(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 new file mode 100644 index 0000000000..2eeb9a4f6b --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.server-fn-raw-response.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnTransportScenario, + runServerFnRawResponseRequestLoop, + serverFnTransportBenchOptions, + setupServerFnTransportBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +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) +}) 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 new file mode 100644 index 0000000000..a73905004d --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.server-fn-raw-stream.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnTransportScenario, + runServerFnRawStreamRequestLoop, + serverFnTransportBenchOptions, + setupServerFnTransportBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +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) +}) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/vue/tsconfig.json b/benchmarks/ssr/scenarios/server-fn-transport/vue/tsconfig.json index 29efa76d67..5b7742b414 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/tsconfig.json +++ b/benchmarks/ssr/scenarios/server-fn-transport/vue/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "../bench.ts", diff --git a/benchmarks/ssr/scenarios/server-fn-transport/vue/vite.config.ts b/benchmarks/ssr/scenarios/server-fn-transport/vue/vite.config.ts index 5d74904e14..0f3e2ce84d 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/vite.config.ts +++ b/benchmarks/ssr/scenarios/server-fn-transport/vue/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr server-fn-transport (vue)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/server-fns/react/speed.bench.ts b/benchmarks/ssr/scenarios/server-fns/react/speed.bench.ts index 46dca5adc7..c876772ad1 100644 --- a/benchmarks/ssr/scenarios/server-fns/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-fns/react/speed.bench.ts @@ -1,12 +1,7 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertServerFnScenario, - runServerFnDocumentSsrRequestLoop, runServerFnGetRequestLoop, - runServerFnNotFoundRequestLoop, - runServerFnPostRequestLoop, - runServerFnRedirectRequestLoop, - runServerFnSendContextRequestLoop, serverFnBenchOptions, setupServerFnBench, } from '../bench' @@ -17,45 +12,12 @@ const { default: handler } = (await import( )) as { default: StartRequestHandler } - const context = await setupServerFnBench(handler) await assertServerFnScenario(handler, context) -describe('ssr', () => { - bench( - 'ssr server-fn GET (react)', - () => runServerFnGetRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn POST (react)', - () => runServerFnPostRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn redirect (react)', - () => runServerFnRedirectRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn not-found (react)', - () => runServerFnNotFoundRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn send-context (react)', - () => runServerFnSendContextRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn during document ssr (react)', - () => runServerFnDocumentSsrRequestLoop(handler), - serverFnBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr server-fn GET (react)', async () => + runServerFnGetRequestLoop(handler, context), + ).run(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 new file mode 100644 index 0000000000..6a0cb55f78 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-during-document-ssr.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnDocumentSsrRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +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) +}) 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 new file mode 100644 index 0000000000..96f1160078 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-not-found.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnNotFoundRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +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) +}) 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 new file mode 100644 index 0000000000..e85d5debd3 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-post.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnPostRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +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) +}) 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 new file mode 100644 index 0000000000..5dae598549 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-redirect.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnRedirectRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +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) +}) 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 new file mode 100644 index 0000000000..40d6961206 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-send-context.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnSendContextRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +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) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/react/tsconfig.json b/benchmarks/ssr/scenarios/server-fns/react/tsconfig.json index 91027bfc88..cf14e1d440 100644 --- a/benchmarks/ssr/scenarios/server-fns/react/tsconfig.json +++ b/benchmarks/ssr/scenarios/server-fns/react/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "./src/**/*" diff --git a/benchmarks/ssr/scenarios/server-fns/react/vite.config.ts b/benchmarks/ssr/scenarios/server-fns/react/vite.config.ts index 4f608f0444..cd56edda95 100644 --- a/benchmarks/ssr/scenarios/server-fns/react/vite.config.ts +++ b/benchmarks/ssr/scenarios/server-fns/react/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr server-fns (react)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/server-fns/solid/speed.bench.ts b/benchmarks/ssr/scenarios/server-fns/solid/speed.bench.ts index a116ea9102..f6bbdc9e73 100644 --- a/benchmarks/ssr/scenarios/server-fns/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-fns/solid/speed.bench.ts @@ -1,12 +1,7 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertServerFnScenario, - runServerFnDocumentSsrRequestLoop, runServerFnGetRequestLoop, - runServerFnNotFoundRequestLoop, - runServerFnPostRequestLoop, - runServerFnRedirectRequestLoop, - runServerFnSendContextRequestLoop, serverFnBenchOptions, setupServerFnBench, } from '../bench' @@ -17,45 +12,12 @@ const { default: handler } = (await import( )) as { default: StartRequestHandler } - const context = await setupServerFnBench(handler) await assertServerFnScenario(handler, context) -describe('ssr', () => { - bench( - 'ssr server-fn GET (solid)', - () => runServerFnGetRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn POST (solid)', - () => runServerFnPostRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn redirect (solid)', - () => runServerFnRedirectRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn not-found (solid)', - () => runServerFnNotFoundRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn send-context (solid)', - () => runServerFnSendContextRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn during document ssr (solid)', - () => runServerFnDocumentSsrRequestLoop(handler), - serverFnBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr server-fn GET (solid)', async () => + runServerFnGetRequestLoop(handler, context), + ).run(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 new file mode 100644 index 0000000000..933f61b59c --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-during-document-ssr.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnDocumentSsrRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +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) +}) 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 new file mode 100644 index 0000000000..513b69f4ba --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-not-found.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnNotFoundRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +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) +}) 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 new file mode 100644 index 0000000000..e2ce8ad9ee --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-post.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnPostRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +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) +}) 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 new file mode 100644 index 0000000000..14353f1290 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-redirect.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnRedirectRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +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) +}) 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 new file mode 100644 index 0000000000..76d3a554bd --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-send-context.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnSendContextRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +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) +}) 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 3db5e487b3..3d0bd34eaa 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 SsrCallIdRouteImport } from './routes/ssr-call.$id' import { Route as ApiFnUrlsRouteImport } from './routes/api.fn-urls' +import { Route as SsrCallIdRouteImport } from './routes/ssr-call.$id' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', 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) +const SsrCallIdRoute = SsrCallIdRouteImport.update({ + id: '/ssr-call/$id', + path: '/ssr-call/$id', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -68,13 +68,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/ssr-call/$id': { - id: '/ssr-call/$id' - path: '/ssr-call/$id' - fullPath: '/ssr-call/$id' - preLoaderRoute: typeof SsrCallIdRouteImport - parentRoute: typeof rootRouteImport - } '/api/fn-urls': { id: '/api/fn-urls' path: '/api/fn-urls' @@ -82,6 +75,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ApiFnUrlsRouteImport parentRoute: typeof rootRouteImport } + '/ssr-call/$id': { + id: '/ssr-call/$id' + path: '/ssr-call/$id' + fullPath: '/ssr-call/$id' + preLoaderRoute: typeof SsrCallIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/ssr/scenarios/server-fns/solid/tsconfig.json b/benchmarks/ssr/scenarios/server-fns/solid/tsconfig.json index b1806caa67..42c3a2160f 100644 --- a/benchmarks/ssr/scenarios/server-fns/solid/tsconfig.json +++ b/benchmarks/ssr/scenarios/server-fns/solid/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "./src/**/*" diff --git a/benchmarks/ssr/scenarios/server-fns/solid/vite.config.ts b/benchmarks/ssr/scenarios/server-fns/solid/vite.config.ts index ef8292a042..2f2f78b75c 100644 --- a/benchmarks/ssr/scenarios/server-fns/solid/vite.config.ts +++ b/benchmarks/ssr/scenarios/server-fns/solid/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr server-fns (solid)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/server-fns/vue/speed.bench.ts b/benchmarks/ssr/scenarios/server-fns/vue/speed.bench.ts index 02cb03efd1..3f67c1a500 100644 --- a/benchmarks/ssr/scenarios/server-fns/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-fns/vue/speed.bench.ts @@ -1,12 +1,7 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertServerFnScenario, - runServerFnDocumentSsrRequestLoop, runServerFnGetRequestLoop, - runServerFnNotFoundRequestLoop, - runServerFnPostRequestLoop, - runServerFnRedirectRequestLoop, - runServerFnSendContextRequestLoop, serverFnBenchOptions, setupServerFnBench, } from '../bench' @@ -17,45 +12,12 @@ const { default: handler } = (await import( )) as { default: StartRequestHandler } - const context = await setupServerFnBench(handler) await assertServerFnScenario(handler, context) -describe('ssr', () => { - bench( - 'ssr server-fn GET (vue)', - () => runServerFnGetRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn POST (vue)', - () => runServerFnPostRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn redirect (vue)', - () => runServerFnRedirectRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn not-found (vue)', - () => runServerFnNotFoundRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn send-context (vue)', - () => runServerFnSendContextRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn during document ssr (vue)', - () => runServerFnDocumentSsrRequestLoop(handler), - serverFnBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr server-fn GET (vue)', async () => + runServerFnGetRequestLoop(handler, context), + ).run(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 new file mode 100644 index 0000000000..56c9addca5 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-during-document-ssr.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnDocumentSsrRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +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) +}) 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 new file mode 100644 index 0000000000..e9a6e31617 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-not-found.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnNotFoundRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +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) +}) 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 new file mode 100644 index 0000000000..df9312ccd1 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-post.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnPostRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +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) +}) 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 new file mode 100644 index 0000000000..67c4611644 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-redirect.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnRedirectRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +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) +}) 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 new file mode 100644 index 0000000000..6f51ef4bab --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-send-context.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnSendContextRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +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) +}) 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 fa27fb1a5d..0e24cd9c15 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 SsrCallIdRouteImport } from './routes/ssr-call.$id' import { Route as ApiFnUrlsRouteImport } from './routes/api.fn-urls' +import { Route as SsrCallIdRouteImport } from './routes/ssr-call.$id' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', 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) +const SsrCallIdRoute = SsrCallIdRouteImport.update({ + id: '/ssr-call/$id', + path: '/ssr-call/$id', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -68,13 +68,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/ssr-call/$id': { - id: '/ssr-call/$id' - path: '/ssr-call/$id' - fullPath: '/ssr-call/$id' - preLoaderRoute: typeof SsrCallIdRouteImport - parentRoute: typeof rootRouteImport - } '/api/fn-urls': { id: '/api/fn-urls' path: '/api/fn-urls' @@ -82,6 +75,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ApiFnUrlsRouteImport parentRoute: typeof rootRouteImport } + '/ssr-call/$id': { + id: '/ssr-call/$id' + path: '/ssr-call/$id' + fullPath: '/ssr-call/$id' + preLoaderRoute: typeof SsrCallIdRouteImport + 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 8abe77c2af..45fad23dc0 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,6 +1,17 @@ +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({ @@ -15,9 +26,3 @@ 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-fns/vue/tsconfig.json b/benchmarks/ssr/scenarios/server-fns/vue/tsconfig.json index 4fe3ccecb1..08c94853f4 100644 --- a/benchmarks/ssr/scenarios/server-fns/vue/tsconfig.json +++ b/benchmarks/ssr/scenarios/server-fns/vue/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "./src/**/*" diff --git a/benchmarks/ssr/scenarios/server-fns/vue/vite.config.ts b/benchmarks/ssr/scenarios/server-fns/vue/vite.config.ts index 2a7783ed7a..5f3e3ca4b5 100644 --- a/benchmarks/ssr/scenarios/server-fns/vue/vite.config.ts +++ b/benchmarks/ssr/scenarios/server-fns/vue/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr server-fns (vue)', watch: false, environment: 'node', 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 8e96bc8e04..6331216522 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 { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertServerRouteMiddlewareResponse, runServerRouteMiddlewareLoop, @@ -16,10 +16,8 @@ const { default: handler } = (await import( await assertServerRouteMiddlewareResponse(handler) -describe('ssr', () => { - bench( - 'ssr server-route middleware (react)', - () => runServerRouteMiddlewareLoop(handler), - serverRouteMiddlewareBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr server-route middleware (react)', async () => + runServerRouteMiddlewareLoop(handler), + ).run(serverRouteMiddlewareBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/react/vite.config.ts b/benchmarks/ssr/scenarios/server-routes-middleware/react/vite.config.ts index 9c41f6d542..f6998c2ac8 100644 --- a/benchmarks/ssr/scenarios/server-routes-middleware/react/vite.config.ts +++ b/benchmarks/ssr/scenarios/server-routes-middleware/react/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr server-routes-middleware (react)', watch: false, environment: 'node', 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 7e6fac4bbe..77d58e7b19 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 { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertServerRouteMiddlewareResponse, runServerRouteMiddlewareLoop, @@ -16,10 +16,8 @@ const { default: handler } = (await import( await assertServerRouteMiddlewareResponse(handler) -describe('ssr', () => { - bench( - 'ssr server-route middleware (solid)', - () => runServerRouteMiddlewareLoop(handler), - serverRouteMiddlewareBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr server-route middleware (solid)', async () => + runServerRouteMiddlewareLoop(handler), + ).run(serverRouteMiddlewareBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/solid/vite.config.ts b/benchmarks/ssr/scenarios/server-routes-middleware/solid/vite.config.ts index 89116c111e..800cf9db9f 100644 --- a/benchmarks/ssr/scenarios/server-routes-middleware/solid/vite.config.ts +++ b/benchmarks/ssr/scenarios/server-routes-middleware/solid/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr server-routes-middleware (solid)', watch: false, environment: 'node', 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 e67ca0a420..3d03b9c1fa 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 { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertServerRouteMiddlewareResponse, runServerRouteMiddlewareLoop, @@ -16,10 +16,8 @@ const { default: handler } = (await import( await assertServerRouteMiddlewareResponse(handler) -describe('ssr', () => { - bench( - 'ssr server-route middleware (vue)', - () => runServerRouteMiddlewareLoop(handler), - serverRouteMiddlewareBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr server-route middleware (vue)', async () => + runServerRouteMiddlewareLoop(handler), + ).run(serverRouteMiddlewareBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/vue/vite.config.ts b/benchmarks/ssr/scenarios/server-routes-middleware/vue/vite.config.ts index a1b26182f7..909b7cca50 100644 --- a/benchmarks/ssr/scenarios/server-routes-middleware/vue/vite.config.ts +++ b/benchmarks/ssr/scenarios/server-routes-middleware/vue/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr server-routes-middleware (vue)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/server-routes/react/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes/react/speed.bench.ts index 1bdb7946b2..631314148a 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 { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertServerRouteResponse, runServerRouteLoop, @@ -16,10 +16,8 @@ const { default: handler } = (await import( await assertServerRouteResponse(handler) -describe('ssr', () => { - bench( - 'ssr server-route (react)', - () => runServerRouteLoop(handler), - serverRouteBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr server-route (react)', async () => + runServerRouteLoop(handler), + ).run(serverRouteBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/server-routes/react/vite.config.ts b/benchmarks/ssr/scenarios/server-routes/react/vite.config.ts index fdc16bf50c..2c723c749c 100644 --- a/benchmarks/ssr/scenarios/server-routes/react/vite.config.ts +++ b/benchmarks/ssr/scenarios/server-routes/react/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr server-routes (react)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/server-routes/solid/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes/solid/speed.bench.ts index ce3e1f8a21..4788d31854 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 { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertServerRouteResponse, runServerRouteLoop, @@ -16,10 +16,8 @@ const { default: handler } = (await import( await assertServerRouteResponse(handler) -describe('ssr', () => { - bench( - 'ssr server-route (solid)', - () => runServerRouteLoop(handler), - serverRouteBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr server-route (solid)', async () => + runServerRouteLoop(handler), + ).run(serverRouteBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/server-routes/solid/vite.config.ts b/benchmarks/ssr/scenarios/server-routes/solid/vite.config.ts index 24e502a63a..994e04f1d6 100644 --- a/benchmarks/ssr/scenarios/server-routes/solid/vite.config.ts +++ b/benchmarks/ssr/scenarios/server-routes/solid/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr server-routes (solid)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/server-routes/vue/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes/vue/speed.bench.ts index f2b9e27acb..09c0bbe90b 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 { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertServerRouteResponse, runServerRouteLoop, @@ -16,10 +16,8 @@ const { default: handler } = (await import( await assertServerRouteResponse(handler) -describe('ssr', () => { - bench( - 'ssr server-route (vue)', - () => runServerRouteLoop(handler), - serverRouteBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr server-route (vue)', async () => + runServerRouteLoop(handler), + ).run(serverRouteBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/server-routes/vue/vite.config.ts b/benchmarks/ssr/scenarios/server-routes/vue/vite.config.ts index c56f3c872a..0457453532 100644 --- a/benchmarks/ssr/scenarios/server-routes/vue/vite.config.ts +++ b/benchmarks/ssr/scenarios/server-routes/vue/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr server-routes (vue)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/streaming/react/speed.bench.ts b/benchmarks/ssr/scenarios/streaming/react/speed.bench.ts index c1dbf38ae5..eb4c9dc1d6 100644 --- a/benchmarks/ssr/scenarios/streaming/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/streaming/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertStreamingSanity, benchOptions, @@ -16,10 +16,8 @@ const { default: handler } = (await import( await assertStreamingSanity(handler) -describe('ssr', () => { - bench( - 'ssr streaming deferred (react)', - () => runStreamingLoop(handler), - benchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr streaming deferred (react)', async () => + runStreamingLoop(handler), + ).run(benchOptions) }) diff --git a/benchmarks/ssr/scenarios/streaming/react/vite.config.ts b/benchmarks/ssr/scenarios/streaming/react/vite.config.ts index bdbfebdfce..e1cc5f534b 100644 --- a/benchmarks/ssr/scenarios/streaming/react/vite.config.ts +++ b/benchmarks/ssr/scenarios/streaming/react/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr streaming (react)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/streaming/shared-data.ts b/benchmarks/ssr/scenarios/streaming/shared-data.ts index 550a351794..695ed107c6 100644 --- a/benchmarks/ssr/scenarios/streaming/shared-data.ts +++ b/benchmarks/ssr/scenarios/streaming/shared-data.ts @@ -15,7 +15,11 @@ export const streamChunkCount = 96 export const streamChunkLength = 192 export function sleep0() { - return new Promise((resolve) => setTimeout(resolve, 1)) + // Give SSR a render turn before resolving deferred values. Counted turns + // avoid grouping concurrent requests by wall-clock timer expiration. + return new Promise((resolve) => { + setImmediate(() => setImmediate(resolve)) + }) } function hashId(id: string) { diff --git a/benchmarks/ssr/scenarios/streaming/solid/speed.bench.ts b/benchmarks/ssr/scenarios/streaming/solid/speed.bench.ts index 0828715220..19d5817d32 100644 --- a/benchmarks/ssr/scenarios/streaming/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/streaming/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertStreamingSanity, benchOptions, @@ -16,10 +16,8 @@ const { default: handler } = (await import( await assertStreamingSanity(handler) -describe('ssr', () => { - bench( - 'ssr streaming deferred (solid)', - () => runStreamingLoop(handler), - benchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr streaming deferred (solid)', async () => + runStreamingLoop(handler), + ).run(benchOptions) }) diff --git a/benchmarks/ssr/scenarios/streaming/solid/vite.config.ts b/benchmarks/ssr/scenarios/streaming/solid/vite.config.ts index 5b736899c0..353c21f552 100644 --- a/benchmarks/ssr/scenarios/streaming/solid/vite.config.ts +++ b/benchmarks/ssr/scenarios/streaming/solid/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr streaming (solid)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/streaming/vue/speed.bench.ts b/benchmarks/ssr/scenarios/streaming/vue/speed.bench.ts index a484f95d6a..42473fc694 100644 --- a/benchmarks/ssr/scenarios/streaming/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/streaming/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertStreamingSanity, benchOptions, @@ -16,10 +16,8 @@ const { default: handler } = (await import( await assertStreamingSanity(handler) -describe('ssr', () => { - bench( - 'ssr streaming deferred (vue)', - () => runStreamingLoop(handler), - benchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr streaming deferred (vue)', async () => + runStreamingLoop(handler), + ).run(benchOptions) }) diff --git a/benchmarks/ssr/scenarios/streaming/vue/vite.config.ts b/benchmarks/ssr/scenarios/streaming/vue/vite.config.ts index 8c65f71268..a09a30076f 100644 --- a/benchmarks/ssr/scenarios/streaming/vue/vite.config.ts +++ b/benchmarks/ssr/scenarios/streaming/vue/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr streaming (vue)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/solid/speed.bench.ts b/benchmarks/ssr/solid/speed.bench.ts index 0c4317415d..2f72977612 100644 --- a/benchmarks/ssr/solid/speed.bench.ts +++ b/benchmarks/ssr/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { runSsrRequestLoop } from '../bench-utils' import type { StartRequestHandler } from '../bench-utils' @@ -11,14 +11,12 @@ const { default: handler } = (await import( default: StartRequestHandler } -describe('ssr', () => { - bench( - 'ssr request loop (solid)', - () => runSsrRequestLoop(handler, { seed: benchmarkSeed }), - { - warmupIterations: 100, - time: 10_000, - throws: true, - }, - ) +test('ssr', async ({ bench }) => { + await bench('ssr request loop (solid)', async () => + runSsrRequestLoop(handler, { seed: benchmarkSeed }), + ).run({ + warmupIterations: 100, + time: 10_000, + throws: true, + }) }) diff --git a/benchmarks/ssr/solid/vite.config.ts b/benchmarks/ssr/solid/vite.config.ts index dc9cbf90e3..dfd82d9192 100644 --- a/benchmarks/ssr/solid/vite.config.ts +++ b/benchmarks/ssr/solid/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr (solid)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/tsconfig.json b/benchmarks/ssr/tsconfig.json index 6702925d13..7279177023 100644 --- a/benchmarks/ssr/tsconfig.json +++ b/benchmarks/ssr/tsconfig.json @@ -3,5 +3,10 @@ "compilerOptions": { "types": ["node", "vite/client", "vitest/globals"] }, - "include": ["bench-utils.ts", "bench-utils.test.ts", "vitest.unit.config.ts"] + "include": [ + "bench-utils.ts", + "bench-utils.test.ts", + "scenarios/streaming/shared-data.ts", + "vitest.unit.config.ts" + ] } diff --git a/benchmarks/ssr/vue/speed.bench.ts b/benchmarks/ssr/vue/speed.bench.ts index 849f042e3c..57b59e0504 100644 --- a/benchmarks/ssr/vue/speed.bench.ts +++ b/benchmarks/ssr/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { runSsrRequestLoop } from '../bench-utils' import type { StartRequestHandler } from '../bench-utils' @@ -11,14 +11,12 @@ const { default: handler } = (await import( default: StartRequestHandler } -describe('ssr', () => { - bench( - 'ssr request loop (vue)', - () => runSsrRequestLoop(handler, { seed: benchmarkSeed }), - { - warmupIterations: 100, - time: 10_000, - throws: true, - }, - ) +test('ssr', async ({ bench }) => { + await bench('ssr request loop (vue)', async () => + runSsrRequestLoop(handler, { seed: benchmarkSeed }), + ).run({ + warmupIterations: 100, + time: 10_000, + throws: true, + }) }) diff --git a/benchmarks/ssr/vue/vite.config.ts b/benchmarks/ssr/vue/vite.config.ts index 312f43a7ae..b2b9fc8a09 100644 --- a/benchmarks/ssr/vue/vite.config.ts +++ b/benchmarks/ssr/vue/vite.config.ts @@ -3,6 +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 { cpuSimulationExecArgv } from '../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr (vue)', watch: false, environment: 'node', diff --git a/benchmarks/tsconfig.json b/benchmarks/tsconfig.json new file mode 100644 index 0000000000..5e9ff9a8e1 --- /dev/null +++ b/benchmarks/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "types": ["node"] + }, + "include": ["cpu-simulation.ts"] +} diff --git a/docs/AGENTS.md b/docs/AGENTS.md new file mode 100644 index 0000000000..ab2d4117e2 --- /dev/null +++ b/docs/AGENTS.md @@ -0,0 +1,4 @@ +# 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 ad3e07fad7..7c94d484d1 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. +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 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 ac35cdc845..2adfc6e5c6 100644 --- a/docs/router/api/router/RouteOptionsType.md +++ b/docs/router/api/router/RouteOptionsType.md @@ -280,22 +280,26 @@ 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 -- Type: `(error: Error, errorInfo: ErrorInfo) => void` +- Type: `(error: unknown) => void` in React and Vue; `(error: Error) => void` in Solid - Optional - Defaults to `routerOptions.defaultOnCatch` - A function that will be called when errors are caught when the route encounters an error. diff --git a/docs/router/api/router/RouterEventsType.md b/docs/router/api/router/RouterEventsType.md index c79bb47f81..c27887fba1 100644 --- a/docs/router/api/router/RouterEventsType.md +++ b/docs/router/api/router/RouterEventsType.md @@ -47,9 +47,6 @@ type RouterEvents = { hrefChanged: boolean hashChanged: boolean } - onInjectedHtml: { - type: 'onInjectedHtml' - } onRendered: { type: 'onRendered' fromLocation?: ParsedLocation @@ -67,7 +64,7 @@ Once an event is emitted, the following properties will be present on the event ### `type` property -- Type: `onBeforeNavigate | onBeforeLoad | onLoad | onBeforeRouteMount | onResolved | onRendered | onInjectedHtml` +- Type: `onBeforeNavigate | onBeforeLoad | onLoad | onBeforeRouteMount | onResolved | onRendered` - 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 709d08c621..31f410b208 100644 --- a/docs/router/api/router/RouterOptionsType.md +++ b/docs/router/api/router/RouterOptionsType.md @@ -141,7 +141,7 @@ The `RouterOptions` type accepts an object with the following properties and met ### `defaultOnCatch` property -- Type: `(error: Error, errorInfo: ErrorInfo) => void` +- Type: `(error: unknown, errorInfo: ErrorInfo) => void` - Optional - The default `onCatch` handler for errors caught by the Router ErrorBoundary @@ -223,6 +223,13 @@ 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` @@ -368,9 +375,10 @@ const router = createRouter({ ### `pathParamsAllowedCharacters` property -- Type: `Array<';' | ':' | '@' | '&' | '=' | '+' | '$' | ','>` +- Type: `ReadonlyArray<';' | ':' | '@' | '&' | '=' | '+' | '$' | ','>` - 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 cf8fdebeae..3fde90e32e 100644 --- a/docs/router/api/router/RouterType.md +++ b/docs/router/api/router/RouterType.md @@ -11,8 +11,9 @@ An instance of the `Router` has the following properties and methods: ### `.update` method -- Type: `(newOptions: RouterOptions) => void` +- Type: `(newOptions: Omit) => 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/catchBoundaryComponent.md b/docs/router/api/router/catchBoundaryComponent.md index deef0ffa22..aa2f6eb7ce 100644 --- a/docs/router/api/router/catchBoundaryComponent.md +++ b/docs/router/api/router/catchBoundaryComponent.md @@ -29,7 +29,7 @@ The `CatchBoundary` component accepts the following props: ### `props.onCatch` prop -- Type: `(error: any) => void` +- Type: `(error: unknown, errorInfo: ErrorInfo) => void` in React; `(error: unknown) => void` in Vue; `(error: Error) => void` in Solid - Optional - A callback that will be called with the error that was thrown by the component's children. diff --git a/docs/router/api/router/errorComponentComponent.md b/docs/router/api/router/errorComponentComponent.md index 04399f124d..07d7187580 100644 --- a/docs/router/api/router/errorComponentComponent.md +++ b/docs/router/api/router/errorComponentComponent.md @@ -3,7 +3,7 @@ id: errorComponentComponent title: ErrorComponent component --- -The `ErrorComponent` component is a component that renders an error message and optionally the error's message. +The `ErrorComponent` component renders an error notice and optional details about the thrown value. ## ErrorComponent props @@ -11,8 +11,8 @@ The `ErrorComponent` component accepts the following props: ### `props.error` prop -- Type: `TError` (defaults to `Error`) -- The error that was thrown by the component's children +- Type: `unknown` in React and Vue; `Error` in Solid +- The caught error. Solid normalizes non-`Error` values, including SSR loader errors, into an `Error` with the original value in `cause`. ### `props.info` prop @@ -27,6 +27,6 @@ The `ErrorComponent` component accepts the following props: ## ErrorComponent returns -- Returns a formatted error message with the error's message if it exists. +- Displays an error notice, with details when the thrown value has a nonempty `message`. Values without a message still display the error notice. - The error message can be toggled by clicking the "Show Error" button. - By default, the error message will be shown in development. diff --git a/docs/router/api/router/linkComponent.md b/docs/router/api/router/linkComponent.md index a8227913b5..478271a208 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, update the [pathParamsAllowedCharacters](../router/RouterOptionsType#pathparamsallowedcharacters-property) config on the router +To opt out, set [pathParamsAllowedCharacters](../router/RouterOptionsType#pathparamsallowedcharacters-property) when creating the router. This setting cannot be changed on an existing router instance. ```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 c22aa7c52d..453fd64acc 100644 --- a/docs/router/eslint/create-route-property-order.md +++ b/docs/router/eslint/create-route-property-order.md @@ -37,7 +37,10 @@ import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/path')({ loader: async ({ context }) => { - await context.queryClient.ensureQueryData(getQueryOptions(context.hello)) + await context.queryClient.query({ + ...getQueryOptions(context.hello), + staleTime: 'static', + }) }, beforeLoad: () => ({ hello: 'world' }), }) @@ -55,7 +58,10 @@ import { createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/path')({ loader: async ({ context }) => { - await context.queryClient.ensureQueryData(getQueryOptions(context.hello)) + await context.queryClient.query({ + ...getQueryOptions(context.hello), + staleTime: 'static', + }) }, beforeLoad: () => ({ hello: 'world' }), }) @@ -80,7 +86,10 @@ import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/path')({ beforeLoad: () => ({ hello: 'world' }), loader: async ({ context }) => { - await context.queryClient.ensureQueryData(getQueryOptions(context.hello)) + await context.queryClient.query({ + ...getQueryOptions(context.hello), + staleTime: 'static', + }) }, }) ``` @@ -98,7 +107,10 @@ import { createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/path')({ beforeLoad: () => ({ hello: 'world' }), loader: async ({ context }) => { - await context.queryClient.ensureQueryData(getQueryOptions(context.hello)) + await context.queryClient.query({ + ...getQueryOptions(context.hello), + staleTime: 'static', + }) }, }) ``` diff --git a/docs/router/guide/automatic-code-splitting.md b/docs/router/guide/automatic-code-splitting.md index be599845bc..859a19ff09 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. +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. ```ts // vite.config.ts diff --git a/docs/router/guide/data-loading.md b/docs/router/guide/data-loading.md index 26a82eaad6..6b9fd42777 100644 --- a/docs/router/guide/data-loading.md +++ b/docs/router/guide/data-loading.md @@ -570,7 +570,7 @@ The `routeOptions.onCatch` option is a function that is called whenever an error ```tsx // src/routes/posts.tsx export const Route = createFileRoute('/posts')({ - onCatch: ({ error, errorInfo }) => { + onCatch: (error) => { // Log the error console.error(error) }, @@ -581,16 +581,20 @@ export const Route = createFileRoute('/posts')({ The `routeOptions.errorComponent` option is a component that is rendered when an error occurs during the route loading or rendering lifecycle. It is rendered with the following props: -- `error` - The error that occurred +- `error` - The caught value (`unknown` in React and Vue; `Error` in Solid) - `reset` - A function to reset the internal `CatchBoundary` +`ErrorComponentProps` defaults its `error` property to `unknown` in React and Vue, where you must narrow the value before accessing properties such as `message`. In Solid, it defaults to `Error`. `ErrorComponentProps` can describe an error after you have narrowed it; it does not restrict what a route can throw. This applies to boundary components and `onCatch` callbacks, including `defaultOnCatch`; it does not change the `onError` callback. + +React and Vue boundaries pass through the caught value, including falsy values. Solid wraps non-`Error` throws in an `Error` whose `cause` contains the original value. This also applies to Solid error components rendered during SSR: existing `Error` instances are preserved, strings become the error message, and other values use the message `Unknown error`. Router state and loader `onError` callbacks retain the original value. + ```tsx // src/routes/posts.tsx export const Route = createFileRoute('/posts')({ loader: () => fetchPosts(), errorComponent: ({ error }) => { // Render an error message - return
{error.message}
+ return
{error instanceof Error ? error.message : String(error)}
}, }) ``` @@ -604,7 +608,7 @@ export const Route = createFileRoute('/posts')({ errorComponent: ({ error, reset }) => { return (
- {error.message} + {error instanceof Error ? error.message : String(error)} diff --git a/docs/router/installation/with-esbuild.md b/docs/router/installation/with-esbuild.md index b5cad0622c..8ecd9b8d0a 100644 --- a/docs/router/installation/with-esbuild.md +++ b/docs/router/installation/with-esbuild.md @@ -25,7 +25,6 @@ export default { plugins: [ tanstackRouter({ target: 'react', - autoCodeSplitting: true, }), ], } @@ -50,10 +49,7 @@ const ctx = await esbuild.context({ format: 'esm', target: ['esnext'], sourcemap: true, - plugins: [ - solidPlugin(), - tanstackRouter({ target: 'solid', autoCodeSplitting: true }), - ], + plugins: [solidPlugin(), tanstackRouter({ target: 'solid' })], }) if (isDev) { @@ -72,6 +68,9 @@ 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 243fcefdf4..707f90900c 100644 --- a/docs/router/integrations/query.md +++ b/docs/router/integrations/query.md @@ -17,7 +17,7 @@ title: TanStack Query Integration The TanStack query integration is a separate package that you need to install: - + react: @tanstack/react-router-ssr-query solid: @tanstack/solid-router-ssr-query @@ -152,7 +152,7 @@ Preload critical data in the route `loader` to avoid waterfalls and loading flas -# React +# Blocking `query` in loader ```tsx title="src/routes/posts.tsx" import { queryOptions, useSuspenseQuery, useQuery } from '@tanstack/react-query' @@ -165,7 +165,12 @@ const postsQuery = queryOptions({ export const Route = createFileRoute('/posts')({ // Ensure the data is in the cache before render - loader: ({ context }) => context.queryClient.ensureQueryData(postsQuery), + loader: ({ context }) => + context.queryClient.query({ + ...postsQuery, + // returns data from cache immediately, otherwise executes a fetch + staleTime: 'static', + }), component: PostsPage, }) @@ -180,15 +185,15 @@ function PostsPage() { ### Prefetching and streaming -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. +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. -# React +# Non-blocking `query` in loader ```tsx title="src/routes/users.$id.tsx" import { createFileRoute } from '@tanstack/react-router' -import { queryOptions, useQuery } from '@tanstack/react-query' +import { noop, queryOptions, useQuery } from '@tanstack/react-query' const userQuery = (id: string) => queryOptions({ @@ -197,15 +202,18 @@ const userQuery = (id: string) => }) export const Route = createFileRoute('/user/$id')({ - 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)) + 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) }, }) ``` +> [!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 57703aad89..36af0e6e0d 100644 --- a/docs/start/config.json +++ b/docs/start/config.json @@ -36,6 +36,10 @@ { "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" } ] }, @@ -53,6 +57,10 @@ { "label": "Build from Scratch", "to": "framework/solid/build-from-scratch" + }, + { + "label": "Migrate from the Release Candidate", + "to": "framework/solid/migrate-from-release-candidate" } ] } @@ -276,6 +284,10 @@ { "label": "react", "children": [ + { + "label": "Production Checklist", + "to": "framework/react/guide/production-checklist" + }, { "label": "Hosting", "to": "framework/react/guide/hosting" @@ -310,7 +322,7 @@ "label": "react", "children": [ { - "label": "Authentication Overview", + "label": "Choose Authentication", "to": "framework/react/guide/authentication-overview" }, { @@ -318,12 +330,16 @@ "to": "framework/react/guide/authentication-server-primitives" }, { - "label": "Authentication", + "label": "Implement Authentication", "to": "framework/react/guide/authentication" }, { "label": "Databases", "to": "framework/react/guide/databases" + }, + { + "label": "TanStack Query", + "to": "framework/react/guide/tanstack-query" } ] }, @@ -331,7 +347,7 @@ "label": "solid", "children": [ { - "label": "Authentication Overview", + "label": "Choose Authentication", "to": "framework/solid/guide/authentication-overview" }, { @@ -339,7 +355,7 @@ "to": "framework/solid/guide/authentication-server-primitives" }, { - "label": "Authentication", + "label": "Implement Authentication", "to": "framework/solid/guide/authentication" }, { diff --git a/docs/start/framework/react/comparison.md b/docs/start/framework/react/comparison.md index 5c39e0f602..b72e286a76 100644 --- a/docs/start/framework/react/comparison.md +++ b/docs/start/framework/react/comparison.md @@ -1,338 +1,61 @@ --- 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 --- -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). +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). -> **🚨 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. +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. -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. +## Rendering and data -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). +| 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 | -Feature/Capability Key: +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. -- ✅ 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 +## Server APIs and forms -| | 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) | ✅ | ✅ | +| 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) | ---- +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). -> **⚠️ 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. +## Tooling and deployment ---- +| 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) | -## Key Philosophical Differences - -### TanStack Start - -**Philosophy**: Maximum developer freedom with best-in-class type safety. - -- **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 - -### Choose TanStack Start if you: - -- 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. +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. ## Performance Considerations -### Production Performance +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. -All three frameworks are capable of achieving excellent production performance and top Lighthouse scores. The differences come down to optimization strategies: +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. -- **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 +## When to Choose Each Framework -### Development Performance +- **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. -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 +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). diff --git a/docs/start/framework/react/getting-started.md b/docs/start/framework/react/getting-started.md index 0320fdab4e..6e5bcd8841 100644 --- a/docs/start/framework/react/getting-started.md +++ b/docs/start/framework/react/getting-started.md @@ -3,6 +3,7 @@ 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 8b5838a9f9..e80ba97f8c 100644 --- a/docs/start/framework/react/guide/authentication-overview.md +++ b/docs/start/framework/react/guide/authentication-overview.md @@ -1,8 +1,11 @@ --- id: authentication-overview -title: Authentication +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. --- +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) @@ -113,7 +116,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 via `setResponseHeader`, read with `getRequestHeader` +- **Session Management**: HTTP-only cookies written with `setCookie`, read with `getCookie` - **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 20cc143d2f..103e9c4455 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/guide/authenticated-routes.md) (`_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/latest/docs/framework/react/guide/authenticated-routes) (`_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,47 +28,39 @@ Whichever you choose, the cookie flags matter: ```ts // src/server/session.ts import { - getRequestHeader, - setResponseHeader, + deleteCookie, + getCookie, + setCookie, } 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) { - setResponseHeader( - 'Set-Cookie', - [ - `${SESSION_COOKIE}=${token}`, - `HttpOnly`, - `Secure`, - `SameSite=Lax`, - `Path=/`, - `Max-Age=${ONE_DAY}`, - ].join('; '), - ) + setCookie(SESSION_COOKIE, token, { + ...sessionCookieOptions, + maxAge: ONE_DAY, + }) } export function clearSessionCookie() { - setResponseHeader( - 'Set-Cookie', - `${SESSION_COOKIE}=; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=0`, - ) + deleteCookie(SESSION_COOKIE, sessionCookieOptions) } export function readSessionToken(): string | 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 + return getCookie(SESSION_COOKIE) ?? 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. | @@ -169,7 +161,7 @@ For OAuth authorization-code flow: // src/server/oauth.functions.ts import { createServerFn } from '@tanstack/react-start' import { redirect } from '@tanstack/react-router' -import { setResponseHeader } from '@tanstack/react-start/server' +import { setCookie } from '@tanstack/react-start/server' import crypto from 'node:crypto' const OAUTH_STATE_COOKIE = '__Host-oauth' @@ -190,10 +182,13 @@ export const startOAuth = createServerFn({ method: 'GET' }).handler( crypto.createHash('sha256').update(verifier).digest(), ) - setResponseHeader( - 'Set-Cookie', - `${OAUTH_STATE_COOKIE}=${signed({ state, verifier })}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=600`, - ) + setCookie(OAUTH_STATE_COOKIE, signed({ state, verifier }), { + httpOnly: true, + secure: true, + sameSite: 'lax', + path: '/', + maxAge: 600, + }) throw redirect({ href: @@ -349,7 +344,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/guide/authenticated-routes.md) — the routing-side guide. +- [Authenticated Routes (Router)](/router/latest/docs/framework/react/guide/authenticated-routes) — 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 da839e1fbe..c77c681ee0 100644 --- a/docs/start/framework/react/guide/authentication.md +++ b/docs/start/framework/react/guide/authentication.md @@ -1,11 +1,12 @@ --- id: authentication -title: 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. --- -This guide covers authentication patterns and shows how to implement your own authentication system with TanStack Start. +Implement the authentication workflow in your React app, from sessions and sign-in to protected routes and authorization. -> **📋 Before You Start:** Check our [Authentication Overview](./authentication-overview.md) for all available options including partner solutions and hosted services. +To compare libraries and hosted services, read [Choose Authentication for React Apps](./authentication-overview.md). ## Authentication Approaches @@ -34,7 +35,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 the tools for both through server functions, sessions, and route protection. +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. > 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. @@ -47,6 +48,7 @@ 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' }) @@ -60,11 +62,9 @@ export const loginFn = createServerFn({ method: 'POST' }) } // Create session - const session = await useAppSession() - await session.update({ - userId: user.id, - email: user.email, - }) + const session = await getAppSession() + session.userId = user.id + await session.save() // Redirect to protected area throw redirect({ to: '/dashboard' }) @@ -72,98 +72,131 @@ export const loginFn = createServerFn({ method: 'POST' }) // Logout server function export const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await useAppSession() - await session.clear() + const session = await getAppSession() + session.destroy() throw redirect({ to: '/' }) }) // Get current user export const getCurrentUserFn = createServerFn({ method: 'GET' }).handler( async () => { - const session = await useAppSession() - const userId = session.data.userId + const session = await getAppSession() + const userId = session.userId if (!userId) { return null } - return await getUserById(userId) + const user = await getUserById(userId) + return user ? { id: user.id, email: user.email, role: user.role } : null }, ) ``` ### 2. Session Management -TanStack Start provides secure HTTP-only cookie sessions: +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. ```tsx -// utils/session.ts -import { useSession } from '@tanstack/react-start/server' +// utils/session.ts — import only from server code +import { getIronSession } from 'iron-session' +import { getCookie, setCookie } from '@tanstack/react-start/server' type SessionData = { - userId?: string - email?: string - role?: string + userId: string + oauthState: string } -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, +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: '/', + }, }, - }) + ) } ``` +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 -Share authentication state across your application: +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: ```tsx -// contexts/auth.tsx -import { createContext, useContext, ReactNode } from 'react' -import { useServerFn } from '@tanstack/react-start' +// routes/__root.tsx +import { + createRootRoute, + HeadContent, + Outlet, + Scripts, +} from '@tanstack/react-router' +import type { ReactNode } from 'react' import { getCurrentUserFn } from '../server/auth' -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) +export const Route = createRootRoute({ + headers: () => ({ 'Cache-Control': 'private, no-store' }), + beforeLoad: async () => ({ user: await getCurrentUserFn() }), + component: Outlet, + shellComponent: RootDocument, +}) +function RootDocument({ children }: { children: ReactNode }) { return ( - - {children} - + + + + + + {children} + + + ) } +``` -export function useAuth() { - const context = useContext(AuthContext) - if (!context) { - throw new Error('useAuth must be used within AuthProvider') - } - return context +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'} } ``` +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`: @@ -240,8 +273,9 @@ export const registerFn = createServerFn({ method: 'POST' }) }) // Create session - const session = await useAppSession() - await session.update({ userId: user.id }) + const session = await getAppSession() + session.userId = user.id + await session.save() return { success: true, user: { id: user.id, email: user.email } } }) @@ -309,8 +343,9 @@ export const initiateOAuthFn = createServerFn({ method: 'POST' }) const state = generateRandomState() // Store state in session for CSRF protection - const session = await useAppSession() - await session.update({ oauthState: state }) + const session = await getAppSession() + session.oauthState = state + await session.save() // Generate OAuth URL const authUrl = generateOAuthUrl(provider, state) @@ -373,21 +408,9 @@ const hashedPassword = await bcrypt.hash(password, saltRounds) ### 2. Session Security -```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 - }, - }) -} -``` +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. ### 3. Rate Limiting @@ -489,28 +512,69 @@ 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 -function LoginForm() { +// 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() const [isLoading, setIsLoading] = useState(false) - const loginMutation = useServerFn(loginFn) + 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 handleSubmit = async (data: LoginData) => { setIsLoading(true) + setError('') try { - await loginMutation.mutate(data) - } catch (error) { - // Handle error + 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 ( - - {/* Form fields */} - + +
+ + + +
+

{error}

) } @@ -525,16 +589,14 @@ 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 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 - }, - ) + const ttl = data.rememberMe ? 30 * 24 * 60 * 60 : 8 * 60 * 60 + const session = await getAppSession(ttl) + session.userId = user.id + await session.save() return { success: true } }) @@ -562,7 +624,6 @@ 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 28c9c8c030..ac5f3e7b57 100644 --- a/docs/start/framework/react/guide/cdn-asset-urls.md +++ b/docs/start/framework/react/guide/cdn-asset-urls.md @@ -3,8 +3,6 @@ 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 02d0ecd426..3d81a13ac2 100644 --- a/docs/start/framework/react/guide/client-entry-point.md +++ b/docs/start/framework/react/guide/client-entry-point.md @@ -3,8 +3,6 @@ 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 cbafa13f51..774a9df61b 100644 --- a/docs/start/framework/react/guide/databases.md +++ b/docs/start/framework/react/guide/databases.md @@ -1,6 +1,7 @@ --- 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 1dc4760fa7..ba07d65b24 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 { useQueryClient } from '@tanstack/react-query' +import { noop, useQueryClient } from '@tanstack/react-query' import { Hydrate } from '@tanstack/react-start' import { visible } from '@tanstack/react-start/hydration' @@ -255,8 +255,10 @@ function DeferredReviews() { { - await preload() - await queryClient.prefetchQuery(reviewsQueryOptions) + await Promise.all([ + preload(), + queryClient.query(reviewsQueryOptions).catch(noop), + ]) }} > diff --git a/docs/start/framework/react/guide/early-hints.md b/docs/start/framework/react/guide/early-hints.md index da633a84d7..2341215022 100644 --- a/docs/start/framework/react/guide/early-hints.md +++ b/docs/start/framework/react/guide/early-hints.md @@ -3,8 +3,6 @@ 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. @@ -166,6 +164,7 @@ 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 f472a3a26a..94fbb52501 100644 --- a/docs/start/framework/react/guide/environment-functions.md +++ b/docs/start/framework/react/guide/environment-functions.md @@ -121,3 +121,37 @@ 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 aa1806c6bf..2d02f881b3 100644 --- a/docs/start/framework/react/guide/hosting.md +++ b/docs/start/framework/react/guide/hosting.md @@ -1,6 +1,7 @@ --- 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. @@ -115,6 +116,32 @@ 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_ @@ -474,7 +501,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 v2 or v3, this should be `./.output`) + - **Output directory:** `./dist` (if you're using Nitro, 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 8bf47c729a..451d405f81 100644 --- a/docs/start/framework/react/guide/import-protection.md +++ b/docs/start/framework/react/guide/import-protection.md @@ -3,8 +3,6 @@ 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 5704af1a11..98007d3f15 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/guide/data-loading.md) - Client-side cache control +- [Data Loading](/router/latest/docs/guide/data-loading) - 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 ff9735df83..bd75dc01ed 100644 --- a/docs/start/framework/react/guide/path-aliases.md +++ b/docs/start/framework/react/guide/path-aliases.md @@ -26,9 +26,7 @@ After updating your `tsconfig.json` file, configure your build tool so it resolv # Vite -## 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: +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: ```ts // vite.config.ts @@ -42,31 +40,6 @@ 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 new file mode 100644 index 0000000000..b46cd70f2e --- /dev/null +++ b/docs/start/framework/react/guide/production-checklist.md @@ -0,0 +1,42 @@ +--- +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 4258d6f4f1..bf644124d9 100644 --- a/docs/start/framework/react/guide/rendering-markdown.md +++ b/docs/start/framework/react/guide/rendering-markdown.md @@ -3,191 +3,85 @@ id: rendering-markdown title: Rendering Markdown --- -This guide covers two methods for importing and rendering markdown content in your TanStack Start application: +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. -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 +This guide covers static posts loaded with Content Collections and remote content fetched through a server function. Both use the same Markdown component. -Both methods share a common rendering pipeline using the `unified` ecosystem. +## Rendering Markdown -## Setting Up the Markdown Processor - -Both approaches use the same markdown-to-HTML processing pipeline. First, install the required dependencies: +Install TanStack Markdown: ```bash -npm install unified remark-parse remark-gfm remark-rehype rehype-raw rehype-slug rehype-autolink-headings rehype-stringify shiki html-react-parser gray-matter +npm install @tanstack/markdown ``` -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: +Create a shared component that accepts either Markdown source or a parsed document: ```tsx // src/components/Markdown.tsx -import parse, { type HTMLReactParserOptions, Element } from 'html-react-parser' -import { renderMarkdown, type MarkdownResult } from '~/utils/markdown' +import { Markdown as ReactMarkdown } from '@tanstack/markdown/react' +import type { MarkdownDocument } from '@tanstack/markdown' type MarkdownProps = { - content: string + content: string | MarkdownDocument className?: string } export function Markdown({ content, className }: MarkdownProps) { - 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)}
+ return ( +
+ {content} +
+ ) } ``` -## Method 1: Static Markdown with content-collections +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. -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. - -### Installation - -```bash -npm install @content-collections/core @content-collections/vite -``` - -### Configuration - -Create a `content-collections.ts` file in your project root: +Use the `components` prop to customize elements, for example to lazy-load images: ```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 + +```bash +npm install -D @content-collections/core @content-collections/vite zod +``` + +```ts // content-collections.ts import { defineCollection, defineConfig } from '@content-collections/core' -import matter from 'gray-matter' - -function extractFrontMatter(content: string) { - const { data, content: body, excerpt } = matter(content, { excerpt: true }) - return { data, body, excerpt: excerpt || '' } -} +import { z } from 'zod' const posts = defineCollection({ name: 'posts', - directory: './src/blog', // Directory containing your .md files + directory: './src/blog', include: '*.md', - schema: (z) => ({ + schema: z.object({ title: z.string(), - published: z.string().date(), - description: z.string().optional(), - authors: z.string().array(), + 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, }), - 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({ @@ -195,39 +89,55 @@ export default defineConfig({ }) ``` -### Vite Integration +Content Collections already separates frontmatter from `content`, so this transform does not need a second frontmatter parser. -Add the content-collections plugin to your Vite config: +Add the plugin to your existing Vite configuration, keeping any deployment plugins your app needs: -```tsx -// app.config.ts -import { defineConfig } from '@tanstack/react-start/config' +```ts +// vite.config.ts 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({ - vite: { - plugins: [contentCollections()], - }, + plugins: [ + contentCollections(), + tsConfigPaths({ projects: ['./tsconfig.json'] }), + tanstackStart(), + viteReact(), + ], }) ``` -### Creating Blog Posts +Add the generated collection alias to your existing `tsconfig.json`: -Create markdown files in your designated directory: +```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`: ````markdown -## - -title: Hello World -published: 2024-01-15 -authors: - -- Jane Doe - description: My first blog post - --- - -![Hero Image](/images/hero.jpg) +title: Hello World +published: '2026-01-15' +description: My first blog post +authors: + - Jane Doe +--- Welcome to my blog! This is my first post. @@ -240,13 +150,11 @@ console.log('Hello, world!') ``` ```` -### Using the Collection - -Access your posts through the generated collection: +### Listing Posts ```tsx // src/routes/blog.index.tsx -import { createFileRoute } from '@tanstack/react-router' +import { createFileRoute, Link } from '@tanstack/react-router' import { allPosts } from 'content-collections' export const Route = createFileRoute('/blog/')({ @@ -254,31 +162,30 @@ export const Route = createFileRoute('/blog/')({ }) function BlogIndex() { - // Posts are sorted by published date - const sortedPosts = allPosts.sort( - (a, b) => new Date(b.published).getTime() - new Date(a.published).getTime(), + const sortedPosts = [...allPosts].sort((a, b) => + b.published.localeCompare(a.published), ) return ( -
+

Blog

    {sortedPosts.map((post) => (
  • -

    {post.title}

    -

    {post.excerpt}

    - {post.published} + {post.title} +

    {post.description}

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

{post.title}

-

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

-
+

{post.title}

+

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

) } ``` -## Method 2: Dynamic Markdown from Remote Sources +The renderer parses the Markdown synchronously and renders React elements on both the server and client. -For content stored externally (like GitHub repositories), you can fetch and render markdown dynamically using server functions. +## Remote Markdown with a Server Function -### Creating a Fetch Utility +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: -```tsx -// src/utils/docs.server.ts +```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' -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}`, - }, - }) + .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: ${response.status}`) + throw new Error(`Failed to fetch document: ${response.status}`) } - const rawContent = await response.text() - const { data: frontmatter, content } = matter(rawContent) + const { data, content } = matter(await response.text()) return { - frontmatter, - content, - filePath, + title: typeof data.title === 'string' ? data.title : slug, + document: parseMarkdown(content), } }) ``` -### 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 +// src/routes/docs.$slug.tsx import { createFileRoute } from '@tanstack/react-router' -import { fetchDocs } from '~/utils/docs.server' import { Markdown } from '~/components/Markdown' +import { fetchDocs } from '~/utils/docs' -export const Route = createFileRoute('/docs/$path')({ - loader: async ({ params }) => { - return fetchDocs({ - data: { - repo: 'your-org/your-repo', - branch: 'main', - filePath: `docs/${params.path}.md`, - }, - }) - }, +export const Route = createFileRoute('/docs/$slug')({ + loader: ({ params }) => fetchDocs({ data: params.slug }), component: DocsPage, }) function DocsPage() { - const { frontmatter, content } = Route.useLoaderData() + const { title, document } = Route.useLoaderData() return (
-

{frontmatter.title}

- +

{title}

+
) } ``` -### Fetching Directory Contents +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. -To build navigation from a GitHub directory: +## Syntax Highlighting with TanStack Highlight -```tsx -// src/utils/docs.server.ts -type GitHubContent = { - name: string - path: string - type: 'file' | 'dir' -} +Install [TanStack Highlight](https://tanstack.com/highlight/latest/docs/overview). The Markdown adapter requires version `0.0.6` or newer: -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, - })) - }) +```bash +npm install @tanstack/highlight ``` -## Adding Syntax Highlighting with Shiki +Register the languages your content uses and create the Markdown adapter: -For code blocks with syntax highlighting, integrate Shiki into your markdown processor: +```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' -```tsx -// src/utils/markdown.ts -import { codeToHtml } from 'shiki' +const highlighter = createHighlighter({ + languages: [plaintext, js, ts, tsx], +}) -// 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', - }, - }) -} +export const highlightMarkdownCode = + createTanStackMarkdownHighlighter(highlighter) ``` -Then handle code blocks in your Markdown component: +Update the shared component to pass the highlighter and include its theme styles: ```tsx -// In your Markdown component's replace function -if (domNode.name === 'pre') { - const codeElement = domNode.children.find( - (child) => child instanceof Element && child.name === 'code', +// 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 +} + +export function Markdown({ content, className }: MarkdownProps) { + return ( +
+ + + {content} + +
) - if (codeElement) { - const className = codeElement.attribs.class || '' - const language = className.replace('language-', '') || 'text' - const code = getText(codeElement) - - return - } } ``` -## Summary +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.
 
-| 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 |
+## Table of Contents
 
-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.
+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.
diff --git a/docs/start/framework/react/guide/seo.md b/docs/start/framework/react/guide/seo.md
index 2d3e98757d..1a202503a8 100644
--- a/docs/start/framework/react/guide/seo.md
+++ b/docs/start/framework/react/guide/seo.md
@@ -1,6 +1,7 @@
 ---
 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 893a633339..581ae145bd 100644
--- a/docs/start/framework/react/guide/server-components.md
+++ b/docs/start/framework/react/guide/server-components.md
@@ -74,7 +74,7 @@ import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild'
 
 export default defineConfig({
   plugins: [
-    pluginReact({ splitChunks: false }),
+    pluginReact(),
     tanstackStart({
       rsc: {
         enabled: true,
@@ -86,7 +86,7 @@ export default defineConfig({
 
 
 
-**Requirements:** React 19+, Vite 7+ or Rsbuild 2+
+**Requirements:** React 19+, Vite 8+ or Rsbuild 2+
 
 ## Quick Start
 
@@ -401,7 +401,10 @@ 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.ensureQueryData(postQueryOptions(params.postId))
+    await context.queryClient.query({
+      ...postQueryOptions(params.postId),
+      staleTime: 'static',
+    })
   },
   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 5acc8ee550..5f74eb7846 100644
--- a/docs/start/framework/react/guide/server-entry-point.md
+++ b/docs/start/framework/react/guide/server-entry-point.md
@@ -3,38 +3,72 @@ id: server-entry-point
 title: Server Entry Point
 ---
 
-# Server Entry Point
-
 > [!NOTE]
-> 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.
+> 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 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.
 
-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.
+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:
 
 ```tsx
 // src/server.ts
 import handler, { createServerEntry } from '@tanstack/react-start/server-entry'
 
 export default createServerEntry({
-  fetch(request) {
-    return handler.fetch(request)
+  fetch(request, opts) {
+    return handler.fetch(request, opts)
   },
 })
 ```
 
 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:
@@ -53,16 +87,155 @@ const customHandler = defineHandlerCallback((ctx) => {
   return defaultStreamHandler(ctx)
 })
 
-const fetch = createStartHandler(customHandler)
+const startHandler = createStartHandler(customHandler)
 
 export default createServerEntry({
-  fetch,
+  fetch(request, opts) {
+    return startHandler(request, opts)
+  },
 })
 ```
 
+## 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. 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.
+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.
 
 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:
 
@@ -83,8 +256,11 @@ declare module '@tanstack/react-router' {
 }
 
 export default createServerEntry({
-  async fetch(request) {
-    return handler.fetch(request, { context: { hello: 'world', foo: 123 } })
+  fetch(request, opts) {
+    return handler.fetch(request, {
+      ...opts,
+      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 903e5d7b86..879aa9e867 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 `Response` objects binary data, or custom content types.
+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.
 
 ### Progressive Enhancement
 
@@ -425,7 +425,9 @@ Customization:
 
 You can customize function ID generation for the production build by providing a `generateFunctionId` function when configuring the TanStack Start build tool plugin.
 
-Prefer deterministic inputs (filename + functionName) so IDs remain stable between builds.
+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.
 
 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
new file mode 100644
index 0000000000..dec42ca26c
--- /dev/null
+++ b/docs/start/framework/react/guide/tanstack-query.md
@@ -0,0 +1,158 @@
+---
+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 2f4d988449..dc5377df08 100644 --- a/docs/start/framework/react/migrate-from-next-js.md +++ b/docs/start/framework/react/migrate-from-next-js.md @@ -1,510 +1,187 @@ --- 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 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. +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. -## Step-by-Step (Basics) +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. -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. +## Run the reference application -### 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): +Use Node 24 or newer and pnpm 12: ```sh -npx gitpick nrjdalal/awesome-templates/tree/main/next.js-apps/next.js-start next.js-start-er +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 ``` -This structure is a basic Next.js application using the App Router, which we will migrate to TanStack Start. +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`. -### 1. Remove Next.js +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. -First, uninstall Next.js and remove related configuration files: +With those ports free, run: ```sh -npm uninstall @tailwindcss/postcss next -rm postcss.config.* next.config.* +pnpm exec playwright install chromium +pnpm test:e2e +pnpm build:next +pnpm build +MIGRATION_PRODUCTION=1 pnpm test:e2e ``` -### 2. Install Required Dependencies +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. -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. +## Inventory the application before changing it - +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. -# Vite +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. -```sh -npm i @tanstack/react-router @tanstack/react-start nitro vite @vitejs/plugin-react +| 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 ``` -# Rsbuild +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. -```sh -npm i @tanstack/react-router @tanstack/react-start @rsbuild/core @rsbuild/plugin-react -``` +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 -For Tailwind CSS, install the build tool integration you want to use: +| 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`. -# Vite +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. -```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" - } -} -``` - -# Rsbuild - -```json -{ - "type": "module", - "scripts": { - "dev": "rsbuild dev", - "build": "rsbuild build" - } -} -``` - - - - - -# Vite - -```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' - -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(), - ], -}) -``` - -# 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({ - 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 - }, - }), - ], -}) -``` - -```js title="postcss.config.mjs" -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} -``` - - - -By default, `routesDirectory` is set to `routes`. To maintain consistency with Next.js App Router conventions, you can set it to `app` instead. - -### 4. Adapt the Root Layout - -> 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. - -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. - -- `src/app/layout.tsx` to `src/app/__root.tsx` +Replace `next/link` with Router's `Link`. Dynamic paths use typed `params`: ```tsx -- import type { Metadata } from "next" // [!code --] -import { - Outlet, - createRootRoute, - HeadContent, - Scripts, -} from "@tanstack/react-router" -import appCss from "./globals.css?url" + + {article.title} + +``` -- 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, - }, - ], +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 + +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: RootLayout, + component: Articles, }) -- 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 ( - - - - - - - - - - ) +function Articles() { + const { q } = Route.useSearch() + return

Searching for: {q}

} ``` -### 5. Adapt the Home Page +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). -Instead of `page.tsx`, create an `index.tsx` file for the `/` route. +## Move server reads into server functions -- `src/app/page.tsx` to `src/app/index.tsx` +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. -```tsx -+ import { createFileRoute } from '@tanstack/react-router' // [!code ++] +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. -- export default function Home() { // [!code --] -+ export const Route = createFileRoute('/')({ // [!code ++] -+ component: Home, // [!code ++] -+ }) // [!code ++] +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. -+ function Home() { // [!code ++] - return ( -
- ) -} -``` +## Translate mutations and their invalidation -### 6. Are we migrated yet? +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. -Before you can run the development server, you need to create a file that will define the behavior of TanStack Router within TanStack Start. +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. -- `src/router.tsx` +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. -```tsx -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' +`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 function getRouter() { - const router = createRouter({ - routeTree, - scrollRestoration: true, - }) +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. - return router -} -``` +## Preserve authentication and session boundaries -> 🧠 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). +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. -Don't worry if you see some TypeScript errors at this point; the next step will resolve them. +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. -### 7. Verify the Migration +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. -Run the development server: +## Preserve metadata and search responses -```sh -npm run dev -``` +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. -Then, visit `http://localhost:3000`. You should see the TanStack Start welcome page with its logo and a documentation link. +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). -> 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.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. -## Next Steps (Advanced) +## Replace image and font services deliberately -Now that you have migrated the basic structure of your Next.js application to TanStack Start, you can explore more advanced features and concepts. +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). -### Routing Concepts +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. -| 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` | +The reference uses text and the browser's default font. It does not claim to verify your image transformations or font loading. -Learn more about the [Routing Concepts](/router/latest/docs/framework/react/routing/routing-concepts). +## Rebuild caching and deployment behavior -### Dynamic and Catch-All Routes +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. -Retrieving dynamic route parameters in TanStack Start is straightforward. +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. -```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 ++] +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. -+ function Page() { // [!code ++] -- const { slug } = await params // [!code --] -+ const { slug } = Route.useParams() // [!code ++] - return
My Post: {slug}
-} -``` +## Cut over with a rollback path -> Note: If you've made a catch-all route (like `src/app/posts/$.tsx`), you can access the parameters via `const { _splat } = Route.useParams()`. +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. -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}
  • - ))} -
- ) -} -``` +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. diff --git a/docs/start/framework/react/migrate-from-release-candidate.md b/docs/start/framework/react/migrate-from-release-candidate.md new file mode 100644 index 0000000000..5cfa614cda --- /dev/null +++ b/docs/start/framework/react/migrate-from-release-candidate.md @@ -0,0 +1,39 @@ +--- +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 3494b7a187..ced7b65458 100644 --- a/docs/start/framework/react/overview.md +++ b/docs/start/framework/react/overview.md @@ -1,12 +1,11 @@ --- 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 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 stable. If you're upgrading from a release candidate, follow [Migrate from the Release Candidate](./migrate-from-release-candidate). 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 27b814725f..f1dd175a41 100644 --- a/docs/start/framework/react/start-vs-nextjs.md +++ b/docs/start/framework/react/start-vs-nextjs.md @@ -1,286 +1,67 @@ --- 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. --- -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. +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. -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). +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). -**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. +## Rendering and interactivity -## Two Different Visions of React +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. -Both frameworks want to help you build great React applications. But they start from different assumptions about what "great" means. +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). -### 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. +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. ## Routing -This is where TanStack shines brightest. TanStack Router (which powers Start) is the most powerful, type-safe router in any framework. +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. -**Features Next.js doesn't have:** +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. -- **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 +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. -**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). +For detailed navigation features, see the [Router comparison](/router/latest/docs/comparison). ## Server Functions vs Server Actions -Both frameworks let you call server code from the client. The approaches differ significantly. +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. -### Next.js Server Actions +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). -```tsx -'use server' +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. -export async function createPost(formData: FormData) { - const title = formData.get('title') - // No compile-time type safety on inputs - return db.posts.create({ title }) -} -``` +## Caching -Server Actions integrate with forms and transitions. They're convenient for simple cases but provide limited type safety at the boundary. +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. -### TanStack Server Functions +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). -```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 }) - }) -``` +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. -Server functions give you: +## Build tools -- **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 +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. -**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. +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). ## Where Next.js Has the Advantage -Next.js has been around longer. That's not a technical advantage, but it creates real ecosystem effects: +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. -**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. +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. -**Mindshare** - Next is the default recommendation in many circles. That means more developers have used it, which means more content, which reinforces the cycle. +## When to Choose TanStack Start -**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. +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. -**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). +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). diff --git a/docs/start/framework/react/tutorial/reading-writing-file.md b/docs/start/framework/react/tutorial/reading-writing-file.md index 11b1be0794..f4af4480f1 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/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/guide/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 8ae205ef21..460a58747c 100644 --- a/docs/start/framework/solid/guide/authentication.md +++ b/docs/start/framework/solid/guide/authentication.md @@ -1,11 +1,12 @@ --- id: authentication -title: 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. --- -This guide covers authentication patterns and shows how to implement your own authentication system with TanStack Start. +Implement the authentication workflow in your SolidJS app, from sessions and sign-in to protected routes and authorization. -> **📋 Before You Start:** Check our [Authentication Overview](./authentication-overview.md) for all available options including partner solutions and hosted services. +To compare libraries and hosted services, read [Choose Authentication for SolidJS Apps](./authentication-overview.md). ## Authentication Approaches @@ -34,7 +35,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 the tools for both through server functions, sessions, and route protection. +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. > 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. @@ -47,6 +48,7 @@ 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' }) @@ -60,11 +62,9 @@ export const loginFn = createServerFn({ method: 'POST' }) } // Create session - const session = await useAppSession() - await session.update({ - userId: user.id, - email: user.email, - }) + const session = await getAppSession() + session.userId = user.id + await session.save() // Redirect to protected area throw redirect({ to: '/dashboard' }) @@ -72,98 +72,131 @@ export const loginFn = createServerFn({ method: 'POST' }) // Logout server function export const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await useAppSession() - await session.clear() + const session = await getAppSession() + session.destroy() throw redirect({ to: '/' }) }) // Get current user export const getCurrentUserFn = createServerFn({ method: 'GET' }).handler( async () => { - const session = await useAppSession() - const userId = session.get('userId') + const session = await getAppSession() + const userId = session.userId if (!userId) { return null } - return await getUserById(userId) + const user = await getUserById(userId) + return user ? { id: user.id, email: user.email, role: user.role } : null }, ) ``` ### 2. Session Management -TanStack Start provides secure HTTP-only cookie sessions: +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. ```tsx -// utils/session.ts -import { useSession } from '@tanstack/solid-start/server' +// utils/session.ts — import only from server code +import { getIronSession } from 'iron-session' +import { getCookie, setCookie } from '@tanstack/solid-start/server' type SessionData = { - userId?: string - email?: string - role?: string + userId: string + oauthState: string } -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, +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: '/', + }, }, - }) + ) } ``` +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 -Share authentication state across your application: +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: ```tsx -// contexts/auth.tsx -import { createContext, useContext } from 'solid-js' -import { useServerFn } from '@tanstack/solid-start' +// routes/__root.tsx +import { + createRootRoute, + HeadContent, + Outlet, + Scripts, +} from '@tanstack/solid-router' +import type { JSX } from 'solid-js' import { getCurrentUserFn } from '../server/auth' -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) +export const Route = createRootRoute({ + headers: () => ({ 'Cache-Control': 'private, no-store' }), + beforeLoad: async () => ({ user: await getCurrentUserFn() }), + component: Outlet, + shellComponent: RootDocument, +}) +function RootDocument({ children }: { children: JSX.Element }) { return ( - - {props.children} - + + + + + + {children} + + + ) } +``` -export function useAuth() { - const context = useContext(AuthContext) - if (!context) { - throw new Error('useAuth must be used within AuthProvider') - } - return context +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'} } ``` +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`: @@ -240,8 +273,9 @@ export const registerFn = createServerFn({ method: 'POST' }) }) // Create session - const session = await useAppSession() - await session.update({ userId: user.id }) + const session = await getAppSession() + session.userId = user.id + await session.save() return { success: true, user: { id: user.id, email: user.email } } }) @@ -309,8 +343,9 @@ export const initiateOAuthFn = createServerFn({ method: 'POST' }) const state = generateRandomState() // Store state in session for CSRF protection - const session = await useAppSession() - await session.update({ oauthState: state }) + const session = await getAppSession() + session.oauthState = state + await session.save() // Generate OAuth URL const authUrl = generateOAuthUrl(provider, state) @@ -373,21 +408,9 @@ const hashedPassword = await bcrypt.hash(password, saltRounds) ### 2. Session Security -```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 - }, - }) -} -``` +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. ### 3. Rate Limiting @@ -489,28 +512,70 @@ 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 -function LoginForm() { +// 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() const [isLoading, setIsLoading] = createSignal(false) - const loginMutation = useServerFn(loginFn) + 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 handleSubmit = async (data: LoginData) => { setIsLoading(true) + setError('') try { - await loginMutation.mutate(data) - } catch (error) { - // Handle error + 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 ( -
- {/* Form fields */} - + +
+ + + +
+

{error()}

) } @@ -525,16 +590,14 @@ 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 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 - }, - ) + const ttl = data.rememberMe ? 30 * 24 * 60 * 60 : 8 * 60 * 60 + const session = await getAppSession(ttl) + session.userId = user.id + await session.save() return { success: true } }) @@ -554,7 +617,6 @@ 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 b73408e8e4..929efc7a2d 100644 --- a/docs/start/framework/solid/guide/client-entry-point.md +++ b/docs/start/framework/solid/guide/client-entry-point.md @@ -3,8 +3,6 @@ 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 deleted file mode 100644 index 5aa48d8188..0000000000 --- a/docs/start/framework/solid/guide/reading-writing-file.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -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 new file mode 100644 index 0000000000..9f988a14fc --- /dev/null +++ b/docs/start/framework/solid/migrate-from-release-candidate.md @@ -0,0 +1,8 @@ +--- +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 de3d4d472e..09b58c38f5 100644 --- a/docs/start/framework/solid/tutorial/reading-writing-file.md +++ b/docs/start/framework/solid/tutorial/reading-writing-file.md @@ -1,6 +1,8 @@ --- 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. @@ -152,7 +154,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/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/guide/server-functions). ```tsx // src/serverActions/jokesActions.ts diff --git a/e2e/AGENTS.md b/e2e/AGENTS.md new file mode 100644 index 0000000000..f373ecba4f --- /dev/null +++ b/e2e/AGENTS.md @@ -0,0 +1,9 @@ +# 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 new file mode 100644 index 0000000000..f92ec840e5 --- /dev/null +++ b/e2e/e2e-utils/mock-api.mjs @@ -0,0 +1,4 @@ +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 a0708e0475..fcfa5f8dc0 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": "exit 0; vitest --typecheck" + "test:unit": "vitest run" }, "type": "module", "types": "dist/types/index.d.ts", @@ -22,7 +22,8 @@ "default": "./dist/cjs/index.cjs" } }, - "./package.json": "./package.json" + "./package.json": "./package.json", + "./mock-api": "./mock-api.mjs" }, "sideEffects": false, "files": [ @@ -30,12 +31,14 @@ "src" ], "engines": { - "node": ">=20.19" + "node": "^22.18.0 || >=24.0.0" }, - "dependencies": {}, "devDependencies": { - "get-port-please": "^3.2.0", + "@msw/playwright": "0.6.7", + "msw": "2.15.0", + "rimraf": "catalog:", "vite": "^8.0.14", - "vite-plugin-dts": "^4.5.4" + "vite-plugin-dts": "^4.5.4", + "vitest": "catalog:" } } diff --git a/e2e/e2e-utils/src/api-fixture.ts b/e2e/e2e-utils/src/api-fixture.ts new file mode 100644 index 0000000000..90ca1912a3 --- /dev/null +++ b/e2e/e2e-utils/src/api-fixture.ts @@ -0,0 +1,17 @@ +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 new file mode 100644 index 0000000000..4e2c0498f4 --- /dev/null +++ b/e2e/e2e-utils/src/api-handlers.ts @@ -0,0 +1,32 @@ +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 deleted file mode 100644 index 3ecb86cb53..0000000000 --- a/e2e/e2e-utils/src/derivePort.ts +++ /dev/null @@ -1,27 +0,0 @@ -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 deleted file mode 100644 index d1acf4740e..0000000000 --- a/e2e/e2e-utils/src/e2eSetupTeardown.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 17e58f82e5..960a01a9be 100644 --- a/e2e/e2e-utils/src/index.ts +++ b/e2e/e2e-utils/src/index.ts @@ -1,10 +1,9 @@ -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 { apiTest } from './api-fixture' 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 { collectBrowserErrors, test } from './fixture' +export { resolveRuntimeSuffix } from './resolve-runtime-suffix' +export { toRuntimePath } from './to-runtime-path' +export { appServerReady, appServerReadyPattern } from './webServer' diff --git a/e2e/e2e-utils/src/localDummyServer.ts b/e2e/e2e-utils/src/localDummyServer.ts deleted file mode 100644 index d452f54c59..0000000000 --- a/e2e/e2e-utils/src/localDummyServer.ts +++ /dev/null @@ -1,128 +0,0 @@ -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 new file mode 100644 index 0000000000..77536e4c69 --- /dev/null +++ b/e2e/e2e-utils/src/webServer.ts @@ -0,0 +1,9 @@ +// 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 new file mode 100644 index 0000000000..ba25c1254d --- /dev/null +++ b/e2e/e2e-utils/tests/mock-api.test.ts @@ -0,0 +1,53 @@ +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 new file mode 100644 index 0000000000..fd3a8b239c --- /dev/null +++ b/e2e/e2e-utils/tests/webServer.test.ts @@ -0,0 +1,23 @@ +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 9b21ee123b..5561f5d28f 100644 --- a/e2e/e2e-utils/tsconfig.json +++ b/e2e/e2e-utils/tsconfig.json @@ -1,4 +1,7 @@ { "extends": "../../tsconfig.json", - "include": ["src", "vite.config.ts", "tests"] + "include": ["src", "vite.config.ts", "tests"], + "compilerOptions": { + "rewriteRelativeImportExtensions": true + } } diff --git a/e2e/eslint-plugin-start/package.json b/e2e/eslint-plugin-start/package.json index 87bc81bfe9..e3591d7d1b 100644 --- a/e2e/eslint-plugin-start/package.json +++ b/e2e/eslint-plugin-start/package.json @@ -61,6 +61,6 @@ "eslint": "^9.22.0", "react": "^19.0.0", "typescript": "^5.7.2", - "vitest": "^4.1.4" + "vitest": "catalog:" } } diff --git a/e2e/react-router/basepath-file-based/package.json b/e2e/react-router/basepath-file-based/package.json index a155cc2173..3dfbb58180 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "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 6069bbe59f..4eead86444 100644 --- a/e2e/react-router/basepath-file-based/playwright.config.ts +++ b/e2e/react-router/basepath-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ 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} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, 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 06b90f6528..d6a50de840 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,5 +1,41 @@ -/* eslint-disable */ -import { expect, test } from '@playwright/test' +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([]) +} test.describe('Scroll Restoration with Session Storage Error', () => { test('should not crash when sessionStorage.setItem throws an error', async ({ @@ -9,22 +45,12 @@ test.describe('Scroll Restoration with Session Storage Error', () => { await page.waitForLoadState('networkidle') await page.evaluate(() => { - sessionStorage.setItem = () => { + Storage.prototype.setItem = () => { throw new Error('Test Error') } }) - 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) + await reloadAfterStorageFailure(page) }) test('should not crash when sessionStorage quota is exceeded', async ({ @@ -47,16 +73,6 @@ test.describe('Scroll Restoration with Session Storage Error', () => { } }) - 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) + await reloadAfterStorageFailure(page) }) }) 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/basepath-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/basepath-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 2ff977a4f4..59210c24d7 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -15,7 +15,7 @@ "@tanstack/router-plugin": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "zod": "^4.4.3" }, "devDependencies": { 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 ca0fb7a1da..a38252921f 100644 --- a/e2e/react-router/basic-esbuild-file-based/playwright.config.ts +++ b/e2e/react-router/basic-esbuild-file-based/playwright.config.ts @@ -1,12 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' + +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,18 +13,15 @@ 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\\" --define:process.env.EXTERNAL_PORT="${EXTERNAL_PORT}"`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm run build && pnpm run serve --serve=${PORT} --define:process.env.NODE_ENV=\\"test\\"`, + wait: appServerReady, + reuseExistingServer: false, 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 5f0f4fce03..954ddc026f 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,9 +2,5 @@ import { tanstackRouter } from '@tanstack/router-plugin/esbuild' export default { // ... - plugins: [ - tanstackRouter({ - autoCodeSplitting: true, - }), - ], + plugins: [tanstackRouter()], } 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 8f74b8c9aa..97c96d77eb 100644 --- a/e2e/react-router/basic-esbuild-file-based/src/posts.tsx +++ b/e2e/react-router/basic-esbuild-file-based/src/posts.tsx @@ -7,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (process.env.NODE_ENV === 'test') { - queryURL = `http://localhost:${process.env.EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 7b322a8b1d..c52191a7d4 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,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/basic-esbuild-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/basic-esbuild-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 f3654137be..82ebb90e93 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -17,6 +17,7 @@ "@tanstack/router-plugin": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, 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 22c9bdcd7e..4eead86444 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,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ 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} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, 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 ae7142c5b6..97c96d77eb 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,11 +7,7 @@ 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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 3e5a69ccaa..fbf093cd51 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,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 0bc3265760..fd17fcc47b 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,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/basic-file-based-code-splitting/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/basic-file-based-code-splitting/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 512943c10d..2ad4ec3e78 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,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 be3d8add30..0f3d243432 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e:default": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -18,7 +18,7 @@ "@tanstack/router-plugin": "workspace:^", "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/e2e/react-router/basic-file-based/playwright.config.ts b/e2e/react-router/basic-file-based/playwright.config.ts index 6e4e1d7703..ea3ef9ffec 100644 --- a/e2e/react-router/basic-file-based/playwright.config.ts +++ b/e2e/react-router/basic-file-based/playwright.config.ts @@ -1,14 +1,9 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` -const command = `pnpm build && pnpm preview --port ${PORT}` +const command = `pnpm build && pnpm preview --host 0.0.0.0 --port ${PORT}` console.info('Running with mode: ', process.env.MODE || 'default') @@ -21,9 +16,6 @@ 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, @@ -31,15 +23,12 @@ export default defineConfig({ webServer: { command, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, 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 new file mode 100644 index 0000000000..3b4062b778 --- /dev/null +++ b/e2e/react-router/basic-file-based/public/external.html @@ -0,0 +1,9 @@ + + + + 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 12e202dae4..d6a5aef382 100644 --- a/e2e/react-router/basic-file-based/src/main.tsx +++ b/e2e/react-router/basic-file-based/src/main.tsx @@ -24,6 +24,14 @@ 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 ae7142c5b6..97c96d77eb 100644 --- a/e2e/react-router/basic-file-based/src/posts.tsx +++ b/e2e/react-router/basic-file-based/src/posts.tsx @@ -7,11 +7,7 @@ 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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 2493a8c675..83b504992f 100644 --- a/e2e/react-router/basic-file-based/src/routeTree.gen.ts +++ b/e2e/react-router/basic-file-based/src/routeTree.gen.ts @@ -13,9 +13,12 @@ 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' @@ -149,6 +152,17 @@ 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', @@ -164,6 +178,11 @@ 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', @@ -787,8 +806,11 @@ 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 @@ -903,8 +925,11 @@ 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 @@ -1011,8 +1036,11 @@ 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 @@ -1134,8 +1162,11 @@ export interface FileRouteTypes { | '/대한민국' | '/anchor' | '/component-types-test' + | '/document-navigation' + | '/document-navigation-target' | '/editing-a' | '/editing-b' + | '/history-blocking' | '/hover-preload-hash' | '/lazy-error' | '/masks' @@ -1250,8 +1281,11 @@ export interface FileRouteTypes { | '/대한민국' | '/anchor' | '/component-types-test' + | '/document-navigation' + | '/document-navigation-target' | '/editing-a' | '/editing-b' + | '/history-blocking' | '/hover-preload-hash' | '/lazy-error' | '/masks' @@ -1357,8 +1391,11 @@ 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' @@ -1480,8 +1517,11 @@ 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 @@ -1549,6 +1589,20 @@ 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' @@ -1570,6 +1624,13 @@ 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' @@ -1650,7 +1711,7 @@ declare module '@tanstack/react-router' { '/(group)/_layout': { id: '/(group)/_layout' path: '' - fullPath: '' + fullPath: '/' preLoaderRoute: typeof groupLayoutRouteImport parentRoute: typeof rootRouteImport } @@ -2878,8 +2939,11 @@ 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 aafad6cb6f..cae0a3e583 100644 --- a/e2e/react-router/basic-file-based/src/routes/anchor.tsx +++ b/e2e/react-router/basic-file-based/src/routes/anchor.tsx @@ -25,6 +25,10 @@ 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 new file mode 100644 index 0000000000..905b0c31b9 --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/document-navigation-target.tsx @@ -0,0 +1,3 @@ +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 new file mode 100644 index 0000000000..66c2b704d1 --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/document-navigation.tsx @@ -0,0 +1,97 @@ +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 new file mode 100644 index 0000000000..019893a628 --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/history-blocking.tsx @@ -0,0 +1,119 @@ +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 ae87d350ce..bd9c365484 100644 --- a/e2e/react-router/basic-file-based/tests/app.spec.ts +++ b/e2e/react-router/basic-file-based/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 new file mode 100644 index 0000000000..bd81eaa44b --- /dev/null +++ b/e2e/react-router/basic-file-based/tests/document-navigation.spec.ts @@ -0,0 +1,68 @@ +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 d1bd9c1c41..8f4df9f966 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,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 new file mode 100644 index 0000000000..df1f863a03 --- /dev/null +++ b/e2e/react-router/basic-file-based/tests/history-blocking.spec.ts @@ -0,0 +1,254 @@ +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 b090c2a6b7..1263faf391 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,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 1b77760de6..d5076a5854 100644 --- a/e2e/react-router/basic-file-based/tests/mask.spec.ts +++ b/e2e/react-router/basic-file-based/tests/mask.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 dccdfd4acf..ea0e585c75 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,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 2f0fe256cd..bbb2dac7a1 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,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 a867696ff8..fa0377f3ca 100644 --- a/e2e/react-router/basic-file-based/tests/params.spec.ts +++ b/e2e/react-router/basic-file-based/tests/params.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 1845cc16a4..aaa9c1a6b6 100644 --- a/e2e/react-router/basic-file-based/tests/redirect.spec.ts +++ b/e2e/react-router/basic-file-based/tests/redirect.spec.ts @@ -1,17 +1,13 @@ import queryString from 'node:querystring' -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 = await getTestServerPort(packageJson.name) -const EXTERNAL_HOST_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const EXTERNAL_ORIGIN = `http://127.0.0.1:${PORT}` test.describe('redirects', () => { const internalNavigationTestMatrix = combinate({ @@ -39,7 +35,7 @@ test.describe('redirects', () => { const requestPromise = new Promise((resolve) => { page.on('request', (request) => { if ( - request.url() === `http://localhost:${EXTERNAL_HOST_PORT}/posts` + request.url() === 'https://jsonplaceholder.typicode.com/posts' ) { requestHappened = true resolve() @@ -108,7 +104,7 @@ test.describe('redirects', () => { await page.waitForLoadState('networkidle') const q = queryString.stringify({ - externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, + externalHost: `${EXTERNAL_ORIGIN}/`, }) if (scenario === 'navigate') { @@ -118,7 +114,7 @@ test.describe('redirects', () => { await page.goto(`/redirect/external/via-${thrower}?${q}`) } - const url = `http://localhost:${EXTERNAL_HOST_PORT}/` + const url = `${EXTERNAL_ORIGIN}/` await page.waitForURL(url) expect(page.url()).toBe(url) @@ -184,7 +180,7 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, + externalHost: `${EXTERNAL_ORIGIN}/`, }) if (scenario === 'navigate') { @@ -197,7 +193,7 @@ test.describe('redirects', () => { ) } - const url = `http://localhost:${EXTERNAL_HOST_PORT}/` + const url = `${EXTERNAL_ORIGIN}/` await page.waitForURL(url) expect(page.url()).toBe(url) }) @@ -254,7 +250,7 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, + externalHost: `${EXTERNAL_ORIGIN}/`, }) if (scenario === 'navigate') { @@ -267,7 +263,7 @@ test.describe('redirects', () => { ) } - const url = `http://localhost:${EXTERNAL_HOST_PORT}/` + const url = `${EXTERNAL_ORIGIN}/` 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 4850d3630d..f62c248680 100644 --- a/e2e/react-router/basic-file-based/tests/relative.spec.ts +++ b/e2e/react-router/basic-file-based/tests/relative.spec.ts @@ -1,12 +1,11 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) 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 d1af86adfb..68dfededc2 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,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' import type { Page } from '@playwright/test' const anchors = { @@ -32,6 +33,21 @@ 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 d6307cbcf8..a99488a47a 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,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/basic-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/basic-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 6548381772..3a90a3cd6d 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -19,7 +19,7 @@ "@tanstack/router-plugin": "workspace:^", "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/e2e/react-router/basic-react-query-file-based/playwright.config.ts b/e2e/react-router/basic-react-query-file-based/playwright.config.ts index f3083ff8b6..fbda9bd451 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,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -17,17 +12,15 @@ 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: `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, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, 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 1becc2c242..1f6cb8e308 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,11 +8,7 @@ export type PostType = { export class PostNotFoundError extends Error {} -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 d80e8dada5..2b42d6d589 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,24 +1,23 @@ -import { expect, test } from '@playwright/test' -import { getDummyServerPort } from '@tanstack/router-e2e-utils' -import packageJson from '../package.json' with { type: 'json' } +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') }) -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() - +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) 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/basic-react-query-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/basic-react-query-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 81eb9eb67b..8f28340f56 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -18,7 +18,7 @@ "@tanstack/router-devtools": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2" }, "devDependencies": { diff --git a/e2e/react-router/basic-react-query/playwright.config.ts b/e2e/react-router/basic-react-query/playwright.config.ts index ab42c7c607..4eead86444 100644 --- a/e2e/react-router/basic-react-query/playwright.config.ts +++ b/e2e/react-router/basic-react-query/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ 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_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, 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 5e2a2d3aa3..ffc5a274b7 100644 --- a/e2e/react-router/basic-react-query/src/posts.ts +++ b/e2e/react-router/basic-react-query/src/posts.ts @@ -9,11 +9,7 @@ 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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 3e5a69ccaa..fbf093cd51 100644 --- a/e2e/react-router/basic-react-query/tests/app.spec.ts +++ b/e2e/react-router/basic-react-query/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/basic-react-query/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/basic-react-query/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 d8ebcb414b..c13e92cec8 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -17,7 +17,7 @@ "@tanstack/react-virtual": "^3.13.0", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2" }, "devDependencies": { diff --git a/e2e/react-router/basic-scroll-restoration/playwright.config.ts b/e2e/react-router/basic-scroll-restoration/playwright.config.ts index 0c5cee43e4..6a684ac89e 100644 --- a/e2e/react-router/basic-scroll-restoration/playwright.config.ts +++ b/e2e/react-router/basic-scroll-restoration/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, 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 891f1d6328..0343de0846 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -18,7 +18,7 @@ "@tanstack/virtual-file-routes": "workspace:^", "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/e2e/react-router/basic-virtual-file-based/playwright.config.ts b/e2e/react-router/basic-virtual-file-based/playwright.config.ts index c5de6b5611..4eead86444 100644 --- a/e2e/react-router/basic-virtual-file-based/playwright.config.ts +++ b/e2e/react-router/basic-virtual-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -22,13 +17,10 @@ export default defineConfig({ baseURL, }, - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - webServer: { - 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, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, 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 01831e335c..cc3cb0f9c8 100644 --- a/e2e/react-router/basic-virtual-file-based/src/posts.tsx +++ b/e2e/react-router/basic-virtual-file-based/src/posts.tsx @@ -7,11 +7,7 @@ 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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 3e5a69ccaa..fbf093cd51 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,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/basic-virtual-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/basic-virtual-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 d3872b01e6..6bdb1248f6 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -18,7 +18,7 @@ "@tanstack/virtual-file-routes": "workspace:^", "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/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 ab42c7c607..4eead86444 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,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ 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_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, 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 ae7142c5b6..97c96d77eb 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,11 +7,7 @@ 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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 0aedada786..7d2074182f 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,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 a8de9acc3f..4ff68f5cda 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -16,8 +16,9 @@ "@tanstack/react-router-devtools": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", - "tailwindcss": "^4.2.2" + "redaxios": "catalog:", + "tailwindcss": "^4.2.2", + "zod": "catalog:" }, "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 22c9bdcd7e..4eead86444 100644 --- a/e2e/react-router/basic/playwright.config.ts +++ b/e2e/react-router/basic/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ 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} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-router/basic/src/main.tsx b/e2e/react-router/basic/src/main.tsx index 36e5106654..49fa054776 100644 --- a/e2e/react-router/basic/src/main.tsx +++ b/e2e/react-router/basic/src/main.tsx @@ -1,3 +1,5 @@ +import { useState } from 'react' +import { createPortal } from 'react-dom' import ReactDOM from 'react-dom/client' import { ErrorComponent, @@ -9,12 +11,19 @@ import { createRouter, redirect, } from '@tanstack/react-router' -import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' +import { + TanStackRouterDevtoolsInProd as TanStackRouterDevtools, + TanStackRouterDevtoolsPanelInProd as TanStackRouterDevtoolsPanel, +} from '@tanstack/react-router-devtools' +import { z } from 'zod' 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 ( @@ -27,6 +36,8 @@ const rootRoute = createRootRoute({ }) function RootComponent() { + const { devtools } = rootRoute.useSearch() + return ( <>
@@ -86,12 +97,57 @@ function RootComponent() {
+
+ Devtools: + {(['floating', 'panel', 'shadow'] as const).map((mode) => ( + ({ + ...prev, + devtools: mode === 'floating' ? undefined : mode, + })} + className={ + (devtools ?? 'floating') === mode ? 'font-bold' : undefined + } + > + {mode} + + ))} +
- TanStack Logo -

- Next.js TanStack Start -

-
- Docs - -
- + {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 e859645746..f72d16fee3 100644 --- a/e2e/react-router/basic/src/posts.ts +++ b/e2e/react-router/basic/src/posts.ts @@ -8,11 +8,7 @@ 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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 ec0e24d8a4..9c0a6b6901 100644 --- a/e2e/react-router/basic/tests/app.spec.ts +++ b/e2e/react-router/basic/tests/app.spec.ts @@ -1,8 +1,7 @@ -import { expect, test } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from '../package.json' with { type: 'json' } +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) 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 new file mode 100644 index 0000000000..b8a7e803e6 --- /dev/null +++ b/e2e/react-router/basic/tests/devtools.spec.ts @@ -0,0 +1,42 @@ +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 ac18f39864..f673138047 100644 --- a/e2e/react-router/basic/tests/params.spec.ts +++ b/e2e/react-router/basic/tests/params.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/basic/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/basic/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 71a3cb08ca..af401c49d3 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e:default": "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 6e4e1d7703..629ddefccf 100644 --- a/e2e/react-router/escaped-special-strings/playwright.config.ts +++ b/e2e/react-router/escaped-special-strings/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` const command = `pnpm build && pnpm preview --port ${PORT}` @@ -21,9 +16,6 @@ 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, @@ -31,15 +23,12 @@ export default defineConfig({ webServer: { command, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/escaped-special-strings/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/escaped-special-strings/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 6bbcccf4bd..159ba05500 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -17,7 +17,7 @@ "@tanstack/router-cli": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2" }, "devDependencies": { diff --git a/e2e/react-router/generator-cli-only/playwright.config.ts b/e2e/react-router/generator-cli-only/playwright.config.ts index c9d9a76ae7..4eead86444 100644 --- a/e2e/react-router/generator-cli-only/playwright.config.ts +++ b/e2e/react-router/generator-cli-only/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ 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_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, 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 e859645746..f72d16fee3 100644 --- a/e2e/react-router/generator-cli-only/src/posts.ts +++ b/e2e/react-router/generator-cli-only/src/posts.ts @@ -8,11 +8,7 @@ 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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 5a83a314f2..ced5ac9310 100644 --- a/e2e/react-router/generator-cli-only/tests/app.spec.ts +++ b/e2e/react-router/generator-cli-only/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/generator-cli-only/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/generator-cli-only/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 a100d58e85..d1af160f10 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -29,5 +29,23 @@ "@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 91ef8fbd9f..8e94d5f9a1 100644 --- a/e2e/react-router/i18n-paraglide/playwright.config.ts +++ b/e2e/react-router/i18n-paraglide/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -21,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-router/issue-4759/package.json b/e2e/react-router/issue-4759/package.json index 91a7a5053e..ee6a105ad5 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "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 b5e8249edc..a301f62881 100644 --- a/e2e/react-router/issue-4759/playwright.config.ts +++ b/e2e/react-router/issue-4759/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -12,8 +11,8 @@ export default defineConfig({ use: { baseURL }, webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm dev:e2e --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, projects: [ diff --git a/e2e/react-router/issue-4759/src/main.tsx b/e2e/react-router/issue-4759/src/main.tsx index bc4a99c37f..e251178045 100644 --- a/e2e/react-router/issue-4759/src/main.tsx +++ b/e2e/react-router/issue-4759/src/main.tsx @@ -1,13 +1,25 @@ import { StrictMode } from 'react' import { createRoot } from 'react-dom/client' import { + Outlet, RouterProvider, createRootRoute, createRoute, createRouter, } from '@tanstack/react-router' -const rootRoute = createRootRoute() +const rootRoute = createRootRoute({ + context: () => ({ locale: 'en' }), + component: RootComponent, +}) +function RootComponent() { + const { locale } = rootRoute.useRouteContext() + return ( +
+ +
+ ) +} const indexRoute = createRoute({ getParentRoute: () => rootRoute, path: '/', @@ -19,18 +31,34 @@ const routePendingRoute = createRoute({ path: '/route-pending', pendingMs: 0, pendingMinMs: 0, - pendingComponent: () => ( -
- route pending -
- ), + pendingComponent: RoutePending, loader: () => new Promise((resolve) => setTimeout(resolve, 1_000)), component: () =>
loaded
, }) +function RoutePending() { + const { locale } = routePendingRoute.useRouteContext() + return ( +
+ route pending +
+ ) +} const router = createRouter({ routeTree: rootRoute.addChildren([indexRoute, routePendingRoute]), }) const usesRoutePending = window.location.pathname === '/route-pending' +function DefaultPending() { + const { locale } = indexRoute.useRouteContext() + return ( +
+ default pending +
+ ) +} createRoot(document.getElementById('app')!).render( @@ -39,11 +67,7 @@ createRoot(document.getElementById('app')!).render( router={router} defaultPendingMs={usesRoutePending ? 1_000 : 0} defaultPendingMinMs={0} - defaultPendingComponent={() => ( -
- default pending -
- )} + defaultPendingComponent={DefaultPending} />
, diff --git a/e2e/react-router/issue-4759/tests/issue-4759.spec.ts b/e2e/react-router/issue-4759/tests/issue-4759.spec.ts index 7556b1c47a..95689010c8 100644 --- a/e2e/react-router/issue-4759/tests/issue-4759.spec.ts +++ b/e2e/react-router/issue-4759/tests/issue-4759.spec.ts @@ -5,11 +5,12 @@ async function expectNoBlankFrame( page: Page, pendingSource: 'default' | 'route', ) { - await expect( - page.locator( - `[data-state="pending"][data-pending-source="${pendingSource}"]`, - ), - ).toBeVisible() + const pending = page.locator( + `[data-state="pending"][data-pending-source="${pendingSource}"]`, + ) + await expect(pending).toBeVisible() + await expect(pending).toHaveAttribute('data-locale', 'en') + await expect(page.locator('[data-root-locale="en"]')).toBeVisible() const paintStates = await page.evaluate( () => diff --git a/e2e/react-router/issue-7120/package.json b/e2e/react-router/issue-7120/package.json index a16155eb61..979b32556c 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "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 61a995a815..a8ba116fb4 100644 --- a/e2e/react-router/issue-7120/playwright.config.ts +++ b/e2e/react-router/issue-7120/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -12,8 +11,8 @@ export default defineConfig({ use: { baseURL }, webServer: { command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm dev:e2e --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, projects: [ diff --git a/e2e/react-router/issue-7120/src/routeTree.gen.ts b/e2e/react-router/issue-7120/src/routeTree.gen.ts index fc671589c7..e8c6d92110 100644 --- a/e2e/react-router/issue-7120/src/routeTree.gen.ts +++ b/e2e/react-router/issue-7120/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 PostsRouteImport } from './routes/posts' import { Route as IndexRouteImport } from './routes/index' +import { Route as PostsRouteImport } from './routes/posts' -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any).lazy(() => import('./routes/posts.lazy').then((d) => d.Route)) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any).lazy(() => import('./routes/posts.lazy').then((d) => d.Route)) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/e2e/react-router/issue-7457/package.json b/e2e/react-router/issue-7457/package.json index 3220a4dbb4..838f5173e2 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "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 61a995a815..a8ba116fb4 100644 --- a/e2e/react-router/issue-7457/playwright.config.ts +++ b/e2e/react-router/issue-7457/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -12,8 +11,8 @@ export default defineConfig({ use: { baseURL }, webServer: { command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm dev:e2e --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, projects: [ diff --git a/e2e/react-router/issue-7457/src/routeTree.gen.ts b/e2e/react-router/issue-7457/src/routeTree.gen.ts index 72a8f23384..04a2c94ce8 100644 --- a/e2e/react-router/issue-7457/src/routeTree.gen.ts +++ b/e2e/react-router/issue-7457/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 AnotherRouteImport } from './routes/another' import { Route as IndexRouteImport } from './routes/index' +import { Route as AnotherRouteImport } from './routes/another' -const AnotherRoute = AnotherRouteImport.update({ - id: '/another', - path: '/another', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AnotherRoute = AnotherRouteImport.update({ + id: '/another', + path: '/another', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/another': { - id: '/another' - path: '/another' - fullPath: '/another' - preLoaderRoute: typeof AnotherRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/another': { + id: '/another' + path: '/another' + fullPath: '/another' + preLoaderRoute: typeof AnotherRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/e2e/react-router/js-only-file-based/package.json b/e2e/react-router/js-only-file-based/package.json index d18d4da143..39742d9c84 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -16,7 +16,7 @@ "@tanstack/react-router-devtools": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2" }, "devDependencies": { 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 4f93bc1413..0925936d55 100644 --- a/e2e/react-router/js-only-file-based/playwright.config.ts +++ b/e2e/react-router/js-only-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -18,18 +13,15 @@ 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_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, 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 979e5e381c..36c1c281f6 100644 --- a/e2e/react-router/js-only-file-based/src/posts.js +++ b/e2e/react-router/js-only-file-based/src/posts.js @@ -2,11 +2,7 @@ import axios from 'redaxios' export class NotFoundError extends Error {} -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 5a83a314f2..ced5ac9310 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,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/js-only-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/js-only-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 3282e5e5c2..908be67a9d 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "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 246cf40060..9e8c1fab2b 100644 --- a/e2e/react-router/match-params/playwright.config.ts +++ b/e2e/react-router/match-params/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -14,8 +13,8 @@ export default defineConfig({ }, webServer: { command: `pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, projects: [ diff --git a/e2e/react-router/react-compiler/package.json b/e2e/react-router/react-compiler/package.json index d4d0e6473a..82e6fbf86b 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "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 61a995a815..a8ba116fb4 100644 --- a/e2e/react-router/react-compiler/playwright.config.ts +++ b/e2e/react-router/react-compiler/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -12,8 +11,8 @@ export default defineConfig({ use: { baseURL }, webServer: { command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm dev:e2e --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, 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 455ff94779..5ec9ed9862 100644 --- a/e2e/react-router/rspack-basic-file-based/package.json +++ b/e2e/react-router/rspack-basic-file-based/package.json @@ -7,18 +7,18 @@ "build": "rsbuild build && tsc --noEmit", "preview": "rsbuild preview", "start": "rsbuild preview", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1" + "redaxios": "catalog:" }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.1.0", + "@rsbuild/core": "^2.3.1", "@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 decceaef2f..4eead86444 100644 --- a/e2e/react-router/rspack-basic-file-based/playwright.config.ts +++ b/e2e/react-router/rspack-basic-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ 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: `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, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, 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 a1225b7fe7..97c96d77eb 100644 --- a/e2e/react-router/rspack-basic-file-based/src/posts.tsx +++ b/e2e/react-router/rspack-basic-file-based/src/posts.tsx @@ -7,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.PUBLIC_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.PUBLIC_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 10beff655f..d230263bfe 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,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/rspack-basic-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/rspack-basic-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 28d3e9b302..30c62d0af1 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,18 +7,18 @@ "build": "rsbuild build && tsc --noEmit", "preview": "rsbuild preview", "start": "rsbuild preview", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1" + "redaxios": "catalog:" }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.1.0", + "@rsbuild/core": "^2.3.1", "@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 bf3adc082c..1c1d021f2f 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,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ 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: `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, + command: `pnpm build && pnpm start --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, 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 b196982420..cc3cb0f9c8 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,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.PUBLIC_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.PUBLIC_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 a689f459e3..8b808782f6 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,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 a7fc908019..51e9e70cc5 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": "rm -rf port*.txt; pnpm run test:e2e:browser && pnpm run test:e2e:hash" + "test:e2e": "pnpm run test:e2e:browser && pnpm run test:e2e:hash" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -20,7 +20,7 @@ "@tanstack/router-plugin": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, @@ -31,5 +31,15 @@ "@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 972124647c..eb31d94080 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,15 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, - resolveRuntimeSuffix, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort( - packageJson.name + `-${resolveRuntimeSuffix('browser')}`, -) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -21,18 +13,15 @@ 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_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, + command: `VITE_APP_HISTORY=browser pnpm build && VITE_APP_HISTORY=browser pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, 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 a6fa77afbf..6b160e3908 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,15 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, - resolveRuntimeSuffix, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort( - packageJson.name + `-${resolveRuntimeSuffix('hash')}`, -) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -21,18 +13,15 @@ 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_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, + 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, 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 e45ef52969..c4a2d0dcca 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/src/posts.tsx +++ b/e2e/react-router/scroll-restoration-sandbox-vite/src/posts.tsx @@ -10,11 +10,7 @@ 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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 9c2d944dd5..e396c28686 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,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 db335f8e2e..2db25517c8 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,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' import type { Page } from '@playwright/test' import { toRuntimePath } from '@tanstack/router-e2e-utils' @@ -26,7 +27,7 @@ type ReproAttempt = { async function openFreshSourcePage(page: Page) { await page.goto(toRuntimePath('/issue-7040-source')) - await page.waitForLoadState('networkidle') + await expect(page.getByTestId('issue-7040-source-top')).toBeVisible() await page.evaluate(() => { sessionStorage.clear() @@ -34,7 +35,7 @@ async function openFreshSourcePage(page: Page) { }) await page.reload() - await page.waitForLoadState('networkidle') + await expect(page.getByTestId('issue-7040-source-top')).toBeVisible() } async function fastScrollSourcePage(page: Page) { @@ -96,7 +97,7 @@ async function clickTargetLinkImmediatelyAfterScroll(page: Page) { async function waitForTargetPageToSettle(page: Page) { await page.waitForURL('**/issue-7040-target') - await page.waitForLoadState('networkidle') + await expect(page.getByTestId('issue-7040-target-top')).toBeVisible() 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 f33b5a7aa3..5d58406b2e 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"] + "exclude": ["node_modules", "dist", "dist-hash"] } diff --git a/e2e/react-router/sentry-integration/package.json b/e2e/react-router/sentry-integration/package.json index e275758b83..5ebbdf31d9 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@sentry/react": "^10.32.0", @@ -19,7 +19,7 @@ "@tanstack/react-router-devtools": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2" }, "devDependencies": { diff --git a/e2e/react-router/sentry-integration/playwright.config.ts b/e2e/react-router/sentry-integration/playwright.config.ts index 0c5cee43e4..6a684ac89e 100644 --- a/e2e/react-router/sentry-integration/playwright.config.ts +++ b/e2e/react-router/sentry-integration/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-router/view-transitions/package.json b/e2e/react-router/view-transitions/package.json index ac949c2d7c..e2d7a181e1 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -17,7 +17,7 @@ "@tanstack/router-plugin": "workspace:^", "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/e2e/react-router/view-transitions/playwright.config.ts b/e2e/react-router/view-transitions/playwright.config.ts index c5de6b5611..4eead86444 100644 --- a/e2e/react-router/view-transitions/playwright.config.ts +++ b/e2e/react-router/view-transitions/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -22,13 +17,10 @@ export default defineConfig({ baseURL, }, - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - webServer: { - 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, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, 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 472bd6ed0b..6c1ccf1a6e 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 { test } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/view-transitions/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/view-transitions/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 52a5c12d50..f7ff609e76 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; rm -rf port*.txt; pnpm run prisma-generate && playwright test --project=chromium" + "test:e2e": "exit 0; pnpm run prisma-generate && playwright test --project=chromium" }, "dependencies": { "@libsql/client": "^0.15.15", @@ -19,9 +19,10 @@ "@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": "^0.5.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0" }, "devDependencies": { diff --git a/e2e/react-start/basic-auth/playwright.config.ts b/e2e/react-start/basic-auth/playwright.config.ts index 18b8905468..82678ac00b 100644 --- a/e2e/react-start/basic-auth/playwright.config.ts +++ b/e2e/react-start/basic-auth/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, 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 76e5f8b1d6..fb7868435d 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 { useAppSession } from '~/utils/session.js' +import { getAppSession } 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 useAppSession() + const session = await getAppSession() - if (!session.data.userEmail) { + if (!session.userEmail) { return null } return { - email: session.data.userEmail, + email: session.userEmail, } }) diff --git a/e2e/react-start/basic-auth/src/routes/_authed.tsx b/e2e/react-start/basic-auth/src/routes/_authed.tsx index c457cf5e57..fe73185136 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 { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' export const loginFn = createServerFn({ method: 'POST', @@ -37,12 +37,11 @@ export const loginFn = createServerFn({ } // Create a session - const session = await useAppSession() + const session = await getAppSession() // Store the user's email in the session - await session.update({ - userEmail: user.email, - }) + session.userEmail = user.email + await session.save() }) export const Route = createFileRoute('/_authed')({ @@ -52,7 +51,7 @@ export const Route = createFileRoute('/_authed')({ } }, errorComponent: ({ error }) => { - if (error.message === 'Not authenticated') { + if (error instanceof Error && error.message === 'Not authenticated') { return } diff --git a/e2e/react-start/basic-auth/src/routes/logout.tsx b/e2e/react-start/basic-auth/src/routes/logout.tsx index a08f9c737e..0f86b0d4e3 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 { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await useAppSession() + const session = await getAppSession() - session.clear() + session.destroy() 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 817362dc05..d7d5d40129 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 { useAppSession } from '~/utils/session' +import { getAppSession } 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 useAppSession() + const session = await getAppSession() if (found) { if (found.password !== password) { @@ -36,9 +36,8 @@ export const signupFn = createServerFn({ } // Store the user's email in the session - await session.update({ - userEmail: found.email, - }) + session.userEmail = found.email + await session.save() // Redirect to the prev page stored in the "redirect" search param throw redirect({ @@ -55,9 +54,8 @@ export const signupFn = createServerFn({ }) // Store the user's email in the session - await session.update({ - userEmail: user.email, - }) + session.userEmail = user.email + await session.save() // 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 c38bac1e48..f1deacf85b 100644 --- a/e2e/react-start/basic-auth/src/utils/session.ts +++ b/e2e/react-start/basic-auth/src/utils/session.ts @@ -1,13 +1,25 @@ -// src/services/session.server.ts -import { useSession } from '@tanstack/react-start/server' +import { getIronSession } from 'iron-session' +import { getCookie, setCookie } from '@tanstack/react-start/server' import type { User } from '@prisma/client' type SessionUser = { userEmail: User['email'] } -export function useAppSession() { - return useSession({ - password: 'ChangeThisBeforeShippingToProdOrYouWillBeFired', - }) +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: '/', + }, + }, + ) } diff --git a/e2e/react-start/basic-cloudflare/package.json b/e2e/react-start/basic-cloudflare/package.json index 7baa24073b..b9b8031ac4 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -33,5 +33,15 @@ "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 a545dff891..0925936d55 100644 --- a/e2e/react-start/basic-cloudflare/playwright.config.ts +++ b/e2e/react-start/basic-cloudflare/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -14,9 +13,6 @@ 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, @@ -24,8 +20,8 @@ export default defineConfig({ webServer: { command: `pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, 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 add28cb73e..c9497070dd 100644 --- a/e2e/react-start/basic-cloudflare/tests/app.spec.ts +++ b/e2e/react-start/basic-cloudflare/tests/app.spec.ts @@ -1,3 +1,5 @@ +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' @@ -29,3 +31,19 @@ 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-start/basic-cloudflare/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-start/basic-cloudflare/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 ed7328f336..ee37b82ba6 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-query": "^5.90.0", @@ -20,7 +20,7 @@ "@tanstack/react-start": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0", "zod": "^4.4.3" }, @@ -32,7 +32,7 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "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 fd2150e435..216fade4d5 100644 --- a/e2e/react-start/basic-react-query/playwright.config.ts +++ b/e2e/react-start/basic-react-query/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -18,19 +13,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: `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, + command: `pnpm build && PORT=${PORT} pnpm start`, + wait: appServerReady, + reuseExistingServer: false, 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 bb37c6e68d..924c5b6860 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,11 +2,7 @@ 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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 e11e039652..febea309ea 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,11 +2,7 @@ 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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 3fd16db69a..abb6e95b92 100644 --- a/e2e/react-start/basic-react-query/src/utils/posts.tsx +++ b/e2e/react-start/basic-react-query/src/utils/posts.tsx @@ -9,11 +9,7 @@ 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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 26b934fcb3..15216680e9 100644 --- a/e2e/react-start/basic-react-query/src/utils/users.tsx +++ b/e2e/react-start/basic-react-query/src/utils/users.tsx @@ -1,4 +1,6 @@ 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 = { @@ -7,17 +9,16 @@ export type User = { email: string } -const PORT = - import.meta.env.VITE_SERVER_PORT || process.env.VITE_SERVER_PORT || 3000 - -export const DEPLOY_URL = `http://localhost:${PORT}` +const getOrigin = createIsomorphicFn() + .server(() => getRequestUrl().origin) + .client(() => window.location.origin) export const usersQueryOptions = () => queryOptions({ queryKey: ['users'], queryFn: () => axios - .get>(DEPLOY_URL + '/api/users') + .get>(getOrigin() + '/api/users') .then((r) => r.data) .catch(() => { throw new Error('Failed to fetch users') @@ -29,7 +30,7 @@ export const userQueryOptions = (id: string) => queryKey: ['users', id], queryFn: () => axios - .get(DEPLOY_URL + '/api/users/' + id) + .get(getOrigin() + '/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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-start/basic-react-query/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-start/basic-react-query/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 61f11c2372..99e681ac9d 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -21,9 +21,10 @@ "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "vite": "^8.0.14", + "rimraf": "catalog:" } } diff --git a/e2e/react-start/basic-tsr-config/playwright.config.ts b/e2e/react-start/basic-tsr-config/playwright.config.ts index 18b8905468..82678ac00b 100644 --- a/e2e/react-start/basic-tsr-config/playwright.config.ts +++ b/e2e/react-start/basic-tsr-config/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-start/basic/package.json b/e2e/react-start/basic/package.json index 9bd494b835..3a1a4ea9c8 100644 --- a/e2e/react-start/basic/package.json +++ b/e2e/react-start/basic/package.json @@ -14,8 +14,6 @@ "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": { @@ -24,15 +22,16 @@ "@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", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0" }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.1.0", + "@rsbuild/core": "^2.3.1", "@rsbuild/plugin-react": "^2.0.0", "@tailwindcss/postcss": "^4.2.2", "@tailwindcss/vite": "^4.2.2", @@ -43,7 +42,7 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "combinate": "^1.1.11", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", @@ -51,6 +50,18 @@ "zod": "^4.4.3" }, "nx": { + "targets": { + "test:e2e--vite-spa--dev": { + "dependsOn": [ + "^build" + ] + }, + "test:e2e--rsbuild-spa--dev": { + "dependsOn": [ + "^build" + ] + } + }, "metadata": { "playwrightModes": [ { @@ -63,7 +74,18 @@ }, { "toolchain": "vite", - "mode": "prerender" + "mode": "spa", + "name": "dev", + "env": { + "E2E_DEV_SERVER": "true" + } + }, + { + "toolchain": "vite", + "mode": "prerender", + "env": { + "NODE_OPTIONS": "--import=@tanstack/router-e2e-utils/mock-api" + } }, { "toolchain": "vite", @@ -87,7 +109,18 @@ }, { "toolchain": "rsbuild", - "mode": "prerender" + "mode": "spa", + "name": "dev", + "env": { + "E2E_DEV_SERVER": "true" + } + }, + { + "toolchain": "rsbuild", + "mode": "prerender", + "env": { + "NODE_OPTIONS": "--import=@tanstack/router-e2e-utils/mock-api" + } }, { "toolchain": "rsbuild", diff --git a/e2e/react-start/basic/playwright.config.ts b/e2e/react-start/basic/playwright.config.ts index db07d18608..bb4c2cb761 100644 --- a/e2e/react-start/basic/playwright.config.ts +++ b/e2e/react-start/basic/playwright.config.ts @@ -1,48 +1,42 @@ -import fs from 'node:fs' import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' 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' -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 PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` const previewCommand = toolchain === 'rsbuild' - ? `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` + ? `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' /** * 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, @@ -50,19 +44,16 @@ export default defineConfig({ webServer: { command: commandByMode, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', env: { + NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, MODE: mode, E2E_TOOLCHAIN: toolchain, - VITE_NODE_ENV: 'test', - VITE_EXTERNAL_PORT: String(EXTERNAL_PORT), - VITE_SERVER_PORT: String(PORT), - START_PORT: String(START_PORT), + START_PORT: '0', 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/rsbuild.config.ts b/e2e/react-start/basic/rsbuild.config.ts index d6a9c035eb..23072b6c1b 100644 --- a/e2e/react-start/basic/rsbuild.config.ts +++ b/e2e/react-start/basic/rsbuild.config.ts @@ -7,10 +7,7 @@ const outDir = process.env.E2E_DIST_DIR ?? 'dist' const startModeConfig = getStartModeConfig() export default defineConfig({ - plugins: [ - pluginReact({ splitChunks: false }), - tanstackStart(startModeConfig), - ], + plugins: [pluginReact(), tanstackStart(startModeConfig)], output: { distPath: { root: outDir, diff --git a/e2e/react-start/basic/server.js b/e2e/react-start/basic/server.js index 69c1e4ca91..3e1ddab400 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 = process.env.PORT || 3000 +const port = Number(process.env.PORT ?? 3000) -const startPort = process.env.START_PORT || 3001 +const startPort = Number(process.env.START_PORT ?? 0) 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() { +export async function createSpaServer(backendPort) { const app = express() app.use( '/api', createProxyMiddleware({ - target: `http://localhost:${startPort}/api`, // Replace with your target server's URL + target: `http://localhost:${backendPort}/api`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) @@ -63,7 +63,7 @@ export async function createSpaServer() { app.use( '/_serverFn', createProxyMiddleware({ - target: `http://localhost:${startPort}/_serverFn`, // Replace with your target server's URL + target: `http://localhost:${backendPort}/_serverFn`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) @@ -71,31 +71,28 @@ export async function createSpaServer() { app.use(express.static(distClientDir)) app.get('/{*splat}', (req, res) => { - res.sendFile(path.resolve(distClientDir, 'index.html')) + res.sendFile('index.html', { root: distClientDir }) }) return { app } } -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}`) - }), - ) -} +// 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}`) + } +}) diff --git a/e2e/react-start/basic/src/routeTree.gen.ts b/e2e/react-start/basic/src/routeTree.gen.ts index ea09864d8e..b6603dd01d 100644 --- a/e2e/react-start/basic/src/routeTree.gen.ts +++ b/e2e/react-start/basic/src/routeTree.gen.ts @@ -12,8 +12,11 @@ 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' @@ -29,6 +32,7 @@ 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' @@ -96,6 +100,11 @@ 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', @@ -106,6 +115,16 @@ 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', @@ -181,6 +200,11 @@ 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', @@ -464,8 +488,11 @@ 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 @@ -480,6 +507,7 @@ 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 @@ -534,8 +562,11 @@ 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 @@ -545,6 +576,7 @@ 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 @@ -601,8 +633,11 @@ 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 @@ -618,6 +653,7 @@ 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 @@ -676,8 +712,11 @@ export interface FileRouteTypes { | '/search-params' | '/specialChars' | '/async-scripts' + | '/auth-docs' | '/client-only' | '/deferred' + | '/execution-local' + | '/execution-rpc' | '/inline-scripts' | '/links' | '/plain-ts-type-assertion' @@ -692,6 +731,7 @@ 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' @@ -746,8 +786,11 @@ export interface FileRouteTypes { | '/' | '/specialChars' | '/async-scripts' + | '/auth-docs' | '/client-only' | '/deferred' + | '/execution-local' + | '/execution-rpc' | '/inline-scripts' | '/links' | '/plain-ts-type-assertion' @@ -757,6 +800,7 @@ export interface FileRouteTypes { | '/type-only-reexport' | '/specialChars/malformed' | '/api/users' + | '/auth-docs/private' | '/issue-6221/dashboard' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' @@ -812,8 +856,11 @@ export interface FileRouteTypes { | '/specialChars' | '/_layout' | '/async-scripts' + | '/auth-docs' | '/client-only' | '/deferred' + | '/execution-local' + | '/execution-rpc' | '/inline-scripts' | '/links' | '/plain-ts-type-assertion' @@ -829,6 +876,7 @@ export interface FileRouteTypes { | '/specialChars/malformed' | '/_layout/_layout-2' | '/api/users' + | '/auth-docs/private' | '/issue-6221/dashboard' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' @@ -887,8 +935,11 @@ 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 @@ -933,6 +984,13 @@ 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' @@ -947,6 +1005,20 @@ 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' @@ -1052,6 +1124,13 @@ 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' @@ -1570,6 +1649,18 @@ 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 @@ -1675,8 +1766,11 @@ 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 d8fc0d3b24..ed521817d6 100644 --- a/e2e/react-start/basic/src/routes/__root.tsx +++ b/e2e/react-start/basic/src/routes/__root.tsx @@ -197,6 +197,9 @@ function RootDocument({ children }: { children: React.ReactNode }) { > Client Only {' '} + + Server function loader + {' '} { console.info('Fetching users... @', request.url) - const res = await axios.get>(`${queryURL}/users`) + const res = await axios.get>( + 'https://jsonplaceholder.typicode.com/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 ac665381f1..797dffb637 100644 --- a/e2e/react-start/basic/src/routes/api/users.$id.ts +++ b/e2e/react-start/basic/src/routes/api/users.$id.ts @@ -2,19 +2,15 @@ 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(`${queryURL}/users/` + params.id) + const res = await axios.get( + `https://jsonplaceholder.typicode.com/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 new file mode 100644 index 0000000000..85fc8a0fc9 --- /dev/null +++ b/e2e/react-start/basic/src/routes/auth-docs.private.tsx @@ -0,0 +1,17 @@ +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 new file mode 100644 index 0000000000..6ea1b813ef --- /dev/null +++ b/e2e/react-start/basic/src/routes/auth-docs.tsx @@ -0,0 +1,100 @@ +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 new file mode 100644 index 0000000000..477cd81740 --- /dev/null +++ b/e2e/react-start/basic/src/routes/execution-local.tsx @@ -0,0 +1,16 @@ +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 new file mode 100644 index 0000000000..f934015522 --- /dev/null +++ b/e2e/react-start/basic/src/routes/execution-rpc.tsx @@ -0,0 +1,18 @@ +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 new file mode 100644 index 0000000000..22b36ee808 --- /dev/null +++ b/e2e/react-start/basic/src/utils/auth-docs.ts @@ -0,0 +1,60 @@ +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 new file mode 100644 index 0000000000..97e66573d8 --- /dev/null +++ b/e2e/react-start/basic/src/utils/execution-functions.ts @@ -0,0 +1,5 @@ +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 4cc5dcc4c6..9fdff27673 100644 --- a/e2e/react-start/basic/src/utils/posts.tsx +++ b/e2e/react-start/basic/src/utils/posts.tsx @@ -8,18 +8,12 @@ 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(`${queryURL}/posts/${postId}`) + .get(`https://jsonplaceholder.typicode.com/posts/${postId}`) .then((r) => r.data) .catch((err) => { console.error(err) @@ -36,7 +30,7 @@ export const fetchPosts = createServerFn({ method: 'GET' }).handler( async () => { console.info('Fetching posts...') return axios - .get>(`${queryURL}/posts`) + .get>('https://jsonplaceholder.typicode.com/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 46be4b1580..7ba645b383 100644 --- a/e2e/react-start/basic/src/utils/users.tsx +++ b/e2e/react-start/basic/src/utils/users.tsx @@ -3,7 +3,3 @@ 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 new file mode 100644 index 0000000000..47a57c9da2 --- /dev/null +++ b/e2e/react-start/basic/tests/auth-docs.spec.ts @@ -0,0 +1,89 @@ +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 a3b6f99442..299744f636 100644 --- a/e2e/react-start/basic/tests/client-only.spec.ts +++ b/e2e/react-start/basic/tests/client-only.spec.ts @@ -1,5 +1,6 @@ import { expect } from '@playwright/test' import { test } from '@tanstack/router-e2e-utils' +import { isSpaMode } from './utils/isSpaMode' /** * These tests verify the compiler optimization. @@ -15,7 +16,15 @@ import { test } from '@tanstack/router-e2e-utils' 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 new file mode 100644 index 0000000000..410b1d999e --- /dev/null +++ b/e2e/react-start/basic/tests/environment-functions.spec.ts @@ -0,0 +1,46 @@ +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 new file mode 100644 index 0000000000..6c9b26dc4c --- /dev/null +++ b/e2e/react-start/basic/tests/fixture-api.spec.ts @@ -0,0 +1,11 @@ +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 34ba7b6ea9..010ecec155 100644 --- a/e2e/react-start/basic/tests/redirect.spec.ts +++ b/e2e/react-start/basic/tests/redirect.spec.ts @@ -1,20 +1,15 @@ import queryString from 'node:querystring' -import { expect, type Page } from '@playwright/test' +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' import combinateImport from 'combinate' -import { - getDummyServerPort, - getTestServerPort, - test, -} from '@tanstack/router-e2e-utils' -import { getE2EPortKey } from './utils/getE2EPortKey.ts' +import type { Page } from '@playwright/test' // somehow playwright does not correctly import default exports const combinate = (combinateImport as any).default as typeof combinateImport -const e2ePortKey = getE2EPortKey() -const PORT = await getTestServerPort(e2ePortKey) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) -const EXTERNAL_HOST_PORT = await getDummyServerPort(e2ePortKey) +const EXTERNAL_ORIGIN = `http://127.0.0.1:${PORT}` const POSTS_URL = `http://localhost:${PORT}/posts` async function waitForRouterIdle(page: Page) { @@ -111,7 +106,7 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, + externalHost: `${EXTERNAL_ORIGIN}/`, }) if (scenario === 'navigate') { @@ -124,7 +119,7 @@ test.describe('redirects', () => { await page.goto(`/redirect/external/via-${thrower}?${q}`) } - const url = `http://localhost:${EXTERNAL_HOST_PORT}/` + const url = `${EXTERNAL_ORIGIN}/` await page.waitForURL(url) expect(page.url()).toBe(url) @@ -147,7 +142,7 @@ test.describe('redirects', () => { }) => { let fullPageLoad = false const q = queryString.stringify({ - externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, + externalHost: `${EXTERNAL_ORIGIN}/`, reloadDocument, }) @@ -170,10 +165,7 @@ test.describe('redirects', () => { await page.goto(`/redirect/${target}/serverFn/via-${thrower}?${q}`) } - const url = - target === 'internal' - ? POSTS_URL - : `http://localhost:${EXTERNAL_HOST_PORT}/` + const url = target === 'internal' ? POSTS_URL : `${EXTERNAL_ORIGIN}/` await page.waitForURL(url) @@ -202,7 +194,7 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, + externalHost: `${EXTERNAL_ORIGIN}/`, reloadDocument, }) @@ -219,10 +211,7 @@ test.describe('redirects', () => { await button.click() - const url = - target === 'internal' - ? POSTS_URL - : `http://localhost:${EXTERNAL_HOST_PORT}/` + const url = target === 'internal' ? POSTS_URL : `${EXTERNAL_ORIGIN}/` 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 new file mode 100644 index 0000000000..d16ff0bb54 --- /dev/null +++ b/e2e/react-start/basic/tests/setup/dev-server.setup.ts @@ -0,0 +1,19 @@ +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 deleted file mode 100644 index cd38c35885..0000000000 --- a/e2e/react-start/basic/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 36e5c92858..0000000000 --- a/e2e/react-start/basic/tests/setup/global.teardown.ts +++ /dev/null @@ -1,8 +0,0 @@ -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 deleted file mode 100644 index 88c18fd79e..0000000000 --- a/e2e/react-start/basic/tests/setup/waitForDummyServer.ts +++ /dev/null @@ -1,24 +0,0 @@ -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 new file mode 100644 index 0000000000..f42195e762 --- /dev/null +++ b/e2e/react-start/basic/tests/spa-shell.spec.ts @@ -0,0 +1,53 @@ +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 deleted file mode 100644 index 48be6a9027..0000000000 --- a/e2e/react-start/basic/tests/utils/getE2EPortKey.ts +++ /dev/null @@ -1,5 +0,0 @@ -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 1fb9714180..7838b4cee1 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; rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "exit 0; playwright test --project=chromium" }, "dependencies": { "@clerk/tanstack-react-start": "^0.19.0", @@ -17,7 +17,7 @@ "@tanstack/react-start": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0" }, "devDependencies": { diff --git a/e2e/react-start/clerk-basic/playwright.config.ts b/e2e/react-start/clerk-basic/playwright.config.ts index 18b8905468..82678ac00b 100644 --- a/e2e/react-start/clerk-basic/playwright.config.ts +++ b/e2e/react-start/clerk-basic/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-start/clerk-basic/src/routes/_authed.tsx b/e2e/react-start/clerk-basic/src/routes/_authed.tsx index 226ae0829f..440d0e3f3c 100644 --- a/e2e/react-start/clerk-basic/src/routes/_authed.tsx +++ b/e2e/react-start/clerk-basic/src/routes/_authed.tsx @@ -8,7 +8,7 @@ export const Route = createFileRoute('/_authed')({ } }, errorComponent: ({ error }) => { - if (error.message === 'Not authenticated') { + if (error instanceof Error && error.message === 'Not authenticated') { return (
diff --git a/e2e/react-start/csp/package.json b/e2e/react-start/csp/package.json index bbe4df9bbc..fd8987bcef 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "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": "^0.11.9", + "srvx": "^1.0.0", "@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 5f9de5709e..87b32e1f50 100644 --- a/e2e/react-start/csp/playwright.config.ts +++ b/e2e/react-start/csp/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -21,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-start/css-inline/package.json b/e2e/react-start/css-inline/package.json index 7d9c0520fc..6c5dd031c6 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": "^0.11.9" + "srvx": "^1.0.0" }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.1.0", + "@rsbuild/core": "^2.3.1", "@rsbuild/plugin-react": "^2.0.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", @@ -38,7 +38,47 @@ "nx": { "targets": { "test:e2e": { - "parallelism": false + "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" + ] } }, "metadata": { diff --git a/e2e/react-start/css-inline/playwright.config.ts b/e2e/react-start/css-inline/playwright.config.ts index b5d78f3608..78e7b75252 100644 --- a/e2e/react-start/css-inline/playwright.config.ts +++ b/e2e/react-start/css-inline/playwright.config.ts @@ -1,7 +1,5 @@ -import fs from 'node:fs' import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' const inlineCssTransformAssets = @@ -18,15 +16,8 @@ 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}` -if (process.env.TEST_WORKER_INDEX === undefined) { - fs.rmSync(`port-${e2ePortKey}.txt`, { force: true }) -} - -const PORT = await getTestServerPort(e2ePortKey) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -40,8 +31,8 @@ export default defineConfig({ webServer: { command: `pnpm build:${toolchain} && pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', env: { E2E_DIST_DIR: distDir, diff --git a/e2e/react-start/css-inline/rsbuild.config.ts b/e2e/react-start/css-inline/rsbuild.config.ts index 2fd1208250..8957fc9a06 100644 --- a/e2e/react-start/css-inline/rsbuild.config.ts +++ b/e2e/react-start/css-inline/rsbuild.config.ts @@ -8,7 +8,7 @@ const transformInlineCssAssets = export default defineConfig({ plugins: [ - pluginReact({ splitChunks: false }), + pluginReact(), tanstackStart({ server: { build: { diff --git a/e2e/react-start/css-inline/server.js b/e2e/react-start/css-inline/server.js index fcdec3b888..27b2357284 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 = process.env.PORT || 3000 +const port = Number(process.env.PORT ?? 3000) const distDir = process.env.E2E_DIST_DIR || 'dist-vite-ssr' const distClientDir = path.resolve(distDir, 'client') @@ -37,8 +37,10 @@ async function createStartServer() { } createStartServer().then((app) => { - app.listen(port, (error) => { - if (error) throw error - console.info(`Start Server: http://localhost:${port}`) + const httpServer = app.listen(port, (error) => { + if (error) { + throw error + } + console.info(`E2E app: http://localhost:${httpServer.address().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 a796656b3d..35205cc9cf 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,6 +3,9 @@ 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 339fedd4ca..89d7d3992f 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 { test } from '@tanstack/router-e2e-utils' +import { collectBrowserErrors, test } from '@tanstack/router-e2e-utils' const buildUrl = (baseURL: string, pathname: string) => baseURL.replace(/\/$/, '') + pathname @@ -151,6 +151,23 @@ 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)) @@ -161,6 +178,28 @@ 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 @@ -170,3 +209,45 @@ 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 229709a89d..a1fbca128d 100644 --- a/e2e/react-start/css-modules/.gitignore +++ b/e2e/react-start/css-modules/.gitignore @@ -3,3 +3,4 @@ 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 new file mode 100644 index 0000000000..e2bd5e13f1 --- /dev/null +++ b/e2e/react-start/css-modules/cloudflare.config.ts @@ -0,0 +1,11 @@ +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 2591161d66..25c11d7321 100644 --- a/e2e/react-start/css-modules/package.json +++ b/e2e/react-start/css-modules/package.json @@ -12,6 +12,8 @@ "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", @@ -19,13 +21,16 @@ "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": "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" + "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" }, "dependencies": { "@tanstack/react-router": "workspace:*", @@ -36,17 +41,36 @@ "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", - "@vitejs/plugin-react": "^6.0.1", - "nitro": "^3.0.260311-beta", - "sass": "^1.97.2", - "srvx": "^0.11.9", "@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", + "sass": "^1.97.2", + "srvx": "^1.0.0", "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 644798ca99..7e7ad3d9b3 100644 --- a/e2e/react-start/css-modules/playwright.config.ts +++ b/e2e/react-start/css-modules/playwright.config.ts @@ -1,37 +1,41 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' 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 = await getTestServerPort( - viteConfig ? `${packageJson.name}-${viteConfig}` : packageJson.name, -) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) // 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' +const devCommand = viteConfig + ? `pnpm dev:e2e:${viteConfig}` + : 'pnpm dev:e2e --port 0' 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 : `pnpm build && PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + 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, 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 new file mode 100644 index 0000000000..499ed67ebc --- /dev/null +++ b/e2e/react-start/css-modules/rsbuild.config.ts @@ -0,0 +1,63 @@ +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 new file mode 100644 index 0000000000..e6878a5410 --- /dev/null +++ b/e2e/react-start/css-modules/src/components/Header.module.css @@ -0,0 +1,14 @@ +.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 new file mode 100644 index 0000000000..f16b12e8ff --- /dev/null +++ b/e2e/react-start/css-modules/src/components/Header.tsx @@ -0,0 +1,11 @@ +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 822118990d..2789a3490a 100644 --- a/e2e/react-start/css-modules/src/routeTree.gen.ts +++ b/e2e/react-start/css-modules/src/routeTree.gen.ts @@ -10,6 +10,9 @@ 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' @@ -19,6 +22,21 @@ 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', @@ -37,12 +55,18 @@ 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 @@ -50,20 +74,36 @@ 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: '/' | '/modules' | '/quotes' | '/sass-mixin' + fullPaths: + '/' | '/alpha' | '/beta' | '/gamma' | '/modules' | '/quotes' | '/sass-mixin' fileRoutesByTo: FileRoutesByTo - to: '/' | '/modules' | '/quotes' | '/sass-mixin' - id: '__root__' | '/' | '/modules' | '/quotes' | '/sass-mixin' + to: + '/' | '/alpha' | '/beta' | '/gamma' | '/modules' | '/quotes' | '/sass-mixin' + id: + | '__root__' + | '/' + | '/alpha' + | '/beta' + | '/gamma' + | '/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 @@ -78,6 +118,27 @@ 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' @@ -104,6 +165,9 @@ 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 new file mode 100644 index 0000000000..e894cd758f --- /dev/null +++ b/e2e/react-start/css-modules/src/routes/alpha.tsx @@ -0,0 +1,13 @@ +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 new file mode 100644 index 0000000000..4f139ac41a --- /dev/null +++ b/e2e/react-start/css-modules/src/routes/beta.tsx @@ -0,0 +1,13 @@ +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 new file mode 100644 index 0000000000..a8e036b85f --- /dev/null +++ b/e2e/react-start/css-modules/src/routes/gamma.tsx @@ -0,0 +1,8 @@ +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 new file mode 100644 index 0000000000..12a606a8d3 --- /dev/null +++ b/e2e/react-start/css-modules/src/styles/alpha.module.css @@ -0,0 +1,4 @@ +.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 new file mode 100644 index 0000000000..719686a76b --- /dev/null +++ b/e2e/react-start/css-modules/src/styles/beta.module.css @@ -0,0 +1,4 @@ +.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 new file mode 100644 index 0000000000..d0325ac63e --- /dev/null +++ b/e2e/react-start/css-modules/src/utils/formatTitle.ts @@ -0,0 +1,3 @@ +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 e8879c0165..7c0fce762a 100644 --- a/e2e/react-start/css-modules/tests/setup/global.setup.ts +++ b/e2e/react-start/css-modules/tests/setup/global.setup.ts @@ -1,20 +1,10 @@ -import { - e2eStartDummyServer, - getTestServerPort, - preOptimizeDevServer, - waitForServer, -} from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } +import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' 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 = await getTestServerPort( - viteConfig ? `${packageJson.name}-${viteConfig}` : packageJson.name, - ) + const port = Number(process.env.E2E_APP_PORT ?? 0) 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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-start/css-modules/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 new file mode 100644 index 0000000000..9a9595f819 --- /dev/null +++ b/e2e/react-start/css-modules/tests/shared-css.prod.spec.ts @@ -0,0 +1,94 @@ +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 9923ab3384..c9c27f7f9a 100644 --- a/e2e/react-start/css-modules/vite.config.ts +++ b/e2e/react-start/css-modules/vite.config.ts @@ -21,6 +21,7 @@ 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 1884c5eb5a..b9bf393466 100644 --- a/e2e/react-start/custom-basepath/express-server.ts +++ b/e2e/react-start/custom-basepath/express-server.ts @@ -1,5 +1,6 @@ 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' @@ -40,7 +41,11 @@ if (DEVELOPMENT) { }) } -app.listen(PORT, (error) => { - if (error) throw error - console.log(`Server is running on http://localhost:${PORT}`) +const httpServer = app.listen(PORT, (error) => { + if (error) { + throw error + } + console.log( + `E2E app: http://localhost:${(httpServer.address() as AddressInfo).port}`, + ) }) diff --git a/e2e/react-start/custom-basepath/package.json b/e2e/react-start/custom-basepath/package.json index fe79b158ea..e93949eea2 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -17,7 +17,7 @@ "express": "^5.2.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1" + "redaxios": "catalog:" }, "devDependencies": { "@playwright/test": "^1.61.0", @@ -29,7 +29,7 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "cross-env": "^10.0.0", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "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 5095425f47..e113ce64ad 100644 --- a/e2e/react-start/custom-basepath/playwright.config.ts +++ b/e2e/react-start/custom-basepath/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}/custom/basepath` /** @@ -18,19 +13,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: `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, + command: `pnpm build && PORT=${PORT} pnpm start`, + wait: appServerReady, + reuseExistingServer: false, 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 9e055549ef..6fc8cde830 100644 --- a/e2e/react-start/custom-basepath/src/routes/api.users.ts +++ b/e2e/react-start/custom-basepath/src/routes/api.users.ts @@ -3,11 +3,7 @@ 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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 57682660fd..81c071afb5 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,11 +2,7 @@ import axios from 'redaxios' import type { User } from '~/utils/users' import { createFileRoute } from '@tanstack/react-router' -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 4cc5dcc4c6..d9b98a8c9c 100644 --- a/e2e/react-start/custom-basepath/src/utils/posts.tsx +++ b/e2e/react-start/custom-basepath/src/utils/posts.tsx @@ -8,11 +8,7 @@ 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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 46be4b1580..7ba645b383 100644 --- a/e2e/react-start/custom-basepath/src/utils/users.tsx +++ b/e2e/react-start/custom-basepath/src/utils/users.tsx @@ -3,7 +3,3 @@ 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-start/custom-basepath/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-start/custom-basepath/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 23784f2efc..68537956b4 100644 --- a/e2e/react-start/custom-server-rsbuild/express-server.ts +++ b/e2e/react-start/custom-server-rsbuild/express-server.ts @@ -1,5 +1,6 @@ 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' @@ -58,9 +59,13 @@ if (DEVELOPMENT) { }) const httpServer = app.listen(PORT, async (error) => { - if (error) throw error + if (error) { + throw error + } await devServer.afterListen() - console.log(`Server is running on http://localhost:${PORT}`) + console.log( + `E2E app: http://localhost:${(httpServer.address() as AddressInfo).port}`, + ) }) devServer.connectWebSocket({ server: httpServer }) } else { @@ -75,8 +80,12 @@ if (DEVELOPMENT) { next(error) } }) - app.listen(PORT, (error) => { - if (error) throw error - console.log(`Server is running on http://localhost:${PORT}`) + const httpServer = app.listen(PORT, (error) => { + if (error) { + throw error + } + console.log( + `E2E app: http://localhost:${(httpServer.address() as AddressInfo).port}`, + ) }) } diff --git a/e2e/react-start/custom-server-rsbuild/package.json b/e2e/react-start/custom-server-rsbuild/package.json index 865e424daa..1c5b3af393 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": "rm -rf port*.txt && pnpm run test:e2e:dev && pnpm run test:e2e:prod" + "test:e2e": "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.1.0", + "@rsbuild/core": "^2.3.1", "@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": "^0.11.9", + "srvx": "^1.0.0", "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 eb8b43f648..f0542500fd 100644 --- a/e2e/react-start/custom-server-rsbuild/playwright.config.ts +++ b/e2e/react-start/custom-server-rsbuild/playwright.config.ts @@ -1,11 +1,9 @@ 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 = await getTestServerPort(`${packageJson.name}-${mode}`) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -15,8 +13,8 @@ export default defineConfig({ use: { baseURL }, webServer: { command: isDev ? 'pnpm dev:e2e' : 'pnpm build && pnpm start', - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: { stdout: /E2E app: http:\/\/localhost:(?\d+)/ }, + reuseExistingServer: false, stdout: 'pipe', env: { PORT: String(PORT), diff --git a/e2e/react-start/custom-server-rsbuild/rsbuild.config.ts b/e2e/react-start/custom-server-rsbuild/rsbuild.config.ts index dec3a6d0fc..5f9aa96e16 100644 --- a/e2e/react-start/custom-server-rsbuild/rsbuild.config.ts +++ b/e2e/react-start/custom-server-rsbuild/rsbuild.config.ts @@ -28,7 +28,7 @@ import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' // explicit prefix. export default defineConfig({ plugins: [ - pluginReact({ splitChunks: false }), + pluginReact(), tanstackStart({ rsbuild: { installDevServerMiddleware: false, diff --git a/e2e/react-start/deferred-hydration/package.json b/e2e/react-start/deferred-hydration/package.json index fb8a99c8e3..5a33407435 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.1.0", + "@rsbuild/core": "^2.3.1", "@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": "^0.11.9", + "srvx": "^1.0.0", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" @@ -42,6 +42,12 @@ "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 0125792d4b..d88c59fc9d 100644 --- a/e2e/react-start/deferred-hydration/playwright.config.ts +++ b/e2e/react-start/deferred-hydration/playwright.config.ts @@ -1,12 +1,9 @@ -import fs from 'node:fs' import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' 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' @@ -14,11 +11,7 @@ const startCommand = `pnpm exec srvx --prod --dir=. -s ${distDir}/client --entry const devCommand = toolchain === 'rsbuild' ? 'pnpm dev:rsbuild' : 'pnpm dev:vite' -if (process.env.TEST_WORKER_INDEX === undefined) { - fs.rmSync(`port-${e2ePortKey}.txt`, { force: true }) -} - -const PORT = await getTestServerPort(e2ePortKey) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -26,12 +19,11 @@ 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, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', env: { E2E_DIST_DIR: distDir, @@ -40,7 +32,6 @@ 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/rsbuild.config.ts b/e2e/react-start/deferred-hydration/rsbuild.config.ts index 6279705adb..a9d1942a6f 100644 --- a/e2e/react-start/deferred-hydration/rsbuild.config.ts +++ b/e2e/react-start/deferred-hydration/rsbuild.config.ts @@ -5,7 +5,7 @@ import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' const outDir = process.env.E2E_DIST_DIR ?? 'dist-rsbuild-ssr' export default defineConfig({ - plugins: [pluginReact({ splitChunks: false }), tanstackStart()], + plugins: [pluginReact(), tanstackStart()], output: { distPath: { root: outDir, 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 1117664a14..704bbef3e2 100644 --- a/e2e/react-start/deferred-hydration/tests/setup/global.setup.ts +++ b/e2e/react-start/deferred-hydration/tests/setup/global.setup.ts @@ -1,24 +1,11 @@ -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}` -} +import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' export default async function setup() { - if (process.env.MODE !== 'dev') return + if (process.env.MODE !== 'dev') { + return + } - const e2ePortKey = getE2EPortKey() - - await e2eStartDummyServer(e2ePortKey) - - const port = await getTestServerPort(e2ePortKey) + const port = Number(process.env.E2E_APP_PORT ?? 0) 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 deleted file mode 100644 index df79f50e82..0000000000 --- a/e2e/react-start/deferred-hydration/tests/setup/global.teardown.ts +++ /dev/null @@ -1,13 +0,0 @@ -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 c9c14943d4..a5300e836e 100644 --- a/e2e/react-start/dev-ssr-styles/package.json +++ b/e2e/react-start/dev-ssr-styles/package.json @@ -22,13 +22,9 @@ "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: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" + "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" }, "dependencies": { "@tanstack/react-router": "workspace:*", @@ -44,8 +40,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "nitro": "^3.0.260311-beta", - "srvx": "^0.11.9", + "nitro": "^3.0.260903-beta", + "srvx": "^1.0.0", "@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 a1fdd7c3ef..71cc8ed2da 100644 --- a/e2e/react-start/dev-ssr-styles/playwright.config.ts +++ b/e2e/react-start/dev-ssr-styles/playwright.config.ts @@ -1,6 +1,5 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' import { ssrStylesMode, useNitro, viteBundledDev } from './env' const mode = process.env.MODE ?? 'prod' @@ -9,24 +8,13 @@ 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 = await getTestServerPort(getPortKey()) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) 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') { @@ -44,7 +32,6 @@ export default defineConfig({ reporter: [['line']], globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', use: { baseURL, @@ -52,8 +39,8 @@ export default defineConfig({ webServer: { command: isDev ? getDevCommand() : `pnpm build && PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, 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 new file mode 100644 index 0000000000..49d2f96c39 --- /dev/null +++ b/e2e/react-start/dev-ssr-styles/src/components/CodeSplitStyledBox.tsx @@ -0,0 +1,9 @@ +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 dceedffdc1..96c0a37142 100644 --- a/e2e/react-start/dev-ssr-styles/src/routeTree.gen.ts +++ b/e2e/react-start/dev-ssr-styles/src/routeTree.gen.ts @@ -10,33 +10,63 @@ 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: '/' + fullPaths: '/' | '/css-import-order' | '/inline-css' | '/module-state' fileRoutesByTo: FileRoutesByTo - to: '/' - id: '__root__' | '/' + to: '/' | '/css-import-order' | '/inline-css' | '/module-state' + id: '__root__' | '/' | '/css-import-order' | '/inline-css' | '/module-state' fileRoutesById: FileRoutesById } export interface RootRouteChildren { IndexRoute: typeof IndexRoute + CssImportOrderRoute: typeof CssImportOrderRoute + InlineCssRoute: typeof InlineCssRoute + ModuleStateRoute: typeof ModuleStateRoute } declare module '@tanstack/react-router' { @@ -48,11 +78,35 @@ 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 new file mode 100644 index 0000000000..345254bb8c --- /dev/null +++ b/e2e/react-start/dev-ssr-styles/src/routes/css-import-order.tsx @@ -0,0 +1,17 @@ +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 f5fadf464d..62fb237750 100644 --- a/e2e/react-start/dev-ssr-styles/src/routes/index.tsx +++ b/e2e/react-start/dev-ssr-styles/src/routes/index.tsx @@ -1,4 +1,5 @@ import { createFileRoute } from '@tanstack/react-router' +import { CodeSplitStyledBox } from '../components/CodeSplitStyledBox' export const Route = createFileRoute('/')({ component: Home, @@ -8,9 +9,7 @@ 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 new file mode 100644 index 0000000000..ffc59128e0 --- /dev/null +++ b/e2e/react-start/dev-ssr-styles/src/routes/inline-css.tsx @@ -0,0 +1,19 @@ +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 new file mode 100644 index 0000000000..546217efc3 --- /dev/null +++ b/e2e/react-start/dev-ssr-styles/src/routes/module-state.ts @@ -0,0 +1,11 @@ +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 06b48f8a7c..4285da0c86 100644 --- a/e2e/react-start/dev-ssr-styles/src/styles/app.css +++ b/e2e/react-start/dev-ssr-styles/src/styles/app.css @@ -5,9 +5,10 @@ body { background-color: #f0f4f8; } -.styled-box { - background-color: #3b82f6; - color: white; - padding: 24px; - border-radius: 12px; +@layer utilities { + .inline-css-layout { + margin: 12px; + padding: 24px; + border: 3px solid black; + } } 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 new file mode 100644 index 0000000000..d6a50211ee --- /dev/null +++ b/e2e/react-start/dev-ssr-styles/src/styles/code-split-route.module.css @@ -0,0 +1,7 @@ +.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 new file mode 100644 index 0000000000..4f73ddab9c --- /dev/null +++ b/e2e/react-start/dev-ssr-styles/src/styles/css-import-base.css @@ -0,0 +1,5 @@ +.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 new file mode 100644 index 0000000000..afcb4797d9 --- /dev/null +++ b/e2e/react-start/dev-ssr-styles/src/styles/css-import-order.css @@ -0,0 +1,7 @@ +@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 new file mode 100644 index 0000000000..13810d6c98 --- /dev/null +++ b/e2e/react-start/dev-ssr-styles/src/styles/embedded-preflight.css @@ -0,0 +1,6 @@ +* { + --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 new file mode 100644 index 0000000000..171ed5e174 --- /dev/null +++ b/e2e/react-start/dev-ssr-styles/src/styles/embedded-theme.css @@ -0,0 +1,3 @@ +: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 new file mode 100644 index 0000000000..01f81c3b86 --- /dev/null +++ b/e2e/react-start/dev-ssr-styles/src/styles/embedded-utilities.css @@ -0,0 +1,3 @@ +.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 new file mode 100644 index 0000000000..7b6b68c48d --- /dev/null +++ b/e2e/react-start/dev-ssr-styles/src/styles/embedded.css @@ -0,0 +1,3 @@ +@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 new file mode 100644 index 0000000000..7916b3ef16 --- /dev/null +++ b/e2e/react-start/dev-ssr-styles/src/styles/ssr-background.svg @@ -0,0 +1 @@ + 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 cb1ba0b29b..f5b72a1bca 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 { test } from '@tanstack/router-e2e-utils' +import { createHmrFileEditor, test } from '@tanstack/router-e2e-utils' import { ssrStylesMode } from '../env' // Whitelist errors that can occur in CI: @@ -14,14 +14,60 @@ 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 }) @@ -52,7 +98,9 @@ test.describe(`dev.ssrStyles (mode=${ssrStylesMode})`, () => { expect(href).toMatch(/^\/@tanstack-start\/styles\.css/) }) - test('CSS is applied on initial page load (SSR)', async ({ page }) => { + test('CSS from a code-split route component is applied during SSR', async ({ + page, + }) => { await page.goto('/') const element = page.getByTestId('styled-box') @@ -64,6 +112,81 @@ 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 new file mode 100644 index 0000000000..c564a9977a --- /dev/null +++ b/e2e/react-start/dev-ssr-styles/tests/inline-css.spec.ts @@ -0,0 +1,35 @@ +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 2bfd33163d..43fad46254 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,39 +1,45 @@ -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 -} +import { chromium, expect } from '@playwright/test' +import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' +import { ssrStylesMode } from '../../env' export default async function setup() { - const portKey = getPortKey() + if (process.env.MODE !== 'dev') { + return + } - await e2eStartDummyServer(portKey) - - if (process.env.MODE !== 'dev') return - - const port = await getTestServerPort(portKey) + const port = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${port}` await waitForServer(baseURL) - await preOptimizeDevServer({ - baseURL, - readyTestId: 'home-heading', - }) + + // 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' }) } 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 deleted file mode 100644 index 0e44fca325..0000000000 --- a/e2e/react-start/dev-ssr-styles/tests/setup/global.teardown.ts +++ /dev/null @@ -1,21 +0,0 @@ -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 555137b543..df5ea34504 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: viteBundledDev ? { bundledDev: true } : undefined, + experimental: { bundledDev: viteBundledDev }, server: { port: 3000, }, diff --git a/e2e/react-start/early-hints/package.json b/e2e/react-start/early-hints/package.json index 2945148950..1615b99430 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -27,10 +27,20 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "node-forge": "^1.3.1", - "srvx": "0.11.15", + "srvx": "^1.0.0", "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 a2435bcf7b..b3606d5586 100644 --- a/e2e/react-start/early-hints/playwright.config.ts +++ b/e2e/react-start/early-hints/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `https://localhost:${PORT}` export default defineConfig({ @@ -17,8 +16,8 @@ export default defineConfig({ webServer: { command: `pnpm build && pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, 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 df0984079e..6d2d31d836 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,7 +1,5 @@ -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 { expect, test } from '@playwright/test' import type { IncomingHttpHeaders } from 'node:http2' type Http2Response = { @@ -48,14 +46,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 = await getTestServerPort(packageJson.name) + const PORT = Number(process.env.E2E_APP_PORT ?? 0) baseURL = `https://localhost:${PORT}` }) @@ -105,7 +103,9 @@ 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/) + expect(link).toMatch( + /<[^>]+>;\s*rel=modulepreload;\s*as=script;\s*fetchpriority=low/, + ) }) 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') + expect(link).toContain('rel=modulepreload; as=script; fetchpriority=low') expect(link).toContain('; rel=preconnect') }) diff --git a/e2e/react-start/flamegraph-bench/package.json b/e2e/react-start/flamegraph-bench/package.json index eb72de699a..72410b13e1 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": "^0.11.9" + "srvx": "^1.0.0" }, "devDependencies": { "@platformatic/flame": "latest", "@vitejs/plugin-react": "^6.0.1", - "nitro": "^3.0.260311-beta", + "nitro": "^3.0.260903-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 7a6dc23f76..76a5d86b1f 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.1.0", + "@rsbuild/core": "^2.3.1", "@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 c159aad328..5840ec157a 100644 --- a/e2e/react-start/hmr/playwright.config.ts +++ b/e2e/react-start/hmr/playwright.config.ts @@ -1,13 +1,11 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' 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 = await getTestServerPort(e2ePortKey) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` const devCommand = toolchain === 'rsbuild' ? 'pnpm dev:rsbuild' : 'pnpm dev:vite' @@ -18,7 +16,6 @@ export default defineConfig({ reporter: [['line']], globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', use: { baseURL, @@ -26,15 +23,14 @@ export default defineConfig({ webServer: { command: `${devCommand} --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, 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/rsbuild.config.ts b/e2e/react-start/hmr/rsbuild.config.ts index 126e7d9888..2f3829f661 100644 --- a/e2e/react-start/hmr/rsbuild.config.ts +++ b/e2e/react-start/hmr/rsbuild.config.ts @@ -5,7 +5,7 @@ import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' const outDir = process.env.E2E_DIST_DIR ?? 'dist' export default defineConfig({ - plugins: [pluginReact({ splitChunks: false }), tanstackStart()], + plugins: [pluginReact(), tanstackStart()], output: { distPath: { root: outDir, diff --git a/e2e/react-start/hmr/tests/app.spec.ts b/e2e/react-start/hmr/tests/app.spec.ts index 69ce1d20f3..645c9b06f3 100644 --- a/e2e/react-start/hmr/tests/app.spec.ts +++ b/e2e/react-start/hmr/tests/app.spec.ts @@ -607,8 +607,18 @@ 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') @@ -684,7 +694,7 @@ test.describe('react-start hmr', () => { await expect(page.getByTestId('child')).toHaveText('child') }) - test('rolls back a failed route refresh and accepts the next HMR update', async ({ + test('publishes a failed route refresh and accepts the next HMR update', async ({ page, }) => { await page.goto('/child') @@ -712,7 +722,7 @@ test.describe('react-start hmr', () => { }, ) - await expect(page.getByTestId('crumb-/child')).toHaveText('Child') + await expect(page.getByTestId('crumb-/child')).toHaveText('Child Failed') await expect(page.getByTestId('root-message')).toHaveValue( 'preserved through failure', ) @@ -922,6 +932,7 @@ 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 fb9aad22ae..32207ab79f 100644 --- a/e2e/react-start/hmr/tests/setup/global.setup.ts +++ b/e2e/react-start/hmr/tests/setup/global.setup.ts @@ -1,22 +1,7 @@ -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}` -} +import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' export default async function setup() { - const e2ePortKey = getE2EPortKey() - - await e2eStartDummyServer(e2ePortKey) - - const port = await getTestServerPort(e2ePortKey) + const port = Number(process.env.E2E_APP_PORT ?? 0) 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 deleted file mode 100644 index e17856dd82..0000000000 --- a/e2e/react-start/hmr/tests/setup/global.teardown.ts +++ /dev/null @@ -1,11 +0,0 @@ -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 5b525891a6..ca65ead76d 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -30,5 +30,23 @@ "@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 38690f09d8..972522350e 100644 --- a/e2e/react-start/i18n-paraglide/playwright.config.ts +++ b/e2e/react-start/i18n-paraglide/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -21,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, 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 25ff3f2738..c088eff106 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": "rm -rf port*.txt; playwright test --project=chromium", - "test:e2e:errorMode": "rm -rf port*.txt; BEHAVIOR=error playwright test --project=chromium", + "test:e2e:mockMode": "playwright test --project=chromium", + "test:e2e:errorMode": "BEHAVIOR=error playwright test --project=chromium", "test:e2e": "pnpm run test:e2e:mockMode && pnpm run test:e2e:errorMode" }, "dependencies": { @@ -25,9 +25,23 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "@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 31a55ba3bc..ab90f2911f 100644 --- a/e2e/react-start/import-protection-custom-config/playwright.config.ts +++ b/e2e/react-start/import-protection-custom-config/playwright.config.ts @@ -1,9 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' +import { appServerReady } from '@tanstack/router-e2e-utils' import { isErrorMode } from './tests/utils/isErrorMode' -import packageJson from './package.json' with { type: 'json' } -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` console.log('running in error mode:', isErrorMode.toString()) @@ -27,8 +26,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`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, 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 3e666ca1df..5032988d0c 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 { 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 { stripVTControlCharacters } from 'node:util' +import { appServerReadyPattern } from '@tanstack/router-e2e-utils' +import { chromium, expect } from '@playwright/test' 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,8 +84,7 @@ function captureBuild(cwd: string): void { } async function captureDevErrors(cwd: string): Promise { - const port = await getTestServerPort(`${packageJson.name}_error_dev`) - const baseURL = `http://localhost:${port}` + const port = 0 const logChunks: Array = [] const child = spawn('pnpm', ['exec', 'vite', 'dev', '--port', String(port)], { @@ -99,10 +98,23 @@ 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 c5187fe074..89c8bb2b9a 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 { 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 { stripVTControlCharacters } from 'node:util' +import { chromium, expect } from '@playwright/test' +import { appServerReadyPattern } from '@tanstack/router-e2e-utils' import { extractViolationsFromLog } from './violations.utils' import type { FullConfig } from '@playwright/test' @@ -12,7 +12,6 @@ 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}`) @@ -119,7 +118,6 @@ async function runDevPass( cwd: string, port: number, ): Promise> { - const baseURL = `http://localhost:${port}` const logChunks: Array = [] const child = startDevServer(cwd, port) @@ -127,6 +125,19 @@ 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() @@ -146,7 +157,7 @@ async function runDevPass( } async function captureDevViolations(cwd: string): Promise { - const port = await getTestServerPort(`${packageJson.name}_dev`) + const port = 0 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 5459b84437..ad06ba41ea 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.1.0", + "@rsbuild/core": "^2.3.1", "@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": "^0.11.9", + "srvx": "^1.0.0", "@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 778e865125..6a3df630c3 100644 --- a/e2e/react-start/import-protection/playwright.config.ts +++ b/e2e/react-start/import-protection/playwright.config.ts @@ -1,16 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' +import { appServerReady } 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 = await getTestServerPort(e2ePortKey) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` const violationArtifacts = [ getViolationArtifactName('build'), @@ -42,15 +38,14 @@ export default defineConfig({ : { webServer: { command: `rm -f webserver-dev.log ${violationArtifacts} && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, 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 c05ed1a7e3..ef8544dc3c 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 } from '@tanstack/react-router' +import { createFileRoute, useHydrated } 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,10 +25,12 @@ 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 ab44237539..d74bc6430b 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 -// `useSession` from `@tanstack/react-start/server`. +// `getCookie` 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 c844d59e73..e562128eea 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 { 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 { stripVTControlCharacters } from 'node:util' +import { appServerReadyPattern } from '@tanstack/router-e2e-utils' +import { chromium, expect } from '@playwright/test' import type { FullConfig } from '@playwright/test' /** @@ -20,14 +20,10 @@ 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}`) @@ -122,8 +118,7 @@ async function captureDev(cwd: string): Promise { if (fs.existsSync(p)) fs.unlinkSync(p) } - const port = await getTestServerPort(`${e2ePortKey}-error-dev`) - const baseURL = `http://localhost:${port}` + const port = 0 const logFile = path.resolve(cwd, 'error-dev.log') const out = fs.createWriteStream(logFile) @@ -145,10 +140,28 @@ async function captureDev(cwd: string): Promise { stdio: ['ignore', 'pipe', 'pipe'], }) - child.stdout?.on('data', (d: Buffer) => out.write(d)) - child.stderr?.on('data', (d: Buffer) => out.write(d)) + const logChunks: Array = [] + const record = (data: Buffer) => { + logChunks.push(data.toString()) + out.write(data) + } + child.stdout.on('data', record) + child.stderr.on('data', record) 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 2f863b398e..d0f4f70d03 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 { 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 { stripVTControlCharacters } from 'node:util' +import { chromium, expect } from '@playwright/test' +import { appServerReadyPattern } from '@tanstack/router-e2e-utils' import { extractViolationsFromLog, @@ -12,16 +12,11 @@ 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}`) @@ -177,6 +172,20 @@ 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 @@ -214,7 +223,6 @@ async function runDevPass( cwd: string, port: number, ): Promise> { - const baseURL = `http://localhost:${port}` const logChunks: Array = [] const child = startDevServer(cwd, port) @@ -222,6 +230,19 @@ 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() @@ -247,10 +268,7 @@ async function runDevPass( * modules are pre-transformed so resolveId/transform paths differ. */ async function captureDevViolations(cwd: string): Promise { - const coldViolations = await runDevPass( - cwd, - await getTestServerPort(`${e2ePortKey}-violations-cold`), - ) + const coldViolations = await runDevPass(cwd, 0) fs.writeFileSync( path.resolve(cwd, getViolationArtifactName('dev')), @@ -262,10 +280,7 @@ async function captureDevViolations(cwd: string): Promise { ) // Warm pass: the .vite cache from the cold run is still on disk. - const warmViolations = await runDevPass( - cwd, - await getTestServerPort(`${e2ePortKey}-violations-warm`), - ) + const warmViolations = await runDevPass(cwd, 0) 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 new file mode 100644 index 0000000000..be848d434c --- /dev/null +++ b/e2e/react-start/issue-8049/package.json @@ -0,0 +1,25 @@ +{ + "name": "tanstack-react-start-e2e-issue-8049", + "private": true, + "type": "module", + "scripts": { + "build": "vite build && tsc --noEmit", + "dev": "vite dev --port 3000", + "dev:e2e": "vite dev", + "test:e2e": "playwright test --project=chromium" + }, + "dependencies": { + "@tanstack/react-router": "workspace:^", + "@tanstack/react-start": "workspace:^", + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@playwright/test": "^1.61.0", + "@tanstack/router-e2e-utils": "workspace:^", + "@types/react": "^19.0.8", + "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^6.0.1", + "vite": "^8.0.14" + } +} diff --git a/e2e/react-start/issue-8049/playwright.config.ts b/e2e/react-start/issue-8049/playwright.config.ts new file mode 100644 index 0000000000..46bfbe552e --- /dev/null +++ b/e2e/react-start/issue-8049/playwright.config.ts @@ -0,0 +1,25 @@ +import { defineConfig, devices } from '@playwright/test' +import { appServerReady } from '@tanstack/router-e2e-utils' + +const PORT = + Number(process.env.VITE_SERVER_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: `VITE_SERVER_PORT=${PORT} pnpm dev:e2e --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, + stdout: 'pipe', + }, + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], +}) diff --git a/e2e/react-start/issue-8049/src/routeTree.gen.ts b/e2e/react-start/issue-8049/src/routeTree.gen.ts new file mode 100644 index 0000000000..9f42873a9b --- /dev/null +++ b/e2e/react-start/issue-8049/src/routeTree.gen.ts @@ -0,0 +1,86 @@ +/* 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 TestRouteImport } from './routes/test' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const TestRoute = TestRouteImport.update({ + id: '/test', + path: '/test', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/test': typeof TestRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/test': typeof TestRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/test': typeof TestRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/test' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/test' + id: '__root__' | '/' | '/test' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + TestRoute: typeof TestRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/test': { + id: '/test' + path: '/test' + fullPath: '/test' + preLoaderRoute: typeof TestRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + TestRoute: TestRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() + +import type { getRouter } from './router.tsx' +import type { createStart } from '@tanstack/react-start' +declare module '@tanstack/react-start' { + interface Register { + ssr: true + router: Awaited> + } +} diff --git a/e2e/react-start/issue-8049/src/router.tsx b/e2e/react-start/issue-8049/src/router.tsx new file mode 100644 index 0000000000..db215b280b --- /dev/null +++ b/e2e/react-start/issue-8049/src/router.tsx @@ -0,0 +1,19 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: 'intent', + defaultPreloadStaleTime: 0, + defaultPendingMs: 0, + defaultPendingMinMs: 0, + defaultPendingComponent: () =>
Pending
, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/e2e/react-start/issue-8049/src/routes/__root.tsx b/e2e/react-start/issue-8049/src/routes/__root.tsx new file mode 100644 index 0000000000..d04f508640 --- /dev/null +++ b/e2e/react-start/issue-8049/src/routes/__root.tsx @@ -0,0 +1,37 @@ +import { + HeadContent, + Link, + Scripts, + createRootRoute, +} 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' }, + ], + }), + shellComponent: RootDocument, +}) + +function RootDocument({ children }: { children: ReactNode }) { + return ( + + + + + +
+ + {children} +
+ + + + ) +} diff --git a/e2e/react-start/issue-8049/src/routes/index.tsx b/e2e/react-start/issue-8049/src/routes/index.tsx new file mode 100644 index 0000000000..be54bce8de --- /dev/null +++ b/e2e/react-start/issue-8049/src/routes/index.tsx @@ -0,0 +1,5 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: () =>
Home Page
, +}) diff --git a/e2e/react-start/issue-8049/src/routes/test.tsx b/e2e/react-start/issue-8049/src/routes/test.tsx new file mode 100644 index 0000000000..cca03da69f --- /dev/null +++ b/e2e/react-start/issue-8049/src/routes/test.tsx @@ -0,0 +1,5 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/test')({ + component: () =>
Test Page
, +}) diff --git a/e2e/react-start/issue-8049/tests/issue-8049.spec.ts b/e2e/react-start/issue-8049/tests/issue-8049.spec.ts new file mode 100644 index 0000000000..2560267109 --- /dev/null +++ b/e2e/react-start/issue-8049/tests/issue-8049.spec.ts @@ -0,0 +1,75 @@ +import { expect, test } from '@playwright/test' + +test('#8049: revisiting loaded split routes transitions without pending or blank paint', async ({ + page, +}) => { + await page.addInitScript(() => { + const scope = globalThis as typeof globalThis & { + __paintStates: Array + __recordPaintStates: boolean + } + scope.__paintStates = [] + scope.__recordPaintStates = false + + function recordPaintState() { + if (scope.__recordPaintStates) { + const state = document.querySelector('[data-state="home"]') + ? 'home' + : document.querySelector('[data-state="test"]') + ? 'test' + : document.querySelector('[data-state="pending"]') + ? 'pending' + : document.querySelector('[data-state="shell"]') + ? 'shell' + : 'empty' + scope.__paintStates.push(state) + } + requestAnimationFrame(recordPaintState) + } + + requestAnimationFrame(recordPaintState) + }) + await page.goto('/') + await expect(page.getByText('Home Page')).toBeVisible() + await page.waitForTimeout(1_000) + + await page.getByRole('link', { name: 'Test' }).click() + await expect(page.getByText('Test Page')).toBeVisible() + await page.getByRole('link', { name: 'Home' }).click() + await expect(page.getByText('Home Page')).toBeVisible() + + await page.evaluate( + () => + new Promise((resolve) => { + const scope = globalThis as typeof globalThis & { + __paintStates: Array + __recordPaintStates: boolean + } + scope.__paintStates = [] + scope.__recordPaintStates = true + requestAnimationFrame(() => resolve()) + }), + ) + + await page.getByRole('link', { name: 'Test' }).click() + await expect(page.getByText('Test Page')).toBeVisible() + const paintStates = await page.evaluate( + () => + new Promise>((resolve) => { + requestAnimationFrame(() => { + const scope = globalThis as typeof globalThis & { + __paintStates: Array + __recordPaintStates: boolean + } + scope.__recordPaintStates = false + resolve(scope.__paintStates) + }) + }), + ) + + expect(paintStates[0]).toBe('home') + expect(paintStates).toContain('test') + expect(paintStates).not.toContain('pending') + expect(paintStates).not.toContain('shell') + expect(paintStates).not.toContain('empty') +}) diff --git a/e2e/react-start/issue-8049/tsconfig.json b/e2e/react-start/issue-8049/tsconfig.json new file mode 100644 index 0000000000..0a82952b9a --- /dev/null +++ b/e2e/react-start/issue-8049/tsconfig.json @@ -0,0 +1,13 @@ +{ + "include": ["**/*.ts", "**/*.tsx"], + "compilerOptions": { + "strict": true, + "jsx": "react-jsx", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "resolveJsonModule": true, + "skipLibCheck": true, + "noEmit": true + } +} diff --git a/e2e/react-start/issue-8049/vite.config.ts b/e2e/react-start/issue-8049/vite.config.ts new file mode 100644 index 0000000000..f13cf79861 --- /dev/null +++ b/e2e/react-start/issue-8049/vite.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from 'vite' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import viteReact from '@vitejs/plugin-react' + +export default defineConfig({ + plugins: [tanstackStart(), viteReact()], +}) diff --git a/e2e/react-start/query-integration/package.json b/e2e/react-start/query-integration/package.json index 4ad1839537..694289ccc2 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "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 4d86a1dbe7..82678ac00b 100644 --- a/e2e/react-start/query-integration/playwright.config.ts +++ b/e2e/react-start/query-integration/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { derivePort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await derivePort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-start/response-reconciliation/.gitignore b/e2e/react-start/response-reconciliation/.gitignore new file mode 100644 index 0000000000..16187ac1de --- /dev/null +++ b/e2e/react-start/response-reconciliation/.gitignore @@ -0,0 +1,24 @@ +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 new file mode 100644 index 0000000000..40a96e8819 --- /dev/null +++ b/e2e/react-start/response-reconciliation/.prettierignore @@ -0,0 +1,4 @@ +**/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 new file mode 100644 index 0000000000..7ba0224962 --- /dev/null +++ b/e2e/react-start/response-reconciliation/package.json @@ -0,0 +1,84 @@ +{ + "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 new file mode 100644 index 0000000000..d4c9c58f43 --- /dev/null +++ b/e2e/react-start/response-reconciliation/playwright.config.ts @@ -0,0 +1,37 @@ +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 new file mode 100644 index 0000000000..38f44ef9fb --- /dev/null +++ b/e2e/react-start/response-reconciliation/rsbuild.config.ts @@ -0,0 +1,20 @@ +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 new file mode 100644 index 0000000000..324a462bec --- /dev/null +++ b/e2e/react-start/response-reconciliation/server.js @@ -0,0 +1,62 @@ +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 new file mode 100644 index 0000000000..f3d691814f --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/components/DefaultCatchBoundary.tsx @@ -0,0 +1,20 @@ +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 new file mode 100644 index 0000000000..0b720f0e37 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/components/NotFound.tsx @@ -0,0 +1,10 @@ +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 new file mode 100644 index 0000000000..db9733d5e6 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/response-wrapper.ts @@ -0,0 +1,33 @@ +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 new file mode 100644 index 0000000000..3dbb6301c3 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routeTree.gen.ts @@ -0,0 +1,625 @@ +/* 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 new file mode 100644 index 0000000000..c5c2209e5a --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/router.tsx @@ -0,0 +1,13 @@ +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 new file mode 100644 index 0000000000..a562991887 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/__root.tsx @@ -0,0 +1,57 @@ +/// +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 new file mode 100644 index 0000000000..54082c10f6 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/-response.ts @@ -0,0 +1,85 @@ +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 new file mode 100644 index 0000000000..1ccde76367 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/-tracked-streams.ts @@ -0,0 +1,2 @@ +// 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 new file mode 100644 index 0000000000..0018376035 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/-upstream.ts @@ -0,0 +1,14 @@ +// 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 new file mode 100644 index 0000000000..62f706a9f1 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/base.ts @@ -0,0 +1,10 @@ +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 new file mode 100644 index 0000000000..db7ded6c54 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/bulk-headers.ts @@ -0,0 +1,19 @@ +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 new file mode 100644 index 0000000000..fd3b88c172 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/clear-returned-headers.ts @@ -0,0 +1,15 @@ +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 new file mode 100644 index 0000000000..96823887e5 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/direct-mutation-visible.ts @@ -0,0 +1,11 @@ +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 new file mode 100644 index 0000000000..3ea2bc6d75 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/explicit-set-cookie-header.ts @@ -0,0 +1,16 @@ +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 new file mode 100644 index 0000000000..baeab15780 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/framing-error.ts @@ -0,0 +1,16 @@ +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 new file mode 100644 index 0000000000..b597882ff6 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/get-response-header-helper.ts @@ -0,0 +1,17 @@ +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 new file mode 100644 index 0000000000..168d38bad4 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/get-response-headers-helper.ts @@ -0,0 +1,20 @@ +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 new file mode 100644 index 0000000000..eebf7a167e --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/multiple-cookies.ts @@ -0,0 +1,14 @@ +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 new file mode 100644 index 0000000000..d11056e7a8 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/null-body-status.ts @@ -0,0 +1,18 @@ +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 new file mode 100644 index 0000000000..7b42955052 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/readonly-after-next.ts @@ -0,0 +1,11 @@ +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 new file mode 100644 index 0000000000..5b0072f35a --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/redirect-with-cookies.ts @@ -0,0 +1,18 @@ +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 new file mode 100644 index 0000000000..96f82bf98d --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/remove-returned-header.ts @@ -0,0 +1,15 @@ +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 new file mode 100644 index 0000000000..890280483d --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/replace-after-direct-mutation.ts @@ -0,0 +1,11 @@ +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 new file mode 100644 index 0000000000..97df27d915 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/replace-explicit-set-cookie.ts @@ -0,0 +1,15 @@ +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 new file mode 100644 index 0000000000..7d3650147f --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/route-after-next.ts @@ -0,0 +1,11 @@ +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 new file mode 100644 index 0000000000..b52c7642af --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/route-before-next.ts @@ -0,0 +1,11 @@ +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 new file mode 100644 index 0000000000..7ac086d652 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/same-boundary-conflict.ts @@ -0,0 +1,21 @@ +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 new file mode 100644 index 0000000000..43fd72ec07 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/status-contracts.ts @@ -0,0 +1,42 @@ +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 new file mode 100644 index 0000000000..9d93d75b61 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/throw-after-status.ts @@ -0,0 +1,26 @@ +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 new file mode 100644 index 0000000000..1aaffd8d36 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/tracked-stream-status.ts @@ -0,0 +1,13 @@ +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 new file mode 100644 index 0000000000..640074a035 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/tracked-stream.ts @@ -0,0 +1,23 @@ +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 new file mode 100644 index 0000000000..f433778fd8 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/two-returned-responses.ts @@ -0,0 +1,15 @@ +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 new file mode 100644 index 0000000000..ab938397e9 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/index.tsx @@ -0,0 +1,15 @@ +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 new file mode 100644 index 0000000000..580309b31e --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/server-functions.tsx @@ -0,0 +1,285 @@ +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 new file mode 100644 index 0000000000..c0cb69c8ec --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/ssr.tsx @@ -0,0 +1,29 @@ +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 new file mode 100644 index 0000000000..8d6a6227cd --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/streamed.tsx @@ -0,0 +1,25 @@ +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 new file mode 100644 index 0000000000..cbee8ad31a --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/server-entry.ts @@ -0,0 +1,84 @@ +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 new file mode 100644 index 0000000000..2ac158b799 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/start.ts @@ -0,0 +1,170 @@ +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 new file mode 100644 index 0000000000..a38fb439a6 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/styles/app.css @@ -0,0 +1,12 @@ +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 new file mode 100644 index 0000000000..728b0782c5 --- /dev/null +++ b/e2e/react-start/response-reconciliation/tests/response-reconciliation.spec.ts @@ -0,0 +1,1038 @@ +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 new file mode 100644 index 0000000000..3824b148e1 --- /dev/null +++ b/e2e/react-start/response-reconciliation/tsconfig.json @@ -0,0 +1,22 @@ +{ + "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 new file mode 100644 index 0000000000..355e12a2f7 --- /dev/null +++ b/e2e/react-start/response-reconciliation/vite.config.ts @@ -0,0 +1,19 @@ +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/.gitignore b/e2e/react-start/root-document-hydration/.gitignore new file mode 100644 index 0000000000..229709a89d --- /dev/null +++ b/e2e/react-start/root-document-hydration/.gitignore @@ -0,0 +1,5 @@ +node_modules +dist +test-results +playwright-report +port*.txt diff --git a/e2e/react-start/root-document-hydration/.prettierignore b/e2e/react-start/root-document-hydration/.prettierignore new file mode 100644 index 0000000000..083bdb7c4c --- /dev/null +++ b/e2e/react-start/root-document-hydration/.prettierignore @@ -0,0 +1 @@ +src/routeTree.gen.ts diff --git a/e2e/react-start/root-document-hydration/package.json b/e2e/react-start/root-document-hydration/package.json new file mode 100644 index 0000000000..9dcfcb6fbc --- /dev/null +++ b/e2e/react-start/root-document-hydration/package.json @@ -0,0 +1,40 @@ +{ + "name": "tanstack-react-start-e2e-root-document-hydration", + "private": true, + "sideEffects": false, + "type": "module", + "scripts": { + "dev": "vite dev --port 3000", + "dev:e2e": "vite dev --port $PORT", + "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:prod": "MODE=prod playwright test --project=chromium", + "test:e2e": "pnpm run test:e2e:dev && pnpm run test:e2e:prod" + }, + "dependencies": { + "@tanstack/react-router": "workspace:*", + "@tanstack/react-start": "workspace:*", + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@playwright/test": "^1.61.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", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" + }, + "nx": { + "targets": { + "test:e2e": { + "parallelism": false + } + } + } +} diff --git a/e2e/react-start/root-document-hydration/playwright.config.ts b/e2e/react-start/root-document-hydration/playwright.config.ts new file mode 100644 index 0000000000..13dda4e328 --- /dev/null +++ b/e2e/react-start/root-document-hydration/playwright.config.ts @@ -0,0 +1,37 @@ +import { defineConfig, devices } from '@playwright/test' +import { appServerReady } from '@tanstack/router-e2e-utils' + +const isDev = process.env.MODE === 'dev' +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: isDev + ? 'pnpm dev:e2e --port 0' + : `pnpm build && PORT=${PORT} pnpm start`, + wait: appServerReady, + reuseExistingServer: false, + stdout: 'pipe', + env: { + PORT: String(PORT), + }, + }, + + projects: [ + { + name: 'chromium', + use: { + ...devices['Desktop Chrome'], + }, + }, + ], +}) diff --git a/e2e/react-start/root-document-hydration/src/routeTree.gen.ts b/e2e/react-start/root-document-hydration/src/routeTree.gen.ts new file mode 100644 index 0000000000..dceedffdc1 --- /dev/null +++ b/e2e/react-start/root-document-hydration/src/routeTree.gen.ts @@ -0,0 +1,68 @@ +/* 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' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' + fileRoutesByTo: FileRoutesByTo + to: '/' + id: '__root__' | '/' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() + +import type { getRouter } from './router.tsx' +import type { createStart } from '@tanstack/react-start' +declare module '@tanstack/react-start' { + interface Register { + ssr: true + router: Awaited> + } +} diff --git a/e2e/react-start/root-document-hydration/src/router.tsx b/e2e/react-start/root-document-hydration/src/router.tsx new file mode 100644 index 0000000000..58f4d54e88 --- /dev/null +++ b/e2e/react-start/root-document-hydration/src/router.tsx @@ -0,0 +1,6 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ routeTree }) +} diff --git a/e2e/react-start/root-document-hydration/src/routes/__root.tsx b/e2e/react-start/root-document-hydration/src/routes/__root.tsx new file mode 100644 index 0000000000..2dc235e951 --- /dev/null +++ b/e2e/react-start/root-document-hydration/src/routes/__root.tsx @@ -0,0 +1,36 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' +import { useEffect } from 'react' + +export const Route = createRootRoute({ + pendingComponent: () => null, + component: RootComponent, +}) + +function RootComponent() { + useEffect(() => { + document.documentElement.dataset.hydrated = 'true' + }, []) + + return ( + + + + + +
+ ', 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('')) - }) + 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 new file mode 100644 index 0000000000..a9cf8a8142 --- /dev/null +++ b/e2e/react-start/streaming-ssr/tests/router-html-buffer.spec.ts @@ -0,0 +1,34 @@ +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 c3631a7fc0..0d5a87363f 100644 --- a/e2e/react-start/streaming-ssr/tests/slow-render.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/slow-render.spec.ts @@ -1,73 +1 @@ -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', - ) - }) -}) +import '../../../streaming-ssr-specs/slow-render' diff --git a/e2e/react-start/streaming-ssr/tests/stream.spec.ts b/e2e/react-start/streaming-ssr/tests/stream.spec.ts index 5e4c134f82..a51614f09a 100644 --- a/e2e/react-start/streaming-ssr/tests/stream.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/stream.spec.ts @@ -1,46 +1 @@ -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, - }) - }, - ) -}) +import '../../../streaming-ssr-specs/stream' 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 a0060a07ee..0e9278d3f2 100644 --- a/e2e/react-start/streaming-ssr/tests/sync-only.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/sync-only.spec.ts @@ -1,84 +1 @@ -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!', - ) -}) +import '../../../streaming-ssr-specs/sync-only' diff --git a/e2e/react-start/streaming-ssr/vite.config.ts b/e2e/react-start/streaming-ssr/vite.config.ts index 275bfacde2..0590c197a5 100644 --- a/e2e/react-start/streaming-ssr/vite.config.ts +++ b/e2e/react-start/streaming-ssr/vite.config.ts @@ -1,9 +1,10 @@ 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()], + plugins: [tanstackStart(), viteReact()], }) diff --git a/e2e/react-start/transform-asset-urls/package.json b/e2e/react-start/transform-asset-urls/package.json index 95e39e459b..e0a5ffec59 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; 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: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: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": "^0.11.9", + "srvx": "^1.0.0", "@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 bbef6838fe..209a7e0596 100644 --- a/e2e/react-start/transform-asset-urls/playwright.config.ts +++ b/e2e/react-start/transform-asset-urls/playwright.config.ts @@ -1,12 +1,10 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const APP_PORT = await getTestServerPort(packageJson.name) -const CDN_PORT = await getTestServerPort(`${packageJson.name}_cdn`) +const APP_PORT = Number(process.env.E2E_APP_PORT ?? 0) +const CDN_PORT = Number(process.env.E2E_CDN_PORT ?? 0) 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' @@ -26,8 +24,11 @@ export default defineConfig({ { // CDN server — serves built client assets on a separate port with CORS command: `node tests/cdn-server.mjs`, - url: `http://localhost:${CDN_PORT}/health`, - reuseExistingServer: !process.env.CI, + wait: { + stdout: + /CDN Server: (?http:\/\/localhost:(?\d+))/, + }, + reuseExistingServer: false, stdout: 'pipe', env: { CDN_PORT: String(CDN_PORT), @@ -37,12 +38,11 @@ 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`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, 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 241fc2fe51..a51f29ad66 100644 --- a/e2e/react-start/transform-asset-urls/src/server.ts +++ b/e2e/react-start/transform-asset-urls/src/server.ts @@ -83,4 +83,18 @@ const handler = createStartHandler( : defaultStreamHandler, ) -export default createServerEntry({ fetch: handler }) +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) + }, +}) 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 ea9bf62cd0..280c626867 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 = process.env.CDN_PORT || 3002 +const port = Number(process.env.CDN_PORT ?? 0) const app = express() @@ -36,7 +36,7 @@ app.use((req, res, next) => { app.use(express.static(path.resolve(__dirname, '..', 'dist', 'client'))) -app.listen(port, (error) => { +const server = app.listen(port, (error) => { if (error) throw error - console.info(`CDN Server: http://localhost:${port}`) + console.info(`CDN Server: http://localhost:${server.address().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 new file mode 100644 index 0000000000..22251df671 --- /dev/null +++ b/e2e/react-start/transform-asset-urls/tests/script-url-escaping.spec.ts @@ -0,0 +1,46 @@ +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 new file mode 100644 index 0000000000..a70ef94459 --- /dev/null +++ b/e2e/streaming-ssr-fixtures/index.ts @@ -0,0 +1,381 @@ +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 new file mode 100644 index 0000000000..759f8e0282 --- /dev/null +++ b/e2e/streaming-ssr-specs/client-navigation.ts @@ -0,0 +1,372 @@ +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 new file mode 100644 index 0000000000..ef14f80367 --- /dev/null +++ b/e2e/streaming-ssr-specs/concurrent.ts @@ -0,0 +1,86 @@ +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 new file mode 100644 index 0000000000..3e944b1c0c --- /dev/null +++ b/e2e/streaming-ssr-specs/deferred-rejection.ts @@ -0,0 +1,21 @@ +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 new file mode 100644 index 0000000000..abece0b43e --- /dev/null +++ b/e2e/streaming-ssr-specs/deferred.ts @@ -0,0 +1,113 @@ +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 new file mode 100644 index 0000000000..03201f0a55 --- /dev/null +++ b/e2e/streaming-ssr-specs/fast-serial.ts @@ -0,0 +1,74 @@ +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 new file mode 100644 index 0000000000..d85e19bfa7 --- /dev/null +++ b/e2e/streaming-ssr-specs/home.ts @@ -0,0 +1,34 @@ +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 new file mode 100644 index 0000000000..768859c7e4 --- /dev/null +++ b/e2e/streaming-ssr-specs/many-promises.ts @@ -0,0 +1,82 @@ +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 new file mode 100644 index 0000000000..0146a23162 --- /dev/null +++ b/e2e/streaming-ssr-specs/nested-deferred.ts @@ -0,0 +1,52 @@ +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 new file mode 100644 index 0000000000..5087dff730 --- /dev/null +++ b/e2e/streaming-ssr-specs/preview-streaming.ts @@ -0,0 +1,13 @@ +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 new file mode 100644 index 0000000000..b33a64f366 --- /dev/null +++ b/e2e/streaming-ssr-specs/query-heavy.ts @@ -0,0 +1,142 @@ +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 new file mode 100644 index 0000000000..117559701e --- /dev/null +++ b/e2e/streaming-ssr-specs/slow-render.ts @@ -0,0 +1,71 @@ +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 new file mode 100644 index 0000000000..ee61f170de --- /dev/null +++ b/e2e/streaming-ssr-specs/stream.ts @@ -0,0 +1,55 @@ +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 new file mode 100644 index 0000000000..9850265109 --- /dev/null +++ b/e2e/streaming-ssr-specs/sync-only.ts @@ -0,0 +1,80 @@ +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 c9e06e47b3..3af9176e83 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -17,7 +17,7 @@ "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "vue": "^3.5.16" }, diff --git a/e2e/vue-router/basepath-file-based/playwright.config.ts b/e2e/vue-router/basepath-file-based/playwright.config.ts index 6069bbe59f..4eead86444 100644 --- a/e2e/vue-router/basepath-file-based/playwright.config.ts +++ b/e2e/vue-router/basepath-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ 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} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/basepath-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/basepath-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 fb0109db1a..a51cf9149c 100644 --- a/e2e/vue-router/basic-esbuild-file-based/package.json +++ b/e2e/vue-router/basic-esbuild-file-based/package.json @@ -7,14 +7,14 @@ "build": "node src/esbuild.run.js build && vue-tsc --noEmit", "preview": "node src/esbuild.run.js preview", "start": "pnpm dev", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/router-plugin": "workspace:^", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "postcss": "^8.5.1", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "vue": "^3.5.16", "zod": "^4.4.3" }, 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 836ea41bd8..9d9c8d49a3 100644 --- a/e2e/vue-router/basic-esbuild-file-based/playwright.config.ts +++ b/e2e/vue-router/basic-esbuild-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ 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_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, + 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, 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 c4aba8798e..16f6fbca44 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,7 +9,6 @@ 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 19e882c1a9..0ab294f2bf 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,8 +1,7 @@ -import * as esbuild from 'esbuild' import http from 'node:http' -import { createReadStream } from 'node:fs' -import { promises as fs } from 'node:fs' +import { createReadStream, promises as fs } from 'node:fs' import path from 'node:path' +import * as esbuild from 'esbuild' import esbuildConfig from './esbuild.config.js' const args = process.argv.slice(2) @@ -18,7 +17,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 @@ -138,7 +137,7 @@ function startStaticServer({ port }) { return new Promise((resolve) => { server.listen(port, () => { - console.log(`http://localhost:${port}`) + console.log(`E2E app: http://localhost:${server.address().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 727c1b4d94..8869cefc01 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,27 +1,32 @@ +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 4b239f3ef4..f2998803fd 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,27 +1,30 @@ +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 f12ca517d3..20e0d5afdb 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,27 +1,30 @@ +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 05b34eb201..a46da658d6 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,27 +1,30 @@ +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 317c766186..715d2cc972 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,27 +1,30 @@ +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 59c9e6fa48..62c4af3aa4 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,3 +1,4 @@ +import { defineComponent } from 'vue' import { HeadContent, Link, @@ -10,95 +11,97 @@ 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 15d17387c8..54ae789c8e 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,24 +1,27 @@ +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 ae580dfc02..e0afd27b4c 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,7 +1,38 @@ +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: [ @@ -13,31 +44,3 @@ 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 57963c6b64..22979c93c9 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,23 +1,28 @@ +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 543746d64d..7380859e7b 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,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/basic-esbuild-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/basic-esbuild-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 ceb7352a88..9ab7f21e82 100644 --- a/e2e/vue-router/basic-file-based-jsx/package.json +++ b/e2e/vue-router/basic-file-based-jsx/package.json @@ -8,14 +8,14 @@ "build": "vite build && vue-tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/router-plugin": "workspace:^", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "vue": "^3.5.16", "zod": "^4.4.3" 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 836ea41bd8..4eead86444 100644 --- a/e2e/vue-router/basic-file-based-jsx/playwright.config.ts +++ b/e2e/vue-router/basic-file-based-jsx/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ 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_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, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, 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 1b4c92b41d..f7a1941605 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/posts.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/posts.tsx @@ -7,11 +7,7 @@ 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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 3922025c82..5922c5f7b1 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 727c1b4d94..8869cefc01 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,27 +1,32 @@ +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 4b239f3ef4..f2998803fd 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,27 +1,30 @@ +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 f12ca517d3..20e0d5afdb 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,27 +1,30 @@ +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 05b34eb201..a46da658d6 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,27 +1,30 @@ +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 317c766186..715d2cc972 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,27 +1,30 @@ +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 59c9e6fa48..62c4af3aa4 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,3 +1,4 @@ +import { defineComponent } from 'vue' import { HeadContent, Link, @@ -10,95 +11,97 @@ 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 15d17387c8..54ae789c8e 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,24 +1,27 @@ +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 ae580dfc02..e0afd27b4c 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,7 +1,38 @@ +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: [ @@ -13,31 +44,3 @@ 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 57963c6b64..22979c93c9 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,23 +1,28 @@ +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 543746d64d..7380859e7b 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,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/basic-file-based-jsx/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/basic-file-based-jsx/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 69e7338500..e6ffa156f9 100644 --- a/e2e/vue-router/basic-file-based-sfc/package.json +++ b/e2e/vue-router/basic-file-based-sfc/package.json @@ -8,14 +8,14 @@ "build": "vite build && vue-tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/router-plugin": "workspace:^", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "vue": "^3.5.16", "zod": "^4.4.3" 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 836ea41bd8..4eead86444 100644 --- a/e2e/vue-router/basic-file-based-sfc/playwright.config.ts +++ b/e2e/vue-router/basic-file-based-sfc/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ 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_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, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, 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 1b4c92b41d..f7a1941605 100644 --- a/e2e/vue-router/basic-file-based-sfc/src/posts.ts +++ b/e2e/vue-router/basic-file-based-sfc/src/posts.ts @@ -7,11 +7,7 @@ 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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 09d62b0706..0bfdddab3d 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 543746d64d..7380859e7b 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,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/basic-file-based-sfc/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/basic-file-based-sfc/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 3a3a7c375e..f4616a5651 100644 --- a/e2e/vue-router/basic-scroll-restoration/package.json +++ b/e2e/vue-router/basic-scroll-restoration/package.json @@ -8,14 +8,14 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-virtual": "^3.13.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "vue": "^3.5.16", "tailwindcss": "^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 0c5cee43e4..6a684ac89e 100644 --- a/e2e/vue-router/basic-scroll-restoration/playwright.config.ts +++ b/e2e/vue-router/basic-scroll-restoration/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, 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 567999f255..3701c2254c 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -18,7 +18,7 @@ "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "vue": "^3.5.16" }, 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 836ea41bd8..4eead86444 100644 --- a/e2e/vue-router/basic-virtual-file-based/playwright.config.ts +++ b/e2e/vue-router/basic-virtual-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ 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_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, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, 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 8576a3799a..5f5463a668 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/posts.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/posts.tsx @@ -7,11 +7,7 @@ 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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 b4c91d3e85..aa5387a4d8 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,3 +1,4 @@ +import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -6,6 +7,19 @@ 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, @@ -14,14 +28,3 @@ 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 265faaf650..2a4e8deddd 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,39 +1,42 @@ +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 3e5a69ccaa..fbf093cd51 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,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/basic-virtual-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/basic-virtual-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 66f1b47955..d3a69ed573 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -18,7 +18,7 @@ "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "vue": "^3.5.16" }, 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 836ea41bd8..4eead86444 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,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ 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_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, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, 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 8576a3799a..5f5463a668 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,11 +7,7 @@ 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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 b4c91d3e85..aa5387a4d8 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,3 +1,4 @@ +import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -6,6 +7,19 @@ 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, @@ -14,14 +28,3 @@ 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 265faaf650..2a4e8deddd 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,39 +1,42 @@ +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 3e5a69ccaa..fbf093cd51 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,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 772e630366..3b4422d8d8 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -17,7 +17,7 @@ "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "vue": "^3.5.16", "zod": "^4.4.3" 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 6e7c123f74..fbda9bd451 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,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -17,17 +12,15 @@ 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: `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, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, 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 1becc2c242..1f6cb8e308 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,11 +8,7 @@ export type PostType = { export class PostNotFoundError extends Error {} -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 72109fc891..e8b66ddf5d 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,3 +1,4 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { ErrorComponent, useRouter } from '@tanstack/vue-router' import { useQuery } from '@tanstack/vue-query' @@ -5,6 +6,21 @@ 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)) @@ -32,16 +48,3 @@ 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 f9e20f99d6..e1c35d59ad 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,42 +1,45 @@ +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 d80e8dada5..2b42d6d589 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,24 +1,23 @@ -import { expect, test } from '@playwright/test' -import { getDummyServerPort } from '@tanstack/router-e2e-utils' -import packageJson from '../package.json' with { type: 'json' } +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') }) -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() - +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) 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/basic-vue-query-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/basic-vue-query-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 123a2f4122..28889522fc 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"] + "types": ["vite/client", "node"] }, "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 b1bc234595..68f1a8c9ea 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -16,7 +16,7 @@ "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "vue": "^3.5.16" }, diff --git a/e2e/vue-router/basic-vue-query/playwright.config.ts b/e2e/vue-router/basic-vue-query/playwright.config.ts index 836ea41bd8..4eead86444 100644 --- a/e2e/vue-router/basic-vue-query/playwright.config.ts +++ b/e2e/vue-router/basic-vue-query/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ 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_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, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, 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 4f862a9b31..3235f26ce3 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 } from 'vue' +import { createApp, defineComponent } from 'vue' import { ErrorComponent, Link, @@ -108,6 +108,21 @@ 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', @@ -137,19 +152,6 @@ 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 eb844bc68d..d42d3d49dc 100644 --- a/e2e/vue-router/basic-vue-query/src/posts.lazy.tsx +++ b/e2e/vue-router/basic-vue-query/src/posts.lazy.tsx @@ -1,39 +1,42 @@ +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 18f8a9f93f..69e1814af5 100644 --- a/e2e/vue-router/basic-vue-query/src/posts.ts +++ b/e2e/vue-router/basic-vue-query/src/posts.ts @@ -9,11 +9,7 @@ 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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 3e5a69ccaa..fbf093cd51 100644 --- a/e2e/vue-router/basic-vue-query/tests/app.spec.ts +++ b/e2e/vue-router/basic-vue-query/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/basic-vue-query/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/basic-vue-query/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 00ec22e5b4..1b57dae772 100644 --- a/e2e/vue-router/basic/package.json +++ b/e2e/vue-router/basic/package.json @@ -8,13 +8,13 @@ "build": "vite build && vue-tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "vue": "^3.5.16" }, diff --git a/e2e/vue-router/basic/playwright.config.ts b/e2e/vue-router/basic/playwright.config.ts index 836ea41bd8..4eead86444 100644 --- a/e2e/vue-router/basic/playwright.config.ts +++ b/e2e/vue-router/basic/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ 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_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, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic/src/main.tsx b/e2e/vue-router/basic/src/main.tsx index 3e5ac6f1e0..c2293018fc 100644 --- a/e2e/vue-router/basic/src/main.tsx +++ b/e2e/vue-router/basic/src/main.tsx @@ -1,4 +1,4 @@ -import { createApp } from 'vue' +import { createApp, defineComponent } from 'vue' import { ErrorComponent, Link, @@ -133,6 +133,20 @@ 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', @@ -141,18 +155,6 @@ 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', @@ -315,14 +317,30 @@ 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: function ParamsNamedFoo() { - const p = paramsPsNamedFooRoute.useParams() - return ( + component: ParamsNamedFoo, +}) + +const ParamsNamedFooMarkdown = defineComponent({ + setup() { + const p = paramsPsNamedFooPrefixRoute.useParams() + return () => (
-

ParamsNamedFoo

+

ParamsNamedFooPrefix

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

ParamsNamedFooPrefix

+

ParamsNamedFooSuffix

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

ParamsNamedFooSuffix

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

ParamsWildcardSplat

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

ParamsWildcardSplat

+

ParamsWildcardSplatPrefix

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

ParamsWildcardSplatPrefix

+

ParamsWildcardSplatSuffix

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

ParamsWildcardSplatSuffix

-
{JSON.stringify(p.value)}
-
- ) - }, + component: ParamsWildcardSplatSuffix, }) 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 b2df740010..a236404d84 100644 --- a/e2e/vue-router/basic/src/posts.lazy.tsx +++ b/e2e/vue-router/basic/src/posts.lazy.tsx @@ -1,36 +1,39 @@ +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 e859645746..f72d16fee3 100644 --- a/e2e/vue-router/basic/src/posts.ts +++ b/e2e/vue-router/basic/src/posts.ts @@ -8,11 +8,7 @@ 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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 ec0e24d8a4..9c0a6b6901 100644 --- a/e2e/vue-router/basic/tests/app.spec.ts +++ b/e2e/vue-router/basic/tests/app.spec.ts @@ -1,8 +1,7 @@ -import { expect, test } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from '../package.json' with { type: 'json' } +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) 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 ac18f39864..f673138047 100644 --- a/e2e/vue-router/basic/tests/params.spec.ts +++ b/e2e/vue-router/basic/tests/params.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/basic/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/basic/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 6f605caa76..f9324643ac 100644 --- a/e2e/vue-router/generator-cli-only/package.json +++ b/e2e/vue-router/generator-cli-only/package.json @@ -8,14 +8,14 @@ "build": "tsr generate && vite build && tsc --noEmit", "preview": "vite preview", "start": "tsr generate && vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/router-cli": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "vue": "^3.5.16", "tailwindcss": "^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 c9d9a76ae7..4eead86444 100644 --- a/e2e/vue-router/generator-cli-only/playwright.config.ts +++ b/e2e/vue-router/generator-cli-only/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ 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_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, 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 e859645746..f72d16fee3 100644 --- a/e2e/vue-router/generator-cli-only/src/posts.ts +++ b/e2e/vue-router/generator-cli-only/src/posts.ts @@ -8,11 +8,7 @@ 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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 f4f1b04f88..bb2d728afd 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,7 +1,21 @@ +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, @@ -14,14 +28,3 @@ 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 eaaa35fd5c..518bdc3d70 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,39 +1,42 @@ +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 5a83a314f2..ced5ac9310 100644 --- a/e2e/vue-router/generator-cli-only/tests/app.spec.ts +++ b/e2e/vue-router/generator-cli-only/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/generator-cli-only/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/generator-cli-only/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 d7f062038e..cda098978c 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -17,7 +17,7 @@ "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "vue": "^3.5.16" }, 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 4f93bc1413..0925936d55 100644 --- a/e2e/vue-router/js-only-file-based/playwright.config.ts +++ b/e2e/vue-router/js-only-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -18,18 +13,15 @@ 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_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, 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 979e5e381c..36c1c281f6 100644 --- a/e2e/vue-router/js-only-file-based/src/posts.js +++ b/e2e/vue-router/js-only-file-based/src/posts.js @@ -2,11 +2,7 @@ import axios from 'redaxios' export class NotFoundError extends Error {} -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 b769e23862..05599a6780 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,8 +1,22 @@ +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, @@ -15,14 +29,3 @@ 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 c1fef7213d..5925dbed54 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,41 +1,44 @@ +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 5a83a314f2..ced5ac9310 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,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/js-only-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/js-only-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 d80486bc1a..93439f7d5b 100644 --- a/e2e/vue-router/rspack-basic-file-based/package.json +++ b/e2e/vue-router/rspack-basic-file-based/package.json @@ -7,17 +7,17 @@ "build": "rsbuild build && tsc --noEmit", "preview": "rsbuild preview", "start": "rsbuild preview", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "vue": "^3.5.16" }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.1.0", + "@rsbuild/core": "^2.3.1", "@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 5f20415459..4eead86444 100644 --- a/e2e/vue-router/rspack-basic-file-based/playwright.config.ts +++ b/e2e/vue-router/rspack-basic-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ 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: `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, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, 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 d5e4b7456c..c91449b6c3 100644 --- a/e2e/vue-router/rspack-basic-file-based/rsbuild.config.ts +++ b/e2e/vue-router/rspack-basic-file-based/rsbuild.config.ts @@ -12,19 +12,6 @@ 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 0b557a0f65..5f5463a668 100644 --- a/e2e/vue-router/rspack-basic-file-based/src/posts.tsx +++ b/e2e/vue-router/rspack-basic-file-based/src/posts.tsx @@ -7,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.PUBLIC_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.PUBLIC_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 e271c139f5..a86ea0762f 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,3 +1,4 @@ +import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -6,6 +7,19 @@ 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, @@ -14,14 +28,3 @@ 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 653918c370..90744370ff 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,40 +1,43 @@ +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 10beff655f..d230263bfe 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,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/rspack-basic-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/rspack-basic-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 17d8fd711e..536435a09e 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,17 +7,17 @@ "build": "rsbuild build && tsc --noEmit", "preview": "rsbuild preview", "start": "rsbuild preview", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "vue": "^3.5.16" }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.1.0", + "@rsbuild/core": "^2.3.1", "@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 bf3adc082c..1c1d021f2f 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,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ 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: `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, + command: `pnpm build && pnpm start --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, 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 b09f6ccda8..e5c7e8b77e 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,19 +12,6 @@ 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 0b557a0f65..5f5463a668 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,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.PUBLIC_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.PUBLIC_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 cb1924e993..5e3fe4d130 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,3 +1,4 @@ +import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -6,6 +7,19 @@ 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, @@ -14,14 +28,3 @@ 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 265faaf650..2a4e8deddd 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,39 +1,42 @@ +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 10beff655f..d230263bfe 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,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 de5da25aaf..d071ee546a 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/package.json +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/package.json @@ -11,14 +11,14 @@ "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": "rm -rf port*.txt; pnpm run test:e2e:browser && pnpm run test:e2e:hash" + "test:e2e": "pnpm run test:e2e:browser && pnpm run test:e2e:hash" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/router-plugin": "workspace:^", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "vue": "^3.5.16", "zod": "^4.4.3" @@ -31,5 +31,15 @@ "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 9d7691f0fd..e2681daea5 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,15 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, - resolveRuntimeSuffix, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort( - packageJson.name + `-${resolveRuntimeSuffix('browser')}`, -) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,18 +12,15 @@ 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_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, + command: `VITE_APP_HISTORY=browser pnpm build && VITE_APP_HISTORY=browser pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, 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 80a340cef4..445616b9bd 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,15 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, - resolveRuntimeSuffix, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort( - packageJson.name + `-${resolveRuntimeSuffix('hash')}`, -) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,18 +12,15 @@ 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_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, + 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, 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 c6cba486ab..bc56dff904 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/src/posts.tsx +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/src/posts.tsx @@ -12,11 +12,7 @@ export type PostType = { export class PostNotFoundError extends Error {} -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 5f226c6db3..067f0341c4 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,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 3e5b04987f..b47cca9589 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"] + "exclude": ["node_modules", "dist", "dist-hash"] } diff --git a/e2e/vue-router/sentry-integration/package.json b/e2e/vue-router/sentry-integration/package.json index d75ebed0c7..045ddd99be 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@sentry/vue": "^10.32.0", @@ -17,7 +17,7 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "vue": "^3.5.16" }, diff --git a/e2e/vue-router/sentry-integration/playwright.config.ts b/e2e/vue-router/sentry-integration/playwright.config.ts index 0c5cee43e4..6a684ac89e 100644 --- a/e2e/vue-router/sentry-integration/playwright.config.ts +++ b/e2e/vue-router/sentry-integration/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/view-transitions/package.json b/e2e/vue-router/view-transitions/package.json index 1e693e25db..21a0f1d8a0 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -17,7 +17,7 @@ "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "vue": "^3.5.16" }, diff --git a/e2e/vue-router/view-transitions/playwright.config.ts b/e2e/vue-router/view-transitions/playwright.config.ts index c5de6b5611..4eead86444 100644 --- a/e2e/vue-router/view-transitions/playwright.config.ts +++ b/e2e/vue-router/view-transitions/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -22,13 +17,10 @@ export default defineConfig({ baseURL, }, - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - webServer: { - 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, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, 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 e271c139f5..a86ea0762f 100644 --- a/e2e/vue-router/view-transitions/src/routes/posts.$postId.tsx +++ b/e2e/vue-router/view-transitions/src/routes/posts.$postId.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -6,6 +7,19 @@ 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, @@ -14,14 +28,3 @@ 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 01d90b7ad6..6802b073f6 100644 --- a/e2e/vue-router/view-transitions/src/routes/posts.route.tsx +++ b/e2e/vue-router/view-transitions/src/routes/posts.route.tsx @@ -1,43 +1,46 @@ +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 472bd6ed0b..6c1ccf1a6e 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 { test } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/view-transitions/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/view-transitions/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 31d8b12b04..e62662a1d2 100644 --- a/e2e/vue-router/view-transitions/tests/view-transitions.spec.ts +++ b/e2e/vue-router/view-transitions/tests/view-transitions.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 c57e0973ca..7f6fb798da 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": "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" + "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" }, "dependencies": { "@libsql/client": "^0.15.15", @@ -19,7 +19,8 @@ "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", - "redaxios": "^0.5.1", + "iron-session": "^9.0.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0", "vue": "^3.5.25" }, @@ -32,10 +33,21 @@ "@vitejs/plugin-vue-jsx": "^5.1.5", "dotenv": "^17.2.3", "prisma": "^7.0.0", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "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 18b8905468..82678ac00b 100644 --- a/e2e/vue-start/basic-auth/playwright.config.ts +++ b/e2e/vue-start/basic-auth/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, 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 02caf56456..0687372ae0 100644 --- a/e2e/vue-start/basic-auth/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/basic-auth/src/components/DefaultCatchBoundary.tsx @@ -1,3 +1,5 @@ +import { defineComponent } from 'vue' +import type { PropType } from 'vue' import { ErrorComponent, Link, @@ -6,46 +8,54 @@ import { } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -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 - - )} -
-
- ) -} +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 + + )} +
+
+ ) + } + }, +}) diff --git a/e2e/vue-start/basic-auth/src/routes/__root.tsx b/e2e/vue-start/basic-auth/src/routes/__root.tsx index 89802cfd2f..e5b6f6778f 100644 --- a/e2e/vue-start/basic-auth/src/routes/__root.tsx +++ b/e2e/vue-start/basic-auth/src/routes/__root.tsx @@ -1,4 +1,5 @@ /// +import { defineComponent } from 'vue' import { Body, HeadContent, @@ -15,21 +16,69 @@ 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 { useAppSession } from '~/utils/session.js' +import { getAppSession } 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 useAppSession() + const session = await getAppSession() - if (!session.data.userEmail) { + if (!session.userEmail) { return null } return { - email: session.data.userEmail, + email: session.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() @@ -81,50 +130,3 @@ 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 153efc39eb..606de3e487 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 { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' export const loginFn = createServerFn({ method: 'POST', @@ -37,12 +37,11 @@ export const loginFn = createServerFn({ } // Create a session - const session = await useAppSession() + const session = await getAppSession() // Store the user's email in the session - await session.update({ - userEmail: user.email, - }) + session.userEmail = user.email + await session.save() }) export const Route = createFileRoute('/_authed')({ @@ -52,7 +51,7 @@ export const Route = createFileRoute('/_authed')({ } }, errorComponent: ({ error }) => { - if (error.message === 'Not authenticated') { + if (error instanceof Error && error.message === 'Not authenticated') { return } 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 da0c26f27f..45d6bbab0d 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,3 +1,4 @@ +import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -8,6 +9,18 @@ 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, @@ -16,14 +29,3 @@ 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 cfac133b51..6b8b54c666 100644 --- a/e2e/vue-start/basic-auth/src/routes/_authed/posts.tsx +++ b/e2e/vue-start/basic-auth/src/routes/_authed/posts.tsx @@ -1,36 +1,38 @@ +import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '~/utils/posts.js' -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)}
    - -
  • - ))} -
-
- -
- ) -} +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('/_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 f1d7b58e29..8372b33608 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 { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await useAppSession() + const session = await getAppSession() - session.clear() + session.destroy() 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 eade8363e6..5f37f109c7 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 { useAppSession } from '~/utils/session' +import { getAppSession } 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 useAppSession() + const session = await getAppSession() if (found) { if (found.password !== password) { @@ -37,9 +37,8 @@ export const signupFn = createServerFn({ } // Store the user's email in the session - await session.update({ - userEmail: found.email, - }) + session.userEmail = found.email + await session.save() // Redirect to the prev page stored in the "redirect" search param throw redirect({ @@ -56,9 +55,8 @@ export const signupFn = createServerFn({ }) // Store the user's email in the session - await session.update({ - userEmail: user.email, - }) + session.userEmail = user.email + await session.save() // 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 7cf2a41792..7d078225a0 100644 --- a/e2e/vue-start/basic-auth/src/utils/session.ts +++ b/e2e/vue-start/basic-auth/src/utils/session.ts @@ -1,13 +1,25 @@ -// src/services/session.server.ts -import { useSession } from '@tanstack/vue-start/server' +import { getIronSession } from 'iron-session' +import { getCookie, setCookie } from '@tanstack/vue-start/server' import type { User } from '~/prisma-generated/client' type SessionUser = { userEmail: User['email'] } -export function useAppSession() { - return useSession({ - password: 'ChangeThisBeforeShippingToProdOrYouWillBeFired', - }) +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: '/', + }, + }, + ) } diff --git a/e2e/vue-start/basic-cloudflare/package.json b/e2e/vue-start/basic-cloudflare/package.json index 612a6b8d19..5ab77db8fc 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -31,5 +31,15 @@ "@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 a545dff891..0925936d55 100644 --- a/e2e/vue-start/basic-cloudflare/playwright.config.ts +++ b/e2e/vue-start/basic-cloudflare/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -14,9 +13,6 @@ 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, @@ -24,8 +20,8 @@ export default defineConfig({ webServer: { command: `pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, 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 02caf56456..0687372ae0 100644 --- a/e2e/vue-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx @@ -1,3 +1,5 @@ +import { defineComponent } from 'vue' +import type { PropType } from 'vue' import { ErrorComponent, Link, @@ -6,46 +8,54 @@ import { } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -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 - - )} -
-
- ) -} +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 + + )} +
+
+ ) + } + }, +}) diff --git a/e2e/vue-start/basic-cloudflare/src/routes/index.tsx b/e2e/vue-start/basic-cloudflare/src/routes/index.tsx index 1c708a7ec6..d3a020c7ad 100644 --- a/e2e/vue-start/basic-cloudflare/src/routes/index.tsx +++ b/e2e/vue-start/basic-cloudflare/src/routes/index.tsx @@ -1,7 +1,21 @@ +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, @@ -13,15 +27,3 @@ 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 7b0f9fd232..14d0c06294 100644 --- a/e2e/vue-start/basic-cloudflare/src/routes/static.tsx +++ b/e2e/vue-start/basic-cloudflare/src/routes/static.tsx @@ -1,7 +1,20 @@ +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, @@ -12,14 +25,3 @@ 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-start/basic-cloudflare/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-start/basic-cloudflare/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 11c2973f13..828dce5b2a 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -19,11 +19,12 @@ "devDependencies": { "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", - "vite": "^8.0.14" + "vite": "^8.0.14", + "rimraf": "catalog:" } } diff --git a/e2e/vue-start/basic-tsr-config/playwright.config.ts b/e2e/vue-start/basic-tsr-config/playwright.config.ts index f6dd61ba6c..e6b92ce385 100644 --- a/e2e/vue-start/basic-tsr-config/playwright.config.ts +++ b/e2e/vue-start/basic-tsr-config/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -21,8 +20,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, 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 3f4de50817..b4b520e8af 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,3 +1,4 @@ +import { defineComponent } from 'vue' import * as fs from 'node:fs' import { createFileRoute, useRouter } from '@tanstack/vue-router' import { createServerFn } from '@tanstack/vue-start' @@ -17,25 +18,26 @@ 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 9162a2b6a6..ab9589376d 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-query": "^5.92.1", @@ -18,7 +18,7 @@ "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-router-ssr-query": "workspace:^", "@tanstack/vue-start": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0", "vue": "^3.5.25", "zod": "^4.4.3" @@ -30,7 +30,7 @@ "@types/node": "^22.10.2", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "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 84636ab0f9..0618b7272a 100644 --- a/e2e/vue-start/basic-vue-query/playwright.config.ts +++ b/e2e/vue-start/basic-vue-query/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` @@ -16,18 +11,18 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { baseURL, }, webServer: { - 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, + command: `pnpm build && PORT=${PORT} pnpm start`, + wait: appServerReady, + reuseExistingServer: false, 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 cab4cafc3f..f9330a87db 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,11 +2,7 @@ import { createFileRoute } from '@tanstack/vue-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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 4cc4b33a0b..d138746730 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,11 +2,7 @@ import { createFileRoute } from '@tanstack/vue-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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 27baf4bd5f..fd8deaf291 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,3 +1,4 @@ +import { defineComponent } from 'vue' import { useQuery } from '@tanstack/vue-query' import { ErrorComponent, @@ -11,27 +12,30 @@ export function PostErrorComponent(props: ErrorComponentProps) { return } -function PostComponent() { - const params = Route.useParams() - const postQuery = useQuery(() => postQueryOptions(params.value.postId)) - - return ( -
-

{postQuery.data.value?.title}

-
{postQuery.data.value?.body}
- - Deep View - -
- ) -} +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 + +
+ ) + }, +}) 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 38e7429f6e..211b3ca4b1 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,22 +1,26 @@ +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' -function PostDeepComponent() { - const params = Route.useParams() - const postQuery = useQuery(() => postQueryOptions(params.value.postId)) - - return ( -
- - ← All Posts - -

{postQuery.data.value?.title}

-
{postQuery.data.value?.body}
-
- ) -} +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}
+
+ ) + }, +}) 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 6d12790dc9..f5004aa21d 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 { ref, watchEffect } from 'vue' +import { defineComponent, ref, watchEffect } from 'vue' const doubleQueryOptions = (n: number) => queryOptions({ @@ -19,6 +19,37 @@ 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 (
@@ -39,34 +70,3 @@ 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 2ab0562203..32b1943c71 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,3 +1,4 @@ +import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' import { queryOptions, useQuery } from '@tanstack/vue-query' import { z } from 'zod' @@ -16,6 +17,32 @@ 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 }) => { @@ -24,28 +51,3 @@ 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 91376b9498..bf1b75861e 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,3 +1,4 @@ +import { defineComponent } from 'vue' import { useQuery } from '@tanstack/vue-query' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -5,19 +6,20 @@ import type { ErrorComponentProps } from '@tanstack/vue-router' import { NotFound } from '~/components/NotFound' import { userQueryOptions } from '~/utils/users' -function UserComponent() { - const params = Route.useParams() - const userQuery = useQuery(() => userQueryOptions(params.value.userId)) - - return ( -
-

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

-
{userQuery.data.value?.email ?? ''}
-
- ) -} +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 ?? ''}
+
+ ) + }, +}) 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 b0a0b8f60d..c6b5e70a0b 100644 --- a/e2e/vue-start/basic-vue-query/src/utils/posts.tsx +++ b/e2e/vue-start/basic-vue-query/src/utils/posts.tsx @@ -7,11 +7,7 @@ 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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 29bf08c315..fe7a902fa2 100644 --- a/e2e/vue-start/basic-vue-query/src/utils/users.tsx +++ b/e2e/vue-start/basic-vue-query/src/utils/users.tsx @@ -1,4 +1,6 @@ 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 = { @@ -7,17 +9,16 @@ export type User = { email: string } -const PORT = - import.meta.env.VITE_SERVER_PORT || process.env.VITE_SERVER_PORT || 3000 - -export const DEPLOY_URL = `http://localhost:${PORT}` +const getOrigin = createIsomorphicFn() + .server(() => getRequestUrl().origin) + .client(() => window.location.origin) export const usersQueryOptions = () => queryOptions({ queryKey: ['users'], queryFn: () => axios - .get>(DEPLOY_URL + '/api/users') + .get>(getOrigin() + '/api/users') .then((r) => r.data) .catch(() => { throw new Error('Failed to fetch users') @@ -29,7 +30,7 @@ export const userQueryOptions = (id: string) => queryKey: ['users', id], queryFn: () => axios - .get(DEPLOY_URL + '/api/users/' + id) + .get(getOrigin() + '/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 ab2469f68d..4ce5c20ef7 100644 --- a/e2e/vue-start/basic-vue-query/tests/app.spec.ts +++ b/e2e/vue-start/basic-vue-query/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-start/basic-vue-query/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-start/basic-vue-query/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 2c28fc72a2..a0f3bf0964 100644 --- a/e2e/vue-start/basic-vue-query/tests/transition.spec.ts +++ b/e2e/vue-start/basic-vue-query/tests/transition.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 173ab3175b..2ff8329543 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": "vite build && tsc --noEmit", + "build": "pnpm build:vite", "preview": "vite 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" + "test:e2e:local": "playwright test --project=chromium", + "build:vite": "vite build && tsc --noEmit", + "build:rsbuild": "rsbuild build && tsc --noEmit" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -20,14 +20,14 @@ "express": "^5.2.1", "http-proxy-middleware": "^3.0.5", "js-cookie": "^3.0.5", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0", "vue": "^3.5.16", "zod": "^4.4.3" }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.1.0", + "@rsbuild/core": "^2.3.1", "@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": "^0.11.9", + "srvx": "^1.0.0", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", @@ -59,7 +59,10 @@ }, { "toolchain": "vite", - "mode": "prerender" + "mode": "prerender", + "env": { + "NODE_OPTIONS": "--import=@tanstack/router-e2e-utils/mock-api" + } }, { "toolchain": "vite", diff --git a/e2e/vue-start/basic/playwright.config.ts b/e2e/vue-start/basic/playwright.config.ts index 6924134cd1..9322874f3a 100644 --- a/e2e/vue-start/basic/playwright.config.ts +++ b/e2e/vue-start/basic/playwright.config.ts @@ -1,59 +1,37 @@ -import fs from 'node:fs' import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' const mode = process.env.MODE ?? 'ssr' -const e2ePortKey = process.env.E2E_PORT_KEY ?? packageJson.name + const distDir = process.env.E2E_DIST_DIR ?? 'dist' -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 PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` const commandByMode = mode === 'preview' - ? `pnpm run test:e2e:startDummyServer && pnpm preview --outDir ${distDir} --port ${PORT}` - : `pnpm run test:e2e:startDummyServer && pnpm start` + ? `pnpm preview --host 0.0.0.0 --outDir ${distDir} --port ${PORT}` + : `pnpm start` export default defineConfig({ testDir: './tests', workers: 1, reporter: [['line']], - globalTeardown: './tests/setup/global.teardown.ts', - use: { baseURL, }, webServer: { command: commandByMode, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', env: { + NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, MODE: mode, - VITE_NODE_ENV: 'test', - VITE_EXTERNAL_PORT: String(EXTERNAL_PORT), - VITE_SERVER_PORT: String(PORT), - START_PORT: String(START_PORT), + START_PORT: '0', PORT: String(PORT), E2E_DIST_DIR: distDir, - E2E_PORT_KEY: e2ePortKey, }, }, diff --git a/e2e/vue-start/basic/rsbuild.config.ts b/e2e/vue-start/basic/rsbuild.config.ts index 93af798c3c..aad3a76e73 100644 --- a/e2e/vue-start/basic/rsbuild.config.ts +++ b/e2e/vue-start/basic/rsbuild.config.ts @@ -16,11 +16,6 @@ export default defineConfig({ pluginVueJsx(), tanstackStart(), ], - performance: { - chunkSplit: { - strategy: 'split-by-experience', - }, - }, source: { define: { __TSR_PRERENDER__: JSON.stringify(isPrerender), diff --git a/e2e/vue-start/basic/server.js b/e2e/vue-start/basic/server.js index 69c1e4ca91..3e1ddab400 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 = process.env.PORT || 3000 +const port = Number(process.env.PORT ?? 3000) -const startPort = process.env.START_PORT || 3001 +const startPort = Number(process.env.START_PORT ?? 0) 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() { +export async function createSpaServer(backendPort) { const app = express() app.use( '/api', createProxyMiddleware({ - target: `http://localhost:${startPort}/api`, // Replace with your target server's URL + target: `http://localhost:${backendPort}/api`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) @@ -63,7 +63,7 @@ export async function createSpaServer() { app.use( '/_serverFn', createProxyMiddleware({ - target: `http://localhost:${startPort}/_serverFn`, // Replace with your target server's URL + target: `http://localhost:${backendPort}/_serverFn`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) @@ -71,31 +71,28 @@ export async function createSpaServer() { app.use(express.static(distClientDir)) app.get('/{*splat}', (req, res) => { - res.sendFile(path.resolve(distClientDir, 'index.html')) + res.sendFile('index.html', { root: distClientDir }) }) return { app } } -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}`) - }), - ) -} +// 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}`) + } +}) diff --git a/e2e/vue-start/basic/src/routes/__root.tsx b/e2e/vue-start/basic/src/routes/__root.tsx index 843ec05893..9da2c581fe 100644 --- a/e2e/vue-start/basic/src/routes/__root.tsx +++ b/e2e/vue-start/basic/src/routes/__root.tsx @@ -1,4 +1,5 @@ /// +import { defineComponent } from 'vue' import { Body, ClientOnly, @@ -16,6 +17,119 @@ 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: [ @@ -62,119 +176,11 @@ export const Route = createRootRoute({ }, ], }), - errorComponent: (props) =>

{props.error.stack}

, + errorComponent: (props) => ( +

+ {props.error instanceof Error ? props.error.stack : String(props.error)} +

+ ), 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 50b9ca995a..24938d51c2 100644 --- a/e2e/vue-start/basic/src/routes/api/users.$userId.ts +++ b/e2e/vue-start/basic/src/routes/api/users.$userId.ts @@ -1,19 +1,15 @@ 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(`${queryURL}/users/${params.userId}`) + const res = await fetch( + `https://jsonplaceholder.typicode.com/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 97989b93ca..c6045977b8 100644 --- a/e2e/vue-start/basic/src/routes/api/users.ts +++ b/e2e/vue-start/basic/src/routes/api/users.ts @@ -38,19 +38,13 @@ 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(`${queryURL}/users`) + const res = await fetch('https://jsonplaceholder.typicode.com/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 9f7e3b4b33..ecd12d1dad 100644 --- a/e2e/vue-start/basic/src/routes/not-found/index.tsx +++ b/e2e/vue-start/basic/src/routes/not-found/index.tsx @@ -1,9 +1,10 @@ +import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute('/not-found/')({ - component: () => { +const RouteComponent = defineComponent({ + setup() { const preload = Route.useSearch({ select: (s) => s.preload }) - return ( + return () => (
( +
+
+ {loaderData.value.parentLoaderData} +
+
+ ) + }, +}) + export const Route = createFileRoute('/not-found/parent-boundary')({ loader: () => ({ parentLoaderData: 'ready', @@ -15,15 +29,3 @@ 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 4d71080d64..edda7f0017 100644 --- a/e2e/vue-start/basic/src/routes/posts.$postId.tsx +++ b/e2e/vue-start/basic/src/routes/posts.$postId.tsx @@ -1,9 +1,32 @@ +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, @@ -12,24 +35,3 @@ 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 1a9d58a31d..64d4754f2f 100644 --- a/e2e/vue-start/basic/src/routes/posts.tsx +++ b/e2e/vue-start/basic/src/routes/posts.tsx @@ -1,7 +1,36 @@ +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: [ @@ -13,30 +42,3 @@ 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 a52c6f32f7..f77ae7d3ab 100644 --- a/e2e/vue-start/basic/src/routes/posts_.$postId.deep.tsx +++ b/e2e/vue-start/basic/src/routes/posts_.$postId.deep.tsx @@ -1,24 +1,26 @@ +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 a8c3c75b1f..e39bda5bcf 100644 --- a/e2e/vue-start/basic/src/routes/redirect/$target/index.tsx +++ b/e2e/vue-start/basic/src/routes/redirect/$target/index.tsx @@ -1,9 +1,10 @@ +import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute('/redirect/$target/')({ - component: () => { +const RouteComponent = defineComponent({ + setup() { const preload = Route.useSearch({ select: (s) => s.preload }) - return ( + return () => (
{ +const RouteComponent = defineComponent({ + setup() { const params = Route.useParams() - return ( + return () => (

redirect test with server functions (target {params.value.target}) @@ -87,3 +88,7 @@ export const Route = createFileRoute('/redirect/$target/serverFn/')({ ) }, }) + +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 399e8ac995..093a591636 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,13 +1,12 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { RedirectOnClick } from '~/components/RedirectOnClick' -export const Route = createFileRoute( - '/redirect/$target/serverFn/via-useServerFn', -)({ - component: () => { +const RouteComponent = defineComponent({ + setup() { 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'), @@ -15,14 +29,5 @@ export const Route = createFileRoute('/search-params/default')({ throw new Error('Context hello is not "world"') } }, - component: () => { - const search = Route.useSearch() - const context = Route.useRouteContext() - return ( - <> -
{search.value.default}
-
{context.value.hello}
- - ) - }, + component: RouteComponent, }) 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 14b137abc6..ccd1276387 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,6 +1,19 @@ +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(), @@ -14,13 +27,5 @@ export const Route = createFileRoute('/search-params/loader-throws-redirect')({ }) } }, - component: () => { - const search = Route.useSearch() - return ( -
-

SearchParams

-
{search.value.step}
-
- ) - }, + component: RouteComponent, }) diff --git a/e2e/vue-start/basic/src/routes/specialChars/$param.tsx b/e2e/vue-start/basic/src/routes/specialChars/$param.tsx index de3cba0a97..ec315ede1f 100644 --- a/e2e/vue-start/basic/src/routes/specialChars/$param.tsx +++ b/e2e/vue-start/basic/src/routes/specialChars/$param.tsx @@ -1,15 +1,18 @@ +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 7160964549..2b19e7e36e 100644 --- a/e2e/vue-start/basic/src/routes/specialChars/malformed/$param.tsx +++ b/e2e/vue-start/basic/src/routes/specialChars/malformed/$param.tsx @@ -1,15 +1,20 @@ +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 2438604954..8d6ad5b1dd 100644 --- a/e2e/vue-start/basic/src/routes/specialChars/malformed/search.tsx +++ b/e2e/vue-start/basic/src/routes/specialChars/malformed/search.tsx @@ -1,22 +1,24 @@ +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 5ba858e747..b4e022639d 100644 --- a/e2e/vue-start/basic/src/routes/specialChars/search.tsx +++ b/e2e/vue-start/basic/src/routes/specialChars/search.tsx @@ -1,22 +1,24 @@ +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 420b7e4a50..76340cf9fb 100644 --- a/e2e/vue-start/basic/src/routes/users.$userId.tsx +++ b/e2e/vue-start/basic/src/routes/users.$userId.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import axios from 'redaxios' @@ -6,6 +7,18 @@ 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() @@ -22,14 +35,3 @@ 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 1e0b297dd2..3d8ef31598 100644 --- a/e2e/vue-start/basic/src/routes/users.tsx +++ b/e2e/vue-start/basic/src/routes/users.tsx @@ -1,9 +1,41 @@ +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() @@ -16,33 +48,3 @@ 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 66cb298f83..d8e2dc7450 100644 --- a/e2e/vue-start/basic/src/utils/posts.tsx +++ b/e2e/vue-start/basic/src/utils/posts.tsx @@ -8,18 +8,12 @@ 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(`${queryURL}/posts/${postId}`) + .get(`https://jsonplaceholder.typicode.com/posts/${postId}`) .then((r) => r.data) .catch((err) => { console.error(err) @@ -36,7 +30,7 @@ export const fetchPosts = createServerFn({ method: 'GET' }).handler( async () => { console.info('Fetching posts...') return axios - .get>(`${queryURL}/posts`) + .get>('https://jsonplaceholder.typicode.com/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 46be4b1580..7ba645b383 100644 --- a/e2e/vue-start/basic/src/utils/users.tsx +++ b/e2e/vue-start/basic/src/utils/users.tsx @@ -3,7 +3,3 @@ 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 e8259b1e33..4da6234c8a 100644 --- a/e2e/vue-start/basic/src/vite-env.d.ts +++ b/e2e/vue-start/basic/src/vite-env.d.ts @@ -2,7 +2,6 @@ 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 new file mode 100644 index 0000000000..6c9b26dc4c --- /dev/null +++ b/e2e/vue-start/basic/tests/fixture-api.spec.ts @@ -0,0 +1,11 @@ +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 2f6354aa81..8e6ceba5b9 100644 --- a/e2e/vue-start/basic/tests/redirect.spec.ts +++ b/e2e/vue-start/basic/tests/redirect.spec.ts @@ -1,19 +1,14 @@ import queryString from 'node:querystring' -import { expect, type Page } from '@playwright/test' +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' import combinateImport from 'combinate' -import { - getDummyServerPort, - getTestServerPort, - test, -} from '@tanstack/router-e2e-utils' -import { getE2EPortKey } from './utils/getE2EPortKey.ts' +import type { Page } from '@playwright/test' // somehow playwright does not correctly import default exports const combinate = (combinateImport as any).default as typeof combinateImport -const e2ePortKey = getE2EPortKey() -const PORT = await getTestServerPort(e2ePortKey) -const EXTERNAL_HOST_PORT = await getDummyServerPort(e2ePortKey) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const EXTERNAL_ORIGIN = `http://127.0.0.1:${PORT}` const POSTS_URL = `http://localhost:${PORT}/posts` async function waitForRouterIdle(page: Page) { @@ -106,7 +101,7 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, + externalHost: `${EXTERNAL_ORIGIN}/`, }) if (scenario === 'navigate') { @@ -119,7 +114,7 @@ test.describe('redirects', () => { await page.goto(`/redirect/external/via-${thrower}?${q}`) } - const url = `http://localhost:${EXTERNAL_HOST_PORT}/` + const url = `${EXTERNAL_ORIGIN}/` await page.waitForURL(url) expect(page.url()).toBe(url) @@ -140,7 +135,7 @@ test.describe('redirects', () => { }) => { let fullPageLoad = false const q = queryString.stringify({ - externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, + externalHost: `${EXTERNAL_ORIGIN}/`, reloadDocument, }) @@ -159,10 +154,7 @@ test.describe('redirects', () => { await page.goto(`/redirect/${target}/serverFn/via-${thrower}?${q}`) } - const url = - target === 'internal' - ? POSTS_URL - : `http://localhost:${EXTERNAL_HOST_PORT}/` + const url = target === 'internal' ? POSTS_URL : `${EXTERNAL_ORIGIN}/` await page.waitForURL(url) expect(page.url()).toBe(url) if (target === 'internal' && scenario === 'navigate') { @@ -184,7 +176,7 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, + externalHost: `${EXTERNAL_ORIGIN}/`, reloadDocument, }) @@ -201,10 +193,7 @@ test.describe('redirects', () => { await button.click() - const url = - target === 'internal' - ? POSTS_URL - : `http://localhost:${EXTERNAL_HOST_PORT}/` + const url = target === 'internal' ? POSTS_URL : `${EXTERNAL_ORIGIN}/` 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 deleted file mode 100644 index cd38c35885..0000000000 --- a/e2e/vue-start/basic/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 36e5c92858..0000000000 --- a/e2e/vue-start/basic/tests/setup/global.teardown.ts +++ /dev/null @@ -1,8 +0,0 @@ -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 deleted file mode 100644 index 88c18fd79e..0000000000 --- a/e2e/vue-start/basic/tests/setup/waitForDummyServer.ts +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index 48be6a9027..0000000000 --- a/e2e/vue-start/basic/tests/utils/getE2EPortKey.ts +++ /dev/null @@ -1,5 +0,0 @@ -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 c739f09ea0..3671774644 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": "rm -rf port*.txt; pnpm run test:e2e:dev" + "test:e2e": "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": "^0.11.9", + "srvx": "^1.0.0", "@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 0b810d5372..a50ac5ae63 100644 --- a/e2e/vue-start/css-modules/playwright.config.ts +++ b/e2e/vue-start/css-modules/playwright.config.ts @@ -1,10 +1,9 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' const mode = process.env.MODE ?? 'prod' const isDev = mode === 'dev' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -13,16 +12,17 @@ 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` : `pnpm build && PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: isDev + ? `pnpm dev:e2e --port 0` + : `pnpm build && PORT=${PORT} pnpm start`, + wait: appServerReady, + reuseExistingServer: false, 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 2d3a1db946..17be637f77 100644 --- a/e2e/vue-start/css-modules/tests/setup/global.setup.ts +++ b/e2e/vue-start/css-modules/tests/setup/global.setup.ts @@ -1,17 +1,9 @@ -import { - e2eStartDummyServer, - getTestServerPort, - preOptimizeDevServer, - waitForServer, -} from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } +import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' export default async function setup() { - await e2eStartDummyServer(packageJson.name) - if (process.env.MODE !== 'dev') return - const port = await getTestServerPort(packageJson.name) + const port = Number(process.env.E2E_APP_PORT ?? 0) 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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-start/css-modules/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 1884c5eb5a..b9bf393466 100644 --- a/e2e/vue-start/custom-basepath/express-server.ts +++ b/e2e/vue-start/custom-basepath/express-server.ts @@ -1,5 +1,6 @@ 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' @@ -40,7 +41,11 @@ if (DEVELOPMENT) { }) } -app.listen(PORT, (error) => { - if (error) throw error - console.log(`Server is running on http://localhost:${PORT}`) +const httpServer = app.listen(PORT, (error) => { + if (error) { + throw error + } + console.log( + `E2E app: http://localhost:${(httpServer.address() as AddressInfo).port}`, + ) }) diff --git a/e2e/vue-start/custom-basepath/package.json b/e2e/vue-start/custom-basepath/package.json index 787d0480a5..c1032ea88b 100644 --- a/e2e/vue-start/custom-basepath/package.json +++ b/e2e/vue-start/custom-basepath/package.json @@ -8,14 +8,14 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "tsx express-server.ts", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", "express": "^5.2.1", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "vue": "^3.5.25" }, "devDependencies": { @@ -25,7 +25,7 @@ "@types/express": "^5.0.6", "@types/node": "^22.10.2", "cross-env": "^10.0.0", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "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 5095425f47..e113ce64ad 100644 --- a/e2e/vue-start/custom-basepath/playwright.config.ts +++ b/e2e/vue-start/custom-basepath/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}/custom/basepath` /** @@ -18,19 +13,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: `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, + command: `pnpm build && PORT=${PORT} pnpm start`, + wait: appServerReady, + reuseExistingServer: false, 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 d06f4a948b..77c03c5afa 100644 --- a/e2e/vue-start/custom-basepath/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/custom-basepath/src/components/DefaultCatchBoundary.tsx @@ -1,3 +1,5 @@ +import { defineComponent } from 'vue' +import type { PropType } from 'vue' import { ErrorComponent, Link, @@ -6,46 +8,54 @@ import { } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -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 - - )} -
-
- ) -} +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 + + )} +
+
+ ) + } + }, +}) diff --git a/e2e/vue-start/custom-basepath/src/routes/__root.tsx b/e2e/vue-start/custom-basepath/src/routes/__root.tsx index 8bc947b03a..c6d1eb197c 100644 --- a/e2e/vue-start/custom-basepath/src/routes/__root.tsx +++ b/e2e/vue-start/custom-basepath/src/routes/__root.tsx @@ -49,7 +49,11 @@ export const Route = createRootRoute({ { rel: 'icon', href: '/favicon.ico' }, ], }), - errorComponent: (props) =>

{props.error.stack}

, + errorComponent: (props) => ( +

+ {props.error instanceof Error ? props.error.stack : String(props.error)} +

+ ), notFoundComponent: () => , component: RootComponent, }) 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 50b9ca995a..7e3f528d68 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,11 +1,7 @@ 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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 97989b93ca..dfdb5cd844 100644 --- a/e2e/vue-start/custom-basepath/src/routes/api/users.ts +++ b/e2e/vue-start/custom-basepath/src/routes/api/users.ts @@ -38,11 +38,7 @@ 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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 b4e5a8a6a2..599e0f046e 100644 --- a/e2e/vue-start/custom-basepath/src/routes/posts.$postId.tsx +++ b/e2e/vue-start/custom-basepath/src/routes/posts.$postId.tsx @@ -1,9 +1,32 @@ +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, @@ -12,24 +35,3 @@ 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 1a9d58a31d..64d4754f2f 100644 --- a/e2e/vue-start/custom-basepath/src/routes/posts.tsx +++ b/e2e/vue-start/custom-basepath/src/routes/posts.tsx @@ -1,7 +1,36 @@ +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: [ @@ -13,30 +42,3 @@ 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 a52c6f32f7..f77ae7d3ab 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,24 +1,26 @@ +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 fb7fce5f4c..4effec0d5b 100644 --- a/e2e/vue-start/custom-basepath/src/routes/users.$userId.tsx +++ b/e2e/vue-start/custom-basepath/src/routes/users.$userId.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import axios from 'redaxios' @@ -6,6 +7,18 @@ 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 @@ -21,14 +34,3 @@ 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 1432e50451..fe926d0a44 100644 --- a/e2e/vue-start/custom-basepath/src/routes/users.tsx +++ b/e2e/vue-start/custom-basepath/src/routes/users.tsx @@ -1,8 +1,40 @@ +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 @@ -14,33 +46,3 @@ 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 66cb298f83..11d80d08b5 100644 --- a/e2e/vue-start/custom-basepath/src/utils/posts.tsx +++ b/e2e/vue-start/custom-basepath/src/utils/posts.tsx @@ -8,11 +8,7 @@ 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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 46be4b1580..7ba645b383 100644 --- a/e2e/vue-start/custom-basepath/src/utils/users.tsx +++ b/e2e/vue-start/custom-basepath/src/utils/users.tsx @@ -3,7 +3,3 @@ 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-start/custom-basepath/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-start/custom-basepath/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 new file mode 100644 index 0000000000..950326609c --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/.gitignore @@ -0,0 +1,7 @@ +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 new file mode 100644 index 0000000000..0033a0a5cc --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/package.json @@ -0,0 +1,32 @@ +{ + "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 new file mode 100644 index 0000000000..723cd32789 --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/playwright.config.ts @@ -0,0 +1,28 @@ +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 new file mode 100644 index 0000000000..bd92215136 --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/src/components/SfcStyledBox.vue @@ -0,0 +1,14 @@ + + + diff --git a/e2e/vue-start/dev-ssr-styles/src/router.tsx b/e2e/vue-start/dev-ssr-styles/src/router.tsx new file mode 100644 index 0000000000..c0d7f2b200 --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/src/router.tsx @@ -0,0 +1,10 @@ +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 new file mode 100644 index 0000000000..0dec479a07 --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/src/routes/__root.tsx @@ -0,0 +1,27 @@ +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 new file mode 100644 index 0000000000..733bc1d559 --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/src/routes/index.tsx @@ -0,0 +1,15 @@ +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 new file mode 100644 index 0000000000..9a67f9b153 --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/src/styles/app.css @@ -0,0 +1,5 @@ +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 new file mode 100644 index 0000000000..fe00a856b2 --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/src/vue-shim.d.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..0e052441b7 --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/tests/app.spec.ts @@ -0,0 +1,61 @@ +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 new file mode 100644 index 0000000000..b03b6485c8 --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/tests/setup/global.setup.ts @@ -0,0 +1,15 @@ +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 new file mode 100644 index 0000000000..898ea214b1 --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/tsconfig.json @@ -0,0 +1,23 @@ +{ + "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 new file mode 100644 index 0000000000..f8b7293af9 --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/vite.config.ts @@ -0,0 +1,14 @@ +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 a3b775e0eb..617ce4f430 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "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 4d86a1dbe7..82678ac00b 100644 --- a/e2e/vue-start/query-integration/playwright.config.ts +++ b/e2e/vue-start/query-integration/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { derivePort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await derivePort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, 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 9e928feafe..38f1e209dc 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,8 +1,29 @@ +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: { @@ -24,21 +45,3 @@ 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 b81d8af48b..025b0225be 100644 --- a/e2e/vue-start/scroll-restoration/package.json +++ b/e2e/vue-start/scroll-restoration/package.json @@ -9,13 +9,13 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0", "vue": "^3.5.25", "zod": "^4.4.3" @@ -28,7 +28,7 @@ "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "combinate": "^1.1.11", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "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 b0c365f8bd..1862174905 100644 --- a/e2e/vue-start/scroll-restoration/playwright.config.ts +++ b/e2e/vue-start/scroll-restoration/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -18,19 +13,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: `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, + command: `pnpm build && PORT=${PORT} pnpm start`, + wait: appServerReady, + reuseExistingServer: false, 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 d06f4a948b..77c03c5afa 100644 --- a/e2e/vue-start/scroll-restoration/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/scroll-restoration/src/components/DefaultCatchBoundary.tsx @@ -1,3 +1,5 @@ +import { defineComponent } from 'vue' +import type { PropType } from 'vue' import { ErrorComponent, Link, @@ -6,46 +8,54 @@ import { } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -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 - - )} -
-
- ) -} +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 + + )} +
+
+ ) + } + }, +}) diff --git a/e2e/vue-start/scroll-restoration/src/routes/__root.tsx b/e2e/vue-start/scroll-restoration/src/routes/__root.tsx index a28ab59f79..cd8a558359 100644 --- a/e2e/vue-start/scroll-restoration/src/routes/__root.tsx +++ b/e2e/vue-start/scroll-restoration/src/routes/__root.tsx @@ -53,7 +53,11 @@ export const Route = createRootRoute({ ], }), errorComponent: (props) => { - return

{props.error.stack}

+ return ( +

+ {props.error instanceof Error ? props.error.stack : String(props.error)} +

+ ) }, notFoundComponent: () => , component: RootComponent, diff --git a/e2e/vue-start/scroll-restoration/src/utils/posts.tsx b/e2e/vue-start/scroll-restoration/src/utils/posts.tsx index e45ef52969..c4a2d0dcca 100644 --- a/e2e/vue-start/scroll-restoration/src/utils/posts.tsx +++ b/e2e/vue-start/scroll-restoration/src/utils/posts.tsx @@ -10,11 +10,7 @@ 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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 46be4b1580..7ba645b383 100644 --- a/e2e/vue-start/scroll-restoration/src/utils/users.tsx +++ b/e2e/vue-start/scroll-restoration/src/utils/users.tsx @@ -3,7 +3,3 @@ 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 new file mode 100644 index 0000000000..df75cba73c --- /dev/null +++ b/e2e/vue-start/scroll-restoration/tests/scroll-restoration-lifecycle.spec.ts @@ -0,0 +1,4 @@ +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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-start/scroll-restoration/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-start/scroll-restoration/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 7ffcaae743..b555a01c26 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "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": "^0.11.9", + "srvx": "^1.0.0", "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 badd6db0eb..630989e41f 100644 --- a/e2e/vue-start/selective-ssr/playwright.config.ts +++ b/e2e/vue-start/selective-ssr/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, 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 a952abd4e0..9319a0982a 100644 --- a/e2e/vue-start/selective-ssr/src/routes/__root.tsx +++ b/e2e/vue-start/selective-ssr/src/routes/__root.tsx @@ -1,4 +1,5 @@ /// +import { defineComponent } from 'vue' import { Body, ClientOnly, @@ -14,6 +15,93 @@ 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: [ @@ -74,84 +162,5 @@ export const Route = createRootRoute({ return { root: typeof window === 'undefined' ? 'server' : 'client' } }, shellComponent: RootDocument, - 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} -
-
- -
- ) - }, + component: RouteComponent, }) - -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 4e7065cc48..522b5e9b8e 100644 --- a/e2e/vue-start/selective-ssr/src/routes/posts.$postId.tsx +++ b/e2e/vue-start/selective-ssr/src/routes/posts.$postId.tsx @@ -1,7 +1,47 @@ +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 }) => { @@ -46,37 +86,5 @@ export const Route = createFileRoute('/posts/$postId')({ } return { postId: typeof window === 'undefined' ? 'server' : 'client' } }, - 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} -
-
- ) - }, + component: RouteComponent, }) diff --git a/e2e/vue-start/selective-ssr/src/routes/posts.tsx b/e2e/vue-start/selective-ssr/src/routes/posts.tsx index 6c4e490dde..514628b229 100644 --- a/e2e/vue-start/selective-ssr/src/routes/posts.tsx +++ b/e2e/vue-start/selective-ssr/src/routes/posts.tsx @@ -1,7 +1,48 @@ +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 }) => { @@ -46,39 +87,5 @@ export const Route = createFileRoute('/posts')({ } return { posts: typeof window === 'undefined' ? 'server' : 'client' } }, - 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} -
-
- -
- ) - }, + component: RouteComponent, }) diff --git a/e2e/vue-start/serialization-adapters/package.json b/e2e/vue-start/serialization-adapters/package.json index c5b80bdced..a056e21da3 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "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": "^0.11.9", + "srvx": "^1.0.0", "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 badd6db0eb..630989e41f 100644 --- a/e2e/vue-start/serialization-adapters/playwright.config.ts +++ b/e2e/vue-start/serialization-adapters/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, 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 96911d2500..3ea36c7d46 100644 --- a/e2e/vue-start/serialization-adapters/src/routes/__root.tsx +++ b/e2e/vue-start/serialization-adapters/src/routes/__root.tsx @@ -1,4 +1,5 @@ /// +import { defineComponent } from 'vue' import { Body, ClientOnly, @@ -12,6 +13,51 @@ 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: [ @@ -31,46 +77,3 @@ 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/index.tsx b/e2e/vue-start/serialization-adapters/src/routes/index.tsx index 2d90e4b073..d6bacefdc0 100644 --- a/e2e/vue-start/serialization-adapters/src/routes/index.tsx +++ b/e2e/vue-start/serialization-adapters/src/routes/index.tsx @@ -2,7 +2,9 @@ import { Link, createFileRoute } from '@tanstack/vue-router' export const Route = createFileRoute('/')({ component: Home, - errorComponent: (e) =>
{e.error.message}
, + errorComponent: (e) => ( +
{e.error instanceof Error ? e.error.message : String(e.error)}
+ ), }) function Home() { 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 ecb35d0a55..e71906f03e 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,6 +1,47 @@ +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: () => { @@ -9,43 +50,6 @@ export const Route = createFileRoute('/ssr/data-only')({ loader: ({ context }) => { return context }, - 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)} -
-
-
-
- -
- ) - }, + component: RouteComponent, 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 bbc240b96d..b4f7fd8f23 100644 --- a/e2e/vue-start/serialization-adapters/src/routes/ssr/nested.tsx +++ b/e2e/vue-start/serialization-adapters/src/routes/ssr/nested.tsx @@ -1,6 +1,14 @@ +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() } @@ -8,8 +16,5 @@ export const Route = createFileRoute('/ssr/nested')({ loader: ({ context }) => { return context }, - component: () => { - const loaderData = Route.useLoaderData() - return - }, + component: RouteComponent, }) 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 4fce3271f8..f6056699af 100644 --- a/e2e/vue-start/serialization-adapters/src/routes/ssr/stream.tsx +++ b/e2e/vue-start/serialization-adapters/src/routes/ssr/stream.tsx @@ -1,7 +1,32 @@ import { Await, createFileRoute } from '@tanstack/vue-router' -import { Suspense } from 'vue' +import { defineComponent, 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) => @@ -13,29 +38,8 @@ export const Route = createFileRoute('/ssr/stream')({ } }, - errorComponent: (e) =>
{e.error.message}
, + errorComponent: (e) => ( +
{e.error instanceof Error ? e.error.message : String(e.error)}
+ ), 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 7c631b1fcc..dd1a7a9c6b 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-query": "^5.90.9", @@ -18,7 +18,7 @@ "@tanstack/vue-router-ssr-query": "workspace:^", "@tanstack/vue-start": "workspace:^", "js-cookie": "^3.0.5", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0", "vue": "^3.5.25", "zod": "^4.4.3" @@ -32,7 +32,7 @@ "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "combinate": "^1.1.11", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "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 cb1da03b94..48e14683f4 100644 --- a/e2e/vue-start/server-functions/playwright.config.ts +++ b/e2e/vue-start/server-functions/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -export const PORT = await getTestServerPort(packageJson.name) +export const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -21,8 +20,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, 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 d06f4a948b..77c03c5afa 100644 --- a/e2e/vue-start/server-functions/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/server-functions/src/components/DefaultCatchBoundary.tsx @@ -1,3 +1,5 @@ +import { defineComponent } from 'vue' +import type { PropType } from 'vue' import { ErrorComponent, Link, @@ -6,46 +8,54 @@ import { } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -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 - - )} -
-
- ) -} +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 + + )} +
+
+ ) + } + }, +}) diff --git a/e2e/vue-start/server-functions/src/routes/__root.tsx b/e2e/vue-start/server-functions/src/routes/__root.tsx index 342f7a79b3..a52b12deae 100644 --- a/e2e/vue-start/server-functions/src/routes/__root.tsx +++ b/e2e/vue-start/server-functions/src/routes/__root.tsx @@ -25,7 +25,11 @@ export const Route = createRootRoute({ links: [{ rel: 'stylesheet', href: appCss }], }), errorComponent: (props) => { - return

{props.error.stack}

+ return ( +

+ {props.error instanceof Error ? props.error.stack : String(props.error)} +

+ ) }, notFoundComponent: () => , component: RootComponent, 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 d7fef10223..90dddad0af 100644 --- a/e2e/vue-start/server-functions/src/routes/cookies/index.tsx +++ b/e2e/vue-start/server-functions/src/routes/cookies/index.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' @@ -5,21 +6,23 @@ 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 8b0c623b8c..8bfcc55ca3 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,7 +1,51 @@ +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({ @@ -31,44 +75,3 @@ 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 958aeaf617..099a8665bf 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,18 +1,21 @@ +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 4407103e81..6a8e1babed 100644 --- a/e2e/vue-start/server-routes/package.json +++ b/e2e/vue-start/server-routes/package.json @@ -18,7 +18,7 @@ "@tanstack/vue-router-ssr-query": "workspace:^", "@tanstack/vue-start": "workspace:^", "js-cookie": "^3.0.5", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0", "vue": "^3.5.25", "zod": "^4.4.3" @@ -32,7 +32,7 @@ "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "combinate": "^1.1.11", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "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 cb1da03b94..48e14683f4 100644 --- a/e2e/vue-start/server-routes/playwright.config.ts +++ b/e2e/vue-start/server-routes/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -export const PORT = await getTestServerPort(packageJson.name) +export const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -21,8 +20,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, 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 d06f4a948b..77c03c5afa 100644 --- a/e2e/vue-start/server-routes/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/server-routes/src/components/DefaultCatchBoundary.tsx @@ -1,3 +1,5 @@ +import { defineComponent } from 'vue' +import type { PropType } from 'vue' import { ErrorComponent, Link, @@ -6,46 +8,54 @@ import { } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -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 - - )} -
-
- ) -} +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 + + )} +
+
+ ) + } + }, +}) diff --git a/e2e/vue-start/server-routes/src/routes/__root.tsx b/e2e/vue-start/server-routes/src/routes/__root.tsx index 999d80fff1..aa4b1f31fa 100644 --- a/e2e/vue-start/server-routes/src/routes/__root.tsx +++ b/e2e/vue-start/server-routes/src/routes/__root.tsx @@ -25,7 +25,11 @@ export const Route = createRootRoute({ links: [{ rel: 'stylesheet', href: appCss }], }), errorComponent: (props) => { - return

{props.error.stack}

+ return ( +

+ {props.error instanceof Error ? props.error.stack : String(props.error)} +

+ ) }, notFoundComponent: () => , component: RootComponent, diff --git a/e2e/vue-start/spa-mode/package.json b/e2e/vue-start/spa-mode/package.json index b33ed9c859..c4270cfccd 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": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "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 badd6db0eb..630989e41f 100644 --- a/e2e/vue-start/spa-mode/playwright.config.ts +++ b/e2e/vue-start/spa-mode/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, 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 1e38664739..45aee73c06 100644 --- a/e2e/vue-start/spa-mode/src/routes/__root.tsx +++ b/e2e/vue-start/spa-mode/src/routes/__root.tsx @@ -1,4 +1,5 @@ /// +import { defineComponent } from 'vue' import { Body, ClientOnly, @@ -13,6 +14,71 @@ 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: [ @@ -44,65 +110,6 @@ export const Route = createRootRoute({ return { root: typeof window === 'undefined' ? 'server' : 'client' } }, shellComponent: RootDocument, - component: () => { - const loaderData = Route.useLoaderData() - const context = Route.useRouteContext() - return ( -
-

root

-
- loader: {loaderData.value.root} -
-
- context: {context.value.root} -
-
- -
- ) - }, + component: RouteComponent, 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 6733ef7436..9c25cbad25 100644 --- a/e2e/vue-start/spa-mode/src/routes/posts.$postId.tsx +++ b/e2e/vue-start/spa-mode/src/routes/posts.$postId.tsx @@ -1,5 +1,24 @@ +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( @@ -15,20 +34,6 @@ export const Route = createFileRoute('/posts/$postId')({ ) return { postId: typeof window === 'undefined' ? 'server' : 'client' } }, - component: () => { - const loaderData = Route.useLoaderData() - const context = Route.useRouteContext() - return ( -
-

postId

-
- loader: {loaderData.value.postId} -
-
- context: {context.value.postId} -
-
- ) - }, + component: RouteComponent, 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 e69ae1ea86..44c536adc4 100644 --- a/e2e/vue-start/spa-mode/src/routes/posts.tsx +++ b/e2e/vue-start/spa-mode/src/routes/posts.tsx @@ -1,5 +1,26 @@ +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( @@ -16,22 +37,6 @@ export const Route = createFileRoute('/posts')({ return { posts: typeof window === 'undefined' ? 'server' : 'client' } }, - component: () => { - const loaderData = Route.useLoaderData() - const context = Route.useRouteContext() - return ( -
-

posts

-
- loader: {loaderData.value.posts} -
-
- context: {context.value.posts} -
-
- -
- ) - }, + component: RouteComponent, pendingComponent: () =>
posts Loading...
, }) diff --git a/e2e/vue-start/start-manifest/package.json b/e2e/vue-start/start-manifest/package.json index dbf889db71..ae682f7a9d 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": "^0.11.9", + "srvx": "^1.0.0", "@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 b9f835c16a..653e08253f 100644 --- a/e2e/vue-start/start-manifest/playwright.config.ts +++ b/e2e/vue-start/start-manifest/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -16,8 +15,8 @@ export default defineConfig({ webServer: { command: `pnpm build && PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, 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 6c0f0d15ab..4d5bea0a33 100644 --- a/e2e/vue-start/start-manifest/tests/start-manifest.spec.ts +++ b/e2e/vue-start/start-manifest/tests/start-manifest.spec.ts @@ -372,24 +372,19 @@ test('shared widget CSS stays applied when navigating from static to lazy route' const widget = page.getByTestId('shared-widget') await expect(widget).toBeVisible() - expect(await getBackgroundColor('shared-widget', page)).toBe(SHARED_WIDGET_BG) - expect( - await widget.evaluate( - (element) => getComputedStyle(element).borderTopColor, - ), - ).toBe(SHARED_WIDGET_BORDER) + await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) + await expect(widget).toHaveCSS('border-top-color', 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 - .poll(() => getBackgroundColor('shared-widget', page), { - timeout: 5_000, - }) - .toBe(SHARED_WIDGET_BG) + await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) + await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) }) test('shared widget CSS stays applied when navigating from lazy to static route', async ({ @@ -399,27 +394,19 @@ 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() - await expect - .poll(() => getBackgroundColor('shared-widget', page), { - timeout: 5_000, - }) - .toBe(SHARED_WIDGET_BG) + 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 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 - .poll(() => getBackgroundColor('shared-widget', page), { - timeout: 5_000, - }) - .toBe(SHARED_WIDGET_BG) - expect( - await widget.evaluate( - (element) => getComputedStyle(element).borderTopColor, - ), - ).toBe(SHARED_WIDGET_BORDER) + await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) + await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) }) test('shared widget CSS is applied on direct navigation to lazy route', async ({ @@ -431,17 +418,8 @@ 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 - .poll(() => getBackgroundColor('shared-widget', page), { - timeout: 5_000, - }) - .toBe(SHARED_WIDGET_BG) - expect( - await widget.evaluate( - (element) => getComputedStyle(element).borderTopColor, - ), - ).toBe(SHARED_WIDGET_BORDER) + await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) + await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) }) test('shared widget CSS persists after navigating away from lazy and back', async ({ @@ -451,19 +429,21 @@ 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('shared-widget')).toBeVisible() + await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() + await expect(widget).toBeVisible() await page.getByTestId('nav-home').click() - await page.waitForURL(/\/([^/]*)(\/)?($|\?)/) + 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 - .poll(() => getBackgroundColor('shared-widget', page), { - timeout: 5_000, - }) - .toBe(SHARED_WIDGET_BG) + await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) + await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) }) diff --git a/e2e/vue-start/streaming-ssr/package.json b/e2e/vue-start/streaming-ssr/package.json new file mode 100644 index 0000000000..382120860a --- /dev/null +++ b/e2e/vue-start/streaming-ssr/package.json @@ -0,0 +1,59 @@ +{ + "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 new file mode 100644 index 0000000000..c2f3b67a0c --- /dev/null +++ b/e2e/vue-start/streaming-ssr/playwright.config.ts @@ -0,0 +1,39 @@ +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 new file mode 100644 index 0000000000..ac4c9ab156 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/routeTree.gen.ts @@ -0,0 +1,282 @@ +/* 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 new file mode 100644 index 0000000000..257eb8dac9 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/router.tsx @@ -0,0 +1,18 @@ +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 new file mode 100644 index 0000000000..d3b3339720 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/routes/__root.tsx @@ -0,0 +1,103 @@ +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 new file mode 100644 index 0000000000..5fed8ab517 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/routes/concurrent.tsx @@ -0,0 +1,54 @@ +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 new file mode 100644 index 0000000000..5018f9e07c --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/routes/deferred-rejection.tsx @@ -0,0 +1,49 @@ +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 new file mode 100644 index 0000000000..6a8affe1b4 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/routes/deferred.tsx @@ -0,0 +1,100 @@ +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 new file mode 100644 index 0000000000..ac004b041c --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/routes/fast-serial.tsx @@ -0,0 +1,49 @@ +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 new file mode 100644 index 0000000000..0350eb5d4a --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/routes/index.tsx @@ -0,0 +1,58 @@ +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 new file mode 100644 index 0000000000..4361696107 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/routes/many-promises.tsx @@ -0,0 +1,94 @@ +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 new file mode 100644 index 0000000000..b24336ec40 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/routes/nested-deferred.tsx @@ -0,0 +1,143 @@ +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 new file mode 100644 index 0000000000..b22154b78e --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/routes/query-heavy.tsx @@ -0,0 +1,168 @@ +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 new file mode 100644 index 0000000000..f897e03ff0 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/routes/slow-render.tsx @@ -0,0 +1,77 @@ +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 new file mode 100644 index 0000000000..31368bedfc --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/routes/stream.tsx @@ -0,0 +1,171 @@ +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 new file mode 100644 index 0000000000..bbad10839e --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/routes/sync-only.tsx @@ -0,0 +1,25 @@ +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 new file mode 100644 index 0000000000..8b9b3a8dcc --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/client-navigation.spec.ts @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000000..8625473a58 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/concurrent.spec.ts @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000000..355b5019bc --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/deferred-rejection.spec.ts @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000000..3145897d7b --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/deferred.spec.ts @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000000..95df0555e2 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/fast-serial.spec.ts @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000000..5d49d34a56 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/home.spec.ts @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000000..b747bd7d0a --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/many-promises.spec.ts @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000000..8df20a8a95 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/nested-deferred.spec.ts @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000000..34241cfbaa --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/preview-streaming.spec.ts @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000000..d15c092f6e --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/query-heavy.spec.ts @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000000..0d5a87363f --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/slow-render.spec.ts @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000000..9dfc6820ad --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/stream.spec.ts @@ -0,0 +1,22 @@ +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 new file mode 100644 index 0000000000..b25572f615 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/sync-only.spec.ts @@ -0,0 +1,7 @@ +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 new file mode 100644 index 0000000000..390dad84c0 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tsconfig.json @@ -0,0 +1,22 @@ +{ + "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 new file mode 100644 index 0000000000..6519ec54c8 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/vite.config.ts @@ -0,0 +1,10 @@ +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 efafbb2b35..90f09ce911 100644 --- a/e2e/vue-start/virtual-routes/package.json +++ b/e2e/vue-start/virtual-routes/package.json @@ -9,14 +9,14 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/virtual-file-routes": "workspace:^", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0", "vue": "^3.5.25", "zod": "^4.4.3" @@ -29,7 +29,7 @@ "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "combinate": "^1.1.11", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "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 b0c365f8bd..1862174905 100644 --- a/e2e/vue-start/virtual-routes/playwright.config.ts +++ b/e2e/vue-start/virtual-routes/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -18,19 +13,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: `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, + command: `pnpm build && PORT=${PORT} pnpm start`, + wait: appServerReady, + reuseExistingServer: false, 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 1b4c92b41d..f7a1941605 100644 --- a/e2e/vue-start/virtual-routes/src/posts.tsx +++ b/e2e/vue-start/virtual-routes/src/posts.tsx @@ -7,11 +7,7 @@ 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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 5086e3ad88..4bc3824f62 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,7 +1,20 @@ +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, @@ -14,14 +27,3 @@ 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 f56d6550a6..dd380aa353 100644 --- a/e2e/vue-start/virtual-routes/src/routes/posts/posts.tsx +++ b/e2e/vue-start/virtual-routes/src/routes/posts/posts.tsx @@ -1,37 +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) => ( +
  • + +
    {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 66cb298f83..11d80d08b5 100644 --- a/e2e/vue-start/virtual-routes/src/utils/posts.tsx +++ b/e2e/vue-start/virtual-routes/src/utils/posts.tsx @@ -8,11 +8,7 @@ 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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 46be4b1580..7ba645b383 100644 --- a/e2e/vue-start/virtual-routes/src/utils/users.tsx +++ b/e2e/vue-start/virtual-routes/src/utils/users.tsx @@ -3,7 +3,3 @@ 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 3182febfa0..e9db98e3f3 100644 --- a/e2e/vue-start/virtual-routes/tests/app.spec.ts +++ b/e2e/vue-start/virtual-routes/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' 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 deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-start/virtual-routes/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-start/virtual-routes/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 9ddcbc13fe..6c30b1500f 100644 --- a/e2e/vue-start/website/package.json +++ b/e2e/vue-start/website/package.json @@ -9,13 +9,13 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0", "vue": "^3.5.25", "zod": "^4.4.3" @@ -27,7 +27,7 @@ "@types/node": "^22.10.2", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "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 f6dd61ba6c..e6b92ce385 100644 --- a/e2e/vue-start/website/playwright.config.ts +++ b/e2e/vue-start/website/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -21,8 +20,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-start/website/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/website/src/components/DefaultCatchBoundary.tsx index d06f4a948b..77c03c5afa 100644 --- a/e2e/vue-start/website/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/website/src/components/DefaultCatchBoundary.tsx @@ -1,3 +1,5 @@ +import { defineComponent } from 'vue' +import type { PropType } from 'vue' import { ErrorComponent, Link, @@ -6,46 +8,54 @@ import { } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -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 - - )} -
-
- ) -} +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 + + )} +
+
+ ) + } + }, +}) 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 f56c911b88..1d9173f200 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,9 +1,27 @@ +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/$', )({ @@ -26,19 +44,3 @@ 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 97f8fdd49a..1ca9e97cbe 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,7 +1,24 @@ +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/$', )({ @@ -15,18 +32,3 @@ 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 1b422b2ea0..e1c57491aa 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,3 +1,4 @@ +import { defineComponent } from 'vue' import { Link, Outlet, @@ -7,6 +8,108 @@ 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', )({ @@ -20,104 +123,3 @@ 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/__root.tsx b/e2e/vue-start/website/src/routes/__root.tsx index 64228c166e..744cac4b11 100644 --- a/e2e/vue-start/website/src/routes/__root.tsx +++ b/e2e/vue-start/website/src/routes/__root.tsx @@ -51,7 +51,11 @@ export const Route = createRootRoute({ ], }), errorComponent: (props) => { - return

{props.error.stack}

+ return ( +

+ {props.error instanceof Error ? props.error.stack : String(props.error)} +

+ ) }, notFoundComponent: () => , component: RootComponent, 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 ed8e4d0bb4..d6c9b00671 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,23 +1,31 @@ +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 fcbeaa35d0..b52198950d 100644 --- a/e2e/vue-start/website/src/routes/_library.tsx +++ b/e2e/vue-start/website/src/routes/_library.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { Link, Outlet, @@ -6,6 +7,53 @@ 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() @@ -15,48 +63,3 @@ 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 new file mode 100644 index 0000000000..eb47fbd925 --- /dev/null +++ b/examples/AGENTS.md @@ -0,0 +1,4 @@ +# 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 89bc91e3bd..1efa172047 100644 --- a/examples/react/authenticated-routes-firebase/package.json +++ b/examples/react/authenticated-routes-firebase/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "firebase": "^11.4.0", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/authenticated-routes/package.json b/examples/react/authenticated-routes/package.json index 4d0bf221ed..6af48f1d34 100644 --- a/examples/react/authenticated-routes/package.json +++ b/examples/react/authenticated-routes/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/basic-default-search-params/package.json b/examples/react/basic-default-search-params/package.json index 71b766b864..96c68fecd4 100644 --- a/examples/react/basic-default-search-params/package.json +++ b/examples/react/basic-default-search-params/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-query": "^5.102.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/basic-devtools-panel/package.json b/examples/react/basic-devtools-panel/package.json index 7f45996dce..ccae95d73f 100644 --- a/examples/react/basic-devtools-panel/package.json +++ b/examples/react/basic-devtools-panel/package.json @@ -10,9 +10,10 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", + "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.67.2", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/basic-file-based/package.json b/examples/react/basic-file-based/package.json index 9c483a9003..9c3cacada1 100644 --- a/examples/react/basic-file-based/package.json +++ b/examples/react/basic-file-based/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/basic-non-nested-devtools/package.json b/examples/react/basic-non-nested-devtools/package.json index 75461ace4b..32e856ebcf 100644 --- a/examples/react/basic-non-nested-devtools/package.json +++ b/examples/react/basic-non-nested-devtools/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/basic-react-query-file-based/package.json b/examples/react/basic-react-query-file-based/package.json index e889f5668c..d01a02872e 100644 --- a/examples/react/basic-react-query-file-based/package.json +++ b/examples/react/basic-react-query-file-based/package.json @@ -10,11 +10,11 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.90.0", + "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/basic-react-query/package.json b/examples/react/basic-react-query/package.json index e00c550d9b..edab96afac 100644 --- a/examples/react/basic-react-query/package.json +++ b/examples/react/basic-react-query/package.json @@ -10,10 +10,10 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.90.0", + "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/basic-ssr-file-based/package.json b/examples/react/basic-ssr-file-based/package.json index ff7a73a841..3222c33e19 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.27", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/react-router": "^1.170.46", + "@tanstack/router-plugin": "^1.169.0", "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.1", + "@tanstack/react-router-devtools": "^1.167.3", "@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 d746dc9ac3..c3c87c8d88 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.27", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/react-router": "^1.170.46", + "@tanstack/router-plugin": "^1.169.0", "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.1", + "@tanstack/react-router-devtools": "^1.167.3", "@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 331faca7e9..84d326435c 100644 --- a/examples/react/basic-virtual-file-based/package.json +++ b/examples/react/basic-virtual-file-based/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "@tanstack/virtual-file-routes": "^1.162.0", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/basic-virtual-inside-file-based/package.json b/examples/react/basic-virtual-inside-file-based/package.json index 430d2fc971..c04cb6012e 100644 --- a/examples/react/basic-virtual-inside-file-based/package.json +++ b/examples/react/basic-virtual-inside-file-based/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "@tanstack/virtual-file-routes": "^1.162.0", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/basic/package.json b/examples/react/basic/package.json index 9e070e3e36..2c09a3dfdf 100644 --- a/examples/react/basic/package.json +++ b/examples/react/basic/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/deferred-data/package.json b/examples/react/deferred-data/package.json index be214567c7..99afb661ee 100644 --- a/examples/react/deferred-data/package.json +++ b/examples/react/deferred-data/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/i18n-paraglide/package.json b/examples/react/i18n-paraglide/package.json index 2b678ad81d..88140e8911 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.27", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/react-router": "^1.170.46", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.1.1", "react-dom": "^19.1.1", "tailwindcss": "^4.2.2" @@ -26,5 +26,16 @@ "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 a84776db90..e02defb3ce 100644 --- a/examples/react/kitchen-sink-file-based/package.json +++ b/examples/react/kitchen-sink-file-based/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", 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 90046f03bf..e3dd032ac2 100644 --- a/examples/react/kitchen-sink-react-query-file-based/package.json +++ b/examples/react/kitchen-sink-react-query-file-based/package.json @@ -10,11 +10,11 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.90.0", + "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/kitchen-sink-react-query/package.json b/examples/react/kitchen-sink-react-query/package.json index cbd5f9e430..14d0dc8e86 100644 --- a/examples/react/kitchen-sink-react-query/package.json +++ b/examples/react/kitchen-sink-react-query/package.json @@ -10,10 +10,10 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.90.0", + "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/kitchen-sink/package.json b/examples/react/kitchen-sink/package.json index 44e34975d6..f738efc37e 100644 --- a/examples/react/kitchen-sink/package.json +++ b/examples/react/kitchen-sink/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/large-file-based/package.json b/examples/react/large-file-based/package.json index 83396cca79..23d469d120 100644 --- a/examples/react/large-file-based/package.json +++ b/examples/react/large-file-based/package.json @@ -12,10 +12,10 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/router-plugin": "^1.168.30", + "@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", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/location-masking/package.json b/examples/react/location-masking/package.json index edfee0495b..fe005c0d2f 100644 --- a/examples/react/location-masking/package.json +++ b/examples/react/location-masking/package.json @@ -11,9 +11,9 @@ "dependencies": { "@radix-ui/react-dialog": "^1.1.6", "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-query": "^5.102.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/navigation-blocking/package.json b/examples/react/navigation-blocking/package.json index 6194bbd4e7..a7677dfd51 100644 --- a/examples/react/navigation-blocking/package.json +++ b/examples/react/navigation-blocking/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-query": "^5.102.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/quickstart-esbuild-file-based/esbuild.config.js b/examples/react/quickstart-esbuild-file-based/esbuild.config.js index fb7950d1fa..2f83a79984 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', autoCodeSplitting: true })], + plugins: [tanstackRouter({ target: 'react' })], } diff --git a/examples/react/quickstart-esbuild-file-based/package.json b/examples/react/quickstart-esbuild-file-based/package.json index 77c0de6e15..d855694fec 100644 --- a/examples/react/quickstart-esbuild-file-based/package.json +++ b/examples/react/quickstart-esbuild-file-based/package.json @@ -9,9 +9,9 @@ "start": "dev" }, "dependencies": { - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/quickstart-file-based/package.json b/examples/react/quickstart-file-based/package.json index ebf82a35b0..976ec838d1 100644 --- a/examples/react/quickstart-file-based/package.json +++ b/examples/react/quickstart-file-based/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/quickstart-rspack-file-based/package.json b/examples/react/quickstart-rspack-file-based/package.json index cf99236599..824998f428 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.27", - "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "postcss": "^8.5.1", "react": "^19.0.0", "react-dom": "^19.0.0", "tailwindcss": "^4.2.2" }, "devDependencies": { - "@rsbuild/core": "^2.1.0", + "@rsbuild/core": "^2.3.1", "@rsbuild/plugin-react": "^2.0.0", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/router-plugin": "^1.169.0", "@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 9065791476..baa14b89dd 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.27", - "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { "@swc/core": "^1.15.33", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/router-plugin": "^1.169.0", "@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 18060c100e..b6db476ea8 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.27", - "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "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 4d6ec07e10..b158eeda56 100644 --- a/examples/react/router-monorepo-react-query/package.json +++ b/examples/react/router-monorepo-react-query/package.json @@ -10,11 +10,11 @@ "dev": "pnpm post-query build && pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/react-query": "^5.90.0", + "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" 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 336998abe7..f0994165c2 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.90.0", + "@tanstack/react-query": "^5.102.0", "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { - "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-router-devtools": "^1.167.3", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", @@ -33,6 +33,12 @@ "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 ce3a7d2339..196cb055a9 100644 --- a/examples/react/router-monorepo-react-query/packages/app/tsconfig.json +++ b/examples/react/router-monorepo-react-query/packages/app/tsconfig.json @@ -8,5 +8,6 @@ "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 21dc0d7793..7f5e186ab0 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.90.0", + "@tanstack/react-query": "^5.102.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 15b1daa463..98a06051be 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,7 +8,7 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/react-query": "^5.90.0", + "@tanstack/react-query": "^5.102.0", "redaxios": "^0.5.1", "zod": "^4.4.3" }, 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 47d06d6298..1397db14b5 100644 --- a/examples/react/router-monorepo-react-query/packages/router/package.json +++ b/examples/react/router-monorepo-react-query/packages/router/package.json @@ -9,10 +9,10 @@ "types": "./dist/index.d.ts", "dependencies": { "@router-mono-react-query/post-query": "workspace:*", - "@tanstack/history": "^1.162.1", - "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.170.27", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/history": "^1.162.5", + "@tanstack/react-query": "^5.102.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/router-monorepo-simple-lazy/package.json b/examples/react/router-monorepo-simple-lazy/package.json index 4d94d0af5c..e044d86681 100644 --- a/examples/react/router-monorepo-simple-lazy/package.json +++ b/examples/react/router-monorepo-simple-lazy/package.json @@ -8,9 +8,9 @@ "dev": "pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" 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 a1e792cc3d..cfc7a94942 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.1", + "@tanstack/react-router-devtools": "^1.167.3", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", @@ -32,6 +32,12 @@ "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 ce3a7d2339..196cb055a9 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/app/tsconfig.json +++ b/examples/react/router-monorepo-simple-lazy/packages/app/tsconfig.json @@ -8,5 +8,6 @@ "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 5e387f61f4..65738d6025 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.90.0", + "@tanstack/react-query": "^5.102.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 5b89330354..afd4702b5d 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/router/package.json +++ b/examples/react/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.1", - "@tanstack/react-router": "^1.170.27", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/history": "^1.162.5", + "@tanstack/react-router": "^1.170.46", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/router-monorepo-simple/package.json b/examples/react/router-monorepo-simple/package.json index 18065c806d..800d948c81 100644 --- a/examples/react/router-monorepo-simple/package.json +++ b/examples/react/router-monorepo-simple/package.json @@ -8,9 +8,9 @@ "dev": "pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" diff --git a/examples/react/router-monorepo-simple/packages/app/package.json b/examples/react/router-monorepo-simple/packages/app/package.json index 01da864c38..a06431ef86 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.1", + "@tanstack/react-router-devtools": "^1.167.3", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", @@ -32,6 +32,12 @@ "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 ce3a7d2339..196cb055a9 100644 --- a/examples/react/router-monorepo-simple/packages/app/tsconfig.json +++ b/examples/react/router-monorepo-simple/packages/app/tsconfig.json @@ -8,5 +8,6 @@ "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 168472d5f9..391b72e610 100644 --- a/examples/react/router-monorepo-simple/packages/router/package.json +++ b/examples/react/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.1", - "@tanstack/react-router": "^1.170.27", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/history": "^1.162.5", + "@tanstack/react-router": "^1.170.46", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/scroll-restoration/package.json b/examples/react/scroll-restoration/package.json index e7ee10c8e1..704ff13838 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.27", - "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "@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 ba3ccc3de5..35e041e825 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.90.0", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/router-plugin": "^1.168.30", + "@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/valibot-adapter": "^1.167.0", "@tanstack/zod-adapter": "^1.167.0", "arktype": "^2.1.7", @@ -26,13 +26,15 @@ "zod": "^3.24.2" }, "devDependencies": { - "@testing-library/jest-dom": "^6.6.3", + "@testing-library/jest-dom": "^7.0.1", "@testing-library/react": "^16.2.0", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "@typescript/native": "npm:typescript@^7.0.2", + "jsdom": "^27.0.0", "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "vite": "^8.0.14", + "vitest": "^5.0.4" } } diff --git a/examples/react/search-validator-adapters/tests/arktype.test.tsx b/examples/react/search-validator-adapters/tests/arktype.test.tsx index 1c3a1baf76..776cc8369e 100644 --- a/examples/react/search-validator-adapters/tests/arktype.test.tsx +++ b/examples/react/search-validator-adapters/tests/arktype.test.tsx @@ -8,7 +8,6 @@ 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 new file mode 100644 index 0000000000..8f7cbf15be --- /dev/null +++ b/examples/react/search-validator-adapters/tests/jest-dom.setup.ts @@ -0,0 +1,18 @@ +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 3680d2302c..d3e18db414 100644 --- a/examples/react/search-validator-adapters/tests/valibot.test.tsx +++ b/examples/react/search-validator-adapters/tests/valibot.test.tsx @@ -8,7 +8,6 @@ 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 5b41e6e26b..e4b93f5cc3 100644 --- a/examples/react/search-validator-adapters/vite.config.ts +++ b/examples/react/search-validator-adapters/vite.config.ts @@ -11,6 +11,7 @@ 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 330b1d0152..4ab9aff272 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.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/react-start": "^1.168.44", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "react": "^19.0.0", "react-dom": "^19.0.0", "zod": "^4.4.3" diff --git a/examples/react/start-bare/src/router.tsx b/examples/react/start-bare/src/router.tsx index a464233af9..6f82cbf378 100644 --- a/examples/react/start-bare/src/router.tsx +++ b/examples/react/start-bare/src/router.tsx @@ -5,7 +5,9 @@ export function getRouter() { const router = createRouter({ routeTree, defaultPreload: 'intent', - defaultErrorComponent: (err) =>

{err.error.stack}

, + defaultErrorComponent: (err) => ( +

{err.error instanceof Error ? err.error.stack : String(err.error)}

+ ), defaultNotFoundComponent: () =>

not found

, scrollRestoration: true, }) diff --git a/examples/react/start-basic-auth/README.md b/examples/react/start-basic-auth/README.md index 4e5ee29b40..7f1b093ba5 100644 --- a/examples/react/start-basic-auth/README.md +++ b/examples/react/start-basic-auth/README.md @@ -39,3 +39,13 @@ 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 56713b8430..9ab89bdac9 100644 --- a/examples/react/start-basic-auth/package.json +++ b/examples/react/start-basic-auth/package.json @@ -14,9 +14,10 @@ "@libsql/client": "^0.15.15", "@prisma/adapter-libsql": "^7.0.0", "@prisma/client": "^7.0.0", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/react-start": "^1.168.44", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", + "iron-session": "^9.0.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/start-basic-auth/src/routes/__root.tsx b/examples/react/start-basic-auth/src/routes/__root.tsx index 5728345fcf..3367c62f27 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 { useAppSession } from '~/utils/session.js' +import { getAppSession } 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 useAppSession() + const session = await getAppSession() - if (!session.data.userEmail) { + if (!session.userEmail) { return null } return { - email: session.data.userEmail, + email: session.userEmail, } }) diff --git a/examples/react/start-basic-auth/src/routes/_authed.tsx b/examples/react/start-basic-auth/src/routes/_authed.tsx index 3944e590f9..0b5c6f9047 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 { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' export const loginFn = createServerFn({ method: 'POST' }) .validator((d: { email: string; password: string }) => d) @@ -33,13 +33,10 @@ export const loginFn = createServerFn({ method: 'POST' }) } } - // Create a session - const session = await useAppSession() - // Store the user's email in the session - await session.update({ - userEmail: user.email, - }) + const session = await getAppSession() + session.userEmail = user.email + await session.save() }) export const Route = createFileRoute('/_authed')({ @@ -49,7 +46,7 @@ export const Route = createFileRoute('/_authed')({ } }, errorComponent: ({ error }) => { - if (error.message === 'Not authenticated') { + if (error instanceof Error && error.message === 'Not authenticated') { return } diff --git a/examples/react/start-basic-auth/src/routes/logout.tsx b/examples/react/start-basic-auth/src/routes/logout.tsx index 28f3c9f8fe..73cdaf1600 100644 --- a/examples/react/start-basic-auth/src/routes/logout.tsx +++ b/examples/react/start-basic-auth/src/routes/logout.tsx @@ -1,11 +1,10 @@ import { redirect, createFileRoute } from '@tanstack/react-router' import { createServerFn } from '@tanstack/react-start' -import { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' const logoutFn = createServerFn().handler(async () => { - const session = await useAppSession() - - session.clear() + const session = await getAppSession() + session.destroy() 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 247a94c03c..4dc8e350ac 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 { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' export const signupFn = createServerFn({ method: 'POST' }) .validator( @@ -20,9 +20,6 @@ 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 { @@ -33,9 +30,9 @@ export const signupFn = createServerFn({ method: 'POST' }) } // Store the user's email in the session - await session.update({ - userEmail: found.email, - }) + const session = await getAppSession() + session.userEmail = found.email + await session.save() // Redirect to the prev page stored in the "redirect" search param throw redirect({ @@ -52,9 +49,9 @@ export const signupFn = createServerFn({ method: 'POST' }) }) // Store the user's email in the session - await session.update({ - userEmail: user.email, - }) + const session = await getAppSession() + session.userEmail = user.email + await session.save() // 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 c38bac1e48..7df7bc4da2 100644 --- a/examples/react/start-basic-auth/src/utils/session.ts +++ b/examples/react/start-basic-auth/src/utils/session.ts @@ -1,13 +1,29 @@ -// src/services/session.server.ts -import { useSession } from '@tanstack/react-start/server' +import { getIronSession } from 'iron-session' +import { getCookie, setCookie } from '@tanstack/react-start/server' import type { User } from '@prisma/client' type SessionUser = { userEmail: User['email'] } -export function useAppSession() { - return useSession({ - password: 'ChangeThisBeforeShippingToProdOrYouWillBeFired', - }) +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: '/', + }, + }, + ) } diff --git a/examples/react/start-basic-authjs/package.json b/examples/react/start-basic-authjs/package.json index 317124a800..e9fa789ea6 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.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/react-start": "^1.168.44", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "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 95cc169a06..2108922446 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.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/react-start": "^1.168.44", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "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 77c61c2504..70cc728ae4 100644 --- a/examples/react/start-basic-react-query/README.md +++ b/examples/react/start-basic-react-query/README.md @@ -38,5 +38,18 @@ This example demonstrates how to use TanStack Query with TanStack Start for: - Server-side data fetching - Client-side caching and synchronization -- Optimistic updates -- Automatic refetching +- 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. diff --git a/examples/react/start-basic-react-query/package.json b/examples/react/start-basic-react-query/package.json index 00573ed053..9d819d4390 100644 --- a/examples/react/start-basic-react-query/package.json +++ b/examples/react/start-basic-react-query/package.json @@ -7,15 +7,16 @@ "dev": "vite dev", "build": "vite build && tsc --noEmit", "preview": "vite preview", - "start": "pnpx srvx --prod -s ../client dist/server/server.js" + "start": "pnpx srvx --prod -s ../client dist/server/server.js", + "test:e2e": "playwright test" }, "dependencies": { - "@tanstack/react-query": "^5.90.0", + "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/react-router-ssr-query": "^1.167.1", - "@tanstack/react-start": "^1.168.44", + "@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", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -30,6 +31,7 @@ "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "vite": "^8.0.14", + "@playwright/test": "^1.61.0" } } diff --git a/examples/react/start-basic-react-query/playwright.config.ts b/examples/react/start-basic-react-query/playwright.config.ts new file mode 100644 index 0000000000..298a1133e9 --- /dev/null +++ b/examples/react/start-basic-react-query/playwright.config.ts @@ -0,0 +1,14 @@ +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 e010af19fe..0c7a90d4a1 100644 --- a/examples/react/start-basic-react-query/src/routeTree.gen.ts +++ b/examples/react/start-basic-react-query/src/routeTree.gen.ts @@ -13,6 +13,7 @@ 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' @@ -45,6 +46,11 @@ 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', @@ -113,6 +119,7 @@ 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 @@ -127,6 +134,7 @@ 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 @@ -145,6 +153,7 @@ 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 @@ -164,6 +173,7 @@ export interface FileRouteTypes { | '/posts' | '/users' | '/deferred' + | '/preferences' | '/redirect' | '/api/users' | '/posts/$postId' @@ -178,6 +188,7 @@ export interface FileRouteTypes { to: | '/' | '/deferred' + | '/preferences' | '/redirect' | '/api/users' | '/posts/$postId' @@ -195,6 +206,7 @@ export interface FileRouteTypes { | '/users' | '/_pathlessLayout' | '/deferred' + | '/preferences' | '/redirect' | '/_pathlessLayout/_nested-layout' | '/api/users' @@ -214,6 +226,7 @@ export interface RootRouteChildren { UsersRouteRoute: typeof UsersRouteRouteWithChildren PathlessLayoutRoute: typeof PathlessLayoutRouteWithChildren DeferredRoute: typeof DeferredRoute + PreferencesRoute: typeof PreferencesRoute RedirectRoute: typeof RedirectRoute ApiUsersRoute: typeof ApiUsersRouteWithChildren PostsPostIdDeepRoute: typeof PostsPostIdDeepRoute @@ -249,6 +262,13 @@ 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' @@ -412,6 +432,7 @@ const rootRouteChildren: RootRouteChildren = { UsersRouteRoute: UsersRouteRouteWithChildren, PathlessLayoutRoute: PathlessLayoutRouteWithChildren, DeferredRoute: DeferredRoute, + PreferencesRoute: PreferencesRoute, RedirectRoute: RedirectRoute, ApiUsersRoute: ApiUsersRouteWithChildren, PostsPostIdDeepRoute: PostsPostIdDeepRoute, @@ -421,10 +442,11 @@ export const routeTree = rootRouteImport ._addFileTypes() import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/react-start' +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-basic-react-query/src/router.tsx b/examples/react/start-basic-react-query/src/router.tsx index 314b29edd0..345055c116 100644 --- a/examples/react/start-basic-react-query/src/router.tsx +++ b/examples/react/start-basic-react-query/src/router.tsx @@ -6,12 +6,15 @@ import { DefaultCatchBoundary } from './components/DefaultCatchBoundary' import { NotFound } from './components/NotFound' export function getRouter() { - const queryClient = new QueryClient() + const queryClient = new QueryClient({ + defaultOptions: { queries: { staleTime: 30_000 } }, + }) 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 bc278f8036..71c19b2c6f 100644 --- a/examples/react/start-basic-react-query/src/routes/__root.tsx +++ b/examples/react/start-basic-react-query/src/routes/__root.tsx @@ -83,6 +83,7 @@ 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 new file mode 100644 index 0000000000..5fb1e247fb --- /dev/null +++ b/examples/react/start-basic-react-query/src/start.ts @@ -0,0 +1,9 @@ +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 new file mode 100644 index 0000000000..74c33e5848 --- /dev/null +++ b/examples/react/start-basic-react-query/src/utils/preferences.ts @@ -0,0 +1,34 @@ +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 new file mode 100644 index 0000000000..309c402798 --- /dev/null +++ b/examples/react/start-basic-react-query/tests/preferences.spec.ts @@ -0,0 +1,67 @@ +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 44afd5733f..bea4ba26ef 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.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/react-start": "^1.168.44", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "react": "^19.2.3", "react-dom": "^19.2.3", "tailwind-merge": "^3.6.0", "zod": "^4.4.3" }, "devDependencies": { - "@rsbuild/core": "^2.0.11", + "@rsbuild/core": "^2.3.1", "@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": "^0.11.18", + "srvx": "^1.0.0", "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 d8e4c367b9..58d573ca36 100644 --- a/examples/react/start-basic-static/package.json +++ b/examples/react/start-basic-static/package.json @@ -10,10 +10,10 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/react-start": "^1.168.44", - "@tanstack/start-static-server-functions": "^1.167.27", + "@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", "@vitejs/plugin-react": "^6.0.1", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/start-basic/package.json b/examples/react/start-basic/package.json index 70165026a4..46df8e4650 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.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/react-start": "^1.168.44", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "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.260311-beta", + "nitro": "^3.0.260903-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 4bd6f10b48..24f7113912 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.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/react-router-ssr-query": "^1.167.1", - "@tanstack/react-start": "^1.168.44", - "@tanstack/router-plugin": "^1.168.30", + "@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", "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": "^4.1.4", + "vitest": "^5.0.4", "web-vitals": "^5.1.0" } } diff --git a/examples/react/start-clerk-basic/package.json b/examples/react/start-clerk-basic/package.json index 7e4697e46d..022300e159 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.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/react-start": "^1.168.44", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "@vitejs/plugin-react": "^6.0.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "tailwind-merge": "^3.6.0" }, "devDependencies": { diff --git a/examples/react/start-clerk-basic/src/routes/_authed.tsx b/examples/react/start-clerk-basic/src/routes/_authed.tsx index 1a97917c12..04f8196894 100644 --- a/examples/react/start-clerk-basic/src/routes/_authed.tsx +++ b/examples/react/start-clerk-basic/src/routes/_authed.tsx @@ -8,7 +8,7 @@ export const Route = createFileRoute('/_authed')({ } }, errorComponent: ({ error }) => { - if (error.message === 'Not authenticated') { + if (error instanceof Error && error.message === 'Not authenticated') { return (
diff --git a/examples/react/start-convex-trellaux/package.json b/examples/react/start-convex-trellaux/package.json index 89b2f1587c..3452f910d0 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.90.0", + "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/react-router-ssr-query": "^1.167.1", - "@tanstack/react-start": "^1.168.44", + "@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", "concurrently": "^8.2.2", "convex": "^1.19.0", "ky": "^1.7.4", diff --git a/examples/react/start-counter/package.json b/examples/react/start-counter/package.json index 257959da0f..8f4673143e 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.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/react-start": "^1.168.44", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "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 f8519b2f95..074f714d5c 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.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/react-start": "^1.168.44", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "react": "^19.1.1", "react-dom": "^19.1.1" }, @@ -27,5 +27,16 @@ "@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 e9a5b627b5..f9f86b81d1 100644 --- a/examples/react/start-large/package.json +++ b/examples/react/start-large/package.json @@ -12,10 +12,10 @@ "test:types": "tsc --extendedDiagnostics" }, "dependencies": { - "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/react-start": "^1.168.44", + "@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", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/start-material-ui/package.json b/examples/react/start-material-ui/package.json index 8ff3e1d6ce..1647e95f20 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.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/react-start": "^1.168.44", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "react": "^19.0.0", "react-dom": "^19.0.0", "zod": "^4.4.3" diff --git a/examples/react/start-material-ui/src/router.tsx b/examples/react/start-material-ui/src/router.tsx index a464233af9..6f82cbf378 100644 --- a/examples/react/start-material-ui/src/router.tsx +++ b/examples/react/start-material-ui/src/router.tsx @@ -5,7 +5,9 @@ export function getRouter() { const router = createRouter({ routeTree, defaultPreload: 'intent', - defaultErrorComponent: (err) =>

{err.error.stack}

, + defaultErrorComponent: (err) => ( +

{err.error instanceof Error ? err.error.stack : String(err.error)}

+ ), defaultNotFoundComponent: () =>

not found

, scrollRestoration: true, }) diff --git a/examples/react/start-next-migration/.gitignore b/examples/react/start-next-migration/.gitignore new file mode 100644 index 0000000000..24e8148a7d --- /dev/null +++ b/examples/react/start-next-migration/.gitignore @@ -0,0 +1,13 @@ +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 new file mode 100644 index 0000000000..03bb53244e --- /dev/null +++ b/examples/react/start-next-migration/README.md @@ -0,0 +1,61 @@ +# 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 new file mode 100644 index 0000000000..7073518994 --- /dev/null +++ b/examples/react/start-next-migration/next-app/account.ts @@ -0,0 +1,14 @@ +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 new file mode 100644 index 0000000000..325a4de176 --- /dev/null +++ b/examples/react/start-next-migration/next-app/app/actions.ts @@ -0,0 +1,36 @@ +'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 new file mode 100644 index 0000000000..2aafe653dd --- /dev/null +++ b/examples/react/start-next-migration/next-app/app/layout.tsx @@ -0,0 +1,16 @@ +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 new file mode 100644 index 0000000000..41347eb65b --- /dev/null +++ b/examples/react/start-next-migration/next-app/app/login/form.tsx @@ -0,0 +1,25 @@ +'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 new file mode 100644 index 0000000000..9cbb900629 --- /dev/null +++ b/examples/react/start-next-migration/next-app/app/login/page.tsx @@ -0,0 +1,13 @@ +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 new file mode 100644 index 0000000000..5da341bf43 --- /dev/null +++ b/examples/react/start-next-migration/next-app/app/not-found.tsx @@ -0,0 +1,9 @@ +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 new file mode 100644 index 0000000000..75653b8344 --- /dev/null +++ b/examples/react/start-next-migration/next-app/app/page.tsx @@ -0,0 +1,37 @@ +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 new file mode 100644 index 0000000000..36ed5b62da --- /dev/null +++ b/examples/react/start-next-migration/next-app/app/posts/[slug]/page.tsx @@ -0,0 +1,36 @@ +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 new file mode 100644 index 0000000000..5310dbc37e --- /dev/null +++ b/examples/react/start-next-migration/next-app/app/saved/page.tsx @@ -0,0 +1,28 @@ +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 new file mode 100644 index 0000000000..9859cffa17 --- /dev/null +++ b/examples/react/start-next-migration/next-app/app/sitemap.ts @@ -0,0 +1,7 @@ +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 new file mode 100644 index 0000000000..2a9d15c1c0 --- /dev/null +++ b/examples/react/start-next-migration/next-app/content.ts @@ -0,0 +1,15 @@ +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 new file mode 100644 index 0000000000..dc72c3ae72 --- /dev/null +++ b/examples/react/start-next-migration/next-app/next.config.ts @@ -0,0 +1,13 @@ +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 new file mode 100644 index 0000000000..8786ab9834 --- /dev/null +++ b/examples/react/start-next-migration/next-app/tsconfig.json @@ -0,0 +1,30 @@ +{ + "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 new file mode 100644 index 0000000000..0c2a2a9563 --- /dev/null +++ b/examples/react/start-next-migration/package.json @@ -0,0 +1,43 @@ +{ + "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 new file mode 100644 index 0000000000..ce48715df4 --- /dev/null +++ b/examples/react/start-next-migration/playwright.config.ts @@ -0,0 +1,30 @@ +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 new file mode 100644 index 0000000000..2a9d15c1c0 --- /dev/null +++ b/examples/react/start-next-migration/src/content.ts @@ -0,0 +1,15 @@ +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 new file mode 100644 index 0000000000..15eeafce02 --- /dev/null +++ b/examples/react/start-next-migration/src/routeTree.gen.ts @@ -0,0 +1,167 @@ +/* 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 new file mode 100644 index 0000000000..9711e610bf --- /dev/null +++ b/examples/react/start-next-migration/src/router.tsx @@ -0,0 +1,5 @@ +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 new file mode 100644 index 0000000000..a7eaa0168f --- /dev/null +++ b/examples/react/start-next-migration/src/routes/__root.tsx @@ -0,0 +1,46 @@ +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 new file mode 100644 index 0000000000..8778d9d01f --- /dev/null +++ b/examples/react/start-next-migration/src/routes/index.tsx @@ -0,0 +1,45 @@ +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 new file mode 100644 index 0000000000..628261cc8e --- /dev/null +++ b/examples/react/start-next-migration/src/routes/login.tsx @@ -0,0 +1,70 @@ +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 new file mode 100644 index 0000000000..1fb5ce846b --- /dev/null +++ b/examples/react/start-next-migration/src/routes/old-notes.tsx @@ -0,0 +1,10 @@ +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 new file mode 100644 index 0000000000..1998717393 --- /dev/null +++ b/examples/react/start-next-migration/src/routes/posts.$slug.tsx @@ -0,0 +1,34 @@ +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 new file mode 100644 index 0000000000..2f526eb7b5 --- /dev/null +++ b/examples/react/start-next-migration/src/routes/saved.tsx @@ -0,0 +1,79 @@ +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 new file mode 100644 index 0000000000..a7dfcaa594 --- /dev/null +++ b/examples/react/start-next-migration/src/routes/sitemap[.]xml.ts @@ -0,0 +1,13 @@ +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 new file mode 100644 index 0000000000..85e921c74b --- /dev/null +++ b/examples/react/start-next-migration/src/server/account.ts @@ -0,0 +1,77 @@ +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 new file mode 100644 index 0000000000..5fb1e247fb --- /dev/null +++ b/examples/react/start-next-migration/src/start.ts @@ -0,0 +1,9 @@ +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 new file mode 100644 index 0000000000..7009095977 --- /dev/null +++ b/examples/react/start-next-migration/tests/migration.spec.ts @@ -0,0 +1,163 @@ +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 new file mode 100644 index 0000000000..a41553b9a1 --- /dev/null +++ b/examples/react/start-next-migration/tsconfig.json @@ -0,0 +1,21 @@ +{ + "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 new file mode 100644 index 0000000000..26d0e455d5 --- /dev/null +++ b/examples/react/start-next-migration/vite.config.ts @@ -0,0 +1,5 @@ +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 b8c448ea68..00c88681d7 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.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/react-start": "^1.168.44", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "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.30", - "nitro": "^3.0.260311-beta", + "@vitejs/plugin-rsc": "^0.5.39", + "nitro": "^3.0.260903-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 70e73cdb2a..762bbff733 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.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/react-start": "^1.168.44", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "react": "^19.0.0", "react-dom": "^19.0.0", "zod": "^4.4.3" diff --git a/examples/react/start-streaming-data-from-server-functions/src/router.tsx b/examples/react/start-streaming-data-from-server-functions/src/router.tsx index a464233af9..6f82cbf378 100644 --- a/examples/react/start-streaming-data-from-server-functions/src/router.tsx +++ b/examples/react/start-streaming-data-from-server-functions/src/router.tsx @@ -5,7 +5,9 @@ export function getRouter() { const router = createRouter({ routeTree, defaultPreload: 'intent', - defaultErrorComponent: (err) =>

{err.error.stack}

, + defaultErrorComponent: (err) => ( +

{err.error instanceof Error ? err.error.stack : String(err.error)}

+ ), defaultNotFoundComponent: () =>

not found

, scrollRestoration: true, }) diff --git a/examples/react/start-supabase-basic/.gitignore b/examples/react/start-supabase-basic/.gitignore index 8293849e8d..372dc30373 100644 --- a/examples/react/start-supabase-basic/.gitignore +++ b/examples/react/start-supabase-basic/.gitignore @@ -1,12 +1,11 @@ node_modules -# Keep environment variables out of version control -!.env package-lock.json yarn.lock .DS_Store .cache -.env +# The checked-in .env contains public demo values used by the build. +!.env .vercel .output /build/ diff --git a/examples/react/start-supabase-basic/package.json b/examples/react/start-supabase-basic/package.json index b760367ccd..0bf4b2c246 100644 --- a/examples/react/start-supabase-basic/package.json +++ b/examples/react/start-supabase-basic/package.json @@ -15,9 +15,9 @@ "dependencies": { "@supabase/ssr": "^0.5.2", "@supabase/supabase-js": "^2.48.1", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/react-start": "^1.168.44", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" diff --git a/examples/react/start-supabase-basic/src/routes/_authed.tsx b/examples/react/start-supabase-basic/src/routes/_authed.tsx index ed97848e6a..697e35e427 100644 --- a/examples/react/start-supabase-basic/src/routes/_authed.tsx +++ b/examples/react/start-supabase-basic/src/routes/_authed.tsx @@ -27,7 +27,7 @@ export const Route = createFileRoute('/_authed')({ } }, errorComponent: ({ error }) => { - if (error.message === 'Not authenticated') { + if (error instanceof Error && error.message === 'Not authenticated') { return } diff --git a/examples/react/start-tailwind-v4/package.json b/examples/react/start-tailwind-v4/package.json index 711e4e5ae3..b58fbe4ff0 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.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/react-start": "^1.168.44", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "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 5c2bbf3131..7755d227fc 100644 --- a/examples/react/start-trellaux/package.json +++ b/examples/react/start-trellaux/package.json @@ -10,12 +10,12 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-query": "^5.90.0", + "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/react-router-ssr-query": "^1.167.1", - "@tanstack/react-start": "^1.168.44", + "@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", "ky": "^1.7.4", "msw": "^2.7.0", "react": "^19.0.0", diff --git a/examples/react/start-workos/package.json b/examples/react/start-workos/package.json index f4917595d4..0ab7e89c2d 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.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/react-start": "^1.168.44", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "@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 da746430b4..0be3c60e8f 100644 --- a/examples/react/view-transitions/package.json +++ b/examples/react/view-transitions/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/with-framer-motion/package.json b/examples/react/with-framer-motion/package.json index e833154633..c606070dfb 100644 --- a/examples/react/with-framer-motion/package.json +++ b/examples/react/with-framer-motion/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "framer-motion": "^11.18.2", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/with-trpc-react-query/package.json b/examples/react/with-trpc-react-query/package.json index 47e265328f..11df7bf03b 100644 --- a/examples/react/with-trpc-react-query/package.json +++ b/examples/react/with-trpc-react-query/package.json @@ -11,11 +11,11 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.90.0", + "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "@trpc/client": "^11.4.3", "@trpc/server": "^11.4.3", "@trpc/tanstack-react-query": "^11.4.3", diff --git a/examples/react/with-trpc/package.json b/examples/react/with-trpc/package.json index a43d01e4a0..5612419cae 100644 --- a/examples/react/with-trpc/package.json +++ b/examples/react/with-trpc/package.json @@ -11,9 +11,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.27", - "@tanstack/react-router-devtools": "^1.167.1", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "@trpc/client": "^11.4.3", "@trpc/server": "^11.4.3", "express": "^5.2.1", diff --git a/examples/solid/authenticated-routes-firebase/package.json b/examples/solid/authenticated-routes-firebase/package.json index 3b38a33288..110b4d2621 100644 --- a/examples/solid/authenticated-routes-firebase/package.json +++ b/examples/solid/authenticated-routes-firebase/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.168.30", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "firebase": "^11.4.0", "redaxios": "^0.5.1", "simple-icons": "^14.9.0", diff --git a/examples/solid/authenticated-routes-firebase/src/auth.tsx b/examples/solid/authenticated-routes-firebase/src/auth.tsx index 84f1df8c99..97337889b7 100644 --- a/examples/solid/authenticated-routes-firebase/src/auth.tsx +++ b/examples/solid/authenticated-routes-firebase/src/auth.tsx @@ -1,7 +1,6 @@ import * as Solid from 'solid-js' import { onAuthStateChanged, signInWithPopup, signOut } from 'firebase/auth' -import { flushSync } from 'react-dom' import { auth } from './firebase/config' import type { AuthProvider, User } from 'firebase/auth' @@ -22,7 +21,7 @@ export function AuthContextProvider(props: { children: Solid.JSX.Element }) { Solid.createEffect(() => { const unsubscribe = onAuthStateChanged(auth, (user) => { - flushSync(() => { + Solid.batch(() => { setUser(user) setIsInitialLoading(false) }) @@ -39,7 +38,7 @@ export function AuthContextProvider(props: { children: Solid.JSX.Element }) { const login = async (provider: AuthProvider) => { const result = await signInWithPopup(auth, provider) - flushSync(() => { + Solid.batch(() => { setUser(result.user) setIsInitialLoading(false) }) diff --git a/examples/solid/authenticated-routes/package.json b/examples/solid/authenticated-routes/package.json index 24ce3a3171..ea7d05c902 100644 --- a/examples/solid/authenticated-routes/package.json +++ b/examples/solid/authenticated-routes/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.168.30", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", diff --git a/examples/solid/basic-default-search-params/package.json b/examples/solid/basic-default-search-params/package.json index affe8c838c..830df7b9cf 100644 --- a/examples/solid/basic-default-search-params/package.json +++ b/examples/solid/basic-default-search-params/package.json @@ -11,8 +11,8 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", diff --git a/examples/solid/basic-devtools-panel/package.json b/examples/solid/basic-devtools-panel/package.json index 5b6a9223e2..e7d608f5fe 100644 --- a/examples/solid/basic-devtools-panel/package.json +++ b/examples/solid/basic-devtools-panel/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "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 37dbc14f67..867118382e 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.25", - "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, "devDependencies": { - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/router-plugin": "^1.169.0", "@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 cc0f203619..c8e00ee43e 100644 --- a/examples/solid/basic-non-nested-devtools/package.json +++ b/examples/solid/basic-non-nested-devtools/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "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 cc2f08978c..fdb5f05f52 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.25", - "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, "devDependencies": { - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/router-plugin": "^1.169.0", "@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 ed9fe1d2fb..7b132b11a1 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.25", - "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2" }, "devDependencies": { - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/router-plugin": "^1.169.0", "@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 0c499fa1ec..e3699970a9 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.25", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/router-plugin": "^1.169.0", "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.1", + "@tanstack/solid-router-devtools": "^1.167.3", "@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 d2d4f7b4ac..92367442fc 100644 --- a/examples/solid/basic-ssr-streaming-file-based/package.json +++ b/examples/solid/basic-ssr-streaming-file-based/package.json @@ -12,8 +12,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "compression": "^1.8.0", "express": "^5.2.1", "get-port": "^7.1.0", @@ -24,7 +24,7 @@ "zod": "^4.4.3" }, "devDependencies": { - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/router-plugin": "^1.169.0", "@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 b2515c6213..801b452192 100644 --- a/examples/solid/basic-virtual-file-based/package.json +++ b/examples/solid/basic-virtual-file-based/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.168.30", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "@tanstack/virtual-file-routes": "^1.162.0", "redaxios": "^0.5.1", "solid-js": "^1.9.10", diff --git a/examples/solid/basic-virtual-inside-file-based/package.json b/examples/solid/basic-virtual-inside-file-based/package.json index ca7683073e..a9cc6360a5 100644 --- a/examples/solid/basic-virtual-inside-file-based/package.json +++ b/examples/solid/basic-virtual-inside-file-based/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.168.30", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "@tanstack/virtual-file-routes": "^1.162.0", "redaxios": "^0.5.1", "solid-js": "^1.9.10", diff --git a/examples/solid/basic/package.json b/examples/solid/basic/package.json index 3a08324834..95ec804011 100644 --- a/examples/solid/basic/package.json +++ b/examples/solid/basic/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "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 ff57da0a5b..56114afd04 100644 --- a/examples/solid/deferred-data/package.json +++ b/examples/solid/deferred-data/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", diff --git a/examples/solid/i18n-paraglide/package.json b/examples/solid/i18n-paraglide/package.json index b601f4b1d5..6493a3c7c8 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.25", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/router-plugin": "^1.169.0", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2" }, @@ -23,5 +23,16 @@ "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 24fbd37882..8cd73e38ff 100644 --- a/examples/solid/kitchen-sink-file-based/package.json +++ b/examples/solid/kitchen-sink-file-based/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "immer": "^10.1.1", "redaxios": "^0.5.1", "solid-js": "^1.9.10", @@ -19,7 +19,7 @@ "zod": "^4.4.3" }, "devDependencies": { - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/router-plugin": "^1.169.0", "@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 dd32b6fcc7..25a1c29953 100644 --- a/examples/solid/kitchen-sink-solid-query-file-based/package.json +++ b/examples/solid/kitchen-sink-solid-query-file-based/package.json @@ -10,11 +10,11 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/router-plugin": "^1.169.0", "@tanstack/solid-query": "^5.90.9", "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "immer": "^10.1.1", "redaxios": "^0.5.1", "solid-js": "^1.9.10", diff --git a/examples/solid/kitchen-sink-solid-query/package.json b/examples/solid/kitchen-sink-solid-query/package.json index b75f53b4f5..7a7dc81025 100644 --- a/examples/solid/kitchen-sink-solid-query/package.json +++ b/examples/solid/kitchen-sink-solid-query/package.json @@ -12,8 +12,8 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-query": "^5.90.9", "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "immer": "^10.1.1", "redaxios": "^0.5.1", "solid-js": "^1.9.10", diff --git a/examples/solid/kitchen-sink/package.json b/examples/solid/kitchen-sink/package.json index c64eabfe93..08ad918a60 100644 --- a/examples/solid/kitchen-sink/package.json +++ b/examples/solid/kitchen-sink/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "immer": "^10.1.1", "redaxios": "^0.5.1", "solid-js": "^1.9.10", diff --git a/examples/solid/large-file-based/package.json b/examples/solid/large-file-based/package.json index 3a805d1650..cd758ab704 100644 --- a/examples/solid/large-file-based/package.json +++ b/examples/solid/large-file-based/package.json @@ -12,10 +12,10 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/router-plugin": "^1.169.0", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", diff --git a/examples/solid/location-masking/package.json b/examples/solid/location-masking/package.json index af8f02af2a..7d2fbb6756 100644 --- a/examples/solid/location-masking/package.json +++ b/examples/solid/location-masking/package.json @@ -11,8 +11,8 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "solid-js": "^1.9.10", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2" diff --git a/examples/solid/navigation-blocking/package.json b/examples/solid/navigation-blocking/package.json index df2cb34f47..2338d32305 100644 --- a/examples/solid/navigation-blocking/package.json +++ b/examples/solid/navigation-blocking/package.json @@ -11,8 +11,8 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "solid-js": "^1.9.10", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2" diff --git a/examples/solid/quickstart-esbuild-file-based/build.js b/examples/solid/quickstart-esbuild-file-based/build.js index f8d31fbbd9..af5e01b4cd 100644 --- a/examples/solid/quickstart-esbuild-file-based/build.js +++ b/examples/solid/quickstart-esbuild-file-based/build.js @@ -14,10 +14,7 @@ const ctx = await esbuild.context({ target: ['esnext'], sourcemap: true, conditions: ['style'], - plugins: [ - solidPlugin(), - tanstackRouter({ target: 'solid', autoCodeSplitting: true }), - ], + plugins: [solidPlugin(), tanstackRouter({ target: 'solid' })], }) if (isDev) { diff --git a/examples/solid/quickstart-esbuild-file-based/package.json b/examples/solid/quickstart-esbuild-file-based/package.json index 1434d5b00d..9bcc9a08d0 100644 --- a/examples/solid/quickstart-esbuild-file-based/package.json +++ b/examples/solid/quickstart-esbuild-file-based/package.json @@ -9,9 +9,9 @@ "start": "dev" }, "dependencies": { - "@tanstack/router-plugin": "^1.168.30", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", diff --git a/examples/solid/quickstart-file-based/package.json b/examples/solid/quickstart-file-based/package.json index a880fb5980..920154566d 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.25", - "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, "devDependencies": { - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/router-plugin": "^1.169.0", "@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 209d69fc38..2d9c886ac3 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.25", - "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "postcss": "^8.5.1", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2" }, "devDependencies": { - "@rsbuild/core": "^2.1.0", + "@rsbuild/core": "^2.3.1", "@rsbuild/plugin-babel": "^1.1.2", "@rsbuild/plugin-solid": "^1.1.1", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/router-plugin": "^1.169.0", "@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 9b5b85f1dc..16167be207 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.25", - "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "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.168.30", + "@tanstack/router-plugin": "^1.169.0", "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 90eeb74afd..454382e8cc 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.25", - "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "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 1ce9ff19d5..1d60ab2765 100644 --- a/examples/solid/router-monorepo-simple-lazy/package.json +++ b/examples/solid/router-monorepo-simple-lazy/package.json @@ -8,9 +8,9 @@ "dev": "pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "solid-js": "^1.9.10", "redaxios": "^0.5.1" }, 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 3cfa6a1377..a2e018fa96 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.1", + "@tanstack/solid-router-devtools": "^1.167.3", "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 915d43d08a..0672c42931 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.1", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/history": "^1.162.5", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/router-plugin": "^1.169.0", "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 b0a3729972..3770256692 100644 --- a/examples/solid/router-monorepo-simple/package.json +++ b/examples/solid/router-monorepo-simple/package.json @@ -8,9 +8,9 @@ "dev": "pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "solid-js": "^1.9.10", "redaxios": "^0.5.1" }, diff --git a/examples/solid/router-monorepo-simple/packages/app/package.json b/examples/solid/router-monorepo-simple/packages/app/package.json index 937bf9795c..61234ac455 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.1", + "@tanstack/solid-router-devtools": "^1.167.3", "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 bd41301535..ca08511d3e 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.1", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/history": "^1.162.5", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/router-plugin": "^1.169.0", "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 b398b4929a..3d9fd2e2d0 100644 --- a/examples/solid/router-monorepo-solid-query/package.json +++ b/examples/solid/router-monorepo-solid-query/package.json @@ -12,9 +12,9 @@ "dependencies": { "@tanstack/solid-query": "^5.90.9", "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "solid-js": "^1.9.10", "redaxios": "^0.5.1" }, 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 bf2cc8ab04..76bb059de5 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.1", + "@tanstack/solid-router-devtools": "^1.167.3", "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 303e628c1b..93943a1df8 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.1", + "@tanstack/history": "^1.162.5", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/router-plugin": "^1.169.0", "@router-solid-mono-solid-query/post-query": "workspace:*", "redaxios": "^0.5.1", "zod": "^4.4.3", diff --git a/examples/solid/router-monorepo-solid-query/packages/router/src/router.tsx b/examples/solid/router-monorepo-solid-query/packages/router/src/router.tsx index 6153a54a8b..99874f49e5 100644 --- a/examples/solid/router-monorepo-solid-query/packages/router/src/router.tsx +++ b/examples/solid/router-monorepo-solid-query/packages/router/src/router.tsx @@ -1,4 +1,3 @@ -import React from 'react' import { createRouter } from '@tanstack/solid-router' // Import the generated route tree diff --git a/examples/solid/scroll-restoration/package.json b/examples/solid/scroll-restoration/package.json index daf885ef2e..eaa5a5aaea 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.25", - "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "@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 a9ab46caed..59991edb36 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.25", - "@tanstack/solid-router-devtools": "^1.167.1", - "@tanstack/router-plugin": "^1.168.30", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "@tanstack/valibot-adapter": "^1.167.0", "@tanstack/zod-adapter": "^1.167.0", "arktype": "^2.1.7", @@ -25,11 +25,13 @@ "zod": "^3.24.2" }, "devDependencies": { - "@testing-library/jest-dom": "^6.6.3", + "@testing-library/jest-dom": "^7.0.1", "@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" + "vite": "^8.0.14", + "vitest": "^5.0.4" } } diff --git a/examples/solid/search-validator-adapters/tests/arktype.test.tsx b/examples/solid/search-validator-adapters/tests/arktype.test.tsx index 4ec555fc7b..f22a359995 100644 --- a/examples/solid/search-validator-adapters/tests/arktype.test.tsx +++ b/examples/solid/search-validator-adapters/tests/arktype.test.tsx @@ -8,7 +8,6 @@ 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 new file mode 100644 index 0000000000..8f7cbf15be --- /dev/null +++ b/examples/solid/search-validator-adapters/tests/jest-dom.setup.ts @@ -0,0 +1,18 @@ +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 cd4545397c..8594c1cb29 100644 --- a/examples/solid/search-validator-adapters/tests/valibot.test.tsx +++ b/examples/solid/search-validator-adapters/tests/valibot.test.tsx @@ -8,7 +8,6 @@ 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 5b9dbebfef..4e05d81e75 100644 --- a/examples/solid/search-validator-adapters/vite.config.ts +++ b/examples/solid/search-validator-adapters/vite.config.ts @@ -11,6 +11,7 @@ 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 90cba4aac1..313c930051 100644 --- a/examples/solid/start-basic-auth/README.md +++ b/examples/solid/start-basic-auth/README.md @@ -70,3 +70,13 @@ 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 bedf9fe374..d686fdf616 100644 --- a/examples/solid/start-basic-auth/package.json +++ b/examples/solid/start-basic-auth/package.json @@ -14,9 +14,10 @@ "@libsql/client": "^0.15.15", "@prisma/adapter-libsql": "^7.0.0", "@prisma/client": "^7.0.0", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", - "@tanstack/solid-start": "^1.168.42", + "@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", "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 3aa0bfa18b..05ad0d298a 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 { useAppSession } from '~/utils/session.js' +import { getAppSession } 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 useAppSession() + const session = await getAppSession() - if (!session.data.userEmail) { + if (!session.userEmail) { return null } return { - email: session.data.userEmail, + email: session.userEmail, } }) diff --git a/examples/solid/start-basic-auth/src/routes/_authed.tsx b/examples/solid/start-basic-auth/src/routes/_authed.tsx index 60ad613e56..cded7ca880 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 { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' export const loginFn = createServerFn({ method: 'POST' }) .validator((d: { email: string; password: string }) => d) @@ -33,13 +33,10 @@ export const loginFn = createServerFn({ method: 'POST' }) } } - // Create a session - const session = await useAppSession() - // Store the user's email in the session - await session.update({ - userEmail: user.email, - }) + const session = await getAppSession() + session.userEmail = user.email + await session.save() }) 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 f7d624ff15..56cd70cbc2 100644 --- a/examples/solid/start-basic-auth/src/routes/logout.tsx +++ b/examples/solid/start-basic-auth/src/routes/logout.tsx @@ -1,11 +1,10 @@ import { createFileRoute, redirect } from '@tanstack/solid-router' import { createServerFn } from '@tanstack/solid-start' -import { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' const logoutFn = createServerFn().handler(async () => { - const session = await useAppSession() - - session.clear() + const session = await getAppSession() + session.destroy() 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 7cb9ae7161..b8d6bf89fa 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 { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' export const signupFn = createServerFn({ method: 'POST' }) .validator( @@ -20,9 +20,6 @@ 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 { @@ -33,9 +30,9 @@ export const signupFn = createServerFn({ method: 'POST' }) } // Store the user's email in the session - await session.update({ - userEmail: found.email, - }) + const session = await getAppSession() + session.userEmail = found.email + await session.save() // Redirect to the prev page stored in the "redirect" search param throw redirect({ @@ -52,9 +49,9 @@ export const signupFn = createServerFn({ method: 'POST' }) }) // Store the user's email in the session - await session.update({ - userEmail: user.email, - }) + const session = await getAppSession() + session.userEmail = user.email + await session.save() // 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 120a410b60..4577764d28 100644 --- a/examples/solid/start-basic-auth/src/utils/session.ts +++ b/examples/solid/start-basic-auth/src/utils/session.ts @@ -1,13 +1,29 @@ -// src/services/session.server.ts -import { useSession } from '@tanstack/solid-start/server' +import { getIronSession } from 'iron-session' +import { getCookie, setCookie } from '@tanstack/solid-start/server' import type { User } from '@prisma/client' type SessionUser = { userEmail: User['email'] } -export function useAppSession() { - return useSession({ - password: 'ChangeThisBeforeShippingToProdOrYouWillBeFired', - }) +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: '/', + }, + }, + ) } diff --git a/examples/solid/start-basic-authjs/package.json b/examples/solid/start-basic-authjs/package.json index 971409db71..2c910663bd 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.25", - "@tanstack/solid-router-devtools": "^1.167.1", - "@tanstack/solid-start": "^1.168.42", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "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 ab63107e2c..7ece143f61 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.25", - "@tanstack/solid-router-devtools": "^1.167.1", - "@tanstack/solid-start": "^1.168.42", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "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 1aa8684fbc..69299cdb79 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.25", - "@tanstack/solid-router-devtools": "^1.167.1", - "@tanstack/solid-start": "^1.168.42", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "solid-js": "^1.9.10" }, "devDependencies": { - "@netlify/vite-plugin-tanstack-start": "^1.1.4", + "@netlify/vite-plugin-tanstack-start": "^1.3.19", "@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 06fb9c3840..2c0dc7dad6 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.25", - "@tanstack/solid-router-devtools": "^1.167.1", - "@tanstack/solid-start": "^1.168.42", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "solid-js": "^1.9.10" }, "devDependencies": { "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", - "nitro": "^3.0.260311-beta", + "nitro": "^3.0.260903-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 11508af5b2..ddbb7d8764 100644 --- a/examples/solid/start-basic-solid-query/package.json +++ b/examples/solid/start-basic-solid-query/package.json @@ -12,10 +12,10 @@ "dependencies": { "@tanstack/solid-query": "^5.90.9", "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", - "@tanstack/solid-router-ssr-query": "^1.167.1", - "@tanstack/solid-start": "^1.168.42", + "@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", "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 82aa3c1b76..8b639da68a 100644 --- a/examples/solid/start-basic-static/package.json +++ b/examples/solid/start-basic-static/package.json @@ -10,10 +10,10 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", - "@tanstack/solid-start": "^1.168.42", - "@tanstack/start-static-server-functions": "^1.167.27", + "@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", "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 4833ec29df..758815b669 100644 --- a/examples/solid/start-basic/package.json +++ b/examples/solid/start-basic/package.json @@ -10,9 +10,9 @@ "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", - "@tanstack/solid-start": "^1.168.42", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwind-merge": "^3.6.0" @@ -20,7 +20,7 @@ "devDependencies": { "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", - "nitro": "^3.0.260311-beta", + "nitro": "^3.0.260903-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 d6dea3f4d7..d1ad9a9563 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.25", - "@tanstack/solid-router-devtools": "^1.167.1", - "@tanstack/solid-router-ssr-query": "^1.167.1", - "@tanstack/solid-start": "^1.168.42", - "@tanstack/router-plugin": "^1.168.30", + "@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", "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": "^4.1.4", + "vitest": "^5.0.4", "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 643faf2b22..ea13a1c1e3 100644 --- a/examples/solid/start-convex-better-auth/package.json +++ b/examples/solid/start-convex-better-auth/package.json @@ -13,9 +13,9 @@ "dependencies": { "@convex-dev/better-auth": "^0.9.7", "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", - "@tanstack/solid-start": "^1.168.42", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "better-auth": "^1.6.19", "clsx": "^2.1.1", "convex": "^1.28.2", diff --git a/examples/solid/start-counter/package.json b/examples/solid/start-counter/package.json index d1db924d56..8b49c516bd 100644 --- a/examples/solid/start-counter/package.json +++ b/examples/solid/start-counter/package.json @@ -10,9 +10,9 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", - "@tanstack/solid-start": "^1.168.42", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwind-merge": "^3.6.0", diff --git a/examples/solid/start-i18n-paraglide/package.json b/examples/solid/start-i18n-paraglide/package.json index 37abcb4eaf..076c9b41dc 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.25", - "@tanstack/solid-router-devtools": "^1.167.1", - "@tanstack/solid-start": "^1.168.42", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "solid-js": "^1.9.10" }, "devDependencies": { @@ -24,5 +24,16 @@ "@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 b76d148548..83f3589cc2 100644 --- a/examples/solid/start-large/package.json +++ b/examples/solid/start-large/package.json @@ -13,9 +13,9 @@ }, "dependencies": { "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", - "@tanstack/solid-start": "^1.168.42", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwind-merge": "^3.6.0", 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 c67eecf065..83e0719b39 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.25", - "@tanstack/solid-router-devtools": "^1.167.1", - "@tanstack/solid-start": "^1.168.42", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "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 55cce89826..81ab5cd63c 100644 --- a/examples/solid/start-supabase-basic/package.json +++ b/examples/solid/start-supabase-basic/package.json @@ -14,9 +14,9 @@ "dependencies": { "@supabase/ssr": "^0.5.2", "@supabase/supabase-js": "^2.48.1", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", - "@tanstack/solid-start": "^1.168.42", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "solid-js": "^1.9.9", "redaxios": "^0.5.1" }, diff --git a/examples/solid/start-tailwind-v4/package.json b/examples/solid/start-tailwind-v4/package.json index cc4f6250e8..94db6ac790 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.25", - "@tanstack/solid-router-devtools": "^1.167.1", - "@tanstack/solid-start": "^1.168.42", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "solid-js": "^1.9.10", "tailwind-merge": "^3.6.0", "zod": "^4.4.3" diff --git a/examples/solid/start-tailwind-v4/src/routes/__root.tsx b/examples/solid/start-tailwind-v4/src/routes/__root.tsx index 8347bb3b5a..489680b739 100644 --- a/examples/solid/start-tailwind-v4/src/routes/__root.tsx +++ b/examples/solid/start-tailwind-v4/src/routes/__root.tsx @@ -7,7 +7,6 @@ import { createRootRoute, } from '@tanstack/solid-router' import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' -import * as React from 'react' import { HydrationScript } from 'solid-js/web' import type { JSX } from 'solid-js' import appCss from '~/styles/app.css?url' diff --git a/examples/solid/view-transitions/package.json b/examples/solid/view-transitions/package.json index a3eea7165e..2acb2432bf 100644 --- a/examples/solid/view-transitions/package.json +++ b/examples/solid/view-transitions/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.168.30", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", diff --git a/examples/solid/with-framer-motion/package.json b/examples/solid/with-framer-motion/package.json index 6e1ed4b4a6..449d8a3927 100644 --- a/examples/solid/with-framer-motion/package.json +++ b/examples/solid/with-framer-motion/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "solid-motionone": "^1.0.4", diff --git a/examples/solid/with-trpc/package.json b/examples/solid/with-trpc/package.json index 93525ee7ac..46d33436db 100644 --- a/examples/solid/with-trpc/package.json +++ b/examples/solid/with-trpc/package.json @@ -11,9 +11,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.168.30", - "@tanstack/solid-router": "^1.170.25", - "@tanstack/solid-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "@trpc/client": "^11.4.3", "@trpc/server": "^11.4.3", "express": "^5.2.1", diff --git a/examples/vue/basic-file-based-jsx/package.json b/examples/vue/basic-file-based-jsx/package.json index 3044b8fc36..9cc36a6991 100644 --- a/examples/vue/basic-file-based-jsx/package.json +++ b/examples/vue/basic-file-based-jsx/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.168.30", - "@tanstack/vue-router": "^1.170.24", - "@tanstack/vue-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.169.0", + "@tanstack/vue-router": "^1.170.42", + "@tanstack/vue-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", "vue": "^3.5.16", diff --git a/examples/vue/basic-file-based-jsx/src/posts.tsx b/examples/vue/basic-file-based-jsx/src/posts.tsx index 1b4c92b41d..f7a1941605 100644 --- a/examples/vue/basic-file-based-jsx/src/posts.tsx +++ b/examples/vue/basic-file-based-jsx/src/posts.tsx @@ -7,11 +7,7 @@ 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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 3922025c82..5922c5f7b1 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 727c1b4d94..e475111e40 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,27 +1,32 @@ 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 4b239f3ef4..869e536811 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,27 +1,30 @@ 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 f12ca517d3..4a0caa8f8d 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,27 +1,30 @@ 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 05b34eb201..fdae632aee 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,27 +1,30 @@ 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 317c766186..8c7222ee70 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,27 +1,30 @@ 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 59c9e6fa48..adcc3acbd7 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/__root.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/__root.tsx @@ -8,97 +8,100 @@ 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 15d17387c8..bc1dbfbbd0 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,24 +1,27 @@ 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 ae580dfc02..522988e52b 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/posts.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/posts.tsx @@ -1,7 +1,38 @@ 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: [ @@ -13,31 +44,3 @@ 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 57963c6b64..ad20bcdf97 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,23 +1,28 @@ 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 61c311cf7d..87ab2c332b 100644 --- a/examples/vue/basic-file-based-sfc/package.json +++ b/examples/vue/basic-file-based-sfc/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.168.30", - "@tanstack/vue-router": "^1.170.24", - "@tanstack/vue-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.169.0", + "@tanstack/vue-router": "^1.170.42", + "@tanstack/vue-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", "vue": "^3.5.16", diff --git a/examples/vue/basic-file-based-sfc/src/posts.ts b/examples/vue/basic-file-based-sfc/src/posts.ts index 1b4c92b41d..f7a1941605 100644 --- a/examples/vue/basic-file-based-sfc/src/posts.ts +++ b/examples/vue/basic-file-based-sfc/src/posts.ts @@ -7,11 +7,7 @@ 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}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' 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 09d62b0706..0bfdddab3d 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 8f848d7d1b..af74afff3a 100644 --- a/examples/vue/basic/package.json +++ b/examples/vue/basic/package.json @@ -9,8 +9,8 @@ "start": "vite" }, "dependencies": { - "@tanstack/vue-router": "^1.170.24", - "@tanstack/vue-router-devtools": "^1.167.1", + "@tanstack/vue-router": "^1.170.42", + "@tanstack/vue-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "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 dc12871db0..09878913a8 100644 --- a/examples/vue/basic/src/main.tsx +++ b/examples/vue/basic/src/main.tsx @@ -1,4 +1,4 @@ -import { createApp } from 'vue' +import { createApp, defineComponent } from 'vue' import { ErrorComponent, Link, @@ -102,6 +102,20 @@ 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', @@ -118,18 +132,6 @@ 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 1fd64723e5..8602de045f 100644 --- a/examples/vue/basic/src/posts.lazy.tsx +++ b/examples/vue/basic/src/posts.lazy.tsx @@ -1,36 +1,39 @@ 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 c1ad49328e..9da92bf7ff 100644 --- a/labeler-config.yml +++ b/labeler-config.yml @@ -10,9 +10,6 @@ '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 764112a2f6..b7df8b2c09 100644 --- a/nx.json +++ b/nx.json @@ -1,6 +1,7 @@ { "$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, @@ -10,7 +11,10 @@ "namedInputs": { "sharedGlobals": [ "{workspaceRoot}/.npmrc", - "{workspaceRoot}/.nx/workflows/sandboxing-config.yaml", + "{workspaceRoot}/nx.json", + "{workspaceRoot}/.github/workflows/pr.yml", + "{workspaceRoot}/.nx/ci-config.yaml", + "{workspaceRoot}/.nx/workflows/ultracache-config.yaml", "{workspaceRoot}/.nvmrc", "{workspaceRoot}/package.json", "{workspaceRoot}/tsconfig.json" @@ -21,6 +25,11 @@ "transitive": true } ], + "streamingSsrTests": [ + "{workspaceRoot}/e2e/streaming-ssr-assertions.ts", + "{workspaceRoot}/e2e/streaming-ssr-fixtures/**/*", + "{workspaceRoot}/e2e/streaming-ssr-specs/**/*" + ], "default": [ "sharedGlobals", "{projectRoot}/**/*", @@ -36,7 +45,7 @@ "targetDefaults": { "test:docs": { "cache": true, - "inputs": ["{workspaceRoot}/docs/**/*"] + "inputs": ["sharedGlobals", "{workspaceRoot}/docs/**/*"] }, "test:eslint": { "cache": true, @@ -62,27 +71,27 @@ "test:e2e": { "cache": true, "dependsOn": ["^build", "test:e2e--*"], - "inputs": ["default", "^production", "dependentTaskOutputs"], - "outputs": [ - "{projectRoot}/dist", - "{projectRoot}/port-*.txt", - "{projectRoot}/test-results" - ] + "inputs": ["buildProduction", "^production", "dependentTaskOutputs"], + "outputs": ["{projectRoot}/dist", "{projectRoot}/test-results"], + "parallelism": false }, "test:e2e:nitro": { "cache": true, "dependsOn": ["^build"], - "inputs": ["default", "^production"] + "inputs": ["default", "^production"], + "parallelism": false }, "test:e2e:basepath": { "cache": true, "dependsOn": ["^build"], - "inputs": ["default", "^production"] + "inputs": ["default", "^production"], + "parallelism": false }, "test:e2e:preview": { "cache": true, "dependsOn": ["^build"], - "inputs": ["default", "^production"] + "inputs": ["default", "^production"], + "parallelism": false }, "test:types": { "cache": true, @@ -94,6 +103,21 @@ "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"], @@ -101,6 +125,11 @@ "default", "^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" ] }, @@ -120,6 +149,9 @@ "cache": true, "dependsOn": ["build"], "inputs": ["buildProduction", "dependentTaskOutputs"] + }, + "test:e2e*": { + "parallelism": false } }, "plugins": [ diff --git a/package.json b/package.json index 98682bac38..3ef11b1969 100644 --- a/package.json +++ b/package.json @@ -5,24 +5,25 @@ "type": "git", "url": "git+https://github.com/TanStack/router.git" }, - "packageManager": "pnpm@11.9.0", + "packageManager": "pnpm@12.18.0", "engines": { - "pnpm": ">=11.9.0" + "pnpm": ">=12.18.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:e2e,test:types,test:build,build", - "test:ci": "nx run-many --targets=test:eslint,test:unit,test:e2e,test:types,test:build,build", + "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: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": "nx run @benchmarks/bundle-size:build", + "benchmark:bundle-size": "node scripts/benchmarks/bundle-size/build.mjs", + "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", "benchmark:bundle-size:history": "node scripts/benchmarks/bundle-size/history.mjs", @@ -44,7 +45,8 @@ "format": "prettier --experimental-cli --ignore-unknown '**/*' --write", "changeset": "changeset", "changeset:publish": "changeset publish", - "changeset:version": "changeset version && node scripts/update-example-deps.mjs && pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile && pnpm format", + "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", "gpt-generate": "node gpt/generate.js", "set-ts-version": "node scripts/set-ts-version.js", "labeler-generate": "node scripts/generate-labeler-config.ts", @@ -61,41 +63,21 @@ ] }, "devDependencies": { - "@arethetypeswrong/cli": "^0.18.4", "@changesets/changelog-github": "^0.7.0", "@changesets/cli": "^2.30.0", - "@eslint-react/eslint-plugin": "^1.26.2", - "@nx/devkit": "22.7.5", + "@nx/devkit": "24.0.0", "@playwright/test": "catalog:", - "@swc-node/core": "^1.14.1", "@swc-node/register": "^1.11.1", "@tanstack/eslint-config": "0.4.0", - "@tanstack/query-core": "catalog:", - "@tanstack/react-query": "catalog:", - "@tanstack/solid-query": "catalog:", - "@tanstack/vite-config": "0.5.2", - "@tanstack/vue-query": "catalog:", "@types/node": "catalog:", - "@types/react": "catalog:", - "@types/react-dom": "catalog:", - "@vitest/browser": "^4.1.4", - "@vitest/ui": "^4.1.4", "eslint": "catalog:", - "eslint-plugin-react-hooks": "^5.1.0", "eslint-plugin-unused-imports": "^4.1.4", - "jsdom": "^25.0.1", "markdown-link-extractor": "^4.0.3", - "nx": "22.7.5", + "nx": "24.0.0", "prettier": "^3.8.0", - "publint": "^0.3.16", - "react": "catalog:", - "react-dom": "catalog:", - "redaxios": "^0.5.1", - "rimraf": "^6.1.2", "tinyglobby": "^0.2.15", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "catalog:", - "vitest": "^4.1.4", "@typescript/native": "npm:typescript@^7.0.2", "typescript56": "npm:typescript@5.6", "typescript57": "npm:typescript@5.7", diff --git a/packages/AGENTS.md b/packages/AGENTS.md new file mode 100644 index 0000000000..0c63c3a15c --- /dev/null +++ b/packages/AGENTS.md @@ -0,0 +1,16 @@ +# 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 34bd520f9b..ceca3fad73 100644 --- a/packages/arktype-adapter/package.json +++ b/packages/arktype-adapter/package.json @@ -66,11 +66,19 @@ "devDependencies": { "@tanstack/react-router": "workspace:*", "arktype": "^2.1.7", - "@testing-library/jest-dom": "^6.6.3", - "@testing-library/react": "^16.2.0", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "vite": "*" + "@testing-library/jest-dom": "catalog:", + "@testing-library/react": "catalog:", + "react": "catalog:", + "react-dom": "catalog:", + "vite": "*", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "jsdom": "catalog:", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" }, "peerDependencies": { "arktype": ">=2.0.0-rc <3", diff --git a/packages/arktype-adapter/tests/index.test.tsx b/packages/arktype-adapter/tests/index.test.tsx index a99ecda9c4..ce6eb74756 100644 --- a/packages/arktype-adapter/tests/index.test.tsx +++ b/packages/arktype-adapter/tests/index.test.tsx @@ -9,7 +9,6 @@ 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 new file mode 100644 index 0000000000..8f7cbf15be --- /dev/null +++ b/packages/arktype-adapter/tests/jest-dom.setup.ts @@ -0,0 +1,18 @@ +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 8c8c0c519f..8d553e0a59 100644 --- a/packages/arktype-adapter/vite.config.ts +++ b/packages/arktype-adapter/vite.config.ts @@ -9,6 +9,7 @@ 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 25e742f8f7..9be54c220e 100644 --- a/packages/eslint-plugin-router/package.json +++ b/packages/eslint-plugin-router/package.json @@ -56,11 +56,26 @@ }, "devDependencies": { "@typescript-eslint/rule-tester": "^8.23.0", - "combinate": "^1.1.11", + "combinate": "catalog:", "eslint": "^9.22.0", - "vite": "*" + "vite": "*", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" }, "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 df48592327..803264ed10 100644 --- a/packages/eslint-plugin-start/package.json +++ b/packages/eslint-plugin-start/package.json @@ -30,17 +30,17 @@ "build": "vite build && tsc --noEmit" }, "type": "module", - "types": "dist/esm/src/index.d.ts", + "types": "dist/esm/index.d.ts", "main": "dist/cjs/index.cjs", "module": "dist/esm/index.js", "exports": { ".": { "import": { - "types": "./dist/esm/src/index.d.ts", + "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.js" }, "require": { - "types": "./dist/cjs/src/index.d.cts", + "types": "./dist/cjs/index.d.cts", "default": "./dist/cjs/index.cjs" } }, @@ -58,10 +58,25 @@ "devDependencies": { "@typescript-eslint/rule-tester": "^8.44.1", "eslint": "^9.22.0", - "typescript": "^5.8.2" + "typescript": "^5.8.2", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" }, "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 new file mode 100644 index 0000000000..509da6a4ec --- /dev/null +++ b/packages/history/AGENTS.md @@ -0,0 +1,3 @@ +# 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 8d61013c84..ca3341088c 100644 --- a/packages/history/CHANGELOG.md +++ b/packages/history/CHANGELOG.md @@ -1,5 +1,57 @@ # @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 3573777fc4..d09c710d2f 100644 --- a/packages/history/package.json +++ b/packages/history/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/history", - "version": "1.162.1", + "version": "1.162.5", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -59,6 +59,12 @@ "node": ">=20.19" }, "devDependencies": { - "vite": "*" + "vite": "*", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "jsdom": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" } } diff --git a/packages/history/src/index.ts b/packages/history/src/index.ts index 063174c732..d2f80581b9 100644 --- a/packages/history/src/index.ts +++ b/packages/history/src/index.ts @@ -36,7 +36,9 @@ export interface RouterHistory { flush: () => void destroy: () => void notify: (action: SubscriberHistoryAction) => void + _getBlockers: () => Array _ignoreSubscribers?: boolean + _ignoreNextBeforeUnload?: (href: string) => void } export interface HistoryLocation extends ParsedPath { @@ -96,12 +98,40 @@ 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) => void + go: (n: number, ignoreBlocker: boolean) => void back: (ignoreBlocker: boolean) => void forward: (ignoreBlocker: boolean) => void createHref: (path: string) => string @@ -126,27 +156,21 @@ export function createHistory(opts: { else location = opts.getLocation() } - 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) { + 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') + ) { for (const blocker of blockers) { - const nextLocation = parseHref(actionInfo.path, actionInfo.state) + const nextLocation = parseHref(args.path, args.state) const isBlocked = await blocker.blockerFn({ currentLocation: location, nextLocation, - action: actionInfo.type, + action: args.type, }) if (isBlocked) { opts.onBlocked?.() @@ -155,7 +179,7 @@ export function createHistory(opts: { } } - task() + args.task() } return { @@ -204,7 +228,7 @@ export function createHistory(opts: { go: (index, navigateOpts) => { tryNavigation({ task: () => { - opts.go(index) + opts.go(index, navigateOpts?.ignoreBlocker ?? false) handleIndexChange({ type: 'GO', index }) }, navigateOpts, @@ -246,13 +270,11 @@ 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, @@ -295,7 +317,8 @@ export function createBrowserHistory(opts?: { const _setBlockers = (newBlockers: Array) => (blockers = newBlockers) - const createHref = opts?.createHref ?? ((path) => path) + const createHref = (path: string) => + normalizeHref(opts?.createHref ? opts.createHref(path) : path) const parseLocation = opts?.parseLocation ?? (() => @@ -322,6 +345,9 @@ 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 @@ -368,18 +394,24 @@ export function createBrowserHistory(opts?: { destHref: string, state: any, ) => { - const href = createHref(destHref) + // 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 hasPendingAction = !!next if (!hasPendingAction) { rollbackLocation = currentLocation } - // Update the location in memory + // Keep the optimistic location in the router's logical URL space. currentLocation = parseHref(destHref, state) // Keep track of the next location we need to flush to the URL - next = [href, state, next?.[2 /* is push */] || isPush] + next = [ + href ?? currentLocation.href, + state, + next?.[2 /* is push */] || isPush, + ] if (!hasPendingAction) { // Schedule an update to the browser history @@ -394,6 +426,10 @@ 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 @@ -430,7 +466,7 @@ export function createBrowserHistory(opts?: { }) if (isBlocked) { ignoreNextPop = true - win.history.go(1) + win.history.go(-delta) history.notify(notify) return } @@ -483,20 +519,28 @@ 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) => { + go: (n, ignoreBlocker) => { nextPopIsGo = true + if (ignoreBlocker) { + skipBlockerNextPop = true + ignoreNextBeforeUnload = true + } win.history.go(n) }, - createHref: (href) => createHref(href), + createHref, flush, destroy: () => { win.history.pushState = originalPushState @@ -518,6 +562,21 @@ 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) @@ -548,14 +607,17 @@ export function createHashHistory(opts?: { window?: any }): RouterHistory { return createBrowserHistory({ window: win, parseLocation: () => { - 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) + // `#/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, + ) }, createHref: (href) => `${win.location.pathname}${win.location.search}#${href}`, @@ -595,13 +657,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.splice(index + 1) - states.splice(index + 1) + entries.length = index + 1 + states.length = index + 1 } - states.push(state) - entries.push(path) - index = Math.max(entries.length - 1, 0) }, replaceState: (path, state) => { states[index] = state @@ -616,54 +678,89 @@ export function createMemoryHistory( go: (n) => { index = Math.min(Math.max(index + n, 0), entries.length - 1) }, - createHref: (path) => path, + createHref: normalizeHref, getBlockers: _getBlockers, setBlockers: _setBlockers, }) } -/** - * 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, '') +const noop = () => {} - // 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(/^\/+/, '') +class ServerHistory implements RouterHistory { + declare private _subscribers?: RouterHistory['subscribers'] + + constructor(public location: HistoryLocation) {} + + get length() { + return 1 } - return sanitized + // 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)) } export function parseHref( href: string, state: ParsedHistoryState | undefined, ): HistoryLocation { - const sanitizedHref = sanitizePath(href) + const sanitizedHref = normalizeHref(href) const hashIndex = sanitizedHref.indexOf('#') const searchIndex = sanitizedHref.indexOf('?') - - const addedKey = createRandomKey() + if (!state) { + const key = createRandomKey() + state = { [stateIndexKey]: 0, key, __TSR_key: key } + } return { href: sanitizedHref, - pathname: sanitizedHref.substring( + pathname: sanitizedHref.slice( 0, - hashIndex > 0 - ? searchIndex > 0 + hashIndex > -1 + ? searchIndex > -1 ? Math.min(hashIndex, searchIndex) : hashIndex - : searchIndex > 0 + : searchIndex > -1 ? searchIndex : sanitizedHref.length, ), - hash: hashIndex > -1 ? sanitizedHref.substring(hashIndex) : '', + hash: hashIndex > -1 ? sanitizedHref.slice(hashIndex) : '', search: searchIndex > -1 ? sanitizedHref.slice( @@ -671,11 +768,11 @@ export function parseHref( hashIndex === -1 ? undefined : hashIndex, ) : '', - state: state || { [stateIndexKey]: 0, key: addedKey, __TSR_key: addedKey }, + state, } } // Thanks co-pilot! function createRandomKey() { - return (Math.random() + 1).toString(36).substring(7) + return (Math.random() + 1).toString(36).slice(7) } diff --git a/packages/history/tests/createBrowserHistory.test.ts b/packages/history/tests/createBrowserHistory.test.ts index 97b3c40ef3..5b24744fb5 100644 --- a/packages/history/tests/createBrowserHistory.test.ts +++ b/packages/history/tests/createBrowserHistory.test.ts @@ -1,7 +1,8 @@ import { describe, expect, test, vi } from 'vitest' import { createBrowserHistory } from '../src' -function createBrowserHistoryHarness() { +function createBrowserHistoryHarness(createHref?: (path: string) => string) { + const listeners = new Map any>() const location = { pathname: '/', search: '', @@ -21,19 +22,64 @@ function createBrowserHistoryHarness() { const window = { location, history: nativeHistory, - addEventListener: vi.fn(), - removeEventListener: vi.fn(), + 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), } - const history = createBrowserHistory({ window }) + const history = createBrowserHistory({ window, createHref }) 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() @@ -103,4 +149,159 @@ 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 4d68238249..e54b1a1ae1 100644 --- a/packages/history/tests/createHashHistory.test.ts +++ b/packages/history/tests/createHashHistory.test.ts @@ -1,8 +1,162 @@ -import { describe, expect, test } from 'vitest' +import { describe, expect, test, vi } 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 1a27c04919..c0f565115e 100644 --- a/packages/history/tests/createMemoryHistory.test.ts +++ b/packages/history/tests/createMemoryHistory.test.ts @@ -2,6 +2,53 @@ 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] }) @@ -52,6 +99,38 @@ 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 new file mode 100644 index 0000000000..c036cea185 --- /dev/null +++ b/packages/history/tests/createServerHistory.test.ts @@ -0,0 +1,95 @@ +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 e1b8db9c1a..aa6882e6fc 100644 --- a/packages/history/tests/parseHref.test.ts +++ b/packages/history/tests/parseHref.test.ts @@ -1,7 +1,19 @@ 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') @@ -9,6 +21,42 @@ 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 @@ -45,6 +93,86 @@ 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 deleted file mode 100644 index 934532d11b..0000000000 --- a/packages/nitro-v2-vite-plugin/CHANGELOG.md +++ /dev/null @@ -1,19 +0,0 @@ -# @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 deleted file mode 100644 index 5882e61120..0000000000 --- a/packages/nitro-v2-vite-plugin/README.md +++ /dev/null @@ -1 +0,0 @@ -# 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 deleted file mode 100644 index 8ce6ad05fc..0000000000 --- a/packages/nitro-v2-vite-plugin/eslint.config.js +++ /dev/null @@ -1,5 +0,0 @@ -// @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 deleted file mode 100644 index 68966c5011..0000000000 --- a/packages/nitro-v2-vite-plugin/package.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "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" - } -} diff --git a/packages/nitro-v2-vite-plugin/src/index.ts b/packages/nitro-v2-vite-plugin/src/index.ts deleted file mode 100644 index d8ae5009de..0000000000 --- a/packages/nitro-v2-vite-plugin/src/index.ts +++ /dev/null @@ -1,197 +0,0 @@ -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 - -function isFullUrl(str: string): boolean { - try { - new URL(str) - return true - } catch { - return false - } -} - -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 = !isFullUrl(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 deleted file mode 100644 index 92be18587f..0000000000 --- a/packages/nitro-v2-vite-plugin/tsconfig.build.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "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 deleted file mode 100644 index bd398a8728..0000000000 --- a/packages/nitro-v2-vite-plugin/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "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 deleted file mode 100644 index 7401092b13..0000000000 --- a/packages/nitro-v2-vite-plugin/vite.config.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 7634f3d19e..f74de5f187 100644 --- a/packages/react-router-devtools/CHANGELOG.md +++ b/packages/react-router-devtools/CHANGELOG.md @@ -1,5 +1,21 @@ # @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 262a9294fb..969371a6a6 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.1", + "version": "1.167.3", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -65,11 +65,21 @@ "@tanstack/router-devtools-core": "workspace:*" }, "devDependencies": { - "@vitejs/plugin-react": "^4.3.4", - "react": ">=19", - "react-dom": ">=19", + "@vitejs/plugin-react": "catalog:", + "react": "catalog:", + "react-dom": "catalog:", "vite": "*", - "@types/node": ">=20" + "@types/node": ">=20", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "jsdom": "catalog:", + "@eslint-react/eslint-plugin": "catalog:", + "eslint-plugin-react-hooks": "catalog:", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" }, "peerDependencies": { "@tanstack/react-router": "workspace:^", diff --git a/packages/react-router-ssr-query/CHANGELOG.md b/packages/react-router-ssr-query/CHANGELOG.md index 8e4f3df45d..d0fc73ff50 100644 --- a/packages/react-router-ssr-query/CHANGELOG.md +++ b/packages/react-router-ssr-query/CHANGELOG.md @@ -1,5 +1,39 @@ # @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 + +- Updated dependencies [[`79e3533`](https://github.com/TanStack/router/commit/79e35335b4bb1c3b5e2275a8df5181aa05036628)]: + - @tanstack/router-ssr-query-core@1.169.2 + ## 1.167.1 ### Patch Changes diff --git a/packages/react-router-ssr-query/package.json b/packages/react-router-ssr-query/package.json index 2967d695b0..7333146047 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.1", + "version": "1.167.3", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -67,18 +67,28 @@ "@tanstack/router-ssr-query-core": "workspace:*" }, "devDependencies": { - "@vitejs/plugin-react": "^4.3.4", - "react": ">=19", - "react-dom": ">=19", + "@vitejs/plugin-react": "catalog:", + "react": "catalog:", + "react-dom": "catalog:", "@tanstack/react-router": "workspace:*", - "@tanstack/react-query": ">=5.90.0", - "vite": "*" + "@tanstack/react-query": ">=5.102.0", + "vite": "*", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "jsdom": "catalog:", + "@eslint-react/eslint-plugin": "catalog:", + "eslint-plugin-react-hooks": "catalog:", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" }, "peerDependencies": { "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0", - "@tanstack/query-core": ">=5.90.0", - "@tanstack/react-router": ">=1.127.0", - "@tanstack/react-query": ">=5.90.0" + "@tanstack/query-core": ">=5.102.0", + "@tanstack/react-router": ">=1.170.33", + "@tanstack/react-query": ">=5.102.0" } } diff --git a/packages/react-router/CHANGELOG.md b/packages/react-router/CHANGELOG.md index ab7af2c14e..7e1e2f1a62 100644 --- a/packages/react-router/CHANGELOG.md +++ b/packages/react-router/CHANGELOG.md @@ -1,5 +1,248 @@ # @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 + +- [#8130](https://github.com/TanStack/router/pull/8130) [`cb281d7`](https://github.com/TanStack/router/commit/cb281d70c1f5fe780f9d07bc500ea3a284a4e04b) - preserve context during reloads + +- Updated dependencies [[`fa65287`](https://github.com/TanStack/router/commit/fa652872812c9433ba8b9d9a285e51b535e7367c), [`cb281d7`](https://github.com/TanStack/router/commit/cb281d70c1f5fe780f9d07bc500ea3a284a4e04b)]: + - @tanstack/router-core@1.171.27 + +## 1.170.31 + +### Patch Changes + +- Updated dependencies [[`3e016ac`](https://github.com/TanStack/router/commit/3e016ac84ffec8119f0c25cfdd1fb17e5292bd34)]: + - @tanstack/router-core@1.171.26 + +## 1.170.30 + +### Patch Changes + +- [#8084](https://github.com/TanStack/router/pull/8084) [`5d3785d`](https://github.com/TanStack/router/commit/5d3785dcc366b66b1c261b5d01e66af778ff1175) - preserve pending UI across retained routes + +- [#8068](https://github.com/TanStack/router/pull/8068) [`f75cada`](https://github.com/TanStack/router/commit/f75cada01707e51fb9650dd301bc04f8b2265a2a) - direct export of CatchBoundary class component, remove function wrapper + +- Updated dependencies [[`5d3785d`](https://github.com/TanStack/router/commit/5d3785dcc366b66b1c261b5d01e66af778ff1175), [`63d2cc9`](https://github.com/TanStack/router/commit/63d2cc9155ff5374112f7d067d0b278bafeb8486)]: + - @tanstack/router-core@1.171.25 + +## 1.170.29 + +### Patch Changes + +- [#8073](https://github.com/TanStack/router/pull/8073) [`0fdf9ff`](https://github.com/TanStack/router/commit/0fdf9ff16fc532de9fc131d18df167ebd8038720) - inline isCtrlKey inside Link component for byte shaving + +- Updated dependencies [[`4c89b15`](https://github.com/TanStack/router/commit/4c89b15dd2b46491ee5e57985559bae8e31d62c2), [`cf6ab17`](https://github.com/TanStack/router/commit/cf6ab178b39e7628bf784759f384e0f4230e6d9e), [`bdaf73a`](https://github.com/TanStack/router/commit/bdaf73a4063ee2b02e3c9cc105ad10ce82a5a0ff)]: + - @tanstack/router-core@1.171.24 + +## 1.170.28 + +### Patch Changes + +- [#8055](https://github.com/TanStack/router/pull/8055) [`0c25a7b`](https://github.com/TanStack/router/commit/0c25a7b43b5331ee6ebf94d50e9793002783adab) - Avoid wrapping root components that may render the HTML document in a Suspense boundary during SSR and hydration. + +- [#8054](https://github.com/TanStack/router/pull/8054) [`31882c7`](https://github.com/TanStack/router/commit/31882c7fa87debef236228831655cb112c20ce90) - Reuse resolved lazy route components when revisiting code-split routes, preventing unnecessary pending UI. + +- Updated dependencies [[`31882c7`](https://github.com/TanStack/router/commit/31882c7fa87debef236228831655cb112c20ce90)]: + - @tanstack/router-core@1.171.23 + ## 1.170.27 ### Patch Changes diff --git a/packages/react-router/package.json b/packages/react-router/package.json index 65a417d1bd..9a61d5af25 100644 --- a/packages/react-router/package.json +++ b/packages/react-router/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-router", - "version": "1.170.27", + "version": "1.170.46", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -86,28 +86,40 @@ "sideEffects": false, "files": [ "dist", - "src" + "src", + "skills", + "!skills/_artifacts" ], "engines": { "node": ">=20.19" }, "dependencies": { "@tanstack/history": "workspace:*", - "@tanstack/react-store": "^0.9.3", + "@tanstack/react-store": "^0.11.2", "@tanstack/router-core": "workspace:*", - "isbot": "^5.1.22" + "isbot": "catalog:" }, "devDependencies": { - "@testing-library/jest-dom": "^6.6.3", - "@testing-library/react": "^16.2.0", + "@testing-library/jest-dom": "catalog:", + "@testing-library/react": "catalog:", "@tanstack/react-query": "catalog:", "@types/node": ">=20", - "@vitejs/plugin-react": "^4.3.4", - "combinate": "^1.1.11", - "react": "^19.0.0", - "react-dom": "^19.0.0", + "@vitejs/plugin-react": "catalog:", + "combinate": "catalog:", + "react": "catalog:", + "react-dom": "catalog:", "vite": "*", - "zod": "^4.4.3" + "zod": "catalog:", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "jsdom": "catalog:", + "@eslint-react/eslint-plugin": "catalog:", + "eslint-plugin-react-hooks": "catalog:", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" }, "peerDependencies": { "react": ">=18.0.0 || >=19.0.0", diff --git a/packages/react-router/skills/compositions/router-query/SKILL.md b/packages/react-router/skills/compositions/router-query/SKILL.md index bcb2f939cd..4fdd74fc30 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, ensureQueryData/prefetchQuery in loaders, + in router context, static queries and fire-and-forget queries 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 [router-core](../../../../router-core/skills/router-core/SKILL.md) and [react-router](../../react-router/SKILL.md) first. +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 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: `ensureQueryData` in Loader + `useSuspenseQuery` in Component +## Core Pattern: Static `query` in Loader + `useSuspenseQuery` in Component -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. +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. ```tsx // src/routes/posts.tsx @@ -204,9 +204,12 @@ const postsQueryOptions = queryOptions({ export const Route = createFileRoute('/posts')({ loader: ({ context }) => { - // ensureQueryData returns cached data if available, fetches if not in cache - // To also refetch stale data, pass revalidateIfStale: true - return context.queryClient.ensureQueryData(postsQueryOptions) + // 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', + }) }, component: PostsPage, }) @@ -246,7 +249,10 @@ const postQueryOptions = (postId: string) => export const Route = createFileRoute('/posts/$postId')({ loader: ({ context, params }) => { - return context.queryClient.ensureQueryData(postQueryOptions(params.postId)) + return context.queryClient.query({ + ...postQueryOptions(params.postId), + staleTime: 'static', + }) }, component: PostPage, }) @@ -259,20 +265,23 @@ function PostPage() { } ``` -## Streaming Pattern: `prefetchQuery` (Not Awaited) +## Streaming Pattern: Fire-and-Forget `query` (Not Awaited) -For non-critical data, start the fetch without blocking navigation: +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: ```tsx -import { useQuery, useSuspenseQuery } from '@tanstack/react-query' +import { noop, useQuery, useSuspenseQuery } from '@tanstack/react-query' export const Route = createFileRoute('/dashboard')({ loader: ({ context }) => { // Await critical data - const user = context.queryClient.ensureQueryData(userQueryOptions) + const user = context.queryClient.query({ + ...userQueryOptions, + staleTime: 'static', + }) - // Start non-critical fetch without awaiting — streams during SSR - context.queryClient.prefetchQuery(analyticsQueryOptions) + // Start non-critical query without awaiting — streams during SSR + void context.queryClient.query({ ...analyticsQueryOptions }).catch(noop) return user }, @@ -304,7 +313,10 @@ import { useRouter } from '@tanstack/react-router' export const Route = createFileRoute('/posts')({ loader: ({ context }) => - context.queryClient.ensureQueryData(postsQueryOptions), + context.queryClient.query({ + ...postsQueryOptions, + staleTime: 'static', + }), errorComponent: PostsErrorComponent, component: PostsPage, }) @@ -313,7 +325,7 @@ function PostsErrorComponent({ error, reset, }: { - error: Error + error: unknown reset: () => void }) { const router = useRouter() @@ -325,7 +337,7 @@ function PostsErrorComponent({ return (
-

{error.message}

+

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

) @@ -373,24 +385,29 @@ export function createAppRouter() { } ``` -### 3. MEDIUM: Awaiting `prefetchQuery` in loader blocks rendering +### 3. MEDIUM: Awaiting a fire-and-forget query in a loader blocks rendering -`prefetchQuery` is designed to fire-and-forget. Awaiting it blocks the navigation transition until the data resolves, defeating the purpose of streaming. +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. ```tsx +import { noop } from '@tanstack/react-query' + // WRONG — blocks navigation, no streaming benefit loader: async ({ context }) => { - await context.queryClient.prefetchQuery(analyticsQueryOptions) + await context.queryClient.query({ ...analyticsQueryOptions }).catch(noop) } -// CORRECT — fire and forget for streaming +// CORRECT — fire and forget for streaming, with handled rejection loader: ({ context }) => { - context.queryClient.prefetchQuery(analyticsQueryOptions) + void context.queryClient.query({ ...analyticsQueryOptions }).catch(noop) } -// If you need to block (critical data), use ensureQueryData instead: +// If you need to block (critical data), use a static query instead: loader: ({ context }) => { - return context.queryClient.ensureQueryData(criticalQueryOptions) + return context.queryClient.query({ + ...criticalQueryOptions, + staleTime: 'static', + }) } ``` @@ -415,10 +432,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 `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` +- 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 ## Cross-References -- [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 +- `@tanstack/router-core#router-core/data-loading` — built-in loader caching fundamentals +- `@tanstack/router-core#router-core/ssr` — 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 53f4135316..f8df76df02 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 [router-core](../../../router-core/skills/router-core/SKILL.md) first for foundational concepts. +This skill builds on router-core. Read `@tanstack/router-core#router-core` 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. @@ -346,7 +346,7 @@ import { CatchBoundary } from '@tanstack/react-router' ; 'widget'} onCatch={(error) => console.error(error)} - errorComponent={({ error }) =>
Error: {error.message}
} + errorComponent={({ error }) =>
{String(error)}
} >
@@ -495,4 +495,4 @@ function App() { ## Cross-References -- [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.) +- `@tanstack/router-core#router-core` — 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 5e4f159f52..04cbac9064 100644 --- a/packages/react-router/src/Asset.tsx +++ b/packages/react-router/src/Asset.tsx @@ -42,6 +42,11 @@ 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': @@ -78,11 +83,7 @@ export function Asset( } return ( -