diff --git a/.agents/skills/bundle-size-optimization b/.agents/skills/bundle-size-optimization deleted file mode 120000 index 692e634b24..0000000000 --- a/.agents/skills/bundle-size-optimization +++ /dev/null @@ -1 +0,0 @@ -../../skills/bundle-size-optimization \ No newline at end of file diff --git a/.changeset/config.json b/.changeset/config.json deleted file mode 100644 index 9815b19762..0000000000 --- a/.changeset/config.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "$schema": "https://unpkg.com/@changesets/config@3.1.2/schema.json", - "changelog": [ - "@changesets/changelog-github", - { "repo": "TanStack/router", "disableThanks": true } - ], - "commit": false, - "access": "public", - "baseBranch": "main", - "updateInternalDependencies": "patch", - "fixed": [], - "linked": [], - "ignore": [], - "___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH": { - "onlyUpdatePeerDependentsWhenOutOfRange": true - } -} diff --git a/.changeset/rsbuild-manifest-module-chunks-once.md b/.changeset/rsbuild-manifest-module-chunks-once.md deleted file mode 100644 index 02febd9d84..0000000000 --- a/.changeset/rsbuild-manifest-module-chunks-once.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@tanstack/start-plugin-core': patch ---- - -Rsbuild: the Start manifest pass that runs after every client compilation (builds and each dev update) reads an imported module's chunks once per compilation and counts the module once per importing chunk, instead of once per import connection. The manifest is unchanged; the pass takes about 40 % less time (on a 333-route app, tens of milliseconds less per HMR update). diff --git a/.changeset/rsbuild-manifest-own-chunks.md b/.changeset/rsbuild-manifest-own-chunks.md deleted file mode 100644 index 04e8e29928..0000000000 --- a/.changeset/rsbuild-manifest-own-chunks.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@tanstack/start-plugin-core': patch ---- - -Rsbuild: a route's client manifest entry lists only its own chunks and CSS. When two routes shared a module in a chunk of its own, each route's entry also listed the other route's chunk as a preload and its stylesheet. diff --git a/.changeset/rsbuild-rule-use-falsy-loaders.md b/.changeset/rsbuild-rule-use-falsy-loaders.md deleted file mode 100644 index a84a054fbd..0000000000 --- a/.changeset/rsbuild-rule-use-falsy-loaders.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@tanstack/start-plugin-core': patch ---- - -fix: the Rsbuild RSC integration skips falsy entries in a rule's `use` array (Rspack's conditionally disabled loaders) instead of treating them as loaders. diff --git a/.changeset/rsbuild-virtual-modules-build.md b/.changeset/rsbuild-virtual-modules-build.md deleted file mode 100644 index 01a0c5ee6e..0000000000 --- a/.changeset/rsbuild-virtual-modules-build.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@tanstack/start-plugin-core': patch ---- - -Rsbuild: fix the Rsbuild plugin build after two changes to its virtual modules crossed. Without this fix the package does not build, so no release could ship it. The Rsbuild dev manifest is written to its virtual module under the app's root. diff --git a/.changeset/rsbuild-virtual-modules-root.md b/.changeset/rsbuild-virtual-modules-root.md deleted file mode 100644 index 427043a712..0000000000 --- a/.changeset/rsbuild-virtual-modules-root.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@tanstack/start-plugin-core': patch ---- - -Rsbuild: Start writes its virtual modules under the app's root, not the working directory. An app built or served from another directory (`rsbuild build --root ` from a monorepo root) no longer fails with "Module not found" on the packages they import, such as RSC's serialization adapters. diff --git a/.changeset/rsc-security-floor.md b/.changeset/rsc-security-floor.md deleted file mode 100644 index 9c828f13b3..0000000000 --- a/.changeset/rsc-security-floor.md +++ /dev/null @@ -1,8 +0,0 @@ ---- -'@tanstack/react-start-rsc': patch ---- - -Raise the minimum RSC bundler peer dependencies to versions with the React Server Components fixes for GHSA-xqc2-xf4c-x3h3 (CVE-2026-126187, unauthenticated RCE) and GHSA-h3gv-c5rc-p453 (server function DoS): - -- `@vitejs/plugin-rsc` to `>=0.5.38` (GHSA-59pf-q495-3c99), which vendors a fixed `react-server-dom-webpack`. -- `react-server-dom-rspack` to `>=0.1.1`, the first release built from React sources that include the fix. diff --git a/.changeset/start-server-fn-custom-id-check.md b/.changeset/start-server-fn-custom-id-check.md deleted file mode 100644 index 384f0ade06..0000000000 --- a/.changeset/start-server-fn-custom-id-check.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -'@tanstack/start-plugin-core': minor ---- - -A server function id that a custom `serverFns.generateFunctionId` returns and that never worked over HTTP now fails the build, with an error naming the file, the function and the id: whitespace, a control or non-ASCII character, any of `"`, `#`, `/`, `<`, `>`, `?`, `\`, `^`, `` ` ``, `{`, `}`, the ids `.` and `..`, and a percent-encoding the server reads as another id (`%41`, lowercase hex, `%2E`) or rejects. The client puts the id in the URL unencoded, so a `#` or `?` ended the path and a `/` cut the id short (the call silently ran another server function of the file or none), and the other characters reached the server percent-encoded and matched no function. An id embedding a non-ASCII `functionName` is one of these. One case did work and now fails the build: such an id on a server function only SSR code called. - -Ids with `%` or the other characters URLs allow (such as `:`, `@`, `+`, `=`, `,`, `;`, `!`, `*`, `(`, `)`, `&`, `'`, `|`, `[`, `]`) still build and reach their handler, with a deprecation warning (from the Vite plugin; the Rsbuild plugin does not print compiler warnings yet): the next major version rejects them, since proxies and servers may decode or rewrite them (hash the inputs instead, as the documented example does). An id with `'` no longer breaks the server bundle. diff --git a/.changeset/start-vite-root-library-discovery.md b/.changeset/start-vite-root-library-discovery.md deleted file mode 100644 index d4e8221c59..0000000000 --- a/.changeset/start-vite-root-library-discovery.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@tanstack/start-plugin-core': patch ---- - -Vite: Start finds the Start libraries it bundles in the SSR build from Vite's root, not the working directory. A `vite build ` run from another directory (a monorepo root, a script) no longer leaves them external and uncompiled, where their server fns returned `undefined`. diff --git a/.coderabbit.yaml b/.coderabbit.yaml deleted file mode 100644 index 21d884dbeb..0000000000 --- a/.coderabbit.yaml +++ /dev/null @@ -1,12 +0,0 @@ -# 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/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS deleted file mode 100644 index a4c1d62013..0000000000 --- a/.github/CODEOWNERS +++ /dev/null @@ -1,7 +0,0 @@ -.github/ @TanStack/tanstack-core -.nx/ @TanStack/tanstack-core -nx.json @TanStack/tanstack-core -/scripts/nx @TanStack/tanstack-core -.changeset/config.json @TanStack/tanstack-core -scripts/ @TanStack/tanstack-core -.npmrc @TanStack/tanstack-core \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 9dd0def7bd..5620f4b113 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -4,24 +4,16 @@ 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. + This issue tracker is for reporting bugs found in `router` (https://github.com/tanstack/router). If you have a question about how to achieve something and are struggling, please post a question inside of `router` Discussions tab: https://github.com/tanstack/router/discussions Before submitting a new bug/issue, please check the links below to see if there is a solution or question posted there already: - - Issues tab: https://github.com/tanstack/router/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc - - closed issues tab: https://github.com/tanstack/router/issues?q=is%3Aissue+sort%3Aupdated-desc+is%3Aclosed - - Discussions tab: https://github.com/tanstack/router/discussions + - `router` Issues tab: https://github.com/tanstack/router/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc + - `router` closed issues tab: https://github.com/tanstack/router/issues?q=is%3Aissue+sort%3Aupdated-desc+is%3Aclosed + - `router` Discussions tab: https://github.com/tanstack/router/discussions The more information you fill in, the better the community can help you. - type: dropdown @@ -44,22 +36,22 @@ body: - type: input id: link attributes: - label: Complete minimal reproducer + label: Your Example Website or App description: | - Bug reports need a complete minimal reproducer project. - The reproducer project must be - - either a Stackblitz project (use this pre-configured Stackblitz project ([file-based routes](https://stackblitz.com/github/tanstack/router/tree/main/examples/react/quickstart-file-based?file=src%2Fmain.tsx)|[code-based routes](https://stackblitz.com/github/tanstack/router/tree/main/examples/react/quickstart?file=src%2Fmain.tsx))) - - or a public git repo. - In case of a git repo, the issue must be reproducible **directly** after cloning and installing dependencies. - - If you dont supply a reproducer that meets the above requirements, this issue will be closed. + Which website or app were you using when the bug happened? + Note: + - Please provide a link via our pre-configured Stackblitz project ([file-based routes](https://stackblitz.com/github/tanstack/router/tree/main/examples/react/quickstart-file-based?file=src%2Fmain.tsx)|[code-based routes](https://stackblitz.com/github/tanstack/router/tree/main/examples/react/quickstart?file=src%2Fmain.tsx)) or a link to a repo that can reproduce the issue. + - For Start bugs, use the baseline starters where possible: [React start-basic](https://github.com/tanstack/router/tree/main/examples/react/start-basic) | [Solid start-basic](https://github.com/tanstack/router/tree/main/examples/solid/start-basic). + - Your bug will may get fixed much faster if we can run your code and it doesn't have dependencies other than the `router` npm package / dependency. + - To create a shareable code example you can use Stackblitz. Please no localhost URLs. + - Please read these tips for providing a minimal example: https://stackoverflow.com/help/mcve. placeholder: reproduction URL validations: required: true - type: textarea id: steps attributes: - label: Steps to Reproduce the Bug + label: Steps to Reproduce the Bug or Issue description: Describe the steps we have to take to reproduce the behavior. placeholder: | 1. Go to '...' diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md deleted file mode 100644 index a5ef10f1ff..0000000000 --- a/.github/pull_request_template.md +++ /dev/null @@ -1,22 +0,0 @@ -## 🎯 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 6fd5aa1c86..03cea18d0e 100644 --- a/.github/renovate.json +++ b/.github/renovate.json @@ -3,7 +3,6 @@ "configMigration": true, "extends": [ "config:recommended", - "helpers:pinGitHubActionDigests", "group:allNonMajor", "schedule:weekly", ":approveMajorUpdates", @@ -21,6 +20,7 @@ "@types/node", "@types/react", "@types/react-dom", + "h3", "node", "react", "react-dom", diff --git a/.github/workflows/autofix.yml b/.github/workflows/autofix.yml index 78aea28c12..4ab8d05993 100644 --- a/.github/workflows/autofix.yml +++ b/.github/workflows/autofix.yml @@ -2,6 +2,8 @@ name: autofix.ci # needed to securely identify the workflow on: pull_request: + push: + branches: [main, alpha, beta] concurrency: group: ${{ github.workflow }}-${{ github.event.number || github.ref }} @@ -17,16 +19,14 @@ jobs: if: ${{ github.event_name == 'push' || !github.event.pull_request.draft }} steps: - name: Checkout - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - persist-credentials: false + uses: actions/checkout@v6.0.1 - name: Setup Tools - uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main + uses: tanstack/config/.github/setup@main - name: Fix formatting run: pnpm format - name: Generate labeler config run: pnpm labeler-generate - name: Apply fixes - uses: autofix-ci/action@c5b2d67aa2274e7b5a18224e8171550871fc7e4a # v1.3.4 + uses: autofix-ci/action@635ffb0c9798bd160680f18fd73371e355b85f27 with: commit-message: 'ci: apply automated fixes' diff --git a/.github/workflows/benchmarks.yml b/.github/workflows/benchmarks.yml deleted file mode 100644 index bbc3a1fa24..0000000000 --- a/.github/workflows/benchmarks.yml +++ /dev/null @@ -1,92 +0,0 @@ -# Setup taken from https://codspeed.io/docs/benchmarks/nodejs/vitest -name: Benchmarks - -on: - push: - # Broad on purpose: CodSpeed compares each PR against the run on its - # merge-base commit. Skipping main pushes that don't touch packages/** - # (pnpm config, CI, root tooling) leaves those commits without a baseline - # run, and CodSpeed silently falls back to an older, possibly outlier run — - # which then flags phantom regressions on every PR until the next eligible - # push. Only paths that cannot affect benchmark results are excluded. - branches: - - 'main' - paths-ignore: - - 'docs/**' - - 'examples/**' - - 'e2e/**' - 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 - -env: - NX_CLOUD_ACCESS_TOKEN: ${{ secrets.NX_CLOUD_ACCESS_TOKEN }} - SERVER_PRESET: 'node-server' - NX_NO_CLOUD: true - -jobs: - benchmarks: - name: Run ${{ matrix.benchmark }}:${{ matrix.framework }} CodSpeed benchmark - strategy: - fail-fast: false - matrix: - framework: - - react - - solid - - vue - benchmark: - - client-nav - - ssr - - memory-server - - memory-client - include: - - benchmark: client-nav - mode: simulation - - benchmark: ssr - mode: simulation - - benchmark: memory-server - mode: memory - - benchmark: memory-client - mode: memory - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - persist-credentials: false - - - name: Setup Tools - uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main - - # Run the build outside of the CodSpeed action to avoid being slowed by intrumentation overhead. - # (and then run the task itself with --excludeTaskDependencies) - - name: Prepare ${{ matrix.benchmark }}:${{ matrix.framework }} benchmark - run: >- - pnpm nx run - @benchmarks/${{ matrix.benchmark }}:build:${{ matrix.framework }} - - - name: Run ${{ matrix.benchmark }}:${{ matrix.framework }} CodSpeed benchmark - uses: CodSpeedHQ/action@373d6868929f444bc08d901fd0eb0ad52a8875ea # v5.2.1 - timeout-minutes: 20 - with: - mode: ${{ matrix.mode }} - run: >- - WITH_INSTRUMENTATION=1 - pnpm nx run - @benchmarks/${{ matrix.benchmark }}:test:perf:${{ matrix.framework }} - --excludeTaskDependencies diff --git a/.github/workflows/bundle-size.yml b/.github/workflows/bundle-size.yml deleted file mode 100644 index 51ffa28e4c..0000000000 --- a/.github/workflows/bundle-size.yml +++ /dev/null @@ -1,152 +0,0 @@ -name: Bundle Size - -on: - # We use `pull_request` to split trust boundaries across jobs: - # - `benchmark-pr` checks out PR merge code and runs it as untrusted with read-only permissions. - # - `comment-pr` runs trusted base-repo code with limited write access to upsert the PR comment. - pull_request: - paths: - - '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: - group: ${{ github.workflow }}-${{ github.event.number || github.ref }} - cancel-in-progress: true - -permissions: - contents: read - -env: - NX_NO_CLOUD: true -jobs: - benchmark-pr: - name: Benchmark PR - if: github.event_name == 'pull_request' - runs-on: ubuntu-latest - outputs: - current_json_b64: ${{ steps.capture.outputs.current_json_b64 }} - steps: - - name: Checkout - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - ref: refs/pull/${{ github.event.pull_request.number }}/merge - fetch-depth: 0 - persist-credentials: false - - - name: Setup Tools - uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main - - - name: Measure Bundle Size - run: pnpm benchmark:bundle-size --outputStyle=stream --skipRemoteCache - - - name: Capture Benchmark Outputs - id: capture - run: | - { - echo "current_json_b64=$(base64 -w 0 < benchmarks/bundle-size/results/current.json)" - } >> "$GITHUB_OUTPUT" - - comment-pr: - name: Upsert PR Comment - if: github.event_name == 'pull_request' - runs-on: ubuntu-latest - needs: benchmark-pr - permissions: - contents: read - pull-requests: write - steps: - - name: Checkout - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - fetch-depth: 0 - persist-credentials: false - - - name: Restore Benchmark Outputs - env: - CURRENT_JSON_B64: ${{ needs.benchmark-pr.outputs.current_json_b64 }} - run: | - mkdir -p benchmarks/bundle-size/results - node -e "const fs=require('node:fs'); fs.writeFileSync('benchmarks/bundle-size/results/current.json', Buffer.from(process.env.CURRENT_JSON_B64 || '', 'base64'))" - - - name: Read Historical Data (if available) - run: | - mkdir -p benchmarks/bundle-size/results - if git fetch --depth=1 origin gh-pages; then - if git show origin/gh-pages:benchmarks/bundle-size/data.js > benchmarks/bundle-size/results/history-data.js 2>/dev/null; then - echo "Loaded bundle-size history from gh-pages." - else - rm -f benchmarks/bundle-size/results/history-data.js - echo "No bundle-size history found on gh-pages yet." - fi - fi - - - name: Build PR Report - env: - BASE_SHA: ${{ github.event.pull_request.base.sha }} - REPOSITORY_NAME: ${{ github.event.repository.name }} - REPOSITORY_OWNER: ${{ github.repository_owner }} - run: | - node scripts/benchmarks/bundle-size/pr-report.mjs \ - --current benchmarks/bundle-size/results/current.json \ - --history benchmarks/bundle-size/results/history-data.js \ - --output benchmarks/bundle-size/results/pr-comment.md \ - --base-sha "$BASE_SHA" \ - --dashboard-url "https://${REPOSITORY_OWNER}.github.io/${REPOSITORY_NAME}/benchmarks/bundle-size/" - 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: | - node scripts/benchmarks/common/upsert-pr-comment.mjs \ - --pr "${{ github.event.pull_request.number }}" \ - --body-file benchmarks/bundle-size/results/pr-comment.md - - benchmark-main: - name: Publish Bundle Size History - if: (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && github.ref == 'refs/heads/main' && github.repository_owner == 'TanStack' - runs-on: ubuntu-latest - permissions: - contents: write - steps: - - name: Checkout - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - fetch-depth: 0 - persist-credentials: false - - - name: Setup Tools - uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main - - - name: Measure Bundle Size - run: pnpm benchmark:bundle-size --outputStyle=stream --skipRemoteCache - - name: Publish Benchmark Dashboard - uses: benchmark-action/github-action-benchmark@52576c92bccf6ac60c8223ec7eb2565637cae9ba # v1.22.1 - with: - tool: customSmallerIsBetter - name: Bundle Size (gzip) - output-file-path: benchmarks/bundle-size/results/benchmark-action.json - github-token: ${{ secrets.GITHUB_TOKEN }} - auto-push: true - gh-pages-branch: gh-pages - benchmark-data-dir-path: benchmarks/bundle-size - max-items-in-chart: 200 - summary-always: true - comment-on-alert: false - fail-on-alert: false diff --git a/.github/workflows/check-skills.yml b/.github/workflows/check-skills.yml deleted file mode 100644 index f00a11731b..0000000000 --- a/.github/workflows/check-skills.yml +++ /dev/null @@ -1,122 +0,0 @@ -# check-skills.yml — Drop this into your library repo's .github/workflows/ -# -# Validates intent skills on PRs. After a release or manual run, opens or -# updates one review PR when existing skills, artifact coverage, or workspace -# package coverage need review. -# -# Triggers: pull requests touching skills/artifacts, pushes to main affecting -# docs/source paths, new release published, or manual workflow_dispatch. -# -# intent-workflow-version: 4 -# -# Template variables (replaced by `intent setup`): -# @tanstack/router — e.g. @tanstack/query or my-workspace workspace - -name: Check Skills - -concurrency: - group: check-skills-${{ github.ref }} - cancel-in-progress: true - -on: - pull_request: - paths: - - 'skills/**' - - '**/skills/**' - - '_artifacts/**' - - '**/_artifacts/**' - push: - branches: [main] - paths: - - 'docs/**' - - 'packages/*/src/**' - release: - types: [published] - workflow_dispatch: {} - -permissions: {} - -jobs: - validate: - name: Validate intent skills - if: github.event_name == 'pull_request' - runs-on: ubuntu-latest - permissions: - contents: read - steps: - - name: Checkout - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - persist-credentials: false - - - name: Setup Node - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 - with: - node-version: 24 - package-manager-cache: false - - - name: Install intent - run: npm install -g @tanstack/intent - - - name: Validate skills - run: intent validate --github-summary - - review: - name: Check intent skill coverage - if: github.event_name != 'pull_request' - runs-on: ubuntu-latest - permissions: - contents: write - pull-requests: write - steps: - - name: Checkout - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - fetch-depth: 0 - persist-credentials: true # review job pushes a generated branch - - - name: Setup Node - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 - with: - node-version: 24 - package-manager-cache: false - - - name: Install intent - run: npm install -g @tanstack/intent - - - name: Check skills - id: stale - run: | - intent stale --github-review --package-label "@tanstack/router" - - - name: Open or update review PR - if: steps.stale.outputs.has_review == 'true' - env: - BASE_BRANCH: ${{ github.event.repository.default_branch }} - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - VERSION: ${{ github.event.release.tag_name || 'manual' }} - run: | - BRANCH="skills/review-${VERSION}" - - git config user.name "github-actions[bot]" - git config user.email "41898282+github-actions[bot]@users.noreply.github.com" - - git fetch origin "$BRANCH:refs/remotes/origin/$BRANCH" || true - if git show-ref --verify --quiet "refs/remotes/origin/$BRANCH"; then - git checkout -B "$BRANCH" "origin/$BRANCH" - else - git checkout -b "$BRANCH" - git commit --allow-empty -m "chore: review intent skills for ${VERSION}" - git push origin "$BRANCH" - fi - - PR_URL="$(gh pr list --head "$BRANCH" --json url --jq '.[0].url')" - if [ -n "$PR_URL" ]; then - gh pr edit "$PR_URL" --body-file pr-body.md - else - gh pr create \ - --title "Review intent skills (${VERSION})" \ - --body-file pr-body.md \ - --head "$BRANCH" \ - --base "$BASE_BRANCH" - fi diff --git a/.github/workflows/compiler-platforms.yml b/.github/workflows/compiler-platforms.yml deleted file mode 100644 index ad70e39bb6..0000000000 --- a/.github/workflows/compiler-platforms.yml +++ /dev/null @@ -1,101 +0,0 @@ -name: Compiler Platforms - -# The main PR workflow only runs on Linux x64 (glibc). The compilers load a -# native Yuku binary per platform and handle platform-specific paths, so run -# their unit tests and a Vite and Rsbuild production build on the other -# platforms we ship to. - -on: - pull_request: - paths: - - 'packages/router-utils/**' - - 'packages/router-generator/**' - - 'packages/router-plugin/**' - - 'packages/start-plugin-core/**' - - 'pnpm-lock.yaml' - - '.github/workflows/compiler-platforms.yml' - schedule: - # Weekly, to catch new Yuku releases and runner image updates - - cron: '0 6 * * 1' - workflow_dispatch: - -concurrency: - group: ${{ github.workflow }}-${{ github.event.number || github.ref }} - cancel-in-progress: true - -permissions: - contents: read - -env: - NX_DAEMON: 'false' - NX_NO_CLOUD: 'true' - -defaults: - run: - shell: bash - -jobs: - compiler: - name: ${{ matrix.name }} - runs-on: ${{ matrix.os }} - # actions/setup-node only ships glibc builds, so musl uses Alpine's Node image - container: ${{ matrix.container }} - strategy: - fail-fast: false - matrix: - include: - - name: Windows x64 - os: windows-latest - - name: macOS arm64 - os: macos-latest - - name: Linux arm64 - os: ubuntu-24.04-arm - - name: Linux x64 musl - os: ubuntu-latest - container: node:24.8.0-alpine3.22@sha256:3e843c608bb5232f39ecb2b25e41214b958b0795914707374c8acc28487dea17 - steps: - - name: Install system packages - if: ${{ matrix.container }} - shell: sh - run: apk add --no-cache bash git - - name: Keep LF line endings - # Snapshots are stored with LF. Windows runners check out CRLF by default, - # and with `* text=auto` disabling autocrlf alone still uses the native eol - run: | - git config --global core.autocrlf false - git config --global core.eol lf - - name: Checkout - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - persist-credentials: false - - name: Setup pnpm - if: ${{ !matrix.container }} - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 - - name: Setup Node - if: ${{ !matrix.container }} - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 - with: - node-version-file: .nvmrc - package-manager-cache: false - - name: Setup pnpm (container) - if: ${{ matrix.container }} - run: npm install --global "$(node -p "require('./package.json').packageManager")" - - name: Install dependencies - run: >- - pnpm install --frozen-lockfile - --filter . - --filter "@tanstack/router-utils..." - --filter "@tanstack/router-generator..." - --filter "@tanstack/router-plugin..." - --filter "@tanstack/start-plugin-core..." - --filter "tanstack-react-start-e2e-basic..." - - name: Unit tests - run: >- - pnpm nx run-many --targets=test:unit - --projects=@tanstack/router-utils,@tanstack/router-generator,@tanstack/router-plugin,@tanstack/start-plugin-core - --skip-nx-cache --outputStyle=static - - name: Production builds - run: >- - pnpm nx run-many --targets=build:vite:ssr,build:rsbuild:ssr - --projects=tanstack-react-start-e2e-basic - --skip-nx-cache --outputStyle=static diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml index fde1100409..222c1c7915 100644 --- a/.github/workflows/labeler.yml +++ b/.github/workflows/labeler.yml @@ -1,7 +1,7 @@ name: Labeler on: - pull_request: + - pull_request_target permissions: contents: read @@ -9,12 +9,12 @@ 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 + permissions: + contents: read + pull-requests: write steps: - - name: Labeller - uses: actions/labeler@f27b608878404679385c85cfa523b85ccb86e213 # v6.1.0 + - uses: actions/labeler@v5.0.0 with: repo-token: ${{ secrets.GITHUB_TOKEN }} configuration-path: labeler-config.yml diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index ae19b4f0d2..27afd72710 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -10,16 +10,10 @@ 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 + pull-requests: write jobs: test: @@ -29,53 +23,33 @@ jobs: TSR_TMP_DIR: ./tmp steps: - name: Checkout - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@v6.0.1 with: fetch-depth: 0 - persist-credentials: false - - name: Start Nx Workers - run: npx nx-cloud start-workers + - name: Start Nx Agents + run: npx nx-cloud start-ci-run --distribute-on=".nx/workflows/dynamic-changesets.yaml" - name: Setup Tools - uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main + uses: tanstack/config/.github/setup@main - name: Get base and head commits for `nx affected` - uses: nrwl/nx-set-shas@afb73a62d26e41464e9254689e1fd6122ee683c1 # v5.0.1 + uses: nrwl/nx-set-shas@v4.4.0 with: main-branch-name: main - name: Run Checks run: pnpm run test:pr --parallel=3 - - name: Stop Nx Workers + - name: Stop Nx Agents if: ${{ always() }} - run: npx nx-cloud stop-all-workers + run: npx nx-cloud stop-all-agents preview: name: Preview runs-on: ubuntu-latest - permissions: - contents: read - pull-requests: write steps: - name: Checkout - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@v6.0.1 with: fetch-depth: 0 - persist-credentials: false - name: Setup Tools - uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main + uses: tanstack/config/.github/setup@main - name: Build Packages run: pnpm run build:all - name: Publish Previews run: pnpx pkg-pr-new publish --pnpm './packages/*' --template './examples/*/*' - version-preview: - name: Version Preview - runs-on: ubuntu-latest - permissions: - contents: read - pull-requests: write - steps: - - name: Checkout - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - persist-credentials: false - - name: Setup Tools - uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main - - name: Changeset Preview - uses: TanStack/config/.github/changeset-preview@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 115c3445e6..2ea3eddbf5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,12 +1,17 @@ name: Release on: + workflow_dispatch: + inputs: + tag: + description: override release tag + required: false push: - branches: [main, '*-pre', '*-maint'] + branches: [main, alpha, beta] concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: false + group: ${{ github.workflow }}-${{ github.event.number || github.ref }} + cancel-in-progress: true env: NX_CLOUD_ACCESS_TOKEN: ${{ secrets.NX_CLOUD_ACCESS_TOKEN }} @@ -20,45 +25,27 @@ permissions: jobs: release: name: Release + if: github.repository_owner == 'TanStack' runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + uses: actions/checkout@v6.0.1 with: fetch-depth: 0 - persist-credentials: true # changesets/action pushes Release PR commits + - name: Start Nx Agents + run: npx nx-cloud start-ci-run --distribute-on=".nx/workflows/dynamic-changesets.yaml" - name: Setup Tools - uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main - - name: Run Build - run: pnpm run build:all - - name: Enter Pre-Release Mode - if: "contains(github.ref_name, '-pre') && !hashFiles('.changeset/pre.json')" - run: pnpm changeset pre enter pre - - name: Determine dist-tag - id: dist-tag + uses: tanstack/config/.github/setup@main + - name: Run Tests + run: pnpm run test:ci --parallel=3 + - name: Stop Nx Agents + if: ${{ always() }} + run: npx nx-cloud stop-all-agents + - name: Publish run: | - BRANCH="${GITHUB_REF_NAME}" - if [[ "$BRANCH" == *-pre ]]; then - echo "prerelease=true" >> "$GITHUB_OUTPUT" - elif [[ "$BRANCH" == *-maint ]]; then - echo "tag=maint" >> "$GITHUB_OUTPUT" - else - echo "latest=true" >> "$GITHUB_OUTPUT" - fi - - name: Create Release Pull Request or Publish - id: changesets - uses: changesets/action@63a615b9cd06ba9a3e6d13796c7fbcb080a60a0b # v1.8.0 - with: - version: pnpm run changeset:version - publish: pnpm run changeset:publish ${{ steps.dist-tag.outputs.tag && format('--tag {0}', steps.dist-tag.outputs.tag) }} - title: 'ci: Version Packages' - commit: 'ci: changeset release' + git config --global user.name 'Tanner Linsley' + git config --global user.email 'tannerlinsley@users.noreply.github.com' + pnpm run cipublish env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - NODE_OPTIONS: --max-old-space-size=8192 - - name: Create GitHub Release - if: steps.changesets.outputs.published == 'true' - run: node scripts/create-github-release.mjs ${{ steps.dist-tag.outputs.prerelease == 'true' && '--prerelease' }} ${{ steps.dist-tag.outputs.latest == 'true' && '--latest' }} - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + TAG: ${{ inputs.tag }} diff --git a/.github/workflows/zizmor.yml b/.github/workflows/zizmor.yml deleted file mode 100644 index 55afe41cc7..0000000000 --- a/.github/workflows/zizmor.yml +++ /dev/null @@ -1,25 +0,0 @@ -name: GitHub Actions Security Analysis - -on: - push: - branches: [main] - pull_request: - branches: ['**'] - -permissions: {} - -jobs: - zizmor: - name: Run zizmor - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - persist-credentials: false - - - name: Run zizmor - uses: zizmorcore/zizmor-action@5f14fd08f7cf1cb1609c1e344975f152c7ee938d # v0.5.6 - with: - advanced-security: false - annotations: true diff --git a/.gitignore b/.gitignore index 70028b2860..982044b29b 100644 --- a/.gitignore +++ b/.gitignore @@ -24,7 +24,7 @@ coverage packages/router-generator/tests/**/*.gen.ts packages/router-generator/tests/**/*.gen.js **/port*.txt -**/test-results/** +**/test-results/ # Playwright artifacts **/playwright-report/ @@ -59,14 +59,10 @@ ts-perf /examples/*/*/package-lock.json .netlify -.vercel nx-cloud.env .nx/cache .nx/workspace-data -.nx/polygraph -.nx/self-healing -.nx/migrate-runs gpt/db.json @@ -88,9 +84,3 @@ vite.config.ts.timestamp_* **/llms **/.tanstack - -# eslint-plugin-start perf fixtures -/e2e/eslint-plugin-start/src/perf/generated - -# local memory flame profiles -benchmarks/memory/**/.profiles/ diff --git a/.nvmrc b/.nvmrc index 63f87c20ef..b404027604 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -26.12.1 +24.8.0 diff --git a/.nx/ci-config.yaml b/.nx/ci-config.yaml deleted file mode 100644 index 2f0783feb4..0000000000 --- a/.nx/ci-config.yaml +++ /dev/null @@ -1,5 +0,0 @@ -dte: - distribute-on: - small-changeset: 6 linux-medium-js - medium-changeset: 12 linux-medium-js - large-changeset: 18 linux-medium-js diff --git a/.nx/workflows/dynamic-changesets.yaml b/.nx/workflows/dynamic-changesets.yaml new file mode 100644 index 0000000000..d3536f3ba7 --- /dev/null +++ b/.nx/workflows/dynamic-changesets.yaml @@ -0,0 +1,4 @@ +distribute-on: + small-changeset: 3 linux-medium-js + medium-changeset: 6 linux-medium-js + large-changeset: 10 linux-medium-js diff --git a/.nx/workflows/ultracache-config.yaml b/.nx/workflows/ultracache-config.yaml deleted file mode 100644 index b3ed223621..0000000000 --- a/.nx/workflows/ultracache-config.yaml +++ /dev/null @@ -1,124 +0,0 @@ -ignore-reads: - - e2e/.gitignore - - '**/src/routeTree.gen.ts' -ignore-writes: - - '**/src/routeTree.gen.ts' -task-exclusions: - - target: test:build - ignore-reads: - - LICENSE - # HMR tests edit these inputs in place and restore their original contents. - # Keep them out of cached outputs so cache replay never overwrites source. - - project: tanstack-react-start-e2e-deferred-hydration - target: test:e2e - ignore-writes: - - e2e/react-start/deferred-hydration/src/routes/components.tsx - - project: tanstack-react-start-e2e-hmr - target: test:e2e - ignore-writes: &hmr-source-writes - - e2e/react-start/hmr/src/components/AliasedRouteImportChildPanel.tsx - - e2e/react-start/hmr/src/components/AliasedRouteImportParentPanel.tsx - - e2e/react-start/hmr/src/hmr/server-fn-hmr-factory.ts - - e2e/react-start/hmr/src/routes/__root.tsx - - e2e/react-start/hmr/src/routes/child.tsx - - e2e/react-start/hmr/src/routes/component-hmr-inline-error-split.tsx - - e2e/react-start/hmr/src/routes/component-hmr-inline-nosplit.tsx - - e2e/react-start/hmr/src/routes/component-hmr-inline-split.tsx - - e2e/react-start/hmr/src/routes/component-hmr-lowercase-named-split.tsx - - e2e/react-start/hmr/src/routes/component-hmr-named-error-split.tsx - - e2e/react-start/hmr/src/routes/component-hmr-named-nosplit.tsx - - e2e/react-start/hmr/src/routes/component-hmr-named-split.tsx - - e2e/react-start/hmr/src/routes/index.tsx - - e2e/react-start/hmr/src/routes/inputs.tsx - - project: tanstack-react-start-e2e-hmr - target: test:e2e--vite-ssr - ignore-writes: *hmr-source-writes - - project: tanstack-react-start-e2e-hmr - target: test:e2e--vite-ssr--bundled-dev - ignore-writes: *hmr-source-writes - - project: tanstack-react-start-e2e-hmr - target: test:e2e--rsbuild-ssr - ignore-writes: *hmr-source-writes - - project: tanstack-react-start-e2e-rsbuild - target: test:e2e--rsbuild-ssr - ignore-writes: - - e2e/react-start/rsbuild/src/routes/index.tsx - - project: tanstack-react-start-e2e-server-functions - target: test:e2e - ignore-writes: - - e2e/react-start/server-functions/src/routes/consistent.tsx - # Scaffolding tests deliberately populate tracked empty route fixtures. - - project: '@tanstack/router-generator' - target: test:unit - ignore-writes: - - packages/router-generator/tests/generator/custom-scaffolding/routes/__root.tsx - - packages/router-generator/tests/generator/custom-scaffolding/routes/api/bar.tsx - - packages/router-generator/tests/generator/custom-scaffolding/routes/foo.lazy.tsx - - packages/router-generator/tests/generator/custom-scaffolding/routes/index.tsx - # These reads are of scratch files created by the same test invocation. - - project: tanstack-solid-start-e2e-basic-auth - target: test:e2e - ignore-reads: - - e2e/solid-start/basic-auth/.tmp/dev.db - - project: tanstack-vue-start-e2e-basic-auth - target: test:e2e - ignore-reads: - - e2e/vue-start/basic-auth/.tmp/dev.db - - project: '@tanstack/router-generator' - target: test:unit - ignore-reads: - - packages/router-generator/tests/generator/file-modification/routes/[(]test[)]/initiallyEmpty.tsx - - packages/router-generator/tests/generator/file-modification/routes/[(]test[)]/initiallyEmpty.lazy.tsx - # Mutable counters are scratch state, not artifacts to replay from cache. - - project: tanstack-react-start-e2e-basic-tsr-config - target: test:e2e - ignore-reads: - - e2e/react-start/basic-tsr-config/count.txt - ignore-writes: - - e2e/react-start/basic-tsr-config/count.txt - - project: tanstack-solid-start-e2e-basic-tsr-config - target: test:e2e - ignore-reads: - - e2e/solid-start/basic-tsr-config/count.txt - ignore-writes: - - e2e/solid-start/basic-tsr-config/count.txt - - project: tanstack-vue-start-e2e-basic-tsr-config - target: test:e2e - ignore-reads: - - e2e/vue-start/basic-tsr-config/count.txt - ignore-writes: - - e2e/vue-start/basic-tsr-config/count.txt - # Paraglide downloads compiler plugins from the URLs in settings.json. - # Ignore warm-cache reads; the settings remain inputs and cache files outputs. - - project: tanstack-react-start-e2e-i18n-paraglide - target: build - ignore-reads: - - e2e/react-start/i18n-paraglide/project.inlang/cache/plugins/* - - project: tanstack-router-e2e-react-i18n-paraglide - target: build - ignore-reads: - - e2e/react-router/i18n-paraglide/project.inlang/cache/plugins/* - - project: tanstack-react-start-e2e-i18n-paraglide - target: test:e2e - ignore-reads: - - e2e/react-start/i18n-paraglide/project.inlang/cache/plugins/* - - project: tanstack-router-e2e-react-i18n-paraglide - target: test:e2e - ignore-reads: - - e2e/react-router/i18n-paraglide/project.inlang/cache/plugins/* - - project: tanstack-router-i18n-paraglide - target: build - ignore-reads: - - examples/react/i18n-paraglide/project.inlang/cache/plugins/* - - project: tanstack-start-i18n-paraglide - target: build - ignore-reads: - - examples/react/start-i18n-paraglide/project.inlang/cache/plugins/* - - project: tanstack-router-solid-i18n-paraglide - target: build - ignore-reads: - - examples/solid/i18n-paraglide/project.inlang/cache/plugins/* - - project: tanstack-solid-start-i18n-paraglide - target: build - ignore-reads: - - examples/solid/start-i18n-paraglide/project.inlang/cache/plugins/* diff --git a/.prettierignore b/.prettierignore index de501452ad..888cf74797 100644 --- a/.prettierignore +++ b/.prettierignore @@ -16,8 +16,3 @@ node_modules **/tests/generator/**/routeTree*.snapshot.ts /.nx/workspace-data **/src/routeTree.gen.ts -packages/router-plugin/tests/**/test-files/** -.nx/self-healing - -# Preserve the pinned upstream URL fixtures byte for byte. -packages/router-core/tests/fixtures/wpt-url/urltestdata*.json diff --git a/AGENTS.md b/AGENTS.md index f47b5103e1..6ff30deb95 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,41 +1,176 @@ # AGENTS.md -## Scope +## Project overview -- 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 is a type-safe router with built-in caching and URL state management for React and Solid applications. This monorepo contains two main products: -## Work and validation +- **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 -- 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. +## Setup commands -```sh -CI=1 NX_DAEMON=false pnpm nx run-many -p -t --skipRemoteCache -``` +- 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` -- 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`. +## Code style -## Runtime rules +- 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:*`) -- 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. +## Dev environment tips -## Performance and final bundle pass +- 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. -- 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. +## Testing instructions + +- **Critical**: Always run unit and type tests during development - do not proceed if they fail +- **Test types:** `pnpm test:unit`, `pnpm test:types`, `pnpm test:eslint`, `pnpm test:e2e`, `pnpm test:build` +- **Full CI suite:** `pnpm test:ci` +- **Fix formatting:** `pnpm format` +- **Efficient targeted testing workflow:** + 1. **Affected only:** `pnpm nx affected --target=test:unit` (compares to main branch) + 2. **Specific packages:** `pnpm nx run @tanstack/react-router:test:unit` + 3. **Specific files:** `pnpm nx run @tanstack/react-router:test:unit -- tests/link.test.tsx` + 4. **Specific patterns:** `pnpm nx run @tanstack/react-router:test:unit -- tests/link.test.tsx -t "preloading"` +- **Pro tips:** + - Use `pnpm nx run @tanstack/react-router:test:unit -- list` to explore available tests before running + - Use `-t "pattern"` to focus on specific functionality during development + - Use `--exclude` patterns to skip unrelated tests + - Keep all test filtering arguments behind `pnpm nx run ... -- ...` for maximum precision while preserving task dependencies +- **Example workflow:** `pnpm nx run @tanstack/react-router:test:unit` → `pnpm nx run @tanstack/react-router:test:unit -- tests/link.test.tsx` → `pnpm nx run @tanstack/react-router:test:unit -- tests/link.test.tsx -t "preloading"` + +## PR instructions + +- Always run `pnpm test:eslint`, `pnpm test:types`, and `pnpm test:unit` before committing +- Test changes in relevant example apps: `cd examples/react/basic && pnpm dev` +- Update corresponding documentation in `docs/` directory when adding features +- Add or update tests for any code changes +- Use internal docs links relative to `docs/` folder (e.g., `./guide/data-loading`) + +## Package structure + +**Core packages:** + +- `packages/router-core/` - Framework-agnostic core router logic +- `packages/react-router/`, `packages/solid-router/` - React/Solid bindings and components +- `packages/history/` - Browser history management + +**Tooling:** + +- `packages/router-cli/` - CLI tools for code generation +- `packages/router-generator/` - Route generation utilities +- `packages/router-plugin/` - Universal bundler plugins (Vite, Webpack, ESBuild, Rspack) +- `packages/virtual-file-routes/` - Virtual file routing system + +**Developer experience:** + +- `packages/router-devtools/`, `packages/*-router-devtools/` - Development tools +- `packages/eslint-plugin-router/` - ESLint rules for router + +**Validation adapters:** + +- `packages/zod-adapter/`, `packages/valibot-adapter/`, `packages/arktype-adapter/` + +**Start framework:** + +- `packages/*-start/`, `packages/start-*/` - Full-stack framework packages + +**Examples & testing:** + +- `examples/react/`, `examples/solid/` - Example applications (test changes here) +- `e2e/` - End-to-end tests (requires Playwright) +- `docs/router/`, `docs/start/` - Documentation with React/Solid subdirectories + +**Dependencies:** Uses workspace protocol (`workspace:*`) - core → framework → start packages + +## Common development tasks + +**Adding new routes:** + +- Use file-based routing in `src/routes/` directories +- Or use code-based routing with route definitions +- Run route generation with CLI tools + +**Testing changes:** + +- Build packages: `pnpm build` or `pnpm dev` (watch mode) +- Run example apps to test functionality +- Use devtools for debugging router state + +**Documentation updates:** + +- Update relevant docs in `docs/` directory +- Ensure examples reflect documentation changes +- Test documentation links and references +- Use relative links to `docs/` folder format + +## Framework-specific notes + +**React:** + +- Uses React Router components and hooks +- Supports React Server Components (RSC) +- Examples include React Query integration +- Package: `@tanstack/react-router` + +**Solid:** + +- Uses Solid Router components and primitives +- Supports Solid Start for full-stack applications +- Examples include Solid Query integration +- Package: `@tanstack/solid-router` + +## Environment requirements + +- **Node.js** - Required for development +- **pnpm** - Package manager (required for workspace features) +- **Playwright** - Required for e2e tests (`pnpm exec playwright install`) + +## Key architecture patterns + +- **Type Safety**: Extensive TypeScript for type-safe routing +- **Framework Agnostic**: Core logic separated from framework bindings +- **Plugin Architecture**: Universal bundler plugins using unplugin +- **File-based Routing**: Support for both code-based and file-based routing +- **Search Params**: First-class support for type-safe search parameters + +## Development workflow + +1. **Setup**: `pnpm install` and `pnpm exec playwright install` +2. **Build**: `pnpm build:all` or `pnpm dev` for watch mode +3. **Test**: Make changes and run relevant tests (use nx for targeted testing) +4. **Examples**: Navigate to examples and run `pnpm dev` to test changes +5. **Quality**: Run `pnpm test:eslint`, `pnpm test:types`, `pnpm test:unit` before committing + +## References + +- **Documentation**: https://tanstack.com/router +- **GitHub**: https://github.com/TanStack/router +- **Discord Community**: https://discord.com/invite/WrRKjPJ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4b6e808af1..c28d01241b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,95 +1,30 @@ -# Contributing to TanStack Router +# Contributing -TanStack Router is a community project. Contributions to both TanStack Router and TanStack Start are welcome. - -## Setup - -1. Clone the repository: - - ```sh - gh repo clone TanStack/router - ``` - -2. Install [Node.js](https://nodejs.org/en/) and [pnpm](https://pnpm.io/installation). This repository requires pnpm `11.x.x` or newer. -3. Install dependencies: - - ```sh - pnpm install - ``` - - This installs dependencies for the entire monorepo, including examples. Workspace dependencies are linked automatically. - -4. Install the Playwright browsers if you will run end-to-end tests: - - ```sh - pnpm exec playwright install - ``` - -5. Create a branch for your changes: - - ```sh - git checkout -b my-new-branch - ``` - -## Before you start - -- 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 - -- `pnpm build:all` builds all packages. -- `pnpm build` runs the cached Nx build for affected packages. -- `pnpm dev` builds the packages and starts the development watcher. - -To run an example application, move into its directory and start its development server. For example: - -```sh -cd examples/react/basic -pnpm dev -``` - -## Testing and linting - -Run the checks relevant to your changes while developing: - -- `pnpm test:eslint` checks linting for affected packages. -- `pnpm test:types` checks types for affected packages. -- `pnpm test:unit` runs unit tests for affected packages. -- `pnpm test:build` checks builds for affected packages. -- `pnpm test:e2e` runs end-to-end tests and requires the Playwright browsers. - -Before opening a pull request, run at least: - -```sh -pnpm test:eslint -pnpm test:types -pnpm test:unit -``` - -To run the full CI test suite, use `pnpm test:ci`. For faster feedback, use an Nx target for a specific package or pass a test file or test name after `--`. For example: - -```sh -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" -``` - -Add appropriate unit tests for isolated behavior and end-to-end tests for browser or application workflows. Test relevant example applications when the change affects them. - -## Documentation - -Update the relevant documentation for user-facing changes. Documentation lives in the `docs/` directory, with separate sections for Router and Start. Use relative links within the `docs/` directory, such as `./guide/data-loading`. - -The documentation sites are hosted on [tanstack.com](https://tanstack.com), which is a [TanStack Start application](https://github.com/TanStack/tanstack.com). To preview documentation changes locally, clone both repositories as siblings: +- Clone the repo + - `gh repo clone TanStack/router` +- Ensure `node` is installed + - https://nodejs.org/en/ +- Ensure `pnpm` is installed + - https://pnpm.io/installation + - Why? We use `pnpm` to manage workspace dependencies. It's easily the best monorepo/workspace experience available as of when this was written. +- Install dependencies + - `pnpm install` + - This installs dependencies for all of the packages in the monorepo, even examples! + - Dependencies inside of the packages and examples are automatically linked together as local/dynamic dependencies. +- Install test dependencies + - `pnpm exec playwright install` (required for e2e tests) +- Run the build or dev watcher + - `pnpm build:all` (build all packages) or + - `pnpm build` (cached build with [nx affected](https://nx.dev/nx-api/nx/documents/affected)) or + - `pnpm dev` +- Navigate to an example + - `cd examples/react/basic` +- Run the example + - `pnpm dev` +- Make changes to the code + - If you ran `pnpm dev` the dev watcher will automatically rebuild the code that has changed +- Editing the docs locally and previewing the changes + - The documentations for all the TanStack projects are hosted on [tanstack.com](https://tanstack.com), which is a TanStack Start application (https://github.com/TanStack/tanstack.com). You need to run this app locally to preview your changes in the `TanStack/router` docs. > [!NOTE] > The website fetches the doc pages from GitHub in production, and searches for them at `../router/docs` in development. Your local clone of `TanStack/router` needs to be in the same directory as the local clone of `TanStack/tanstack.com`. @@ -118,7 +53,7 @@ git clone git@github.com:TanStack/tanstack.com.git --depth=1 --single-branch --b > [!NOTE] > Your `tanstack` directory should look like this: > -> ```text +> ``` > tanstack/ > | > +-- router/ (<-- this directory cannot be called anything else!) @@ -140,21 +75,6 @@ pnpm dev > [!WARNING] > You will need to update the `docs/(router or start)config.json` file (in `TanStack/router`) if you add a new documentation page! -## AI-assisted contributions +You can see the whole process in the screen capture below: - - -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. +https://github.com/fulopkovacs/form/assets/43729152/9d35a3c3-8153-4e74-9cb2-af275f7a269b diff --git a/README.md b/README.md index 736715b12a..774a2b096d 100644 --- a/README.md +++ b/README.md @@ -4,20 +4,10 @@ - - - - TanStack Router - + ## TanStack Router @@ -33,20 +23,10 @@ A modern router designed for type safety, data‑driven navigation, and seamless - - - - TanStack Start - + ## TanStack Start @@ -89,22 +69,22 @@ A full‑stack framework built on Router, designed for server rendering, streami - +
- - - - - CodeRabbit - - - + + + + + CodeRabbit + + + - - - - Cloudflare - + + + + Cloudflare + diff --git a/_artifacts/domain_map.yaml b/_artifacts/domain_map.yaml deleted file mode 100644 index 0b2672f0c6..0000000000 --- a/_artifacts/domain_map.yaml +++ /dev/null @@ -1,1093 +0,0 @@ -# domain_map.yaml -# Generated by skill-domain-discovery -# Library: TanStack Router -# Version: 1.166.2 -# Date: 2026-03-07 -# Status: reviewed - -library: - name: '@tanstack/react-router' - version: '1.166.2' - repository: 'https://github.com/TanStack/router' - description: >- - Type-safe router for React and Solid with built-in SWR caching, - JSON-first search params, file-based route generation, and - end-to-end type inference. - primary_framework: 'React' - -domains: - - name: 'Defining Routes' - slug: 'defining-routes' - description: >- - Setting up route trees via file-based, code-based, or virtual - file routes, configuring the router instance, and registering - types for end-to-end inference. - - - name: 'Navigating' - slug: 'navigating' - description: >- - Moving between routes using Links, imperative navigation, - redirects, preloading, active states, and navigation blocking. - - - name: 'Managing URL State' - slug: 'managing-url-state' - description: >- - Reading and writing search params and path params with - validation, serialization, middlewares, and type-safe adapters. - - - name: 'Loading Data' - slug: 'loading-data' - description: >- - Fetching data via route loaders, coordinating external caches, - managing SWR caching, deferred loading, and error/pending states. - - - name: 'Protecting Routes' - slug: 'protecting-routes' - description: >- - Authentication guards, authorization checks, RBAC patterns, - and redirect-based access control via beforeLoad. - - - name: 'Rendering and Layout' - slug: 'rendering-and-layout' - description: >- - Outlets, nested layouts, pathless layouts, code splitting, - error boundaries, not-found handling, route masking, scroll - restoration, and document head management. - - - name: 'Type Safety' - slug: 'type-safety' - description: >- - Router type registration, inference patterns, narrowing with - from, TypeScript performance, and avoiding unnecessary type - annotations. - - - name: 'Server-Side Rendering' - slug: 'server-side-rendering' - description: >- - Non-streaming and streaming SSR setup, hydration, data - serialization, and isomorphic router creation. - -skills: - # ── Defining Routes ────────────────────────────────────────────── - - name: 'Route Setup' - slug: 'route-setup' - domain: 'defining-routes' - description: >- - Set up a TanStack Router project with file-based, code-based, - or virtual file routes, configure the router instance, and - register types. - type: core - packages: - - '@tanstack/react-router' - - '@tanstack/router-core' - - '@tanstack/router-plugin' - - '@tanstack/router-generator' - - '@tanstack/router-cli' - - '@tanstack/virtual-file-routes' - - '@tanstack/eslint-plugin-router' - covers: - - createRouter - - createRootRoute - - createRootRouteWithContext - - createRoute - - createFileRoute - - createLazyFileRoute - - addChildren - - routeTree.gen.ts - - declare module Register - - TanStackRouter bundler plugin - - tsr.config.json - - virtual file routes API - - file naming conventions - - route matching and sorting - tasks: - - 'Scaffold a new TanStack Router project' - - 'Configure file-based routing with Vite plugin' - - 'Set up code-based route tree manually' - - 'Configure virtual file routes for custom conventions' - - 'Register router types via module declaration' - - 'Set up ESLint plugin for route property ordering' - reference_candidates: - - topic: 'file naming conventions' - reason: '>10 distinct conventions (dot separator, $ token, _ prefix/suffix, () groups, [] escaping, index, route.tsx, __root)' - failure_modes: - - mistake: 'Missing router type registration' - mechanism: >- - Without declare module Register, top-level exports like - Link, useNavigate, useParams have no type safety. Code - compiles but all route paths are untyped strings. - wrong_pattern: | - const router = createRouter({ routeTree }) - // no declare module — Link to="" has no autocomplete - correct_pattern: | - const router = createRouter({ routeTree }) - declare module '@tanstack/react-router' { - interface Register { - router: typeof router - } - } - source: 'docs/router/guide/creating-a-router.md' - priority: CRITICAL - status: active - skills: ['route-setup', 'type-safety'] - - - mistake: 'Not committing routeTree.gen.ts' - mechanism: >- - routeTree.gen.ts is runtime code, not a build artifact. - Without it in version control, other developers cannot - build or run the project. - source: 'docs/router/faq.md' - priority: HIGH - status: active - - - mistake: 'Wrong route property order breaks type inference' - mechanism: >- - Properties like beforeLoad must come before loader in - createRoute/createFileRoute calls. Incorrect order causes - context types to not flow into loader. - wrong_pattern: | - createFileRoute('/posts')({ - 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.query({ ...postsQuery, staleTime: 'static' }), - }) - source: 'docs/router/eslint/create-route-property-order.md' - priority: HIGH - status: active - - - mistake: 'Placing TanStackRouter plugin after framework plugin' - mechanism: >- - The TanStackRouter Vite plugin must be listed before the - React/Solid plugin in the Vite config. Wrong order causes - route generation to fail silently. - wrong_pattern: | - plugins: [react(), TanStackRouterVite()] - correct_pattern: | - plugins: [TanStackRouterVite(), react()] - source: 'docs/router/installation/with-vite.md' - priority: HIGH - status: active - - - mistake: 'Using getParentRoute incorrectly in code-based routing' - mechanism: >- - Every non-root route must reference its correct parent via - getParentRoute. Wrong parent breaks type inference for - context, search params, and path params from ancestors. - source: 'docs/router/decisions-on-dx.md' - priority: HIGH - status: active - - compositions: - - library: '@tanstack/eslint-plugin-router' - skill: null - - # ── Navigating ─────────────────────────────────────────────────── - - name: 'Navigation' - slug: 'navigation' - domain: 'navigating' - description: >- - Navigate between routes using Link, useNavigate, Navigate - component, and router.navigate. Configure preloading, active - link states, and navigation blocking. - type: core - packages: - - '@tanstack/react-router' - - '@tanstack/router-core' - covers: - - Link component - - useNavigate hook - - Navigate component - - router.navigate - - ToOptions / NavigateOptions / LinkOptions - - from / to relative navigation - - activeOptions / activeProps / inactiveProps - - preload (intent / viewport / render) - - preloadDelay / defaultPreloadDelay - - useBlocker hook - - Block component - - createLink (custom link components) - - linkOptions helper - - MatchRoute component - - scroll restoration - tasks: - - 'Create type-safe links between routes' - - 'Navigate programmatically after an action' - - 'Set up link preloading on hover intent' - - 'Style active and inactive links' - - 'Block navigation for unsaved changes' - - 'Create custom link components with createLink' - - 'Build reusable navigation options with linkOptions' - - 'Configure scroll restoration' - failure_modes: - - mistake: 'Interpolating params into the to string' - mechanism: >- - Agents build paths like to={`/posts/${id}`} instead of - using the params option. Breaks type safety and param - encoding. - wrong_pattern: | - Post - correct_pattern: | - Post - source: 'docs/router/guide/navigation.md' - priority: CRITICAL - status: active - skills: ['navigation', 'type-safety'] - - - mistake: 'Using useNavigate instead of Link for user-clickable elements' - mechanism: >- - Link renders a real with href, supports cmd/ctrl+click - and preloading. useNavigate produces no accessible element. - source: 'docs/router/guide/navigation.md' - priority: MEDIUM - status: active - - - mistake: 'Not providing from for relative navigation' - mechanism: >- - Without from, the router assumes navigation from root. - Only absolute paths are autocompleted. Relative paths - like ".." resolve from root instead of current route. - wrong_pattern: | - Back - correct_pattern: | - Back - source: 'docs/router/guide/navigation.md' - priority: HIGH - status: active - - - mistake: 'Using search as object instead of function loses existing params' - mechanism: >- - search={{ page: 2 }} replaces all search params. - Must use function form to preserve existing params. - wrong_pattern: | - Page 2 - correct_pattern: | - ({ ...prev, page: 2 })}>Page 2 - source: 'docs/router/how-to/navigate-with-search-params.md' - priority: HIGH - status: active - skills: ['navigation', 'search-params'] - - # ── Managing URL State ─────────────────────────────────────────── - - name: 'Search Params' - slug: 'search-params' - domain: 'managing-url-state' - description: >- - Validate, read, write, and transform search params with - schema validation, adapters, middlewares, and custom - serialization. - type: core - packages: - - '@tanstack/react-router' - - '@tanstack/router-core' - - '@tanstack/zod-adapter' - - '@tanstack/valibot-adapter' - - '@tanstack/arktype-adapter' - covers: - - validateSearch - - useSearch hook - - Route.useSearch - - getRouteApi().useSearch - - search middlewares - - retainSearchParams - - stripSearchParams - - custom serialization (parseSearch / stringifySearch) - - zod adapter / valibot adapter / arktype adapter - - search param inheritance from parent routes - - structural sharing for search params - tasks: - - 'Add validated search params to a route' - - 'Read search params in components' - - 'Update search params while preserving others' - - 'Share search params across parent and child routes' - - 'Set up search param middlewares for retention/stripping' - - 'Configure custom search param serialization' - - 'Handle arrays, objects, and dates in search params' - subsystems: - - name: 'Zod adapter' - package: '@tanstack/zod-adapter' - config_surface: 'zodValidator, fallback() wrapper for .catch/.default type correctness' - - name: 'Valibot adapter' - package: '@tanstack/valibot-adapter' - config_surface: 'Standard Schema compliant, requires valibot 1.0' - - name: 'ArkType adapter' - package: '@tanstack/arktype-adapter' - config_surface: 'Standard Schema compliant, requires arktype 2.0-rc, pass directly to validateSearch' - reference_candidates: - - topic: 'search param validation patterns' - reason: '>10 distinct patterns (basic, optional, arrays, objects, dates, discriminated unions, transforms, conditional, cross-route inheritance, middleware chaining)' - failure_modes: - - mistake: 'Using zod .catch() instead of adapter fallback()' - mechanism: >- - Zod .catch() makes the output type unknown, losing type - safety. The @tanstack/zod-adapter fallback() preserves - the correct inferred type. - wrong_pattern: | - z.object({ page: z.number().catch(1) }) - correct_pattern: | - import { fallback } from '@tanstack/zod-adapter' - z.object({ page: fallback(z.number(), 1) }) - source: 'docs/router/guide/search-params.md' - priority: HIGH - status: active - - - mistake: 'Returning entire search object from loaderDeps' - mechanism: >- - loaderDeps: ({ search }) => search causes loader to - re-run on ANY search param change, not just relevant ones. - Deep equality comparison fires on every unrelated change. - wrong_pattern: | - loaderDeps: ({ search }) => search - correct_pattern: | - loaderDeps: ({ search }) => ({ page: search.page }) - source: 'docs/router/guide/data-loading.md' - priority: HIGH - status: active - skills: ['search-params', 'data-loading'] - - - mistake: 'Passing Date objects in search params' - mechanism: >- - Date objects serialize to [object Object] in URLs. - Must convert to ISO strings for correct serialization. - wrong_pattern: | - - correct_pattern: | - - source: 'docs/router/how-to/arrays-objects-dates-search-params.md' - priority: HIGH - status: active - - - mistake: 'Parent route missing validateSearch blocks inheritance' - mechanism: >- - Child routes cannot access shared search params unless - the parent route defines validateSearch. Without it, - the types and runtime values are not available. - source: 'docs/router/how-to/share-search-params-across-routes.md' - priority: MEDIUM - status: active - - - name: 'Path Params' - slug: 'path-params' - domain: 'managing-url-state' - description: >- - Define and consume dynamic path segments, splat routes, - optional params, and prefix/suffix patterns. - type: core - packages: - - '@tanstack/react-router' - - '@tanstack/router-core' - covers: - - '$paramName dynamic segments' - - '$ splat / _splat' - - '{-$paramName} optional params' - - '{$paramName} prefix/suffix patterns' - - useParams hook - - params.parse / params.stringify - - pathParamsAllowedCharacters - tasks: - - 'Define routes with dynamic path parameters' - - 'Use splat routes for catch-all matching' - - 'Set up optional path parameters for i18n' - - 'Navigate with type-safe path params' - failure_modes: - - mistake: 'Interpolating path params into to string' - mechanism: >- - Same as navigation failure mode — agents build template - literal paths instead of using params option. - source: 'docs/router/guide/navigation.md' - priority: CRITICAL - status: active - skills: ['path-params', 'navigation'] - - - mistake: 'Using * for splat routes instead of $' - mechanism: >- - TanStack Router uses $ for splat routes, not * like some - other routers. The captured value is under _splat key, - not * (though * works in v1 for backwards compat, removed in v2). - source: 'docs/router/routing/routing-concepts.md' - priority: MEDIUM - status: 'fixed-but-legacy-risk' - version_context: '* works in v1 for compat but will be removed in v2' - - - mistake: 'Using curly braces for basic dynamic segments' - mechanism: >- - Basic dynamic segments use $postId (no braces). Curly - braces are only for prefix/suffix patterns like {$postId}.txt - or optional params {-$locale}. - source: 'docs/router/guide/path-params.md' - priority: MEDIUM - status: active - - # ── Loading Data ───────────────────────────────────────────────── - - name: 'Data Loading' - slug: 'data-loading' - domain: 'loading-data' - description: >- - Load data via route loaders with built-in SWR caching, - configure staleTime/gcTime, use loaderDeps for cache keys, - handle pending and error states, and inject dependencies - via router context. - type: core - packages: - - '@tanstack/react-router' - - '@tanstack/router-core' - covers: - - loader option - - loaderDeps - - staleTime / gcTime / defaultPreloadStaleTime - - pendingComponent / pendingMs / pendingMinMs - - errorComponent / onError / onCatch - - beforeLoad - - router context / createRootRouteWithContext - - router.invalidate - - Await component - - deferred data loading - tasks: - - 'Add a data loader to a route' - - 'Configure cache timing (staleTime, gcTime)' - - 'Set up loader dependencies for search-param-driven data' - - 'Show pending UI during slow loads' - - 'Handle loader errors with error boundaries' - - 'Inject dependencies via router context' - - 'Defer non-critical data with unawaited promises' - - 'Invalidate cached data after mutations' - failure_modes: - - mistake: 'Assuming loaders only run on the server' - mechanism: >- - TanStack Router is client-first. Loaders run on the client - by default (and also on the server if using TanStack Start). - Agents trained on Remix/Next assume loaders are server-only - and put server-only code (DB queries, fs access) in them. - source: 'maintainer interview' - priority: CRITICAL - status: active - skills: ['data-loading', 'ssr'] - - - mistake: 'Not understanding staleTime default is 0' - mechanism: >- - Default staleTime is 0, meaning data is always considered - stale and reloads in background on every route re-match. - Agents may not set staleTime, causing excessive refetching. - source: 'docs/router/guide/data-loading.md' - priority: MEDIUM - status: active - - - mistake: 'Using reset() instead of router.invalidate() in error components' - mechanism: >- - For loader errors, reset() only resets the error boundary - but does not re-run the loader. Must use router.invalidate() - to coordinate both reload and boundary reset. - wrong_pattern: | - function PostErrorComponent({ error, reset }) { - return - } - correct_pattern: | - function PostErrorComponent({ error, reset }) { - const router = useRouter() - return - } - source: 'docs/router/guide/data-loading.md' - priority: HIGH - status: active - - - mistake: 'Double parentheses missing on createRootRouteWithContext' - mechanism: >- - createRootRouteWithContext() is a factory — it returns - a function. Must call it twice: createRootRouteWithContext()(routeOptions). - Missing second call is a common error. - wrong_pattern: | - const rootRoute = createRootRouteWithContext<{ auth: AuthState }>({ - component: RootComponent, - }) - correct_pattern: | - const rootRoute = createRootRouteWithContext<{ auth: AuthState }>()({ - component: RootComponent, - }) - source: 'docs/router/guide/data-loading.md' - priority: HIGH - status: active - - - mistake: 'Using React hooks in beforeLoad or loader' - mechanism: >- - beforeLoad and loader are not React components — hooks - cannot be called in them. Must extract hook state in a - wrapper component and pass via router context. - source: 'docs/router/guide/router-context.md' - priority: HIGH - status: active - - compositions: - - library: '@tanstack/react-query' - skill: 'external-data-loading' - - - name: 'External Data Loading' - slug: 'external-data-loading' - domain: 'loading-data' - description: >- - Integrate TanStack Query (or other external caches) with - Router for coordinated data loading, SSR dehydration/hydration, - and streaming. - type: composition - packages: - - '@tanstack/react-router' - - '@tanstack/react-router-ssr-query' - covers: - - External cache coordination pattern - - "queryClient.query with staleTime: 'static' in loader" - - useSuspenseQuery in components - - setupRouterSsrQueryIntegration - - defaultPreloadStaleTime - - dehydrate / hydrate router options - - QueryClient per-request isolation - - Wrap router option for providers - tasks: - - 'Set up TanStack Query with Router' - - 'Preload query data in route loaders' - - 'Configure SSR dehydration/hydration with Query' - - 'Stream query data during SSR' - failure_modes: - - mistake: 'Not setting defaultPreloadStaleTime to 0 with external caches' - mechanism: >- - Router's built-in preload cache (30s default) prevents - external library from controlling freshness. Set - defaultPreloadStaleTime: 0 to let Query manage caching. - wrong_pattern: | - createRouter({ routeTree }) - correct_pattern: | - createRouter({ routeTree, defaultPreloadStaleTime: 0 }) - source: 'docs/router/guide/external-data-loading.md' - priority: HIGH - status: active - - - mistake: 'Creating QueryClient outside createRouter for SSR' - mechanism: >- - For SSR, QueryClient must be created inside createRouter - to ensure per-request isolation. A shared singleton leaks - data between requests. - wrong_pattern: | - const queryClient = new QueryClient() - const router = createRouter({ routeTree, context: { queryClient } }) - correct_pattern: | - function createAppRouter() { - const queryClient = new QueryClient() - return createRouter({ routeTree, context: { queryClient } }) - } - source: 'docs/router/guide/external-data-loading.md' - priority: HIGH - status: active - - - mistake: 'Awaiting a fire-and-forget query in loader blocks rendering' - mechanism: >- - For streaming/deferred patterns, start a query without awaiting - it and handle failures with catch(noop) — it starts fetching on - the server and streams without blocking. Awaiting defeats the purpose. - source: 'docs/router/integrations/query.md' - priority: MEDIUM - status: active - - # ── Protecting Routes ──────────────────────────────────────────── - - name: 'Auth and Guards' - slug: 'auth-and-guards' - domain: 'protecting-routes' - description: >- - Protect routes with authentication checks, authorization - guards, and RBAC patterns using beforeLoad redirects and - layout routes. - type: core - packages: - - '@tanstack/react-router' - - '@tanstack/router-core' - covers: - - beforeLoad for auth checks - - redirect() / throw redirect() - - isRedirect helper - - Authenticated layout routes (_authenticated) - - Non-redirect auth (inline login) - - RBAC with roles and permissions - - Auth provider integration (Auth0, Clerk, Supabase) - - Router context for auth state - tasks: - - 'Protect routes with authentication checks' - - 'Redirect unauthenticated users to login' - - 'Implement role-based access control' - - 'Integrate third-party auth providers' - - 'Pass auth state through router context' - failure_modes: - - mistake: 'Auth check in component instead of beforeLoad' - mechanism: >- - Component-level auth checks cause protected content to - flash before redirect. beforeLoad runs before any - component rendering and prevents the flash entirely. - wrong_pattern: | - component: () => { - const auth = useAuth() - if (!auth.isAuthenticated) return - return - } - correct_pattern: | - beforeLoad: ({ context }) => { - if (!context.auth.isAuthenticated) { - throw redirect({ to: '/login' }) - } - } - source: 'docs/router/how-to/setup-authentication.md' - priority: HIGH - status: active - - - mistake: 'Not re-throwing redirects in try/catch' - mechanism: >- - redirect() works by throwing. If beforeLoad has a try/catch - for error handling, the redirect gets swallowed unless - re-thrown via isRedirect() check. - wrong_pattern: | - beforeLoad: async ({ context }) => { - try { - await validateSession(context.auth) - } catch (e) { - // swallows redirect! - console.error(e) - } - } - correct_pattern: | - beforeLoad: async ({ context }) => { - try { - await validateSession(context.auth) - } catch (e) { - if (isRedirect(e)) throw e - console.error(e) - } - } - source: 'docs/router/guide/authenticated-routes.md' - priority: HIGH - status: active - - - mistake: 'Trying to conditionally render root route component' - mechanism: >- - Root route is always rendered regardless of auth state. - Use a pathless layout route (_authenticated) with - beforeLoad for conditional rendering. - source: 'docs/router/faq.md' - priority: MEDIUM - status: active - - # ── Rendering and Layout ───────────────────────────────────────── - - name: 'Code Splitting' - slug: 'code-splitting' - domain: 'rendering-and-layout' - description: >- - Split route code into lazy-loaded chunks using automatic - code splitting, .lazy.tsx files, or code-based lazy loading. - type: core - packages: - - '@tanstack/react-router' - - '@tanstack/router-plugin' - covers: - - autoCodeSplitting plugin option - - .lazy.tsx file convention - - createLazyFileRoute - - createLazyRoute - - lazyRouteComponent - - getRouteApi for code-split components - - codeSplitGroupings per-route override - - splitBehavior programmatic config - - Critical vs non-critical route properties - tasks: - - 'Enable automatic code splitting' - - 'Manually split a route with .lazy.tsx' - - 'Access typed hooks from code-split components' - - 'Customize which properties are split per route' - failure_modes: - - mistake: 'Exporting route property functions prevents code splitting' - mechanism: >- - Exported functions from route files are included in the - main bundle even with auto code splitting. Component - functions must NOT be exported. - wrong_pattern: | - export function PostsComponent() { return
Posts
} - correct_pattern: | - function PostsComponent() { return
Posts
} - source: 'docs/router/guide/automatic-code-splitting.md' - priority: HIGH - status: active - - - mistake: 'Trying to code-split the root route' - mechanism: >- - __root.tsx does not support code splitting — it is always - rendered regardless of current route. - source: 'docs/router/guide/code-splitting.md' - priority: MEDIUM - status: active - - - mistake: 'Splitting the loader adds double async cost' - mechanism: >- - Loader is already async. Splitting it requires fetching - the chunk AND then executing the loader, adding latency. - Loaders should stay in the main bundle unless there is - a specific reason to split them. - source: 'docs/router/guide/code-splitting.md' - priority: MEDIUM - status: active - - - mistake: 'Importing Route in code-split files for typed hooks' - mechanism: >- - Importing the Route object in a lazy-loaded file pulls - the route config into the lazy chunk, defeating code - splitting. Use getRouteApi('/path') instead. - wrong_pattern: | - import { Route } from './posts.tsx' - const data = Route.useLoaderData() - correct_pattern: | - import { getRouteApi } from '@tanstack/react-router' - const route = getRouteApi('/posts') - const data = route.useLoaderData() - source: 'docs/router/guide/code-splitting.md' - priority: HIGH - status: active - - - name: 'Not Found and Errors' - slug: 'not-found-and-errors' - domain: 'rendering-and-layout' - description: >- - Handle not-found routes, missing resources, and route-level - errors with notFound(), notFoundComponent, errorComponent, - and CatchBoundary. - type: core - packages: - - '@tanstack/react-router' - - '@tanstack/router-core' - covers: - - notFound() function - - notFoundComponent - - defaultNotFoundComponent - - notFoundMode (fuzzy / root) - - errorComponent - - onError / onCatch - - CatchBoundary component - - NotFoundRoute (deprecated) - tasks: - - 'Add a 404 page for unmatched routes' - - 'Throw not-found for missing resources in loaders' - - 'Configure error boundaries per route' - - 'Target specific routes with notFound()' - failure_modes: - - mistake: 'Using deprecated NotFoundRoute' - mechanism: >- - NotFoundRoute is deprecated. When present, notFound() and - notFoundComponent will NOT work. Must remove NotFoundRoute - and use notFoundComponent instead. - source: 'docs/router/guide/not-found-errors.md' - priority: HIGH - status: 'fixed-but-legacy-risk' - version_context: 'NotFoundRoute deprecated, will be removed in next major' - - - mistake: 'Expecting useLoaderData to work in notFoundComponent' - mechanism: >- - When notFoundComponent renders, the route's loader may - not have completed. useLoaderData() may return undefined. - Use useParams, useSearch, or useRouteContext instead. - source: 'docs/router/guide/not-found-errors.md' - priority: MEDIUM - status: active - - - mistake: 'Leaf route cannot handle not-found errors' - mechanism: >- - Routes without children never render Outlet and therefore - cannot catch not-found errors. Only routes with children - (or the root route) can have notFoundComponent. - source: 'docs/router/guide/not-found-errors.md' - priority: MEDIUM - status: active - - - name: 'Route Masking' - slug: 'route-masking' - domain: 'rendering-and-layout' - description: >- - Mask the browser URL while navigating to a different internal - route, with configurable unmask behavior. - type: core - packages: - - '@tanstack/react-router' - - '@tanstack/router-core' - covers: - - mask option on Link / navigate - - createRouteMask - - routeMasks router option - - unmaskOnReload - - location.maskedLocation - - location.state.__tempLocation - tasks: - - 'Show a modal route with a clean URL' - - 'Configure declarative route masks' - - 'Control unmask behavior on page reload' - failure_modes: - - mistake: 'Expecting masked URLs to survive sharing' - mechanism: >- - Masking data is stored in browser history state. When a - URL is shared or opened in a new tab, masking data is - lost and the visible URL is used directly. - source: 'docs/router/guide/route-masking.md' - priority: MEDIUM - status: active - - # ── Type Safety ────────────────────────────────────────────────── - - name: 'Type Safety' - slug: 'type-safety' - domain: 'type-safety' - description: >- - Leverage TanStack Router's fully inferred type system. - Avoid unnecessary type annotations, narrow routes with from, - and optimize TypeScript performance. - type: core - packages: - - '@tanstack/react-router' - - '@tanstack/router-core' - covers: - - Full type inference philosophy - - Register module declaration - - from narrowing on hooks and Link - - strict false for shared components - - getRouteApi for code-split typed access - - addChildren with object syntax for TS perf - - LinkProps / ValidateLinkOptions type utilities - - as const satisfies pattern - tasks: - - 'Register router types for global type safety' - - 'Narrow route types with from parameter' - - 'Use getRouteApi in code-split components' - - 'Optimize TypeScript performance in large route trees' - - 'Build type-safe link option utilities' - failure_modes: - - mistake: 'Adding type annotations or casts to inferred values' - mechanism: >- - TanStack Router is fully type-safe with full inference. - Adding as Type, generic type parameters, satisfies, or - explicit type annotations is unnecessary and can mask - real type errors or break the inference chain. - wrong_pattern: | - const search = useSearch({ from: '/posts' }) as { page: number } - correct_pattern: | - const search = useSearch({ from: '/posts' }) - // search.page is already typed as number - source: 'maintainer interview' - priority: CRITICAL - status: active - - - mistake: 'Using un-narrowed LinkProps type' - mechanism: >- - LinkProps without generics is an extremely large union type. - Using it as a variable type causes severe TS performance - degradation. Use as const satisfies or narrow with generics. - wrong_pattern: | - const props: LinkProps = { to: '/posts' } - correct_pattern: | - const props = { to: '/posts' } as const satisfies LinkProps - source: 'docs/router/guide/type-safety.md' - priority: HIGH - status: active - - - mistake: 'Not narrowing Link/useNavigate with from' - mechanism: >- - Without from, search resolves to a union of ALL routes - search params. TypeScript check time grows linearly with - route count. Always provide from to narrow. - wrong_pattern: | - - correct_pattern: | - - source: 'docs/router/guide/type-safety.md' - priority: HIGH - status: active - - # ── Server-Side Rendering ──────────────────────────────────────── - - name: 'SSR' - slug: 'ssr' - domain: 'server-side-rendering' - description: >- - Set up server-side rendering with non-streaming or streaming - approaches, manage hydration, and handle document head. - type: core - packages: - - '@tanstack/react-router' - - '@tanstack/router-core' - covers: - - RouterClient / RouterServer - - renderRouterToString / renderRouterToStream - - createRequestHandler - - defaultRenderHandler / defaultStreamHandler - - HeadContent / Scripts components - - head route option (meta, links, styles, scripts) - - ScriptOnce component - - Automatic loader dehydration/hydration - - Memory history on server - - Data serialization (Date, Error, FormData, undefined) - tasks: - - 'Set up non-streaming SSR with Express' - - 'Set up streaming SSR' - - 'Configure document head management' - - 'Handle hydration mismatches' - failure_modes: - - mistake: 'Using browser APIs in loaders without environment check' - mechanism: >- - Loaders run on both client and server when using SSR. - Browser-only APIs (window, document, localStorage) will - throw on the server. - source: 'docs/router/guide/ssr.md' - priority: HIGH - status: active - skills: ['ssr', 'data-loading'] - - - mistake: 'Using hash fragments for server-rendered content' - mechanism: >- - Hash fragments are client-only — browsers never send them - to the server. Using hash for conditional rendering causes - hydration mismatches during SSR. - source: 'docs/router/guide/navigation.md' - priority: MEDIUM - status: active - - - mistake: 'Generating Next.js or Remix SSR patterns' - mechanism: >- - Agents trained on Next.js generate getServerSideProps, - App Router patterns, or server components. Agents trained - on Remix generate server-only loader exports. TanStack - Router has its own SSR API (RouterClient/RouterServer). - source: 'maintainer interview' - priority: CRITICAL - status: active - skills: ['ssr', 'route-setup', 'data-loading'] - - # ── Migration ──────────────────────────────────────────────────── - - name: 'Migrate from React Router' - slug: 'migrate-from-react-router' - domain: 'defining-routes' - description: >- - Step-by-step migration from React Router v7 to TanStack Router, - covering route definitions, navigation, search params, and - data loading. - type: lifecycle - packages: - - '@tanstack/react-router' - - '@tanstack/router-plugin' - covers: - - Migration checklist - - Route definition conversion - - Link / useNavigate API differences - - useSearchParams to validateSearch + useSearch - - useParams with from - - Outlet replacement - - Loader conversion - - Code splitting differences - tasks: - - 'Migrate routes from React Router to TanStack Router' - - 'Convert React Router Links and navigation' - - 'Replace useSearchParams with validated search params' - - 'Convert React Router loaders' - failure_modes: - - mistake: 'Leaving React Router imports alongside TanStack Router' - mechanism: >- - React Router and TanStack Router share similar API names - (Link, useNavigate, Outlet). Leftover React Router imports - cause context errors ("cannot use useNavigate outside of - context"). Uninstall react-router-dom to surface these. - source: 'docs/router/how-to/migrate-from-react-router.md' - priority: HIGH - status: active - - - mistake: 'Using React Router useSearchParams pattern' - mechanism: >- - React Router uses useSearchParams() returning URLSearchParams. - TanStack Router uses validateSearch schema + useSearch() - returning typed objects. Agents may generate the RR pattern. - wrong_pattern: | - const [searchParams, setSearchParams] = useSearchParams() - const page = Number(searchParams.get('page')) - correct_pattern: | - // In route definition: - validateSearch: z.object({ page: fallback(z.number(), 1) }) - // In component: - const { page } = Route.useSearch() - source: 'docs/router/installation/migrate-from-react-router.md' - priority: HIGH - status: active - -tensions: - - name: 'Type safety strictness vs rapid prototyping' - skills: ['type-safety', 'route-setup'] - description: >- - Full type inference requires proper setup (Register, correct - property order, getParentRoute). This upfront cost conflicts - with quick prototyping where developers want to skip setup. - implication: >- - Agents skip Register declaration or use type casts to silence - errors, producing code that compiles but has no type safety. - - - name: 'Client-first loaders vs SSR expectations' - skills: ['data-loading', 'ssr'] - description: >- - Loaders are client-first by design but agents assume they are - server-only (Remix/Next mental model). This tension means - browser APIs work in loaders by default but break under SSR. - implication: >- - Agents either put server-only code in client loaders or avoid - browser APIs unnecessarily, depending on which framework mental - model they default to. - - - name: 'Built-in SWR cache vs external cache coordination' - skills: ['data-loading', 'external-data-loading'] - description: >- - Router has built-in caching with staleTime/gcTime defaults. - When using an external cache like React Query, the built-in - cache must be bypassed (defaultPreloadStaleTime: 0) or it - conflicts with the external library's freshness management. - implication: >- - Agents use both caches simultaneously without disabling the - built-in one, causing stale data or double-fetching. - - - name: 'Code splitting granularity vs loader performance' - skills: ['code-splitting', 'data-loading'] - description: >- - Splitting more aggressively reduces initial bundle but splitting - the loader adds a network round-trip before data can be fetched. - The optimal split point differs per route. - implication: >- - Agents split everything including loaders, adding latency to - data loading without understanding the tradeoff. - -cross_references: - - from: 'route-setup' - to: 'type-safety' - reason: 'Register declaration and property order are prerequisites for type inference' - - from: 'navigation' - to: 'search-params' - reason: 'Link search prop and navigate search option directly interact with search param validation' - - from: 'data-loading' - to: 'search-params' - reason: 'loaderDeps consumes validated search params as cache keys' - - from: 'data-loading' - to: 'external-data-loading' - reason: 'Understanding built-in caching is prerequisite for coordinating with external caches' - - from: 'auth-and-guards' - to: 'data-loading' - reason: 'beforeLoad runs before loader — auth context flows into loader via route context' - - from: 'code-splitting' - to: 'data-loading' - reason: 'Loader splitting decisions affect data loading performance' - - from: 'ssr' - to: 'data-loading' - reason: 'SSR changes where loaders execute — must handle both environments' - - from: 'ssr' - to: 'external-data-loading' - reason: 'SSR dehydration/hydration requires special setup for Query integration' - - from: 'not-found-and-errors' - to: 'data-loading' - reason: 'notFound() thrown in loaders interacts with error boundaries and loader data availability' - - from: 'migrate-from-react-router' - to: 'route-setup' - reason: 'Migration requires understanding TanStack Router route setup to replace RR patterns' - -gaps: [] diff --git a/_artifacts/skill_spec.md b/_artifacts/skill_spec.md deleted file mode 100644 index 7eb9554a42..0000000000 --- a/_artifacts/skill_spec.md +++ /dev/null @@ -1,193 +0,0 @@ -# TanStack Router — Skill Spec - -TanStack Router is a type-safe router for React and Solid applications with built-in SWR caching, JSON-first search params, file-based route generation, and end-to-end type inference. It is client-first/isomorphic — loaders run on the client by default and additionally on the server when used with TanStack Start. - -## Domains - -| Domain | Description | Skills | -| --------------------- | ------------------------------------------------------------------- | --------------------------------------------------- | -| Defining Routes | Setting up route trees, configuring the router, registering types | route-setup, migrate-from-react-router | -| Navigating | Links, imperative navigation, preloading, blocking | navigation | -| Managing URL State | Search params and path params with validation and serialization | search-params, path-params | -| Loading Data | Route loaders, SWR caching, external cache coordination, context/DI | data-loading, external-data-loading | -| Protecting Routes | Auth guards, RBAC, beforeLoad redirects | auth-and-guards | -| Rendering and Layout | Code splitting, error/not-found handling, route masking | code-splitting, not-found-and-errors, route-masking | -| Type Safety | Inference patterns, narrowing, TS performance | type-safety | -| Server-Side Rendering | SSR setup, hydration, head management | ssr | - -## Skill Inventory - -| Skill | Type | Domain | What it covers | Failure modes | -| ------------------------- | ----------- | --------------------- | ------------------------------------------------------------------------------------ | ------------- | -| route-setup | core | defining-routes | createRouter, file/code/virtual routing, Register, plugin config, ESLint | 5 | -| navigation | core | navigating | Link, useNavigate, Navigate, preloading, blocking, active states, scroll restoration | 4 | -| search-params | core | managing-url-state | validateSearch, useSearch, middlewares, serialization, adapters | 4 | -| path-params | core | managing-url-state | $params, splats, optional params, prefix/suffix patterns | 3 | -| data-loading | core | loading-data | loader, loaderDeps, staleTime/gcTime, pending/error, context/DI, deferred | 5 | -| external-data-loading | composition | loading-data | TanStack Query integration, SSR dehydration/hydration, streaming | 3 | -| auth-and-guards | core | protecting-routes | beforeLoad redirects, layout auth, RBAC, provider integration | 3 | -| code-splitting | core | rendering-and-layout | autoCodeSplitting, .lazy.tsx, getRouteApi, split groupings | 4 | -| not-found-and-errors | core | rendering-and-layout | notFound(), notFoundComponent, errorComponent, CatchBoundary | 3 | -| route-masking | core | rendering-and-layout | mask option, createRouteMask, unmaskOnReload | 1 | -| type-safety | core | type-safety | Register, from narrowing, TS perf, type utilities | 3 | -| ssr | core | server-side-rendering | RouterClient/Server, streaming, hydration, head management | 3 | -| migrate-from-react-router | lifecycle | defining-routes | Migration checklist, API mapping, search params conversion | 2 | - -## Failure Mode Inventory - -### route-setup (5 failure modes) - -| # | Mistake | Priority | Source | Cross-skill? | -| --- | ------------------------------------------------------ | -------- | --------------------------------------- | ------------ | -| 1 | Missing router type registration | CRITICAL | docs/guide/creating-a-router | type-safety | -| 2 | Not committing routeTree.gen.ts | HIGH | docs/faq | — | -| 3 | Wrong route property order breaks type inference | HIGH | docs/eslint/create-route-property-order | — | -| 4 | Placing TanStackRouter plugin after framework plugin | HIGH | docs/installation/with-vite | — | -| 5 | Using getParentRoute incorrectly in code-based routing | HIGH | docs/decisions-on-dx | — | - -### navigation (4 failure modes) - -| # | Mistake | Priority | Source | Cross-skill? | -| --- | -------------------------------------------------------- | -------- | --------------------------------------- | ------------- | -| 1 | Interpolating params into the to string | CRITICAL | docs/guide/navigation | type-safety | -| 2 | Using useNavigate instead of Link for clickable elements | MEDIUM | docs/guide/navigation | — | -| 3 | Not providing from for relative navigation | HIGH | docs/guide/navigation | — | -| 4 | Using search as object instead of function loses params | HIGH | docs/how-to/navigate-with-search-params | search-params | - -### search-params (4 failure modes) - -| # | Mistake | Priority | Source | Cross-skill? | -| --- | ------------------------------------------------------ | -------- | -------------------------------- | ------------ | -| 1 | Using zod .catch() instead of adapter fallback() | HIGH | docs/guide/search-params | — | -| 2 | Returning entire search object from loaderDeps | HIGH | docs/guide/data-loading | data-loading | -| 3 | Passing Date objects in search params | HIGH | docs/how-to/arrays-objects-dates | — | -| 4 | Parent route missing validateSearch blocks inheritance | MEDIUM | docs/how-to/share-search-params | — | - -### path-params (3 failure modes) - -| # | Mistake | Priority | Source | Cross-skill? | -| --- | --------------------------------------------- | -------- | ----------------------------- | ------------ | -| 1 | Interpolating path params into `to` string | CRITICAL | docs/guide/navigation | navigation | -| 2 | Using \* for splat routes instead of $ | MEDIUM | docs/routing/routing-concepts | — | -| 3 | Using curly braces for basic dynamic segments | MEDIUM | docs/guide/path-params | — | - -### data-loading (5 failure modes) - -| # | Mistake | Priority | Source | Cross-skill? | -| --- | ---------------------------------------------------------------- | -------- | ------------------------- | ------------ | -| 1 | Assuming loaders only run on the server | CRITICAL | maintainer interview | ssr | -| 2 | Not understanding staleTime default is 0 | MEDIUM | docs/guide/data-loading | — | -| 3 | Using reset() instead of router.invalidate() in error components | HIGH | docs/guide/data-loading | — | -| 4 | Double parentheses missing on createRootRouteWithContext | HIGH | docs/guide/data-loading | — | -| 5 | Using React hooks in beforeLoad or loader | HIGH | docs/guide/router-context | — | - -### external-data-loading (3 failure modes) - -| # | Mistake | Priority | Source | Cross-skill? | -| --- | ----------------------------------------------------------- | -------- | -------------------------------- | ------------ | -| 1 | Not setting defaultPreloadStaleTime to 0 | HIGH | docs/guide/external-data-loading | — | -| 2 | Creating QueryClient outside createRouter for SSR | HIGH | docs/guide/external-data-loading | — | -| 3 | Awaiting a fire-and-forget query in loader blocks rendering | MEDIUM | docs/integrations/query | — | - -### auth-and-guards (3 failure modes) - -| # | Mistake | Priority | Source | Cross-skill? | -| --- | --------------------------------------------------- | -------- | -------------------------------- | ------------ | -| 1 | Auth check in component instead of beforeLoad | HIGH | docs/how-to/setup-authentication | — | -| 2 | Not re-throwing redirects in try/catch | HIGH | docs/guide/authenticated-routes | — | -| 3 | Trying to conditionally render root route component | MEDIUM | docs/faq | — | - -### code-splitting (4 failure modes) - -| # | Mistake | Priority | Source | Cross-skill? | -| --- | ---------------------------------------------------------- | -------- | ----------------------------------- | ------------ | -| 1 | Exporting route property functions prevents code splitting | HIGH | docs/guide/automatic-code-splitting | — | -| 2 | Trying to code-split the root route | MEDIUM | docs/guide/code-splitting | — | -| 3 | Splitting the loader adds double async cost | MEDIUM | docs/guide/code-splitting | — | -| 4 | Importing Route in code-split files for typed hooks | HIGH | docs/guide/code-splitting | — | - -### not-found-and-errors (3 failure modes) - -| # | Mistake | Priority | Source | Cross-skill? | -| --- | ---------------------------------------------------- | -------- | --------------------------- | ------------ | -| 1 | Using deprecated NotFoundRoute | HIGH | docs/guide/not-found-errors | — | -| 2 | Expecting useLoaderData to work in notFoundComponent | MEDIUM | docs/guide/not-found-errors | — | -| 3 | Leaf route cannot handle not-found errors | MEDIUM | docs/guide/not-found-errors | — | - -### route-masking (1 failure mode) - -| # | Mistake | Priority | Source | Cross-skill? | -| --- | ---------------------------------------- | -------- | ------------------------ | ------------ | -| 1 | Expecting masked URLs to survive sharing | MEDIUM | docs/guide/route-masking | — | - -### type-safety (3 failure modes) - -| # | Mistake | Priority | Source | Cross-skill? | -| --- | --------------------------------------------------- | -------- | ---------------------- | ------------ | -| 1 | Adding type annotations or casts to inferred values | CRITICAL | maintainer interview | — | -| 2 | Using un-narrowed LinkProps type | HIGH | docs/guide/type-safety | — | -| 3 | Not narrowing Link/useNavigate with from | HIGH | docs/guide/type-safety | — | - -### ssr (3 failure modes) - -| # | Mistake | Priority | Source | Cross-skill? | -| --- | ------------------------------------------------------- | -------- | --------------------- | ------------------------- | -| 1 | Using browser APIs in loaders without environment check | HIGH | docs/guide/ssr | data-loading | -| 2 | Using hash fragments for server-rendered content | MEDIUM | docs/guide/navigation | — | -| 3 | Generating Next.js or Remix SSR patterns | CRITICAL | maintainer interview | route-setup, data-loading | - -### migrate-from-react-router (2 failure modes) - -| # | Mistake | Priority | Source | Cross-skill? | -| --- | ------------------------------------------------------ | -------- | ------------------------------------------- | ------------ | -| 1 | Leaving React Router imports alongside TanStack Router | HIGH | docs/how-to/migrate-from-react-router | — | -| 2 | Using React Router useSearchParams pattern | HIGH | docs/installation/migrate-from-react-router | — | - -## Tensions - -| Tension | Skills | Agent implication | -| ------------------------------------------------- | ------------------------------------ | --------------------------------------------------------------------------------- | -| Type safety strictness vs rapid prototyping | type-safety ↔ route-setup | Agents skip Register declaration or use type casts to silence errors | -| Client-first loaders vs SSR expectations | data-loading ↔ ssr | Agents put server-only code in client loaders or avoid browser APIs unnecessarily | -| Built-in SWR cache vs external cache coordination | data-loading ↔ external-data-loading | Agents use both caches simultaneously causing stale data or double-fetching | -| Code splitting granularity vs loader performance | code-splitting ↔ data-loading | Agents split everything including loaders, adding latency | - -## Cross-References - -| From | To | Reason | -| ------------------------- | --------------------- | ---------------------------------------------------------------------------------- | -| route-setup | type-safety | Register declaration and property order are prerequisites for type inference | -| navigation | search-params | Link search prop directly interacts with search param validation | -| data-loading | search-params | loaderDeps consumes validated search params as cache keys | -| data-loading | external-data-loading | Understanding built-in caching is prerequisite for external cache coordination | -| auth-and-guards | data-loading | beforeLoad runs before loader — auth context flows into loader via route context | -| code-splitting | data-loading | Loader splitting decisions affect data loading performance | -| ssr | data-loading | SSR changes where loaders execute — must handle both environments | -| ssr | external-data-loading | SSR dehydration/hydration requires special Query setup | -| not-found-and-errors | data-loading | notFound() in loaders interacts with error boundaries and loader data availability | -| migrate-from-react-router | route-setup | Migration requires understanding TanStack Router route setup | - -## Subsystems & Reference Candidates - -| Skill | Subsystems | Reference candidates | -| ------------- | --------------------------------------------- | -------------------------------------------------------- | -| route-setup | — | file naming conventions (>10 distinct conventions) | -| search-params | Zod adapter, Valibot adapter, ArkType adapter | search param validation patterns (>10 distinct patterns) | -| All others | — | — | - -## Recommended Skill File Structure - -- **Core skills:** route-setup, navigation, search-params, path-params, data-loading, code-splitting, not-found-and-errors, route-masking, type-safety, ssr, auth-and-guards -- **Framework skills:** None needed separately — React and Solid share the same core API surface. Framework-specific notes belong inline. -- **Lifecycle skills:** migrate-from-react-router -- **Composition skills:** external-data-loading (TanStack Query) -- **Reference files:** search-params (validation patterns), route-setup (file naming conventions) - -## Composition Opportunities - -| Library | Integration points | Composition skill needed? | -| --------------------- | --------------------------------------------------------- | ------------------------------------------ | -| @tanstack/react-query | Loader coordination, SSR dehydration/hydration, streaming | Yes — external-data-loading | -| Zod | Search param validation | No — covered as subsystem in search-params | -| Valibot | Search param validation | No — covered as subsystem in search-params | -| ArkType | Search param validation | No — covered as subsystem in search-params | diff --git a/_artifacts/skill_tree.yaml b/_artifacts/skill_tree.yaml deleted file mode 100644 index 6f7c4c8742..0000000000 --- a/_artifacts/skill_tree.yaml +++ /dev/null @@ -1,278 +0,0 @@ -# skills/_artifacts/skill_tree.yaml -library: - name: '@tanstack/router' - version: '1.166.2' - repository: 'https://github.com/TanStack/router' - description: >- - Type-safe router for React and Solid with built-in SWR caching, - JSON-first search params, and end-to-end type inference. -generated_from: - domain_map: '_artifacts/domain_map.yaml' - skill_spec: '_artifacts/skill_spec.md' -generated_at: '2026-03-07' - -skills: - # ── Router Core Skills ─────────────────────────────────────────── - - name: 'Router Core' - slug: 'router-core' - type: 'core' - domain: 'defining-routes' - path: 'skills/router-core/SKILL.md' - package: 'packages/router-core' - description: >- - Framework-agnostic core concepts for TanStack Router: route trees, - createRouter, createRoute, createRootRoute, createRootRouteWithContext, - addChildren, Register type declaration, route matching, route sorting, - file naming conventions. Entry point for all router skills. - sources: - - 'TanStack/router:docs/router/overview.md' - - 'TanStack/router:docs/router/routing/routing-concepts.md' - - 'TanStack/router:docs/router/routing/route-trees.md' - - 'TanStack/router:docs/router/routing/route-matching.md' - - 'TanStack/router:docs/router/guide/creating-a-router.md' - - 'TanStack/router:docs/router/decisions-on-dx.md' - - 'TanStack/router:packages/router-core/src' - - - name: 'Search Params' - slug: 'router-core/search-params' - type: 'sub-skill' - domain: 'managing-url-state' - path: 'skills/router-core/search-params/SKILL.md' - package: 'packages/router-core' - description: >- - validateSearch, search param validation with Zod/Valibot/ArkType adapters, - fallback(), search middlewares (retainSearchParams, stripSearchParams), - custom serialization (parseSearch, stringifySearch), search param - inheritance, loaderDeps for cache keys, reading and writing search params. - requires: - - 'router-core' - sources: - - 'TanStack/router:docs/router/guide/search-params.md' - - 'TanStack/router:docs/router/how-to/setup-basic-search-params.md' - - 'TanStack/router:docs/router/how-to/validate-search-params.md' - - 'TanStack/router:docs/router/how-to/navigate-with-search-params.md' - - 'TanStack/router:docs/router/how-to/share-search-params-across-routes.md' - - 'TanStack/router:docs/router/how-to/arrays-objects-dates-search-params.md' - - 'TanStack/router:docs/router/guide/custom-search-param-serialization.md' - subsystems: - - 'Zod adapter' - - 'Valibot adapter' - - 'ArkType adapter' - references: - - 'references/validation-patterns.md' - - - name: 'Path Params' - slug: 'router-core/path-params' - type: 'sub-skill' - domain: 'managing-url-state' - path: 'skills/router-core/path-params/SKILL.md' - package: 'packages/router-core' - description: >- - Dynamic path segments ($paramName), splat routes ($ / _splat), - optional params ({-$paramName}), prefix/suffix patterns ({$param}.ext), - useParams, params.parse/stringify, pathParamsAllowedCharacters, - i18n locale patterns. - requires: - - 'router-core' - sources: - - 'TanStack/router:docs/router/guide/path-params.md' - - 'TanStack/router:docs/router/guide/internationalization-i18n.md' - - 'TanStack/router:docs/router/routing/routing-concepts.md' - - - name: 'Navigation' - slug: 'router-core/navigation' - type: 'sub-skill' - domain: 'navigating' - path: 'skills/router-core/navigation/SKILL.md' - package: 'packages/router-core' - description: >- - Link component, useNavigate, Navigate component, router.navigate, - ToOptions/NavigateOptions/LinkOptions, from/to relative navigation, - activeOptions/activeProps, preloading (intent/viewport/render), - preloadDelay, navigation blocking (useBlocker, Block), createLink, - linkOptions helper, scroll restoration, MatchRoute. - requires: - - 'router-core' - sources: - - 'TanStack/router:docs/router/guide/navigation.md' - - 'TanStack/router:docs/router/guide/preloading.md' - - 'TanStack/router:docs/router/guide/navigation-blocking.md' - - 'TanStack/router:docs/router/guide/link-options.md' - - 'TanStack/router:docs/router/guide/custom-link.md' - - 'TanStack/router:docs/router/guide/scroll-restoration.md' - - - name: 'Data Loading' - slug: 'router-core/data-loading' - type: 'sub-skill' - domain: 'loading-data' - path: 'skills/router-core/data-loading/SKILL.md' - package: 'packages/router-core' - description: >- - Route loader option, loaderDeps for cache keys, staleTime/gcTime/ - defaultPreloadStaleTime SWR caching, pendingComponent/pendingMs/ - pendingMinMs, errorComponent/onError/onCatch, beforeLoad, router - context and createRootRouteWithContext DI pattern, router.invalidate, - Await component, deferred data loading with unawaited promises. - requires: - - 'router-core' - sources: - - 'TanStack/router:docs/router/guide/data-loading.md' - - 'TanStack/router:docs/router/guide/deferred-data-loading.md' - - 'TanStack/router:docs/router/guide/router-context.md' - - 'TanStack/router:docs/router/guide/data-mutations.md' - - - name: 'Auth and Guards' - slug: 'router-core/auth-and-guards' - type: 'sub-skill' - domain: 'protecting-routes' - path: 'skills/router-core/auth-and-guards/SKILL.md' - package: 'packages/router-core' - description: >- - Route protection with beforeLoad, redirect()/throw redirect(), - isRedirect helper, authenticated layout routes (_authenticated), - non-redirect auth (inline login), RBAC with roles and permissions, - auth provider integration (Auth0, Clerk, Supabase), router context - for auth state. - requires: - - 'router-core' - sources: - - 'TanStack/router:docs/router/guide/authenticated-routes.md' - - 'TanStack/router:docs/router/how-to/setup-authentication.md' - - 'TanStack/router:docs/router/how-to/setup-auth-providers.md' - - 'TanStack/router:docs/router/how-to/setup-rbac.md' - - - name: 'Code Splitting' - slug: 'router-core/code-splitting' - type: 'sub-skill' - domain: 'rendering-and-layout' - path: 'skills/router-core/code-splitting/SKILL.md' - package: 'packages/router-core' - description: >- - Automatic code splitting (autoCodeSplitting), .lazy.tsx convention, - createLazyFileRoute, createLazyRoute, lazyRouteComponent, getRouteApi - for typed hooks in split files, codeSplitGroupings per-route override, - splitBehavior programmatic config, critical vs non-critical properties. - requires: - - 'router-core' - sources: - - 'TanStack/router:docs/router/guide/code-splitting.md' - - 'TanStack/router:docs/router/guide/automatic-code-splitting.md' - - - name: 'Not Found and Errors' - slug: 'router-core/not-found-and-errors' - type: 'sub-skill' - domain: 'rendering-and-layout' - path: 'skills/router-core/not-found-and-errors/SKILL.md' - package: 'packages/router-core' - description: >- - notFound() function, notFoundComponent, defaultNotFoundComponent, - notFoundMode (fuzzy/root), errorComponent, onError/onCatch, - CatchBoundary, NotFoundRoute (deprecated), route masking (mask - option, createRouteMask, unmaskOnReload). - requires: - - 'router-core' - sources: - - 'TanStack/router:docs/router/guide/not-found-errors.md' - - 'TanStack/router:docs/router/guide/route-masking.md' - - - name: 'Type Safety' - slug: 'router-core/type-safety' - type: 'sub-skill' - domain: 'type-safety' - path: 'skills/router-core/type-safety/SKILL.md' - package: 'packages/router-core' - description: >- - Full type inference philosophy (never cast, never annotate inferred - values), Register module declaration, from narrowing on hooks and - Link, strict:false for shared components, getRouteApi for code-split - typed access, addChildren with object syntax for TS perf, LinkProps - and ValidateLinkOptions type utilities, as const satisfies pattern. - requires: - - 'router-core' - sources: - - 'TanStack/router:docs/router/guide/type-safety.md' - - 'TanStack/router:docs/router/guide/type-utilities.md' - - 'TanStack/router:docs/router/guide/render-optimizations.md' - - - name: 'SSR' - slug: 'router-core/ssr' - type: 'sub-skill' - domain: 'server-side-rendering' - path: 'skills/router-core/ssr/SKILL.md' - package: 'packages/router-core' - description: >- - Non-streaming and streaming SSR, RouterClient/RouterServer, - renderRouterToString/renderRouterToStream, createRequestHandler, - defaultRenderHandler/defaultStreamHandler, HeadContent/Scripts - components, head route option (meta/links/styles/scripts), - ScriptOnce, automatic loader dehydration/hydration, memory - history on server, data serialization, document head management. - requires: - - 'router-core' - - 'router-core/data-loading' - sources: - - 'TanStack/router:docs/router/guide/ssr.md' - - 'TanStack/router:docs/router/guide/document-head-management.md' - - 'TanStack/router:docs/router/how-to/setup-ssr.md' - - # ── React Router Skills ────────────────────────────────────────── - - name: 'React Router' - slug: 'react-router' - type: 'framework' - domain: 'defining-routes' - path: 'skills/react-router/SKILL.md' - package: 'packages/react-router' - description: >- - React bindings for TanStack Router: RouterProvider, useRouter, - useRouterState, useMatch, useMatches, useLocation, useSearch, - useParams, useNavigate, useLoaderData, useLoaderDeps, - useRouteContext, useBlocker, useCanGoBack, Link, Navigate, - Outlet, CatchBoundary, ErrorComponent. React-specific patterns - for hooks, providers, SSR hydration, and createLink with - forwardRef. - requires: - - 'router-core' - sources: - - 'TanStack/router:packages/react-router/src' - - 'TanStack/router:docs/router/guide/creating-a-router.md' - - 'TanStack/router:docs/router/installation/manual.md' - - # ── Composition Skills ─────────────────────────────────────────── - - name: 'External Data Loading (TanStack Query)' - slug: 'compositions/router-query' - type: 'composition' - domain: 'loading-data' - path: 'skills/compositions/router-query/SKILL.md' - package: 'packages/react-router' - description: >- - Integrating TanStack Router with TanStack Query: queryClient - 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. - requires: - - 'router-core' - - 'router-core/data-loading' - - 'react-router' - sources: - - 'TanStack/router:docs/router/guide/external-data-loading.md' - - 'TanStack/router:docs/router/integrations/query.md' - - # ── Lifecycle Skills ───────────────────────────────────────────── - - name: 'Migrate from React Router' - slug: 'lifecycle/migrate-from-react-router' - type: 'lifecycle' - domain: 'defining-routes' - path: 'skills/lifecycle/migrate-from-react-router/SKILL.md' - package: 'packages/react-router' - description: >- - Step-by-step migration from React Router v7 to TanStack Router: - route definition conversion, Link/useNavigate API differences, - useSearchParams to validateSearch + useSearch, useParams with from, - Outlet replacement, loader conversion, code splitting differences. - requires: - - 'router-core' - - 'react-router' - sources: - - 'TanStack/router:docs/router/how-to/migrate-from-react-router.md' - - 'TanStack/router:docs/router/installation/migrate-from-react-router.md' diff --git a/_artifacts/start_domain_map.yaml b/_artifacts/start_domain_map.yaml deleted file mode 100644 index a557901075..0000000000 --- a/_artifacts/start_domain_map.yaml +++ /dev/null @@ -1,482 +0,0 @@ -# domain_map.yaml -# Generated by skill-domain-discovery -# Library: TanStack Start -# Version: 1.166.2 -# Date: 2026-03-07 -# Status: reviewed - -library: - name: '@tanstack/react-start' - version: '1.166.2' - repository: 'https://github.com/TanStack/router' - description: >- - Full-stack React framework built on TanStack Router and Vite. Adds - SSR, streaming, server functions (type-safe RPCs), middleware, - server routes, and universal deployment. Isomorphic by default — - all code runs in both environments unless explicitly constrained. - primary_framework: 'React' - -domains: - - name: 'Project Setup' - slug: 'project-setup' - description: >- - Scaffolding a Start project, configuring Vite plugin, router - setup with getRouter(), root route with document shell, client - and server entry points. - - - name: 'Server Functions' - slug: 'server-functions' - description: >- - Creating type-safe RPCs with createServerFn, input validation, - calling from loaders/components/other server functions, error - handling, streaming responses. - - - name: 'Middleware and Context' - slug: 'middleware-and-context' - description: >- - Request middleware, server function middleware, context passing - with sendContext, global middleware via createStart, middleware - factories, fetch override precedence. - - - name: 'Execution Model' - slug: 'execution-model' - description: >- - Isomorphic code execution, environment functions - (createServerFn, createServerOnlyFn, createClientOnlyFn, - createIsomorphicFn), import protection, dead code elimination, - environment variable safety. - - - name: 'Server Routes' - slug: 'server-routes' - description: >- - Server-side API endpoints defined in routes, HTTP method - handlers, handler middleware, request/response patterns. - - - name: 'Deployment and Rendering' - slug: 'deployment-and-rendering' - description: >- - Hosting providers (Cloudflare, Netlify, Vercel, Node/Docker), - selective SSR, SPA mode, static prerendering, ISR with - Cache-Control headers, SEO and head management. - -skills: - # ── Project Setup ──────────────────────────────────────────────── - - name: 'Start Setup' - slug: 'start-setup' - domain: 'project-setup' - description: >- - Scaffold a TanStack Start project, configure Vite plugin with - tanstackStart(), set up router with getRouter(), create root - route with document shell (HeadContent, Scripts, Outlet), - configure client and server entry points. - type: core - packages: - - '@tanstack/react-start' - - '@tanstack/start-plugin-core' - covers: - - tanstackStart Vite plugin - - getRouter() factory pattern - - Root route document shell - - HeadContent / Scripts / Outlet - - Client entry point (optional) - - Server entry point (optional) - - routeTree.gen.ts - - tsconfig configuration - tasks: - - 'Scaffold a new TanStack Start project' - - 'Configure the Vite plugin' - - 'Set up the router factory' - - 'Customize client/server entry points' - failure_modes: - - mistake: 'React plugin before Start plugin in Vite config' - mechanism: >- - Start's Vite plugin must come before React's plugin. - Wrong order causes route generation and server function - compilation to fail. - wrong_pattern: | - plugins: [react(), tanstackStart()] - correct_pattern: | - plugins: [tanstackStart(), react()] - source: 'docs/start/framework/react/build-from-scratch.md' - priority: CRITICAL - status: active - - - mistake: 'Enabling verbatimModuleSyntax in tsconfig' - mechanism: >- - verbatimModuleSyntax causes server bundles to leak into - client bundles. Must be disabled. - source: 'docs/start/framework/react/build-from-scratch.md' - priority: HIGH - status: active - - - mistake: 'Missing Scripts component in root route' - mechanism: >- - The Scripts component must be rendered in the body of - the root route for proper hydration and functionality. - Without it, client-side JavaScript does not load. - source: 'docs/start/framework/react/guide/routing.md' - priority: HIGH - status: active - - # ── Server Functions ───────────────────────────────────────────── - - name: 'Server Functions' - slug: 'server-functions' - domain: 'server-functions' - description: >- - Create type-safe RPCs with createServerFn, validate inputs - with Zod or plain functions, call from loaders/components/ - event handlers, handle errors/redirects/notFound, stream - responses with ReadableStream or async generators. - type: core - packages: - - '@tanstack/react-start' - - '@tanstack/start-client-core' - - '@tanstack/start-server-core' - covers: - - createServerFn (GET/POST) - - validator (Zod or function) - - useServerFn hook - - Server context utilities (getRequest, getRequestHeader, setResponseHeader, setResponseStatus) - - Error handling (throw errors, redirect, notFound) - - Streaming (ReadableStream, async generators) - - File organization (.functions.ts, .server.ts) - - FormData handling - tasks: - - 'Create a server function for data fetching' - - 'Validate server function inputs' - - 'Call server functions from components' - - 'Stream data from server functions' - - 'Handle errors in server functions' - failure_modes: - - mistake: 'Putting server-only code in loaders instead of server functions' - mechanism: >- - Loaders are ISOMORPHIC — they run on both client and server. - Database queries, file system access, and secret API keys - in loaders will either fail on the client or leak to the - client bundle. Use createServerFn for server-only logic. - wrong_pattern: | - export const Route = createFileRoute('/posts')({ - loader: async () => { - const posts = await db.query('SELECT * FROM posts') - return { posts } - }, - }) - correct_pattern: | - const getPosts = createServerFn({ method: 'GET' }) - .handler(async () => { - const posts = await db.query('SELECT * FROM posts') - return { posts } - }) - - export const Route = createFileRoute('/posts')({ - loader: () => getPosts(), - }) - source: 'maintainer interview' - priority: CRITICAL - status: active - skills: ['server-functions', 'execution-model'] - - - mistake: 'Using dynamic imports for server functions' - mechanism: >- - Dynamic imports of server functions can cause bundler - issues. Static imports are safe — the build process - replaces server implementations with RPC stubs. - wrong_pattern: | - const { getUser } = await import('~/utils/users.functions') - correct_pattern: | - import { getUser } from '~/utils/users.functions' - source: 'docs/start/framework/react/guide/server-functions.md' - priority: HIGH - status: active - - - mistake: 'Generating Next.js or Remix server patterns' - mechanism: >- - Agents generate getServerSideProps, "use server" directives, - or Remix-style loader exports. TanStack Start uses - createServerFn for server-only code. - wrong_pattern: | - 'use server' - export async function getUser() { ... } - correct_pattern: | - const getUser = createServerFn({ method: 'GET' }) - .handler(async () => { ... }) - source: 'maintainer interview' - priority: CRITICAL - status: active - - # ── Middleware and Context ─────────────────────────────────────── - - name: 'Middleware' - slug: 'middleware' - domain: 'middleware-and-context' - description: >- - Request middleware and server function middleware with - createMiddleware, context passing via next(), sendContext - for client-server transfer, global middleware via createStart - in src/start.ts, middleware factories, fetch override - precedence, header merging. - type: core - packages: - - '@tanstack/react-start' - - '@tanstack/start-client-core' - - '@tanstack/start-server-core' - covers: - - createMiddleware - - Request middleware (.server only) - - Server function middleware (.client + .server) - - Context passing via next({ context }) - - sendContext for client-server transfer - - Global middleware (createStart in src/start.ts) - - Middleware factories - - Fetch override precedence - - Header merging - - Method order enforcement (middleware → validator → client → server) - tasks: - - 'Add authentication middleware' - - 'Pass context through middleware chain' - - 'Configure global request middleware' - - 'Create reusable middleware factories' - failure_modes: - - mistake: 'Trusting client context without server validation' - mechanism: >- - Client context via sendContext is NOT validated by default. - Dynamic user-generated data must be validated in server-side - middleware before use. - source: 'docs/start/framework/react/guide/middleware.md' - priority: HIGH - status: active - - - mistake: 'Wrong middleware method order' - mechanism: >- - TypeScript enforces method order: middleware → validator - → client → server. Wrong order causes type errors and - runtime failures. - source: 'docs/start/framework/react/guide/middleware.md' - priority: MEDIUM - status: active - - - mistake: 'Confusing request vs server function middleware' - mechanism: >- - Request middleware runs on ALL server requests (SSR, server - routes, server functions). Server function middleware runs - only for server functions and has .client() method. Using - the wrong type causes unexpected scope. - source: 'docs/start/framework/react/guide/middleware.md' - priority: MEDIUM - status: active - - # ── Execution Model ────────────────────────────────────────────── - - name: 'Execution Model' - slug: 'execution-model' - domain: 'execution-model' - description: >- - Isomorphic code execution model, environment boundary functions - (createServerFn, createServerOnlyFn, createClientOnlyFn, - createIsomorphicFn), import protection, dead code elimination, - environment variable safety (VITE_ prefix), useHydrated hook. - type: core - packages: - - '@tanstack/react-start' - - '@tanstack/start-client-core' - - '@tanstack/start-server-core' - covers: - - Isomorphic-by-default principle - - createServerFn (RPC boundary) - - createServerOnlyFn (throws on client) - - createClientOnlyFn (throws on server) - - createIsomorphicFn (different impl per env) - - ClientOnly component - - useHydrated hook - - Import protection (experimental) - - Environment variables (VITE_ prefix, process.env) - - Dead code elimination / tree shaking - tasks: - - 'Protect server-only code from client bundles' - - 'Use environment-specific implementations' - - 'Handle environment variables safely' - - 'Debug import protection violations' - failure_modes: - - mistake: 'Assuming loaders are server-only' - mechanism: >- - ALL code in TanStack Start is isomorphic by default. - Loaders run on BOTH server and client. Server-only - operations must use createServerFn, createServerOnlyFn, - or server routes. - wrong_pattern: | - export const Route = createFileRoute('/dashboard')({ - loader: async () => { - const secret = process.env.API_SECRET - return fetch(`https://api.example.com/data`, { - headers: { Authorization: secret } - }) - }, - }) - correct_pattern: | - const getData = createServerFn({ method: 'GET' }) - .handler(async () => { - const secret = process.env.API_SECRET - return fetch(`https://api.example.com/data`, { - headers: { Authorization: secret } - }) - }) - - export const Route = createFileRoute('/dashboard')({ - loader: () => getData(), - }) - source: 'docs/start/framework/react/guide/execution-model.md' - priority: CRITICAL - status: active - skills: ['execution-model', 'server-functions'] - - - mistake: 'Exposing secrets via module-level process.env' - mechanism: >- - Module-level process.env access runs in both environments. - The variable value leaks into the client bundle. Access - secrets only inside createServerFn or createServerOnlyFn. - wrong_pattern: | - const apiKey = process.env.SECRET_KEY - export function fetchData() { ... } - correct_pattern: | - const fetchData = createServerFn({ method: 'GET' }) - .handler(async () => { - const apiKey = process.env.SECRET_KEY - return fetch(url, { headers: { Authorization: apiKey } }) - }) - source: 'docs/start/framework/react/guide/execution-model.md' - priority: CRITICAL - status: active - - - mistake: 'Using VITE_ prefix for server secrets' - mechanism: >- - VITE_ prefixed variables are exposed to the client bundle. - Server secrets must NOT have the VITE_ prefix. Access - them via process.env inside server functions only. - source: 'docs/start/framework/react/guide/environment-variables.md' - priority: CRITICAL - status: active - - # ── Server Routes ──────────────────────────────────────────────── - - name: 'Server Routes' - slug: 'server-routes' - domain: 'server-routes' - description: >- - Define server-side API endpoints alongside app routes using - the server property with HTTP method handlers, per-handler - middleware via createHandlers, request/response patterns. - type: core - packages: - - '@tanstack/react-start' - - '@tanstack/start-server-core' - covers: - - server property on createFileRoute - - handlers object (GET, POST, PUT, DELETE) - - createHandlers for per-handler middleware - - Handler context (request, params, context) - - Request body parsing (json, text, formData) - - Response helpers (Response.json) - - File naming for API routes - tasks: - - 'Create a REST API endpoint' - - 'Add middleware to server route handlers' - - 'Handle different HTTP methods' - failure_modes: - - mistake: 'Duplicate path resolution for server routes' - mechanism: >- - Each route can only have a single handler file. Having - both users.ts and users/index.ts causes errors. - source: 'docs/start/framework/react/guide/server-routes.md' - priority: MEDIUM - status: active - - # ── Deployment and Rendering ───────────────────────────────────── - - name: 'Deployment' - slug: 'deployment' - domain: 'deployment-and-rendering' - description: >- - Deploy TanStack Start to Cloudflare Workers, Netlify, Vercel, - Node.js/Docker, Bun, Railway. Configure selective SSR, SPA - mode, static prerendering, ISR with Cache-Control headers. - type: core - packages: - - '@tanstack/react-start' - - '@tanstack/start-plugin-core' - covers: - - Cloudflare Workers deployment - - Netlify deployment - - Vercel / Railway deployment - - Node.js / Docker deployment - - Bun deployment - - Selective SSR (ssr option per route) - - SPA mode configuration - - Static prerendering (prerender option) - - ISR with Cache-Control headers - - SEO (head property, structured data) - tasks: - - 'Deploy to Cloudflare Workers' - - 'Deploy to Netlify' - - 'Configure selective SSR per route' - - 'Enable SPA mode' - - 'Set up static prerendering' - - 'Configure ISR with cache headers' - failure_modes: - - mistake: 'Bun deployment with React 18' - mechanism: >- - Bun-specific deployment only works with React 19. - For React 18, use Node.js deployment guidelines. - source: 'docs/start/framework/react/guide/hosting.md' - priority: MEDIUM - status: active - - - mistake: 'Missing nodejs_compat flag for Cloudflare Workers' - mechanism: >- - Cloudflare Workers requires compatibility_flags: - ["nodejs_compat"] in wrangler config. Without it, - Node.js APIs used by Start fail at runtime. - source: 'docs/start/framework/react/guide/hosting.md' - priority: HIGH - status: active - - - mistake: 'Child route loosening parent SSR config' - mechanism: >- - SSR config inherits from parent and can only become MORE - restrictive (true → data-only → false). A child cannot - set ssr: true if parent has ssr: false. - source: 'docs/start/framework/react/guide/selective-ssr.md' - priority: MEDIUM - status: active - -tensions: - - name: 'Isomorphic defaults vs server-only expectations' - skills: ['execution-model', 'server-functions'] - description: >- - All code runs everywhere by default. Agents trained on - Next.js/Remix assume loaders and route code are server-only. - implication: >- - Agents put secrets, DB queries, and file system access in - loaders instead of server functions, causing client-side - failures or security leaks. - - - name: 'Simplicity of isomorphic code vs security boundaries' - skills: ['execution-model', 'middleware'] - description: >- - The isomorphic model makes code easy to write but requires - explicit boundaries for security. Agents don't realize they - need to actively constrain execution environment. - implication: >- - Agents expose secrets via module-level process.env or - forget to validate sendContext data in middleware. - -cross_references: - - from: 'server-functions' - to: 'execution-model' - reason: 'Server functions ARE the isomorphic boundary — understanding the execution model is prerequisite' - - from: 'server-functions' - to: 'middleware' - reason: 'Server function middleware chains compose with server functions' - - from: 'middleware' - to: 'server-routes' - reason: 'Server routes use the same middleware system' - - from: 'deployment' - to: 'execution-model' - reason: 'Deployment target affects which environment code runs in' - -gaps: [] diff --git a/_artifacts/start_skill_tree.yaml b/_artifacts/start_skill_tree.yaml deleted file mode 100644 index 4d221068fd..0000000000 --- a/_artifacts/start_skill_tree.yaml +++ /dev/null @@ -1,158 +0,0 @@ -# skills/_artifacts/start_skill_tree.yaml -library: - name: '@tanstack/react-start' - version: '1.166.2' - repository: 'https://github.com/TanStack/router' - description: >- - Full-stack React framework built on TanStack Router and Vite. - Adds SSR, streaming, server functions (type-safe RPCs), middleware, - server routes, and universal deployment. Isomorphic by default — - all code runs in both environments unless explicitly constrained. -generated_from: - domain_map: '_artifacts/start_domain_map.yaml' -generated_at: '2026-03-07' - -skills: - # ── Start Core Skills ─────────────────────────────────────────── - - name: 'Start Core' - slug: 'start-core' - type: 'core' - domain: 'project-setup' - path: 'skills/start-core/SKILL.md' - package: 'packages/start-client-core' - description: >- - Core overview for TanStack Start: tanstackStart() Vite plugin, - getRouter() factory, root route document shell (HeadContent, - Scripts, Outlet), client/server entry points, routeTree.gen.ts, - tsconfig configuration. Entry point for all Start skills. - sources: - - 'TanStack/router:docs/start/framework/react/build-from-scratch.md' - - 'TanStack/router:docs/start/framework/react/quick-start.md' - - 'TanStack/router:docs/start/framework/react/guide/routing.md' - - - name: 'Server Functions' - slug: 'start-core/server-functions' - type: 'sub-skill' - domain: 'server-functions' - path: 'skills/start-core/server-functions/SKILL.md' - package: 'packages/start-client-core' - description: >- - createServerFn (GET/POST), validator (Zod or function), - useServerFn hook, server context utilities (getRequest, - getRequestHeader, setResponseHeader, setResponseStatus), error - handling (throw errors, redirect, notFound), streaming - (ReadableStream, async generators), FormData handling, file - organization (.functions.ts, .server.ts). - requires: - - 'start-core' - sources: - - 'TanStack/router:docs/start/framework/react/guide/server-functions.md' - - - name: 'Middleware' - slug: 'start-core/middleware' - type: 'sub-skill' - domain: 'middleware-and-context' - path: 'skills/start-core/middleware/SKILL.md' - package: 'packages/start-client-core' - description: >- - createMiddleware, request middleware (.server only), server - function middleware (.client + .server), context passing via - next({ context }), sendContext for client-server transfer, - global middleware via createStart in src/start.ts, middleware - factories, method order enforcement. - requires: - - 'start-core' - - 'start-core/server-functions' - sources: - - 'TanStack/router:docs/start/framework/react/guide/middleware.md' - - - name: 'Execution Model' - slug: 'start-core/execution-model' - type: 'sub-skill' - domain: 'execution-model' - path: 'skills/start-core/execution-model/SKILL.md' - package: 'packages/start-client-core' - description: >- - Isomorphic-by-default principle, environment boundary functions - (createServerFn, createServerOnlyFn, createClientOnlyFn, - createIsomorphicFn), ClientOnly component, useHydrated hook, - import protection, dead code elimination, environment variable - safety (VITE_ prefix, process.env). - requires: - - 'start-core' - sources: - - 'TanStack/router:docs/start/framework/react/guide/execution-model.md' - - 'TanStack/router:docs/start/framework/react/guide/environment-variables.md' - - - name: 'Server Routes' - slug: 'start-core/server-routes' - type: 'sub-skill' - domain: 'server-routes' - path: 'skills/start-core/server-routes/SKILL.md' - package: 'packages/start-client-core' - description: >- - Server-side API endpoints using the server property on - createFileRoute, HTTP method handlers (GET, POST, PUT, DELETE), - createHandlers for per-handler middleware, handler context - (request, params, context), request body parsing, response - helpers, file naming for API routes. - requires: - - 'start-core' - sources: - - 'TanStack/router:docs/start/framework/react/guide/server-routes.md' - - - name: 'Deployment' - slug: 'start-core/deployment' - type: 'sub-skill' - domain: 'deployment-and-rendering' - path: 'skills/start-core/deployment/SKILL.md' - package: 'packages/start-client-core' - description: >- - Deploy to Cloudflare Workers, Netlify, Vercel, Node.js/Docker, - Bun, Railway. Selective SSR (ssr option per route), SPA mode, - static prerendering, ISR with Cache-Control headers, SEO and - head management. - requires: - - 'start-core' - sources: - - 'TanStack/router:docs/start/framework/react/guide/hosting.md' - - 'TanStack/router:docs/start/framework/react/guide/selective-ssr.md' - - 'TanStack/router:docs/start/framework/react/guide/static-prerendering.md' - - 'TanStack/router:docs/start/framework/react/guide/full-stack-seo.md' - - # ── React Start Skills ────────────────────────────────────────── - - name: 'React Start' - slug: 'react-start' - type: 'framework' - domain: 'project-setup' - path: 'skills/react-start/SKILL.md' - package: 'packages/react-start' - description: >- - React bindings for TanStack Start: createStart, StartClient, - StartServer, React-specific imports, re-exports from - @tanstack/react-router, full project setup with React. - requires: - - 'start-core' - sources: - - 'TanStack/router:packages/react-start/src' - - 'TanStack/router:docs/start/framework/react/build-from-scratch.md' - - # ── Lifecycle Skills ──────────────────────────────────────────── - - name: 'Migrate from Next.js' - slug: 'lifecycle/migrate-from-nextjs' - type: 'lifecycle' - domain: 'project-setup' - path: 'skills/lifecycle/migrate-from-nextjs/SKILL.md' - package: 'packages/react-start' - description: >- - Step-by-step migration from Next.js App Router to TanStack - Start: route definition conversion, API mapping, server - function conversion from Server Actions, middleware conversion, - data fetching pattern changes. - requires: - - 'start-core' - - 'react-start' - sources: - - 'TanStack/router:docs/start/framework/react/guide/server-functions.md' - - 'TanStack/router:docs/start/framework/react/guide/middleware.md' - - 'TanStack/router:docs/start/framework/react/guide/execution-model.md' diff --git a/benchmarks/AGENTS.md b/benchmarks/AGENTS.md deleted file mode 100644 index 9d56a2411a..0000000000 --- a/benchmarks/AGENTS.md +++ /dev/null @@ -1,15 +0,0 @@ -# Benchmarks - -Read the relevant README before running benchmarks. Compare baseline and candidate with the same workload and production builds; add a focused case when existing scenarios miss the changed mechanism. Keep workloads and benchmark names stable for historical comparisons. - -| Changed behavior | Guide | Nx project | -| ------------------------------------------ | ---------------------------------- | -------------------------------------------------------- | -| Standalone Router navigation/rendering CPU | [client-nav](client-nav/README.md) | `@benchmarks/client-nav` | -| Start request/SSR CPU | [ssr](ssr/README.md) | `@benchmarks/ssr` | -| Client/server retention and allocations | [memory](memory/README.md) | `@benchmarks/memory-client`, `@benchmarks/memory-server` | - -Use `test:perf:` through Nx. Plain memory runs only smoke-test; memory metrics require CodSpeed. Client navigation benchmarks do not cover Start hydration or client server-function calls. - -Run `vitest bench` directly only with `--mode benchmark`, as the Nx targets do. Vitest 5 otherwise uses Vite's `test` mode, where vite-plugin-solid injects a jest-dom setup file that benchmark packages cannot resolve. - -For bundle-size work, follow the full optimization skill required by the root guide. Full API fixtures are maintained manually: when public hooks/components change, update matching `bundle-size/scenarios/*-full/src/routes/__root.tsx` fixtures. Save baseline results separately because each run overwrites `bundle-size/results/current.json`; report final gzip deltas and explain remaining growth. diff --git a/benchmarks/README.md b/benchmarks/README.md deleted file mode 100644 index 94d2f31802..0000000000 --- a/benchmarks/README.md +++ /dev/null @@ -1,88 +0,0 @@ -# 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 deleted file mode 100644 index bd05a98cee..0000000000 --- a/benchmarks/bundle-size/.gitignore +++ /dev/null @@ -1,11 +0,0 @@ -node_modules -dist -dist-debug -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 deleted file mode 100644 index 2185d6b43f..0000000000 --- a/benchmarks/bundle-size/README.md +++ /dev/null @@ -1,172 +0,0 @@ -# Bundle Size Benchmarks - -This workspace contains deterministic bundle-size fixtures for: - -- `@tanstack/react-router` -- `@tanstack/solid-router` -- `@tanstack/vue-router` -- `@tanstack/react-start` -- `@tanstack/solid-start` - -Each package has `minimal` and `full` scenarios: - -- `minimal`: Small route app with `__root` + index route that renders `hello world` -- `full`: Same route shape plus a broad root-level harness that imports/uses the full hooks/components surface -- Start `full` scenarios also exercise `createServerFn`, `createMiddleware`, and `useServerFn` -- Start `deferred-hydration` scenarios match the minimal route shape and wrap the index route content in `Hydrate` - -## Design Notes - -- Scenarios use file-based routing as the default app style. -- Router scenarios use `@tanstack/router-plugin/vite` with `autoCodeSplitting: true`. -- Start Vite scenarios use `@tanstack/-start/plugin/vite` with router code-splitting enabled. -- React Start also includes Rsbuild scenarios using `@tanstack/react-start/plugin/rsbuild`. -- Full-surface coverage is manually maintained (no strict export-coverage gate). -- Primary metrics measure all emitted client JS chunks and are reported as raw/gzip/brotli bytes. -- Initial-load JS graph metrics are also recorded as `initialRawBytes`, `initialGzipBytes`, and `initialBrotliBytes` for context. -- Gzip for all emitted client JS is the primary tracking signal for PR deltas and historical charting. - -## Local Run - -```bash -pnpm benchmark:bundle-size:run -``` - -Run one or more scenarios during local optimization: - -```bash -pnpm benchmark:bundle-size:run --scenario react-router.minimal -pnpm benchmark:bundle-size:run --scenario react-router.minimal,react-router.full -``` - -The runner calls `measure.mjs`, which builds the selected package projects through Nx. Full runs build the package projects for all scenarios. -`pnpm benchmark:bundle-size` uses the Nx build cache for the full benchmark, then generates `current.json` with the current commit, branch, dirty status, and report timestamp. CI uses this command as well. - -Nx caches the bundles, `measurements.json`, and `benchmark-action.json`. Git metadata does not affect the build cache. The report preserves the original `measuredAt` and build duration when measurements come from cache; `generatedAt` records when the report was generated. Running `pnpm nx run @benchmarks/bundle-size:measure` directly produces only the cacheable outputs; run `node scripts/benchmarks/bundle-size/report.mjs` afterward to refresh `current.json`. - -If the required packages are already built and unchanged, skip that step: - -```bash -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 -pnpm benchmark:bundle-size:query --id react-router.minimal -pnpm benchmark:bundle-size:diff --baseline /tmp/base-current.json --id react-router.minimal -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 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, 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`. - -## Manual Update Policy - -When router/start public hooks/components evolve, update the corresponding `*-full/src/routes/__root.tsx` harness to keep full scenarios representative. - -## Backfill Readiness - -The measurement script supports optional interfaces for historical backfilling: - -- `--sha` -- `--measured-at` -- `--append-history` -- `--scenario` -- `--analysis` -- `--sourcemap` -- `--skip-package-builds` - -These are intended for one-off scripts that replay historical commits and append results to the same history dataset shape used for chart generation. -If `--append-history` points at a `data.js` file, output is written as `window.BENCHMARK_DATA = ...` for direct GitHub Pages compatibility. diff --git a/benchmarks/bundle-size/package.json b/benchmarks/bundle-size/package.json deleted file mode 100644 index ca34cd6cd7..0000000000 --- a/benchmarks/bundle-size/package.json +++ /dev/null @@ -1,84 +0,0 @@ -{ - "name": "@benchmarks/bundle-size", - "private": true, - "type": "module", - "scripts": { - "measure": "node ../../scripts/benchmarks/bundle-size/measure.mjs --skip-package-builds --measurements-only", - "test:unit": "node --test ../../scripts/benchmarks/bundle-size/pr-report.test.mjs ../../scripts/benchmarks/bundle-size/run.test.mjs ../../scripts/benchmarks/bundle-size/report.test.mjs ../../scripts/benchmarks/bundle-size/build.test.mjs ../../scripts/benchmarks/bundle-size/compress.test.mjs ../../scripts/benchmarks/bundle-size/timings.test.mjs" - }, - "nx": { - "targets": { - "measure": { - "cache": true, - "inputs": [ - "buildProduction", - "^buildProduction", - "dependentTaskOutputs", - "{workspaceRoot}/scripts/benchmarks/bundle-size/measure.mjs", - "{workspaceRoot}/scripts/benchmarks/bundle-size/compress.mjs", - "{workspaceRoot}/scripts/benchmarks/bundle-size/timings.mjs", - "{workspaceRoot}/scripts/benchmarks/bundle-size/report.mjs", - { - "runtime": "node --version" - } - ], - "outputs": [ - "{projectRoot}/dist", - "{projectRoot}/results/measurements.json", - "{projectRoot}/results/benchmark-action.json" - ], - "dependsOn": [ - { - "projects": [ - "@tanstack/react-router", - "@tanstack/react-router-ssr-query", - "@tanstack/react-start", - "@tanstack/router-plugin", - "@tanstack/solid-router", - "@tanstack/solid-start", - "@tanstack/vue-router", - "@tanstack/vue-start" - ], - "target": "build" - } - ] - }, - "test:unit": { - "dependsOn": [], - "inputs": [ - "default", - "^production", - "{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.3.1", - "@rsbuild/plugin-react": "^2.0.0", - "@tanstack/router-plugin": "workspace:^", - "@types/react": "^19.0.8", - "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@vitejs/plugin-vue": "^6.0.5", - "@vitejs/plugin-vue-jsx": "^5.1.5", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "vite-plugin-solid": "^2.11.11" - } -} diff --git a/benchmarks/bundle-size/results/.gitkeep b/benchmarks/bundle-size/results/.gitkeep deleted file mode 100644 index 8b13789179..0000000000 --- a/benchmarks/bundle-size/results/.gitkeep +++ /dev/null @@ -1 +0,0 @@ - diff --git a/benchmarks/bundle-size/scenarios/react-router-full/index.html b/benchmarks/bundle-size/scenarios/react-router-full/index.html deleted file mode 100644 index 1117e75467..0000000000 --- a/benchmarks/bundle-size/scenarios/react-router-full/index.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - react-router-full - - -
- - - diff --git a/benchmarks/bundle-size/scenarios/react-router-full/src/main.tsx b/benchmarks/bundle-size/scenarios/react-router-full/src/main.tsx deleted file mode 100644 index ce55e38d84..0000000000 --- a/benchmarks/bundle-size/scenarios/react-router-full/src/main.tsx +++ /dev/null @@ -1,22 +0,0 @@ -import ReactDOM from 'react-dom/client' -import { RouterProvider, createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -const router = createRouter({ - routeTree, - scrollRestoration: true, -}) - -declare module '@tanstack/react-router' { - interface Register { - router: typeof router - } -} - -const rootElement = document.getElementById('app') -if (!rootElement) { - throw new Error('Root element `#app` not found') -} -if (!rootElement.innerHTML) { - ReactDOM.createRoot(rootElement).render() -} diff --git a/benchmarks/bundle-size/scenarios/react-router-full/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/react-router-full/src/routes/__root.tsx deleted file mode 100644 index d8948fdb7e..0000000000 --- a/benchmarks/bundle-size/scenarios/react-router-full/src/routes/__root.tsx +++ /dev/null @@ -1,185 +0,0 @@ -import { - Asset, - Await, - Block, - CatchBoundary, - CatchNotFound, - ClientOnly, - DefaultGlobalNotFound, - ErrorComponent, - HeadContent, - Link, - Match, - MatchRoute, - Matches, - Navigate, - Outlet, - RouterContextProvider, - ScriptOnce, - Scripts, - ScrollRestoration, - createLink, - createRootRoute, - linkOptions, - useAwaited, - useBlocker, - useCanGoBack, - useElementScrollRestoration, - useHydrated, - useLinkProps, - useLoaderData, - useLoaderDeps, - useLocation, - useMatch, - useMatchRoute, - useMatches, - useNavigate, - useParams, - useParentMatches, - useChildMatches, - useRouteContext, - useRouter, - useRouterState, - useSearch, - useTags, -} from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - const router = useRouter() - const hydrated = useHydrated() - 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, - useHydrated, - 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, - ] - - ;(globalThis as any).__TANSTACK_BUNDLE_SIZE_KEEP__ = { - hooksAndComponents, - } - - void awaited - void linkFactoryResult - void matches - void parentMatches - void childMatches - void match - void loaderDeps - void loaderData - void params - void search - void routeContext - void routerState - void location - void canGoBack - void navigate - void scrollEntry - void tags - void routeMatchResult - - return ( - <> - - {'window.__tsr_bundle_size = true'} - - home - - - - {() => } - }> - - - - {() => } - - false} disabled withResolver={false}> - {() => } - - }> - - - - - - - - -
-
hello world
-
- - ) -} diff --git a/benchmarks/bundle-size/scenarios/react-router-full/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/react-router-full/src/routes/index.tsx deleted file mode 100644 index aeea465e04..0000000000 --- a/benchmarks/bundle-size/scenarios/react-router-full/src/routes/index.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import { - createFileRoute, - retainSearchParams, - stripSearchParams, -} from '@tanstack/react-router' - -const defaultSearch = { page: 1 } - -export const Route = createFileRoute('/')({ - search: { - middlewares: [ - retainSearchParams>(['persist']), - stripSearchParams(defaultSearch), - ], - }, - component: IndexComponent, -}) - -function IndexComponent() { - return
hello world
-} diff --git a/benchmarks/bundle-size/scenarios/react-router-full/vite.config.ts b/benchmarks/bundle-size/scenarios/react-router-full/vite.config.ts deleted file mode 100644 index 45838fe281..0000000000 --- a/benchmarks/bundle-size/scenarios/react-router-full/vite.config.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { defineConfig } from 'vite' -import react from '@vitejs/plugin-react' -import { tanstackRouter } from '@tanstack/router-plugin/vite' - -export default defineConfig({ - plugins: [ - tanstackRouter({ - target: 'react', - autoCodeSplitting: true, - }), - react(), - ], -}) diff --git a/benchmarks/bundle-size/scenarios/react-router-minimal/index.html b/benchmarks/bundle-size/scenarios/react-router-minimal/index.html deleted file mode 100644 index 5de4e4e509..0000000000 --- a/benchmarks/bundle-size/scenarios/react-router-minimal/index.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - react-router-minimal - - -
- - - diff --git a/benchmarks/bundle-size/scenarios/react-router-minimal/src/main.tsx b/benchmarks/bundle-size/scenarios/react-router-minimal/src/main.tsx deleted file mode 100644 index 667de2cdc7..0000000000 --- a/benchmarks/bundle-size/scenarios/react-router-minimal/src/main.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import ReactDOM from 'react-dom/client' -import { RouterProvider, createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -const router = createRouter({ routeTree }) - -declare module '@tanstack/react-router' { - interface Register { - router: typeof router - } -} - -const rootElement = document.getElementById('app') -if (!rootElement) { - throw new Error('Root element `#app` not found') -} -if (!rootElement.innerHTML) { - ReactDOM.createRoot(rootElement).render() -} diff --git a/benchmarks/bundle-size/scenarios/react-router-minimal/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/react-router-minimal/src/routes/__root.tsx deleted file mode 100644 index 889395056b..0000000000 --- a/benchmarks/bundle-size/scenarios/react-router-minimal/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createRootRoute } from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return -} diff --git a/benchmarks/bundle-size/scenarios/react-router-minimal/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/react-router-minimal/src/routes/index.tsx deleted file mode 100644 index 76fb363538..0000000000 --- a/benchmarks/bundle-size/scenarios/react-router-minimal/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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-router-minimal/vite.config.ts b/benchmarks/bundle-size/scenarios/react-router-minimal/vite.config.ts deleted file mode 100644 index 45838fe281..0000000000 --- a/benchmarks/bundle-size/scenarios/react-router-minimal/vite.config.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { defineConfig } from 'vite' -import react from '@vitejs/plugin-react' -import { tanstackRouter } from '@tanstack/router-plugin/vite' - -export default defineConfig({ - plugins: [ - tanstackRouter({ - target: 'react', - autoCodeSplitting: true, - }), - react(), - ], -}) diff --git a/benchmarks/bundle-size/scenarios/react-start-deferred-hydration/src/router.tsx b/benchmarks/bundle-size/scenarios/react-start-deferred-hydration/src/router.tsx deleted file mode 100644 index 9d87d8748b..0000000000 --- a/benchmarks/bundle-size/scenarios/react-start-deferred-hydration/src/router.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - scrollRestoration: true, - }) -} diff --git a/benchmarks/bundle-size/scenarios/react-start-deferred-hydration/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/react-start-deferred-hydration/src/routes/__root.tsx deleted file mode 100644 index ff1da4c304..0000000000 --- a/benchmarks/bundle-size/scenarios/react-start-deferred-hydration/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -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-deferred-hydration/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/react-start-deferred-hydration/src/routes/index.tsx deleted file mode 100644 index a462508abd..0000000000 --- a/benchmarks/bundle-size/scenarios/react-start-deferred-hydration/src/routes/index.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { Hydrate } from '@tanstack/react-start' -import { visible } from '@tanstack/react-start/hydration' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return ( - -
hello world
-
- ) -} diff --git a/benchmarks/bundle-size/scenarios/react-start-deferred-hydration/vite.config.ts b/benchmarks/bundle-size/scenarios/react-start-deferred-hydration/vite.config.ts deleted file mode 100644 index d4e4cd980d..0000000000 --- a/benchmarks/bundle-size/scenarios/react-start-deferred-hydration/vite.config.ts +++ /dev/null @@ -1,7 +0,0 @@ -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/react-start-full/rsbuild.config.ts b/benchmarks/bundle-size/scenarios/react-start-full/rsbuild.config.ts deleted file mode 100644 index 349e11bec1..0000000000 --- a/benchmarks/bundle-size/scenarios/react-start-full/rsbuild.config.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { defineConfig } from '@rsbuild/core' -import { pluginReact } from '@rsbuild/plugin-react' -import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' - -const outDir = process.env.BUNDLE_SIZE_DIST_DIR ?? 'dist-rsbuild' - -export default defineConfig({ - logLevel: 'silent', - plugins: [pluginReact(), tanstackStart()], - output: { - distPath: { - root: outDir, - }, - cleanDistPath: true, - minify: true, - sourceMap: false, - }, - performance: { - printFileSize: false, - }, - environments: { - client: { - output: { - manifest: { - filename: 'manifest.json', - prefix: false, - }, - }, - }, - ssr: { - output: { - manifest: false, - }, - }, - }, -}) diff --git a/benchmarks/bundle-size/scenarios/react-start-full/src/router.tsx b/benchmarks/bundle-size/scenarios/react-start-full/src/router.tsx deleted file mode 100644 index 9d87d8748b..0000000000 --- a/benchmarks/bundle-size/scenarios/react-start-full/src/router.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - scrollRestoration: true, - }) -} diff --git a/benchmarks/bundle-size/scenarios/react-start-full/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/react-start-full/src/routes/__root.tsx deleted file mode 100644 index 07fd3a40be..0000000000 --- a/benchmarks/bundle-size/scenarios/react-start-full/src/routes/__root.tsx +++ /dev/null @@ -1,216 +0,0 @@ -import { - Asset, - Await, - Block, - CatchBoundary, - CatchNotFound, - ClientOnly, - DefaultGlobalNotFound, - ErrorComponent, - HeadContent, - Link, - Match, - MatchRoute, - Matches, - Navigate, - Outlet, - RouterContextProvider, - ScriptOnce, - Scripts, - ScrollRestoration, - createLink, - createRootRoute, - linkOptions, - useAwaited, - useBlocker, - useCanGoBack, - useElementScrollRestoration, - useHydrated, - useLinkProps, - useLoaderData, - useLoaderDeps, - useLocation, - useMatch, - useMatchRoute, - useMatches, - useNavigate, - useParams, - useParentMatches, - useChildMatches, - useRouteContext, - useRouter, - useRouterState, - useSearch, - useTags, -} from '@tanstack/react-router' -import { - createMiddleware, - createServerFn, - useServerFn, -} from '@tanstack/react-start' - -const requestMiddleware = createMiddleware().server(async ({ next }) => { - return next() -}) - -const functionMiddleware = createMiddleware({ type: 'function' }) - .client(async ({ next }) => { - return next() - }) - .server(async ({ next }) => { - return next() - }) - -const helloServerFn = createServerFn({ method: 'GET' }) - .middleware([requestMiddleware, functionMiddleware]) - .handler(async () => { - return 'hello from server fn' - }) - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - const router = useRouter() - const hydrated = useHydrated() - 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, - useHydrated, - 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, - ] - - ;(globalThis as any).__TANSTACK_BUNDLE_SIZE_KEEP__ = { - hooksAndComponents, - startSurface, - } - - void awaited - void linkFactoryResult - void matches - void parentMatches - void childMatches - void match - void loaderDeps - void loaderData - void params - void search - void routeContext - void routerState - void location - void canGoBack - void navigate - void scrollEntry - void tags - void routeMatchResult - void invokeServerFn - - return ( - - - - - - {'window.__tsr_bundle_size = true'} - - home - - - - {() => } - }> - - - - {() => } - - false} disabled withResolver={false}> - {() => } - - }> - - - - - - - - -
-
hello world
-
- - - ) -} diff --git a/benchmarks/bundle-size/scenarios/react-start-full/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/react-start-full/src/routes/index.tsx deleted file mode 100644 index 76fb363538..0000000000 --- a/benchmarks/bundle-size/scenarios/react-start-full/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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-full/vite.config.ts b/benchmarks/bundle-size/scenarios/react-start-full/vite.config.ts deleted file mode 100644 index d4e4cd980d..0000000000 --- a/benchmarks/bundle-size/scenarios/react-start-full/vite.config.ts +++ /dev/null @@ -1,7 +0,0 @@ -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/react-start-minimal/rsbuild.config.ts b/benchmarks/bundle-size/scenarios/react-start-minimal/rsbuild.config.ts deleted file mode 100644 index 7d27421d4d..0000000000 --- a/benchmarks/bundle-size/scenarios/react-start-minimal/rsbuild.config.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { defineConfig } from '@rsbuild/core' -import { pluginReact } from '@rsbuild/plugin-react' -import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' - -const outDir = process.env.BUNDLE_SIZE_DIST_DIR ?? 'dist-rsbuild' -const clientOutput = process.env.BUNDLE_SIZE_RSB_CLIENT_OUTPUT -const startOptions = clientOutput - ? { - rsbuild: { - client: { - output: clientOutput as 'module' | 'iife', - }, - }, - } - : undefined - -export default defineConfig({ - logLevel: 'silent', - plugins: [pluginReact(), tanstackStart(startOptions)], - output: { - distPath: { - root: outDir, - }, - cleanDistPath: true, - minify: true, - sourceMap: false, - }, - performance: { - printFileSize: false, - }, - environments: { - client: { - output: { - manifest: { - filename: 'manifest.json', - prefix: false, - }, - }, - }, - ssr: { - output: { - manifest: false, - }, - }, - }, -}) diff --git a/benchmarks/bundle-size/scenarios/react-start-minimal/src/router.tsx b/benchmarks/bundle-size/scenarios/react-start-minimal/src/router.tsx deleted file mode 100644 index 9d87d8748b..0000000000 --- a/benchmarks/bundle-size/scenarios/react-start-minimal/src/router.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - scrollRestoration: true, - }) -} diff --git a/benchmarks/bundle-size/scenarios/react-start-minimal/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/react-start-minimal/src/routes/__root.tsx deleted file mode 100644 index ff1da4c304..0000000000 --- a/benchmarks/bundle-size/scenarios/react-start-minimal/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -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-minimal/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/react-start-minimal/src/routes/index.tsx deleted file mode 100644 index 76fb363538..0000000000 --- a/benchmarks/bundle-size/scenarios/react-start-minimal/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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-minimal/vite.config.ts b/benchmarks/bundle-size/scenarios/react-start-minimal/vite.config.ts deleted file mode 100644 index d4e4cd980d..0000000000 --- a/benchmarks/bundle-size/scenarios/react-start-minimal/vite.config.ts +++ /dev/null @@ -1,7 +0,0 @@ -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/react-start-query-integration/src/router.tsx b/benchmarks/bundle-size/scenarios/react-start-query-integration/src/router.tsx deleted file mode 100644 index 93b95f3148..0000000000 --- a/benchmarks/bundle-size/scenarios/react-start-query-integration/src/router.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index ff1da4c304..0000000000 --- a/benchmarks/bundle-size/scenarios/react-start-query-integration/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index 76fb363538..0000000000 --- a/benchmarks/bundle-size/scenarios/react-start-query-integration/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index d4e4cd980d..0000000000 --- a/benchmarks/bundle-size/scenarios/react-start-query-integration/vite.config.ts +++ /dev/null @@ -1,7 +0,0 @@ -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/solid-router-full/index.html b/benchmarks/bundle-size/scenarios/solid-router-full/index.html deleted file mode 100644 index 80ef4474ee..0000000000 --- a/benchmarks/bundle-size/scenarios/solid-router-full/index.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - solid-router-full - - -
- - - diff --git a/benchmarks/bundle-size/scenarios/solid-router-full/src/main.tsx b/benchmarks/bundle-size/scenarios/solid-router-full/src/main.tsx deleted file mode 100644 index 505f79aee0..0000000000 --- a/benchmarks/bundle-size/scenarios/solid-router-full/src/main.tsx +++ /dev/null @@ -1,22 +0,0 @@ -import { render } from 'solid-js/web' -import { RouterProvider, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -const router = createRouter({ - routeTree, - scrollRestoration: true, -}) - -declare module '@tanstack/solid-router' { - interface Register { - router: typeof router - } -} - -const rootElement = document.getElementById('app') -if (!rootElement) { - throw new Error('Root element `#app` not found') -} -if (!rootElement.innerHTML) { - render(() => , rootElement) -} diff --git a/benchmarks/bundle-size/scenarios/solid-router-full/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/solid-router-full/src/routes/__root.tsx deleted file mode 100644 index f4c2906016..0000000000 --- a/benchmarks/bundle-size/scenarios/solid-router-full/src/routes/__root.tsx +++ /dev/null @@ -1,185 +0,0 @@ -import { - Asset, - Await, - Block, - CatchBoundary, - CatchNotFound, - ClientOnly, - DefaultGlobalNotFound, - ErrorComponent, - HeadContent, - Link, - Match, - MatchRoute, - Matches, - Navigate, - Outlet, - RouterContextProvider, - ScriptOnce, - Scripts, - ScrollRestoration, - createLink, - createRootRoute, - linkOptions, - useAwaited, - useBlocker, - useCanGoBack, - useChildMatches, - useElementScrollRestoration, - useHydrated, - useLinkProps, - useLoaderData, - useLoaderDeps, - useLocation, - useMatch, - useMatchRoute, - useMatches, - useNavigate, - useParams, - useParentMatches, - useRouteContext, - useRouter, - useRouterState, - useSearch, - useTags, -} from '@tanstack/solid-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - const router = useRouter() - const hydrated = useHydrated() - 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, - useHydrated, - 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, - ] - - ;(globalThis as any).__TANSTACK_BUNDLE_SIZE_KEEP__ = { - hooksAndComponents, - } - - void awaited - void linkFactoryResult - void matches() - void parentMatches() - void childMatches() - void match() - void loaderDeps() - void loaderData() - void params() - void search() - void routeContext() - void routerState() - void location() - void canGoBack() - void navigate - void scrollEntry - void tags() - void routeMatchResult() - - return ( - <> - - {'window.__tsr_bundle_size = true'} - - home - - - - {() => } - }> - - - - {() => } - - false} disabled withResolver={false}> - {() => } - - }> - - - - {() => } - - - - -
-
hello world
-
- - ) -} diff --git a/benchmarks/bundle-size/scenarios/solid-router-full/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/solid-router-full/src/routes/index.tsx deleted file mode 100644 index de52291cac..0000000000 --- a/benchmarks/bundle-size/scenarios/solid-router-full/src/routes/index.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import { - createFileRoute, - retainSearchParams, - stripSearchParams, -} from '@tanstack/solid-router' - -const defaultSearch = { page: 1 } - -export const Route = createFileRoute('/')({ - search: { - middlewares: [ - retainSearchParams>(['persist']), - stripSearchParams(defaultSearch), - ], - }, - component: IndexComponent, -}) - -function IndexComponent() { - return
hello world
-} diff --git a/benchmarks/bundle-size/scenarios/solid-router-full/vite.config.ts b/benchmarks/bundle-size/scenarios/solid-router-full/vite.config.ts deleted file mode 100644 index 9729ada0e8..0000000000 --- a/benchmarks/bundle-size/scenarios/solid-router-full/vite.config.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { defineConfig } from 'vite' -import solid from 'vite-plugin-solid' -import { tanstackRouter } from '@tanstack/router-plugin/vite' - -export default defineConfig({ - plugins: [ - tanstackRouter({ - target: 'solid', - autoCodeSplitting: true, - }), - solid(), - ], -}) diff --git a/benchmarks/bundle-size/scenarios/solid-router-minimal/index.html b/benchmarks/bundle-size/scenarios/solid-router-minimal/index.html deleted file mode 100644 index 29c6fbd787..0000000000 --- a/benchmarks/bundle-size/scenarios/solid-router-minimal/index.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - solid-router-minimal - - -
- - - diff --git a/benchmarks/bundle-size/scenarios/solid-router-minimal/src/main.tsx b/benchmarks/bundle-size/scenarios/solid-router-minimal/src/main.tsx deleted file mode 100644 index 210120b3f1..0000000000 --- a/benchmarks/bundle-size/scenarios/solid-router-minimal/src/main.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import { render } from 'solid-js/web' -import { RouterProvider, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -const router = createRouter({ routeTree }) - -declare module '@tanstack/solid-router' { - interface Register { - router: typeof router - } -} - -const rootElement = document.getElementById('app') -if (!rootElement) { - throw new Error('Root element `#app` not found') -} -if (!rootElement.innerHTML) { - render(() => , rootElement) -} diff --git a/benchmarks/bundle-size/scenarios/solid-router-minimal/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/solid-router-minimal/src/routes/__root.tsx deleted file mode 100644 index cb8d5a688d..0000000000 --- a/benchmarks/bundle-size/scenarios/solid-router-minimal/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createRootRoute } from '@tanstack/solid-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return -} diff --git a/benchmarks/bundle-size/scenarios/solid-router-minimal/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/solid-router-minimal/src/routes/index.tsx deleted file mode 100644 index 01d3b701ae..0000000000 --- a/benchmarks/bundle-size/scenarios/solid-router-minimal/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
hello world
-} diff --git a/benchmarks/bundle-size/scenarios/solid-router-minimal/vite.config.ts b/benchmarks/bundle-size/scenarios/solid-router-minimal/vite.config.ts deleted file mode 100644 index 9729ada0e8..0000000000 --- a/benchmarks/bundle-size/scenarios/solid-router-minimal/vite.config.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { defineConfig } from 'vite' -import solid from 'vite-plugin-solid' -import { tanstackRouter } from '@tanstack/router-plugin/vite' - -export default defineConfig({ - plugins: [ - tanstackRouter({ - target: 'solid', - autoCodeSplitting: true, - }), - solid(), - ], -}) diff --git a/benchmarks/bundle-size/scenarios/solid-start-deferred-hydration/src/router.tsx b/benchmarks/bundle-size/scenarios/solid-start-deferred-hydration/src/router.tsx deleted file mode 100644 index aa7ead6752..0000000000 --- a/benchmarks/bundle-size/scenarios/solid-start-deferred-hydration/src/router.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - scrollRestoration: true, - }) -} diff --git a/benchmarks/bundle-size/scenarios/solid-start-deferred-hydration/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/solid-start-deferred-hydration/src/routes/__root.tsx deleted file mode 100644 index e59de72236..0000000000 --- a/benchmarks/bundle-size/scenarios/solid-start-deferred-hydration/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/solid-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/bundle-size/scenarios/solid-start-deferred-hydration/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/solid-start-deferred-hydration/src/routes/index.tsx deleted file mode 100644 index 80362386b2..0000000000 --- a/benchmarks/bundle-size/scenarios/solid-start-deferred-hydration/src/routes/index.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { Hydrate } from '@tanstack/solid-start' -import { visible } from '@tanstack/solid-start/hydration' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return ( - -
hello world
-
- ) -} diff --git a/benchmarks/bundle-size/scenarios/solid-start-deferred-hydration/vite.config.ts b/benchmarks/bundle-size/scenarios/solid-start-deferred-hydration/vite.config.ts deleted file mode 100644 index 0bd21e64f4..0000000000 --- a/benchmarks/bundle-size/scenarios/solid-start-deferred-hydration/vite.config.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { defineConfig } from 'vite' -import solid from 'vite-plugin-solid' -import { tanstackStart } from '@tanstack/solid-start/plugin/vite' - -export default defineConfig({ - plugins: [tanstackStart(), solid({ ssr: true })], -}) diff --git a/benchmarks/bundle-size/scenarios/solid-start-full/src/router.tsx b/benchmarks/bundle-size/scenarios/solid-start-full/src/router.tsx deleted file mode 100644 index aa7ead6752..0000000000 --- a/benchmarks/bundle-size/scenarios/solid-start-full/src/router.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - scrollRestoration: true, - }) -} diff --git a/benchmarks/bundle-size/scenarios/solid-start-full/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/solid-start-full/src/routes/__root.tsx deleted file mode 100644 index 3daa0019c0..0000000000 --- a/benchmarks/bundle-size/scenarios/solid-start-full/src/routes/__root.tsx +++ /dev/null @@ -1,225 +0,0 @@ -import { - Asset, - Await, - Block, - CatchBoundary, - CatchNotFound, - ClientOnly, - DefaultGlobalNotFound, - ErrorComponent, - HeadContent, - Link, - Match, - MatchRoute, - Matches, - Navigate, - Outlet, - RouterContextProvider, - ScriptOnce, - Scripts, - ScrollRestoration, - createLink, - createRootRoute, - linkOptions, - useAwaited, - useBlocker, - useCanGoBack, - useChildMatches, - useElementScrollRestoration, - useHydrated, - useLinkProps, - useLoaderData, - useLoaderDeps, - useLocation, - useMatch, - useMatchRoute, - useMatches, - useNavigate, - useParams, - useParentMatches, - useRouteContext, - useRouter, - useRouterState, - useSearch, - useTags, -} from '@tanstack/solid-router' -import { - createMiddleware, - createServerFn, - useServerFn, -} from '@tanstack/solid-start' - -type BundleSizeKeep = { - hooksAndComponents: ReadonlyArray - startSurface: ReadonlyArray -} - -declare global { - var __TANSTACK_BUNDLE_SIZE_KEEP__: BundleSizeKeep | undefined -} - -const requestMiddleware = createMiddleware().server(async ({ next }) => { - return next() -}) - -const functionMiddleware = createMiddleware({ type: 'function' }) - .client(async ({ next }) => { - return next() - }) - .server(async ({ next }) => { - return next() - }) - -const helloServerFn = createServerFn({ method: 'GET' }) - .middleware([requestMiddleware, functionMiddleware]) - .handler(async () => { - return 'hello from server fn' - }) - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - const router = useRouter() - const hydrated = useHydrated() - const [awaited] = useAwaited({ promise: Promise.resolve('ready') }) - const linkProps = useLinkProps({ to: '/' }) - const matchRoute = useMatchRoute() - const matches = useMatches() - const parentMatches = useParentMatches() - const childMatches = useChildMatches() - const match = useMatch({ strict: false, shouldThrow: false }) - const loaderDeps = useLoaderDeps({ strict: false }) - const loaderData = useLoaderData({ strict: false }) - const params = useParams({ strict: false }) - const search = useSearch({ strict: false }) - const routeContext = useRouteContext({ strict: false }) - const routerState = useRouterState({ select: (state) => state.status }) - 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: '/' }) - const routeMatchResult = matchRoute({ to: '/' }) - const SvgLink = createLink('svg') - - const startSurface = [createMiddleware, createServerFn, useServerFn] - const hooksAndComponents = [ - useAwaited, - useHydrated, - 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, - ] - - globalThis.__TANSTACK_BUNDLE_SIZE_KEEP__ = { - hooksAndComponents, - startSurface, - } - - void awaited - void linkFactoryResult - void matches() - void parentMatches() - void childMatches() - void match() - void loaderDeps() - void loaderData() - void params() - void search() - void routeContext() - void routerState() - void location() - void canGoBack() - void navigate - void scrollEntry - void tags() - void routeMatchResult() - void invokeServerFn - - return ( - - - - - - {'window.__tsr_bundle_size = true'} - - home - - - - {() => } - }> - - - - {() => } - - false} disabled withResolver={false}> - {() => } - - }> - - - - {() => } - - - - -
-
hello world
-
- - - ) -} diff --git a/benchmarks/bundle-size/scenarios/solid-start-full/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/solid-start-full/src/routes/index.tsx deleted file mode 100644 index 01d3b701ae..0000000000 --- a/benchmarks/bundle-size/scenarios/solid-start-full/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
hello world
-} diff --git a/benchmarks/bundle-size/scenarios/solid-start-full/vite.config.ts b/benchmarks/bundle-size/scenarios/solid-start-full/vite.config.ts deleted file mode 100644 index 0bd21e64f4..0000000000 --- a/benchmarks/bundle-size/scenarios/solid-start-full/vite.config.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { defineConfig } from 'vite' -import solid from 'vite-plugin-solid' -import { tanstackStart } from '@tanstack/solid-start/plugin/vite' - -export default defineConfig({ - plugins: [tanstackStart(), solid({ ssr: true })], -}) diff --git a/benchmarks/bundle-size/scenarios/solid-start-minimal/src/router.tsx b/benchmarks/bundle-size/scenarios/solid-start-minimal/src/router.tsx deleted file mode 100644 index aa7ead6752..0000000000 --- a/benchmarks/bundle-size/scenarios/solid-start-minimal/src/router.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - scrollRestoration: true, - }) -} diff --git a/benchmarks/bundle-size/scenarios/solid-start-minimal/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/solid-start-minimal/src/routes/__root.tsx deleted file mode 100644 index e59de72236..0000000000 --- a/benchmarks/bundle-size/scenarios/solid-start-minimal/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/solid-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/bundle-size/scenarios/solid-start-minimal/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/solid-start-minimal/src/routes/index.tsx deleted file mode 100644 index 01d3b701ae..0000000000 --- a/benchmarks/bundle-size/scenarios/solid-start-minimal/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
hello world
-} diff --git a/benchmarks/bundle-size/scenarios/solid-start-minimal/vite.config.ts b/benchmarks/bundle-size/scenarios/solid-start-minimal/vite.config.ts deleted file mode 100644 index 0bd21e64f4..0000000000 --- a/benchmarks/bundle-size/scenarios/solid-start-minimal/vite.config.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { defineConfig } from 'vite' -import solid from 'vite-plugin-solid' -import { tanstackStart } from '@tanstack/solid-start/plugin/vite' - -export default defineConfig({ - plugins: [tanstackStart(), solid({ ssr: true })], -}) diff --git a/benchmarks/bundle-size/scenarios/vue-router-full/index.html b/benchmarks/bundle-size/scenarios/vue-router-full/index.html deleted file mode 100644 index 583379e36c..0000000000 --- a/benchmarks/bundle-size/scenarios/vue-router-full/index.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - vue-router-full - - -
- - - diff --git a/benchmarks/bundle-size/scenarios/vue-router-full/src/main.tsx b/benchmarks/bundle-size/scenarios/vue-router-full/src/main.tsx deleted file mode 100644 index 84d5f29df5..0000000000 --- a/benchmarks/bundle-size/scenarios/vue-router-full/src/main.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { createApp } from 'vue' -import { RouterProvider, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -const router = createRouter({ - routeTree, - scrollRestoration: true, -}) - -declare module '@tanstack/vue-router' { - interface Register { - router: typeof router - } -} - -const rootElement = document.getElementById('app') -if (!rootElement) { - throw new Error('Root element `#app` not found') -} -if (!rootElement.innerHTML) { - createApp({ - setup() { - return () => - }, - }).mount('#app') -} 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 deleted file mode 100644 index 0ff40aebfc..0000000000 --- a/benchmarks/bundle-size/scenarios/vue-router-full/src/routes/__root.tsx +++ /dev/null @@ -1,196 +0,0 @@ -import { defineComponent } from 'vue' -import { - Asset, - Await, - Block, - Body, - CatchBoundary, - CatchNotFound, - ClientOnly, - DefaultGlobalNotFound, - ErrorComponent, - HeadContent, - Html, - Link, - Match, - MatchRoute, - Matches, - Navigate, - Outlet, - RouterContextProvider, - ScriptOnce, - Scripts, - ScrollRestoration, - createLink, - createRootRoute, - linkOptions, - useAwaited, - useBlocker, - useCanGoBack, - useChildMatches, - useElementScrollRestoration, - useLinkProps, - useLoaderData, - useLoaderDeps, - useLocation, - useMatch, - useMatchRoute, - useMatches, - useNavigate, - useParams, - useParentMatches, - useRouteContext, - useRouter, - useRouterState, - useSearch, - 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, -}) diff --git a/benchmarks/bundle-size/scenarios/vue-router-full/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/vue-router-full/src/routes/index.tsx deleted file mode 100644 index bf165a33b5..0000000000 --- a/benchmarks/bundle-size/scenarios/vue-router-full/src/routes/index.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import { - createFileRoute, - retainSearchParams, - stripSearchParams, -} from '@tanstack/vue-router' - -const defaultSearch = { page: 1 } - -export const Route = createFileRoute('/')({ - search: { - middlewares: [ - retainSearchParams>(['persist']), - stripSearchParams(defaultSearch), - ], - }, - component: IndexComponent, -}) - -function IndexComponent() { - return
hello world
-} diff --git a/benchmarks/bundle-size/scenarios/vue-router-full/vite.config.ts b/benchmarks/bundle-size/scenarios/vue-router-full/vite.config.ts deleted file mode 100644 index 5556bfaa07..0000000000 --- a/benchmarks/bundle-size/scenarios/vue-router-full/vite.config.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { defineConfig } from 'vite' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import { tanstackRouter } from '@tanstack/router-plugin/vite' - -export default defineConfig({ - plugins: [ - tanstackRouter({ - target: 'vue', - autoCodeSplitting: true, - }), - vue(), - vueJsx(), - ], -}) diff --git a/benchmarks/bundle-size/scenarios/vue-router-minimal/index.html b/benchmarks/bundle-size/scenarios/vue-router-minimal/index.html deleted file mode 100644 index e3fe534a21..0000000000 --- a/benchmarks/bundle-size/scenarios/vue-router-minimal/index.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - vue-router-minimal - - -
- - - diff --git a/benchmarks/bundle-size/scenarios/vue-router-minimal/src/main.tsx b/benchmarks/bundle-size/scenarios/vue-router-minimal/src/main.tsx deleted file mode 100644 index 1fc66c27b1..0000000000 --- a/benchmarks/bundle-size/scenarios/vue-router-minimal/src/main.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import { createApp } from 'vue' -import { RouterProvider, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -const router = createRouter({ routeTree }) - -declare module '@tanstack/vue-router' { - interface Register { - router: typeof router - } -} - -const rootElement = document.getElementById('app') -if (!rootElement) { - throw new Error('Root element `#app` not found') -} -if (!rootElement.innerHTML) { - createApp({ - setup() { - return () => - }, - }).mount('#app') -} diff --git a/benchmarks/bundle-size/scenarios/vue-router-minimal/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/vue-router-minimal/src/routes/__root.tsx deleted file mode 100644 index 91296e6f84..0000000000 --- a/benchmarks/bundle-size/scenarios/vue-router-minimal/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createRootRoute } from '@tanstack/vue-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return -} diff --git a/benchmarks/bundle-size/scenarios/vue-router-minimal/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/vue-router-minimal/src/routes/index.tsx deleted file mode 100644 index 3899022bdd..0000000000 --- a/benchmarks/bundle-size/scenarios/vue-router-minimal/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
hello world
-} diff --git a/benchmarks/bundle-size/scenarios/vue-router-minimal/vite.config.ts b/benchmarks/bundle-size/scenarios/vue-router-minimal/vite.config.ts deleted file mode 100644 index 5556bfaa07..0000000000 --- a/benchmarks/bundle-size/scenarios/vue-router-minimal/vite.config.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { defineConfig } from 'vite' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import { tanstackRouter } from '@tanstack/router-plugin/vite' - -export default defineConfig({ - plugins: [ - tanstackRouter({ - target: 'vue', - autoCodeSplitting: true, - }), - vue(), - vueJsx(), - ], -}) diff --git a/benchmarks/bundle-size/scenarios/vue-start-full/src/router.tsx b/benchmarks/bundle-size/scenarios/vue-start-full/src/router.tsx deleted file mode 100644 index 9b893112b4..0000000000 --- a/benchmarks/bundle-size/scenarios/vue-start-full/src/router.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - scrollRestoration: true, - }) -} 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 deleted file mode 100644 index 8e8870a2ce..0000000000 --- a/benchmarks/bundle-size/scenarios/vue-start-full/src/routes/__root.tsx +++ /dev/null @@ -1,227 +0,0 @@ -import { defineComponent } from 'vue' -import { - Asset, - Await, - Block, - Body, - CatchBoundary, - CatchNotFound, - ClientOnly, - DefaultGlobalNotFound, - ErrorComponent, - HeadContent, - Html, - Link, - Match, - MatchRoute, - Matches, - Navigate, - Outlet, - RouterContextProvider, - ScriptOnce, - Scripts, - ScrollRestoration, - createLink, - createRootRoute, - linkOptions, - useAwaited, - useBlocker, - useCanGoBack, - useChildMatches, - useElementScrollRestoration, - useLinkProps, - useLoaderData, - useLoaderDeps, - useLocation, - useMatch, - useMatchRoute, - useMatches, - useNavigate, - useParams, - useParentMatches, - useRouteContext, - useRouter, - useRouterState, - useSearch, - useTags, -} from '@tanstack/vue-router' -import { - createMiddleware, - createServerFn, - useServerFn, -} from '@tanstack/vue-start' - -const requestMiddleware = createMiddleware().server(async ({ next }) => { - return next() -}) - -const functionMiddleware = createMiddleware({ type: 'function' }) - .client(async ({ next }) => { - return next() - }) - .server(async ({ next }) => { - return next() - }) - -const helloServerFn = createServerFn({ method: 'GET' }) - .middleware([requestMiddleware, functionMiddleware]) - .handler(async () => { - 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, -}) diff --git a/benchmarks/bundle-size/scenarios/vue-start-full/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/vue-start-full/src/routes/index.tsx deleted file mode 100644 index 3899022bdd..0000000000 --- a/benchmarks/bundle-size/scenarios/vue-start-full/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
hello world
-} diff --git a/benchmarks/bundle-size/scenarios/vue-start-full/vite.config.ts b/benchmarks/bundle-size/scenarios/vue-start-full/vite.config.ts deleted file mode 100644 index 3005d7504b..0000000000 --- a/benchmarks/bundle-size/scenarios/vue-start-full/vite.config.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { defineConfig } from 'vite' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import { tanstackStart } from '@tanstack/vue-start/plugin/vite' - -export default defineConfig({ - plugins: [tanstackStart(), vue(), vueJsx()], -}) diff --git a/benchmarks/bundle-size/scenarios/vue-start-minimal/src/router.tsx b/benchmarks/bundle-size/scenarios/vue-start-minimal/src/router.tsx deleted file mode 100644 index 9b893112b4..0000000000 --- a/benchmarks/bundle-size/scenarios/vue-start-minimal/src/router.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - scrollRestoration: true, - }) -} diff --git a/benchmarks/bundle-size/scenarios/vue-start-minimal/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/vue-start-minimal/src/routes/__root.tsx deleted file mode 100644 index 49422aac38..0000000000 --- a/benchmarks/bundle-size/scenarios/vue-start-minimal/src/routes/__root.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { - Body, - HeadContent, - Html, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/vue-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/bundle-size/scenarios/vue-start-minimal/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/vue-start-minimal/src/routes/index.tsx deleted file mode 100644 index 3899022bdd..0000000000 --- a/benchmarks/bundle-size/scenarios/vue-start-minimal/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
hello world
-} diff --git a/benchmarks/bundle-size/scenarios/vue-start-minimal/vite.config.ts b/benchmarks/bundle-size/scenarios/vue-start-minimal/vite.config.ts deleted file mode 100644 index 3005d7504b..0000000000 --- a/benchmarks/bundle-size/scenarios/vue-start-minimal/vite.config.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { defineConfig } from 'vite' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import { tanstackStart } from '@tanstack/vue-start/plugin/vite' - -export default defineConfig({ - plugins: [tanstackStart(), vue(), vueJsx()], -}) diff --git a/benchmarks/bundle-size/tsconfig.json b/benchmarks/bundle-size/tsconfig.json deleted file mode 100644 index ec9f5c598c..0000000000 --- a/benchmarks/bundle-size/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "target": "ESNext", - "module": "ESNext", - "moduleResolution": "Bundler", - "jsx": "preserve", - "allowJs": true, - "skipLibCheck": true, - "types": ["vite/client"] - }, - "exclude": ["node_modules", "dist"] -} diff --git a/benchmarks/client-nav/README.md b/benchmarks/client-nav/README.md deleted file mode 100644 index ec34ecc0c1..0000000000 --- a/benchmarks/client-nav/README.md +++ /dev/null @@ -1,307 +0,0 @@ -# Client Navigation Benchmarks - -Cross-framework client-side CPU benchmarks for: - -- `@tanstack/react-router` -- `@tanstack/solid-router` -- `@tanstack/vue-router` - -The benchmarks run in jsdom against production builds of real apps, and are -tracked in CI by CodSpeed (simulation mode). - -> **Scope:** these benchmarks cover the client router. The hydration -> scenarios also cover DOM hydration and the Router state-restoration path -> used by Start. Start-specific entry-point initialization, streamed payload -> arrival and client server-function calls are not included. Server request work -> is covered by `benchmarks/ssr`. - -## Layout - -- `react/`, `solid/`, `vue/` - baseline benchmark (mixed navigation loop) + Vitest config -- `vitest.react.config.ts`, `vitest.solid.config.ts`, `vitest.vue.config.ts` - per-framework aggregate configs that run the baseline first, then scenario projects -- `scenarios/harness.ts` - shared scenario runner (mount, link-click steps, `onRendered` synchronization) -- `scenarios//shared.ts` - framework-agnostic scenario definition (workload data, step sequence, assertions, bench options) -- `scenarios///` - isolated scenario apps - -Scenario app layout: - -```text -scenarios/// - vite.config.ts - speed.bench.ts - speed.flame.ts - setup.ts - project.json - tsconfig.json - src/ - main.tsx - routeTree.gen.ts - routes/ -``` - -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 -another scenario's numbers. The existing baseline apps and bench names stay -stable for CodSpeed continuity. - -## Scenario Responsibilities - -Each scenario isolates one client-side responsibility so benchmark changes can -be attributed to a specific feature area. - -| Scenario | Client-side responsibility | -| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `react/`, `solid/`, `vue/` baseline apps | Mixed navigation loop: path params, search params, route context, and `useParams`/`useSearch`/`useLoaderData` selector subscriptions. | -| `async-pipeline` | The router's async pipeline via counted 0ms timer hops: async loaders (transition-held navigation), async `beforeLoad` context, and parallel nested async loaders. Component-level `Await`/Suspense is excluded: React 19 throttles Suspense reveals by ~300ms wall-clock, which is inherently non-deterministic to benchmark. | -| `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. | -| `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). | -| `route-tree-scale` | Route matching and link-target resolution on a wide (~40 route) tree mixing static, dynamic, prefixed-param, splat, pathless-layout, and route-group paths, with `autoCodeSplitting` enabled so navigations also resolve lazy route chunks. | -| `search-params` | `validateSearch` execution, search middlewares (`retainSearchParams`/`stripSearchParams`), functional search updaters, structural sharing, and `useSearch` selector subscriptions. | - -## 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). - -## Run - -Run all benchmarks through Nx so dependency builds are part of the graph: - -```bash -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:perf --outputStyle=stream --skipRemoteCache -``` - -Run framework-specific benchmarks (baseline + all scenarios): - -```bash -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:perf:react --outputStyle=stream --skipRemoteCache -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:perf:solid --outputStyle=stream --skipRemoteCache -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:perf:vue --outputStyle=stream --skipRemoteCache -``` - -Run a single scenario app manually (after building it through Nx): - -```bash -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav--:build:client --outputStyle=stream --skipRemoteCache -cd benchmarks/client-nav && NODE_ENV=production vitest bench --mode benchmark --config ./scenarios///vite.config.ts -``` - -Run framework-specific flame benchmarks (10 second loop, profiled with `@platformatic/flame`, forced to `NODE_ENV=production`): - -```bash -# baseline -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:flame:react --outputStyle=stream --skipRemoteCache -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:flame:solid --outputStyle=stream --skipRemoteCache -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:flame:vue --outputStyle=stream --skipRemoteCache -# scenarios -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav--:test:flame --outputStyle=stream --skipRemoteCache -``` - -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/jsdom.ts b/benchmarks/client-nav/jsdom.ts deleted file mode 100644 index 855c2a2316..0000000000 --- a/benchmarks/client-nav/jsdom.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { JSDOM } from 'jsdom' - -const dom = new JSDOM('', { - url: 'http://localhost/', -}) - -const { window } = dom - -function setGlobal(name: string, value: unknown) { - Object.defineProperty(globalThis, name, { - value, - configurable: true, - writable: true, - }) -} - -setGlobal('window', window) -setGlobal('document', window.document) -setGlobal('self', window) -setGlobal('navigator', window.navigator) -setGlobal('location', window.location) -setGlobal('history', window.history) -setGlobal('HTMLElement', window.HTMLElement) -setGlobal('Element', window.Element) -setGlobal('SVGElement', window.SVGElement) -setGlobal('DocumentFragment', window.DocumentFragment) -setGlobal('Node', window.Node) -setGlobal('MouseEvent', window.MouseEvent) -setGlobal('MutationObserver', window.MutationObserver) -setGlobal('sessionStorage', window.sessionStorage) -setGlobal('localStorage', window.localStorage) -setGlobal('getComputedStyle', window.getComputedStyle.bind(window)) -setGlobal('addEventListener', window.addEventListener.bind(window)) -setGlobal('removeEventListener', window.removeEventListener.bind(window)) -setGlobal('dispatchEvent', window.dispatchEvent.bind(window)) -setGlobal('CustomEvent', window.CustomEvent) -setGlobal('Event', window.Event) - -setGlobal( - 'requestAnimationFrame', - window.requestAnimationFrame?.bind(window) ?? - ((callback: (time: number) => void) => - setTimeout(() => callback(performance.now()), 16)), -) - -setGlobal( - 'cancelAnimationFrame', - window.cancelAnimationFrame?.bind(window) ?? - ((handle: number) => clearTimeout(handle)), -) - -window.scrollTo = () => {} -setGlobal('scrollTo', () => {}) - -export { window } diff --git a/benchmarks/client-nav/link-performance/cases.ts b/benchmarks/client-nav/link-performance/cases.ts deleted file mode 100644 index a25eac563b..0000000000 --- a/benchmarks/client-nav/link-performance/cases.ts +++ /dev/null @@ -1,360 +0,0 @@ -export const LINK_CASES = [ - { - id: 'shared-params', - label: 'Shared string params', - description: '200 persistent Links reuse 40 string parameter values.', - }, - { - id: 'unique-params', - label: 'Unique string params', - description: '200 distinct parameter values exceed the 128-result cache.', - }, - { - id: 'param-updaters', - label: 'Parameter updaters', - description: 'Parameter functions derive destinations from current params.', - }, - { - id: 'location-updaters', - label: 'Search, hash and state updaters', - description: - 'Functions derive search, hash and history state from the source.', - }, - { - id: 'relative', - label: 'Relative targets', - description: 'Parent and child targets inherit current params and search.', - }, - { - id: 'middleware', - label: 'Search middleware chain', - description: - 'Retain a tenant, strip a default page and normalize a filter.', - }, - { - id: 'numeric-params', - label: 'Numeric params', - description: 'Parse numbers, update them numerically and stringify them.', - }, - { - id: 'optional-params', - label: 'Optional segments', - description: 'Set, inherit and explicitly clear an optional path segment.', - }, - { - id: 'splats', - label: 'Splat params', - description: 'Empty, multi-segment and encoded splat values.', - }, - { - id: 'encoding', - label: 'Allowed path characters', - description: 'Preserve allowed @, : and + while encoding other characters.', - }, - { - id: 'masks', - label: 'Explicit route masks', - description: - 'Build a different public path and search for each destination.', - }, - { - id: 'rewrites', - label: 'Basepath and rewrites', - description: 'Compose /app with input/output locale path rewrites.', - }, - { - id: 'active', - label: 'Active props and structured search', - description: - 'Exact, fuzzy and search matching with props and render children.', - }, -] as const - -export type LinkCaseId = (typeof LINK_CASES)[number]['id'] - -export const LINK_COUNT = 200 -export const NAVIGATION_STATES = [1, 2, 3, 0] as const -export const LOCALES = ['en', 'fr', 'de', 'es'] as const - -export interface Filter { - tag: string - flags: { open: boolean } - tags: Array -} - -export interface LinkSearch { - page?: number - tenant?: string - filter?: Filter -} - -export function sourceFilter(index: number): Filter { - return { - tag: `group-${index}`, - flags: { open: index % 2 === 0 }, - tags: ['links', `state-${index}`], - } -} - -export function sourceSearch( - caseId: LinkCaseId, - stateIndex: number, -): Partial { - switch (caseId) { - case 'location-updaters': - case 'relative': - case 'middleware': - case 'active': - return { - page: stateIndex + 1, - tenant: `tenant-${stateIndex}`, - filter: sourceFilter(stateIndex), - } - case 'rewrites': - return { tenant: LOCALES[stateIndex] } - default: - return {} - } -} - -export function optionalCategory(stateIndex: number) { - return stateIndex % 2 === 0 ? `category-${stateIndex}` : undefined -} - -export function splatValue(index: number) { - switch (index % 4) { - case 0: - return '' - case 1: - return `folder/sub/file-${index % 40}` - case 2: - return 'a b/100%/caf\u00e9?#' - default: - return 'literal%2F/\u{1f680}' - } -} - -export function encodedValue(index: number) { - return `user-${index % 40}@mail.test:tag+value /?#% caf\u00e9` -} - -function url(pathname: string, search: Partial = {}, hash = '') { - const result = new URL(pathname, 'http://localhost') - for (const [key, value] of Object.entries( - search, - )) { - if (value !== undefined) { - result.searchParams.set( - key, - typeof value === 'object' ? JSON.stringify(value) : String(value), - ) - } - } - result.hash = hash - return result.pathname + result.search + result.hash -} - -function sourcePath(caseId: LinkCaseId, stateIndex: number) { - switch (caseId) { - case 'relative': - return `/teams/team-${stateIndex}/item-${stateIndex}` - case 'numeric-params': - return `/numbers/${stateIndex}` - case 'optional-params': { - const category = optionalCategory(stateIndex) - return `/optional/${category ? `${category}/` : ''}item-${stateIndex}` - } - case 'splats': - return `/files/source/state-${stateIndex}` - case 'encoding': - return `/encoded/source-${stateIndex}` - case 'active': - return `/items/item-${stateIndex}/details` - default: - return `/items/item-${stateIndex}` - } -} - -export function getSourceUrl(caseId: LinkCaseId, stateIndex: number): string { - if (!Number.isInteger(stateIndex) || stateIndex < 0 || stateIndex > 3) { - throw new Error(`Invalid Link performance state: ${stateIndex}`) - } - const pathname = sourcePath(caseId, stateIndex) - if (caseId === 'rewrites') { - return `/app/${LOCALES[stateIndex]}${pathname}` - } - return url( - pathname, - sourceSearch(caseId, stateIndex), - caseId === 'location-updaters' ? `source-${stateIndex}` : '', - ) -} - -// These expectations use fixture values and platform encoding, not router APIs. -function expectedHref(caseId: LinkCaseId, stateIndex: number, index: number) { - const itemId = `item-${index % 40}` - switch (caseId) { - case 'shared-params': - return `/items/${itemId}` - case 'unique-params': - return `/items/item-${index}` - case 'param-updaters': - return `/items/item-${stateIndex}-related-${index % 40}` - case 'location-updaters': - return url( - `/items/item-${stateIndex}`, - { - ...sourceSearch(caseId, stateIndex), - page: stateIndex + 2 + (index % 5), - }, - `source-${stateIndex}-link-${index % 5}`, - ) - case 'relative': - return url( - index % 2 === 0 - ? `/teams/team-${stateIndex}` - : `/teams/team-${stateIndex}/item-${stateIndex}/details`, - sourceSearch(caseId, stateIndex), - ) - case 'middleware': - return url(`/filtered/${itemId}`, { - tenant: `tenant-${stateIndex}`, - page: index % 2 === 0 ? undefined : 2, - filter: { ...sourceFilter(index % 4), tag: `LABEL-${index % 40}` }, - }) - case 'numeric-params': - return `/numbers/${stateIndex + (index % 40)}` - case 'optional-params': { - const category = - index % 3 === 0 - ? 'fixed' - : index % 3 === 1 - ? optionalCategory(stateIndex) - : undefined - return `/optional/${category ? `${category}/` : ''}${itemId}` - } - case 'splats': { - const value = splatValue(index) - return `/files${value ? `/${value.split('/').map(encodeURIComponent).join('/')}` : ''}` - } - case 'encoding': { - const value = encodeURIComponent(encodedValue(index)) - .replaceAll('%40', '@') - .replaceAll('%3A', ':') - .replaceAll('%2B', '+') - return `/encoded/${value}` - } - case 'masks': - return url(`/public/display-${index % 40}`, { - tenant: `mask-${index % 4}`, - }) - case 'rewrites': - return url(`/app/${LOCALES[index % 4]}/items/${itemId}`, { - page: (index % 3) + 1, - }) - case 'active': { - const item = Math.floor(index / 5) - const variant = index % 5 - const search = - variant < 3 - ? { filter: sourceFilter(item % 4) } - : { - ...sourceSearch('active', item % 4), - ...(variant === 4 ? { filter: undefined } : {}), - } - return url(`/items/item-${item}${variant < 2 ? '' : '/details'}`, search) - } - } -} - -function assertUrl( - actualHref: string | null, - expectedHref: string, - label: string, -) { - if (actualHref === null) { - throw new Error(`${label}: missing href`) - } - const actual = new URL(actualHref, 'http://localhost') - const expected = new URL(expectedHref, 'http://localhost') - // Query ordering and the platform's '+' versus '%20' are immaterial here. - const query = (value: URL) => - JSON.stringify([...value.searchParams.entries()].sort()) - if ( - actual.origin !== expected.origin || - actual.pathname !== expected.pathname || - actual.hash !== expected.hash || - query(actual) !== query(expected) - ) { - throw new Error( - `${label}: expected ${expectedHref}, received ${actualHref}`, - ) - } -} - -export function assertScenario( - caseId: LinkCaseId, - stateIndex: number, - root: ParentNode, -): void { - const source = root.querySelector('[data-testid="source-path"]') - if (source?.textContent !== sourcePath(caseId, stateIndex)) { - throw new Error( - `${caseId}/${stateIndex}: unexpected source path ${source?.textContent}`, - ) - } - const links = root.querySelectorAll('a[data-perf-link]') - if (links.length !== LINK_COUNT) { - throw new Error( - `${caseId}: expected ${LINK_COUNT} Links, got ${links.length}`, - ) - } - for (const [index, link] of links.entries()) { - const label = `${caseId}/${stateIndex}/link-${index}` - if (link.getAttribute('data-perf-link') !== String(index)) { - throw new Error(`${label}: unexpected Link order`) - } - assertUrl( - link.getAttribute('href'), - expectedHref(caseId, stateIndex, index), - label, - ) - let active: boolean | undefined - if (caseId === 'shared-params') { - active = index % 40 === stateIndex - } else if (caseId === 'unique-params') { - active = index === stateIndex - } else if (caseId === 'active') { - active = - Math.floor(index / 5) === stateIndex && [0, 2, 3].includes(index % 5) - if ( - link.textContent !== `${index}:${active ? 'active' : 'inactive'}` || - link.getAttribute('title') !== (active ? 'active' : 'inactive') || - !link.classList.contains(active ? 'perf-active' : 'perf-inactive') || - link.style.color !== (active ? 'green' : 'gray') || - link.style.opacity !== '0.8' - ) { - throw new Error( - `${label}: active props or render children are incorrect`, - ) - } - } - if ( - active !== undefined && - (link.getAttribute('data-status') === 'active') !== active - ) { - throw new Error(`${label}: expected active=${active}`) - } - } - for (let state = 0; state < 4; state++) { - const control = root.querySelector(`[data-testid="go-state-${state}"]`) - if (!control || control.hasAttribute('data-perf-link')) { - throw new Error(`${caseId}: missing or measured control Link ${state}`) - } - assertUrl( - control.getAttribute('href'), - getSourceUrl(caseId, state), - `${caseId}/control-${state}`, - ) - } -} diff --git a/benchmarks/client-nav/link-performance/client.bench.ts b/benchmarks/client-nav/link-performance/client.bench.ts deleted file mode 100644 index f819fab52b..0000000000 --- a/benchmarks/client-nav/link-performance/client.bench.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../cpu-simulation' -import { LINK_CASES } from './cases' -import { createClientScenario, samplingOptions } from './scenario' -import type * as App from './src/client' - -const appModulePath = './dist/client/app.js' -const app: typeof App = await import(/* @vite-ignore */ appModulePath) -if (app.serverEnvironment !== false) { - throw new Error('Link client benchmarks must use the production client build') -} - -for (const { id, label } of LINK_CASES) { - test(label, async ({ bench }) => { - const scenario = createClientScenario(app, id) - function finish() { - try { - scenario.check() - } finally { - scenario.teardown() - } - } - - await bench( - `client Links: ${id}`, - benchLifecycle({ before: scenario.setup, after: finish }), - scenario.batch, - ).run(samplingOptions) - }) -} diff --git a/benchmarks/client-nav/link-performance/config.test.ts b/benchmarks/client-nav/link-performance/config.test.ts deleted file mode 100644 index 1a468a3169..0000000000 --- a/benchmarks/client-nav/link-performance/config.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { afterEach, describe, expect, test, vi } from 'vitest' -import { createLinkPerformanceConfig } from './config' - -afterEach(() => vi.unstubAllEnvs()) - -describe.each(['client', 'ssr'] as const)('%s configuration', (target) => { - test('discovers only the requested suite', () => { - const config = createLinkPerformanceConfig(target) - expect(config.test?.benchmark?.include).toEqual([`${target}.bench.ts`]) - }) - - test('builds production code for the correct environment', () => { - const config = createLinkPerformanceConfig(target) - expect(config.define?.['process.env.NODE_ENV']).toBe('"production"') - expect(config.resolve?.conditions).toContain( - target === 'ssr' ? 'node' : 'browser', - ) - expect(config.build?.ssr).toBe(target === 'ssr') - expect(config.build?.outDir).toBe(`./dist/${target}`) - expect(config.build?.rolldownOptions?.platform).toBe('node') - expect(config.build?.rolldownOptions?.external).toEqual([ - 'node:module', - 'module', - /^react(?:\/|$)/, - /^react-dom(?:\/|$)/, - ]) - }) - - test('does not retransform built bundles in the test environment', () => { - vi.stubEnv('VITEST', 'true') - const config = createLinkPerformanceConfig(target) - expect(config.ssr?.noExternal).toBeUndefined() - expect(config.test?.server?.deps?.external).toEqual([ - /\/link-performance\/dist\//, - ]) - }) - - test('bundles router dependencies when building app snapshots', () => { - vi.stubEnv('VITEST', undefined) - expect(createLinkPerformanceConfig(target).ssr?.noExternal).toBe(true) - }) -}) diff --git a/benchmarks/client-nav/link-performance/config.ts b/benchmarks/client-nav/link-performance/config.ts deleted file mode 100644 index 416b027057..0000000000 --- a/benchmarks/client-nav/link-performance/config.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { fileURLToPath } from 'node:url' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import type { UserConfig } from 'vite' - -const root = fileURLToPath(new URL('.', import.meta.url)) - -export function createLinkPerformanceConfig( - target: 'client' | 'ssr', -): UserConfig { - const server = target === 'ssr' - - return { - root, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - react(), - ], - resolve: { - conditions: [server ? 'node' : 'browser', 'production'], - }, - ssr: { - noExternal: process.env.VITEST ? undefined : true, - resolve: { - conditions: ['node', 'production'], - }, - }, - build: { - outDir: `./dist/${target}`, - emptyOutDir: true, - minify: false, - ssr: server, - lib: { - entry: `${root}src/${target}.tsx`, - formats: ['es'], - fileName: 'app', - }, - rolldownOptions: { - platform: 'node', - external: [ - 'node:module', - 'module', - /^react(?:\/|$)/, - /^react-dom(?:\/|$)/, - ], - output: { entryFileNames: 'app.js' }, - }, - }, - test: { - name: `react-link-performance-${target}`, - watch: false, - environment: server ? 'node' : 'jsdom', - setupFiles: server ? [] : ['../vitest.setup.ts'], - server: { - deps: { - external: [/\/link-performance\/dist\//], - }, - }, - include: [], - benchmark: { - include: [`${target}.bench.ts`], - }, - }, - } -} diff --git a/benchmarks/client-nav/link-performance/project.json b/benchmarks/client-nav/link-performance/project.json deleted file mode 100644 index fd1751c081..0000000000 --- a/benchmarks/client-nav/link-performance/project.json +++ /dev/null @@ -1,103 +0,0 @@ -{ - "name": "@benchmarks/react-link-performance", - "projectType": "application", - "tags": ["optional-benchmark"], - "targets": { - "build:client": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config ./link-performance/vite.client.config.ts", - "cwd": "benchmarks/client-nav" - } - }, - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config ./link-performance/vite.ssr.config.ts", - "cwd": "benchmarks/client-nav" - } - }, - "test:perf:client": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": ["build:client"], - "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./link-performance/vite.client.config.ts", - "cwd": "benchmarks/client-nav" - } - }, - "test:perf:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": ["build:ssr"], - "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./link-performance/vite.ssr.config.ts", - "cwd": "benchmarks/client-nav" - } - }, - "test:perf:stable": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": ["build:client", "build:ssr"], - "options": { - "command": "NODE_ENV=production node --import=@swc-node/register/esm-register benchmarks/client-nav/link-performance/stable-runner.ts" - } - }, - "test:unit": { - "executor": "nx:run-commands", - "inputs": [ - "...", - "{workspaceRoot}/benchmarks/client-nav/scenarios/harness.ts", - "{workspaceRoot}/benchmarks/client-nav/scenarios/links/shared.ts", - "{workspaceRoot}/benchmarks/client-nav/setup-helpers.ts", - "{workspaceRoot}/benchmarks/client-nav/tsconfig.json" - ], - "dependsOn": [ - { - "projects": ["@tanstack/history"], - "target": "build" - } - ], - "options": { - "command": "vitest run --config ./link-performance/vitest.config.ts", - "cwd": "benchmarks/client-nav" - } - }, - "test:types": { - "executor": "nx:run-commands", - "inputs": [ - "...", - "{workspaceRoot}/benchmarks/client-nav/jsdom.ts", - "{workspaceRoot}/benchmarks/client-nav/scenarios/harness.ts", - "{workspaceRoot}/benchmarks/client-nav/scenarios/links/shared.ts", - "{workspaceRoot}/benchmarks/client-nav/setup-helpers.ts", - "{workspaceRoot}/benchmarks/client-nav/tsconfig.json", - "{workspaceRoot}/benchmarks/client-nav/vitest.setup.ts" - ], - "dependsOn": [ - { - "projects": ["@tanstack/react-router"], - "target": "build" - } - ], - "options": { - "command": "tsc -p ./link-performance/tsconfig.json --noEmit", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/link-performance/scenario.ts b/benchmarks/client-nav/link-performance/scenario.ts deleted file mode 100644 index f1a3fb6df7..0000000000 --- a/benchmarks/client-nav/link-performance/scenario.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { JSDOM } from 'jsdom' -import { createScenarioSetup } from '../scenarios/harness' -import { ticksPerIteration } from '../scenarios/links/shared' -import { NAVIGATION_STATES, assertScenario, getSourceUrl } from './cases' -import type { LinkCaseId } from './cases' -import type * as ClientApp from './src/client' -import type * as SsrApp from './src/ssr' - -export interface LinkScenario { - setup: () => Promise - batch: () => Promise - check: () => void - teardown: () => void -} - -export const samplingOptions = { - warmupIterations: 100, - warmupTime: 1_000, - time: 5_000, - throws: true, -} - -export function createClientScenario( - app: typeof ClientApp, - id: LinkCaseId, -): LinkScenario { - let mounted: ReturnType | undefined - let container: HTMLElement | undefined - let anchors: Array = [] - const test = createScenarioSetup({ - frameworkLabel: 'React', - mount: (element, history) => { - container = element - mounted = app.mountTestApp(element, history, id) - return mounted - }, - initialUrl: getSourceUrl(id, 0), - steps: NAVIGATION_STATES.map((state) => `go-state-${state}`), - assertAfterStep: (index, element) => { - assertScenario(id, NAVIGATION_STATES[index]!, element) - if (!mounted) { - throw new Error('Link benchmark app was not mounted') - } - mounted.assertStateUpdates() - }, - }) - - return { - async setup() { - await test.before() - if (!container) { - throw new Error('Link benchmark container was not created') - } - anchors = [...container.querySelectorAll('a[data-perf-link]')] - }, - async batch() { - for (let index = 0; index < ticksPerIteration; index++) { - await test.tick() - } - await test.finishBatch() - }, - check() { - if (!container || !mounted) { - throw new Error('Link benchmark app was not mounted') - } - assertScenario(id, 0, container) - mounted.assertStateUpdates() - if (mounted.router.history.length !== 1) { - throw new Error('Link benchmark history must remain bounded') - } - const current = container.querySelectorAll('a[data-perf-link]') - if (anchors.some((anchor, index) => current[index] !== anchor)) { - throw new Error('Measured Links must stay mounted across navigations') - } - }, - teardown: test.after, - } -} - -export function createSsrScenario( - app: typeof SsrApp, - id: LinkCaseId, -): LinkScenario { - let html = '' - let state = 0 - function check() { - const dom = new JSDOM(html) - try { - assertScenario(id, state, dom.window.document) - } finally { - dom.window.close() - } - } - - return { - async setup() { - for (const nextState of NAVIGATION_STATES) { - state = nextState - html = await app.renderScenario(id, state, true) - check() - } - }, - async batch() { - for (const nextState of NAVIGATION_STATES) { - state = nextState - html = await app.renderScenario(id, state) - } - }, - check, - teardown() { - html = '' - }, - } -} diff --git a/benchmarks/client-nav/link-performance/src/client.tsx b/benchmarks/client-nav/link-performance/src/client.tsx deleted file mode 100644 index a187ee8c15..0000000000 --- a/benchmarks/client-nav/link-performance/src/client.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { RouterProvider } from '@tanstack/react-router' -import { isServer } from '@tanstack/router-core/isServer' -import { createRoot } from 'react-dom/client' -import { assertStateUpdates, createLinkRouter } from './workload' -import type { LinkRouter } from './workload' -import type { RouterHistory } from '@tanstack/history' -import type { LinkCaseId } from '../cases' - -export const serverEnvironment: boolean | undefined = isServer - -export function mountTestApp( - container: HTMLElement, - history: RouterHistory, - caseId: LinkCaseId, -): { - router: LinkRouter - unmount: () => void - assertStateUpdates: () => void -} { - const router = createLinkRouter(caseId, history, false) - const root = createRoot(container) - root.render() - - return { - router, - unmount: () => root.unmount(), - assertStateUpdates: () => assertStateUpdates(router), - } -} diff --git a/benchmarks/client-nav/link-performance/src/ssr.tsx b/benchmarks/client-nav/link-performance/src/ssr.tsx deleted file mode 100644 index 491191b1f9..0000000000 --- a/benchmarks/client-nav/link-performance/src/ssr.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { RouterProvider, createMemoryHistory } from '@tanstack/react-router' -import { isServer } from '@tanstack/router-core/isServer' -import { renderToString } from 'react-dom/server' -import { getSourceUrl } from '../cases' -import { assertStateUpdates, createLinkRouter } from './workload' -import type { LinkCaseId } from '../cases' - -export const serverEnvironment: boolean | undefined = isServer - -export async function renderScenario( - caseId: LinkCaseId, - stateIndex: number, - verify = false, -) { - const history = createMemoryHistory({ - initialEntries: [getSourceUrl(caseId, stateIndex)], - }) - const router = createLinkRouter(caseId, history, true) - try { - await router.load() - const html = renderToString() - if (verify) { - assertStateUpdates(router) - } - return html - } finally { - history.destroy() - } -} diff --git a/benchmarks/client-nav/link-performance/src/workload.tsx b/benchmarks/client-nav/link-performance/src/workload.tsx deleted file mode 100644 index 8315b85b8b..0000000000 --- a/benchmarks/client-nav/link-performance/src/workload.tsx +++ /dev/null @@ -1,506 +0,0 @@ -import { - Link, - Outlet, - createRootRouteWithContext, - createRoute, - createRouter, - linkOptions, - retainSearchParams, - stripSearchParams, - useLocation, -} from '@tanstack/react-router' -import { - LINK_COUNT, - LOCALES, - encodedValue, - optionalCategory, - sourceFilter, - sourceSearch, - splatValue, -} from '../cases' -import type { RouterHistory } from '@tanstack/history' -import type { SearchSchemaInput } from '@tanstack/react-router' -import type { Filter, LinkCaseId, LinkSearch } from '../cases' - -interface StateUpdates { - calls: number - verifiedCalls: number - input: number - output: number - offset: number -} - -interface WorkloadContext { - caseId: LinkCaseId - stateUpdates: StateUpdates -} - -function isFilter(value: unknown): value is Filter { - return ( - typeof value === 'object' && - value !== null && - 'tag' in value && - typeof value.tag === 'string' && - 'flags' in value && - typeof value.flags === 'object' && - value.flags !== null && - 'open' in value.flags && - typeof value.flags.open === 'boolean' && - 'tags' in value && - Array.isArray(value.tags) && - value.tags.every((tag: unknown) => typeof tag === 'string') - ) -} - -const rootRoute = createRootRouteWithContext()({ - validateSearch: ( - search: Record & SearchSchemaInput, - ): LinkSearch => ({ - page: typeof search.page === 'number' ? search.page : undefined, - tenant: typeof search.tenant === 'string' ? search.tenant : undefined, - filter: isFilter(search.filter) ? search.filter : undefined, - }), - component: RootLayout, -}) - -const itemsRoute = createRoute({ - getParentRoute: () => rootRoute, - path: 'items/$itemId', -}) -const detailsRoute = createRoute({ - getParentRoute: () => itemsRoute, - path: 'details', -}) -const teamRoute = createRoute({ - getParentRoute: () => rootRoute, - path: 'teams/$teamId', -}) -const teamItemRoute = createRoute({ - getParentRoute: () => teamRoute, - path: '$itemId', -}) -const teamDetailsRoute = createRoute({ - getParentRoute: () => teamItemRoute, - path: 'details', -}) -const filteredRoute = createRoute({ - getParentRoute: () => rootRoute, - path: 'filtered/$itemId', - search: { - middlewares: [ - retainSearchParams(['tenant']), - stripSearchParams({ page: 1 }), - ({ search, next }) => { - const result = next(search) - return { - ...result, - filter: result.filter - ? { ...result.filter, tag: result.filter.tag.trim().toUpperCase() } - : undefined, - } - }, - ], - }, -}) -const numericRoute = createRoute({ - getParentRoute: () => rootRoute, - path: 'numbers/$number', - params: { - parse: ({ number }) => { - const value = Number(number) - if (!Number.isFinite(value)) { - throw new Error(`Invalid number: ${number}`) - } - return { number: value } - }, - stringify: ({ number }) => ({ number: String(number) }), - }, -}) -const optionalRoute = createRoute({ - getParentRoute: () => rootRoute, - path: 'optional/{-$category}/$itemId', -}) -const splatRoute = createRoute({ - getParentRoute: () => rootRoute, - path: 'files/$', -}) -const encodedRoute = createRoute({ - getParentRoute: () => rootRoute, - path: 'encoded/$value', -}) -const publicRoute = createRoute({ - getParentRoute: () => rootRoute, - path: 'public/$itemId', -}) - -const routeTree = rootRoute.addChildren([ - itemsRoute.addChildren([detailsRoute]), - teamRoute.addChildren([teamItemRoute.addChildren([teamDetailsRoute])]), - filteredRoute, - numericRoute, - optionalRoute, - splatRoute, - encodedRoute, - publicRoute, -]) - -const localeRewrite = { - input: ({ url }: { url: URL }) => { - const match = /^\/(en|fr|de|es)(\/.*)$/.exec(url.pathname) - if (match) { - url.pathname = match[2]! - url.searchParams.set('tenant', match[1]!) - } - return url - }, - output: ({ url }: { url: URL }) => { - const locale = url.searchParams.get('tenant') - if (locale) { - url.searchParams.delete('tenant') - url.pathname = `/${locale}${url.pathname}` - } - return url - }, -} - -export function createLinkRouter( - caseId: LinkCaseId, - history: RouterHistory, - isServer: boolean, -) { - const context: WorkloadContext = { - caseId, - stateUpdates: { - calls: 0, - verifiedCalls: 0, - input: 0, - output: 0, - offset: 0, - }, - } - return createRouter({ - routeTree, - history, - isServer, - context, - scrollRestoration: false, - defaultPreload: false, - trailingSlash: 'never', - pathParamsAllowedCharacters: - caseId === 'encoding' ? ['@', ':', '+'] : undefined, - ...(caseId === 'rewrites' - ? { basepath: '/app', rewrite: localeRewrite } - : {}), - }) -} - -export type LinkRouter = ReturnType - -declare module '@tanstack/react-router' { - interface Register { - router: LinkRouter - } -} - -declare module '@tanstack/history' { - interface HistoryState { - linkPerfState?: number - } -} - -// Call alongside DOM assertions, outside the timed loop, after each sample. -export function assertStateUpdates(router: LinkRouter): void { - const { caseId, stateUpdates } = router.options.context - if (caseId !== 'location-updaters') { - return - } - const input = router.state.location.state.linkPerfState ?? 0 - if ( - stateUpdates.calls - stateUpdates.verifiedCalls < LINK_COUNT || - stateUpdates.input !== input || - stateUpdates.output !== input + stateUpdates.offset || - stateUpdates.offset < 1 || - stateUpdates.offset > 40 - ) { - throw new Error( - 'Link history-state updaters did not run with current state', - ) - } - stateUpdates.verifiedCalls = stateUpdates.calls -} - -function sourceOptions(caseId: LinkCaseId, stateIndex: number) { - const itemId = `item-${stateIndex}` - const common = { - search: sourceSearch(caseId, stateIndex), - hash: caseId === 'location-updaters' ? `source-${stateIndex}` : '', - state: { linkPerfState: stateIndex + 10 }, - } - switch (caseId) { - case 'relative': - return linkOptions({ - ...common, - to: '/teams/$teamId/$itemId', - params: { teamId: `team-${stateIndex}`, itemId }, - }) - case 'numeric-params': - return linkOptions({ - ...common, - to: '/numbers/$number', - params: { number: stateIndex }, - }) - case 'optional-params': - return linkOptions({ - ...common, - to: '/optional/{-$category}/$itemId', - params: { category: optionalCategory(stateIndex), itemId }, - }) - case 'splats': - return linkOptions({ - ...common, - to: '/files/$', - params: { _splat: `source/state-${stateIndex}` }, - }) - case 'encoding': - return linkOptions({ - ...common, - to: '/encoded/$value', - params: { value: `source-${stateIndex}` }, - }) - case 'active': - return linkOptions({ - ...common, - to: '/items/$itemId/details', - params: { itemId }, - }) - default: - return linkOptions({ - ...common, - to: '/items/$itemId', - params: { itemId }, - }) - } -} - -const indexes = Array.from({ length: LINK_COUNT }, (_, index) => index) -const controls = [0, 1, 2, 3] as const - -function SourcePath() { - const pathname = useLocation({ select: (location) => location.pathname }) - return {pathname} -} - -function RootLayout() { - const context = rootRoute.useRouteContext() - return ( - <> - - -
- {indexes.map((index) => measuredLink(context, index))} -
- - - ) -} - -function measuredLink( - { caseId, stateUpdates }: WorkloadContext, - index: number, -) { - const common = { - key: index, - 'data-perf-link': index, - preload: false, - children: `Link ${index}`, - } as const - const itemId = `item-${index % 40}` - switch (caseId) { - case 'shared-params': - case 'unique-params': - return ( - - ) - case 'param-updaters': - return ( - ({ - itemId: `${previous.itemId}-related-${index % 40}`, - })} - /> - ) - case 'location-updaters': - return ( - ({ - ...previous, - page: (previous.page ?? 1) + 1 + (index % 5), - })} - hash={(previous) => `${previous}-link-${index % 5}`} - state={(previous) => { - const input = previous.linkPerfState ?? 0 - const offset = (index % 40) + 1 - const output = input + offset - stateUpdates.calls++ - stateUpdates.input = input - stateUpdates.output = output - stateUpdates.offset = offset - return { ...previous, linkPerfState: output } - }} - /> - ) - case 'relative': - return ( - - ) - case 'middleware': - return ( - - ) - case 'numeric-params': - return ( - ({ number: previous.number + (index % 40) })} - /> - ) - case 'optional-params': - return ( - - ) - case 'splats': - return ( - - ) - case 'encoding': - return ( - - ) - case 'masks': - return ( - - ) - case 'rewrites': - return ( - - ) - case 'active': { - const item = Math.floor(index / 5) - const variant = index % 5 - return ( - ({ - className: 'perf-active', - title: 'active', - style: { color: 'green' }, - })} - inactiveProps={() => ({ - className: 'perf-inactive', - title: 'inactive', - style: { color: 'gray' }, - })} - > - {({ isActive }) => `${index}:${isActive ? 'active' : 'inactive'}`} - - ) - } - } -} diff --git a/benchmarks/client-nav/link-performance/ssr.bench.ts b/benchmarks/client-nav/link-performance/ssr.bench.ts deleted file mode 100644 index c30084e510..0000000000 --- a/benchmarks/client-nav/link-performance/ssr.bench.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../cpu-simulation' -import { LINK_CASES } from './cases' -import { createSsrScenario, samplingOptions } from './scenario' -import type * as App from './src/ssr' - -const appUrl = new URL('./dist/ssr/app.js', import.meta.url).href -const app: typeof App = await import(/* @vite-ignore */ appUrl) -if (app.serverEnvironment !== true) { - throw new Error('Link SSR benchmarks must use the production server build') -} - -for (const { id, label } of LINK_CASES) { - test(label, async ({ bench }) => { - const scenario = createSsrScenario(app, id) - function finish() { - try { - scenario.check() - } finally { - scenario.teardown() - } - } - - await bench( - `SSR Links: ${id}`, - benchLifecycle({ before: scenario.setup, after: finish }), - scenario.batch, - ).run(samplingOptions) - }) -} diff --git a/benchmarks/client-nav/link-performance/stable-runner.ts b/benchmarks/client-nav/link-performance/stable-runner.ts deleted file mode 100644 index 59ccfa3cb4..0000000000 --- a/benchmarks/client-nav/link-performance/stable-runner.ts +++ /dev/null @@ -1,269 +0,0 @@ -import { fork } from 'node:child_process' -import { createHash } from 'node:crypto' -import { - copyFileSync, - mkdirSync, - readFileSync, - rmSync, - writeFileSync, -} from 'node:fs' -import { dirname, resolve } from 'node:path' -import { fileURLToPath } from 'node:url' -import { parseArgs } from 'node:util' -import { LINK_CASES } from './cases' -import { createStagingDirectory } from './staging' -import { classify, mean, summarizeRatios } from './statistics' -import type { LinkCaseId } from './cases' -import type { - BlockSample, - Mode, - Variant, - WorkerRequest, - WorkerResponse, -} from './worker-protocol' - -const projectRoot = fileURLToPath(new URL('.', import.meta.url)) -const workspaceRoot = resolve(projectRoot, '../../..') - -function startWorker() { - const child = fork( - fileURLToPath(new URL('./stable-worker.ts', import.meta.url)), - { - cwd: workspaceRoot, - env: { ...process.env, NODE_ENV: 'production' }, - execArgv: [ - '--import=@swc-node/register/esm-register', - '--random-seed=42', - '--hash-seed=42', - ], - stdio: ['ignore', 'ignore', 'pipe', 'ipc'], - }, - ) - let stderr = '' - child.stderr?.on('data', (data: Buffer) => { - stderr = (stderr + data.toString()).slice(-4_096) - }) - - function request(message: WorkerRequest): Promise { - return new Promise((resolveResponse, reject) => { - const timeout = setTimeout(() => { - finish( - new Error(`Sampling worker timed out: ${message.kind}\n${stderr}`), - ) - }, 60_000) - const onExit = (code: number | null) => - finish(new Error(`Sampling worker exited (${code})\n${stderr}`)) - const onError = (error: Error) => finish(error) - const onMessage = (response: WorkerResponse) => { - if (response.kind === 'error') { - finish(new Error(response.message)) - } else { - finish(undefined, response) - } - } - function finish(error?: Error, response?: WorkerResponse) { - clearTimeout(timeout) - child.off('message', onMessage) - child.off('error', onError) - child.off('exit', onExit) - if (error) { - reject(error) - } else if (response) { - resolveResponse(response) - } - } - child.once('message', onMessage) - child.once('error', onError) - child.once('exit', onExit) - child.send(message, (error) => { - if (error) { - finish(error) - } - }) - }) - } - - return { - request, - kill: () => child.kill(), - } -} - -async function sampleReplica( - mode: Mode, - caseId: LinkCaseId, - baseline: string, - current: string, - replica: number, -) { - const worker = startWorker() - const samples: Array> = [[], []] - const ratios: Array<{ cpu: number; wall: number }> = [] - try { - const starts: Array = [] - // Balance module initialization and which variant finishes warming last. - const startupOrder: Array = replica % 2 ? [1, 0] : [0, 1] - for (const index of startupOrder) { - const ready = await worker.request({ - kind: 'init', - mode, - caseId, - bundle: index === 0 ? baseline : current, - variant: index, - }) - if (ready.kind !== 'ready') { - throw new Error('Expected a ready sampling worker') - } - starts[index] = ready.batchMs - } - const iterations = Math.max(1, Math.ceil(500 / Math.min(...starts))) - for (let round = 0; round < 2; round++) { - const block: Array> = [[], []] - const order: Array = - (round + replica) % 2 ? [1, 0, 0, 1] : [0, 1, 1, 0] - for (const index of order) { - const result = await worker.request({ - kind: 'measure', - iterations, - variant: index, - }) - if (result.kind !== 'sample') { - throw new Error('Expected a block measurement') - } - samples[index]!.push(result.sample) - block[index]!.push(result.sample) - } - ratios.push({ - cpu: - mean(block[1]!.map((s) => s.cpuMs)) / - mean(block[0]!.map((s) => s.cpuMs)), - wall: - mean(block[1]!.map((s) => s.wallMs)) / - mean(block[0]!.map((s) => s.wallMs)), - }) - } - const response = await worker.request({ kind: 'stop' }) - if (response.kind !== 'stopped') { - throw new Error('Expected successful post-measurement assertions') - } - return { - iterations, - baseline: samples[0]!, - current: samples[1]!, - cpuRatio: Math.exp(mean(ratios.map((r) => Math.log(r.cpu)))), - wallRatio: Math.exp(mean(ratios.map((r) => Math.log(r.wall)))), - } - } finally { - worker.kill() - } -} - -async function main() { - const { values } = parseArgs({ - options: { - baseline: { type: 'string' }, - current: { type: 'string', default: resolve(projectRoot, 'dist') }, - mode: { type: 'string', default: 'all' }, - repeats: { type: 'string', default: '4' }, - outputJson: { type: 'string' }, - testNamePattern: { type: 'string', short: 't' }, - }, - }) - if (!values.baseline || !values.outputJson) { - throw new Error( - 'Specify --baseline and --outputJson ', - ) - } - const repeats = Number(values.repeats) - if (!Number.isInteger(repeats) || repeats < 3 || repeats > 11) { - throw new Error('--repeats must be an integer between 3 and 11') - } - if (!['all', 'client', 'ssr'].includes(values.mode)) { - throw new Error('--mode must be all, client, or ssr') - } - const modes: Array = - values.mode === 'all' - ? ['client', 'ssr'] - : values.mode === 'client' - ? ['client'] - : ['ssr'] - const pattern = values.testNamePattern - ? new RegExp(values.testNamePattern) - : undefined - const cases = LINK_CASES.filter( - (c) => !pattern || pattern.test(`${c.label} ${c.id}`), - ) - if (!cases.length) { - throw new Error('No Link workloads match the requested pattern') - } - const report: { - protocol: string - node: string - complete: boolean - results: Array<{ - mode: Mode - caseId: LinkCaseId - baselineSha256: string - currentSha256: string - replicas: Array>> - cpu: ReturnType - wall: ReturnType - verdict: ReturnType - }> - } = { - protocol: - 'fresh process per case/replica; shared React runtime; separately loaded router variants; 2 ABBA/BAAB rounds; ~500ms calibrated fixed-work blocks; >=2s/100 batches warmup; main-thread CPU and wall time; fixed V8 random/hash seeds', - node: process.version, - complete: false, - results: [], - } - const output = resolve(values.outputJson) - mkdirSync(dirname(output), { recursive: true }) - const staging = createStagingDirectory() - try { - for (const mode of modes) { - const baselineInput = resolve(values.baseline, mode, 'app.js') - const currentInput = resolve(values.current, mode, 'app.js') - // Both snapshots resolve React from the same package installation. - const baseline = resolve(staging, `baseline-${mode}.mjs`) - const current = resolve(staging, `current-${mode}.mjs`) - copyFileSync(baselineInput, baseline) - copyFileSync(currentInput, current) - const digest = (file: string) => - createHash('sha256').update(readFileSync(file)).digest('hex') - const baselineSha256 = digest(baseline) - const currentSha256 = digest(current) - for (const { id } of cases) { - const replicas = [] - for (let replica = 0; replica < repeats; replica++) { - replicas.push( - await sampleReplica(mode, id, baseline, current, replica), - ) - } - const cpu = summarizeRatios(replicas.map((r) => r.cpuRatio)) - const wall = summarizeRatios(replicas.map((r) => r.wallRatio)) - const verdict = classify(cpu, wall) - report.results.push({ - mode, - caseId: id, - baselineSha256, - currentSha256, - replicas, - cpu, - wall, - verdict, - }) - writeFileSync(output, JSON.stringify(report, null, 2)) - console.log( - `${mode} ${id}: CPU ${cpu.changePercent.toFixed(2)}% [${cpu.low95.toFixed(2)}, ${cpu.high95.toFixed(2)}], wall ${wall.changePercent.toFixed(2)}% [${wall.low95.toFixed(2)}, ${wall.high95.toFixed(2)}] ${verdict}`, - ) - } - } - report.complete = true - writeFileSync(output, JSON.stringify(report, null, 2)) - } finally { - rmSync(staging, { recursive: true }) - } -} - -await main() diff --git a/benchmarks/client-nav/link-performance/stable-worker.test.ts b/benchmarks/client-nav/link-performance/stable-worker.test.ts deleted file mode 100644 index 087b32414a..0000000000 --- a/benchmarks/client-nav/link-performance/stable-worker.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { fork } from 'node:child_process' -import { rmdirSync, unlinkSync, writeFileSync } from 'node:fs' -import { join } from 'node:path' -import { fileURLToPath } from 'node:url' -import { expect, test } from 'vitest' -import { createStagingDirectory } from './staging' -import type { WorkerResponse } from './worker-protocol' - -test('loads emitted JavaScript without retranspiling it through SWC', async () => { - const directory = createStagingDirectory() - const bundle = join(directory, 'app.mjs') - const definition = 'function untouched ( ) { return 1 }' - writeFileSync( - bundle, - `${definition}\nawait Promise.resolve()\nthrow new Error(untouched.toString())`, - ) - const worker = fork( - fileURLToPath(new URL('./stable-worker.ts', import.meta.url)), - { - cwd: fileURLToPath(new URL('../../../', import.meta.url)), - execArgv: ['--import=@swc-node/register/esm-register'], - env: { ...process.env, NODE_ENV: 'production' }, - stdio: ['ignore', 'ignore', 'pipe', 'ipc'], - }, - ) - let stderr = '' - worker.stderr?.on('data', (data: Buffer) => { - stderr += data.toString() - }) - let timeout: ReturnType | undefined - try { - const result = new Promise((resolve, reject) => { - worker.once('message', (message: WorkerResponse) => resolve(message)) - worker.once('error', reject) - worker.once('exit', (code) => { - reject(new Error(`Worker exited (${code}): ${stderr}`)) - }) - timeout = setTimeout(() => { - reject(new Error(`Worker timed out: ${stderr}`)) - }, 5_000) - }) - worker.send({ - kind: 'init', - mode: 'ssr', - caseId: 'shared-params', - bundle, - variant: 0, - }) - const response = await result - expect(response.kind).toBe('error') - if (response.kind === 'error') { - expect(response.message).toContain(`Error: ${definition}`) - } - } finally { - clearTimeout(timeout) - worker.kill() - unlinkSync(bundle) - rmdirSync(directory) - } -}) diff --git a/benchmarks/client-nav/link-performance/stable-worker.ts b/benchmarks/client-nav/link-performance/stable-worker.ts deleted file mode 100644 index d98679dc15..0000000000 --- a/benchmarks/client-nav/link-performance/stable-worker.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { pathToFileURL } from 'node:url' -import { createClientScenario, createSsrScenario } from './scenario' -import type { LinkScenario } from './scenario' -import type { WorkerRequest, WorkerResponse } from './worker-protocol' -import type * as ClientApp from './src/client' -import type * as SsrApp from './src/ssr' - -const scenarios: Array = [] -const creationOrder: Array = [] -let closeWindow = () => {} - -function reply(response: WorkerResponse) { - if (!process.send) { - throw new Error('The Link sampling worker requires an IPC parent') - } - process.send(response) -} - -async function handle(request: WorkerRequest) { - if (request.kind === 'init') { - if (typeof process.threadCpuUsage !== 'function') { - throw new Error( - 'Stable sampling requires Node.js with process.threadCpuUsage', - ) - } - if (scenarios[request.variant]) { - throw new Error('A worker must only initialize each variant once') - } - let scenario: LinkScenario - const bundleUrl = pathToFileURL(request.bundle) - bundleUrl.searchParams.set('linkPerfVariant', String(request.variant)) - if (request.mode === 'client') { - const { window } = await import('../jsdom') - closeWindow = () => window.close() - const app: typeof ClientApp = await import(bundleUrl.href) - if (app.serverEnvironment !== false) { - throw new Error('Expected a production client bundle') - } - scenario = createClientScenario(app, request.caseId) - } else { - const app: typeof SsrApp = await import(bundleUrl.href) - if (app.serverEnvironment !== true) { - throw new Error('Expected a production SSR bundle') - } - scenario = createSsrScenario(app, request.caseId) - } - scenarios[request.variant] = scenario - creationOrder.push(scenario) - await scenario.setup() - const start = performance.now() - let iterations = 0 - do { - await scenario.batch() - iterations++ - } while (iterations < 100 || performance.now() - start < 2_000) - reply({ - kind: 'ready', - batchMs: (performance.now() - start) / iterations, - }) - return - } - if (request.kind === 'measure') { - const scenario = scenarios[request.variant] - if (!scenario) { - throw new Error('The sampling worker has not been initialized') - } - if (!Number.isInteger(request.iterations) || request.iterations < 1) { - throw new Error('Expected a positive batch count') - } - const cpuStart = process.threadCpuUsage() - const processStart = process.cpuUsage() - const start = performance.now() - for (let index = 0; index < request.iterations; index++) { - await scenario.batch() - } - const wallMs = performance.now() - start - const cpu = process.threadCpuUsage(cpuStart) - const processCpu = process.cpuUsage(processStart) - reply({ - kind: 'sample', - sample: { - iterations: request.iterations, - wallMs: wallMs / request.iterations, - cpuMs: (cpu.user + cpu.system) / 1_000 / request.iterations, - processCpuMs: - (processCpu.user + processCpu.system) / 1_000 / request.iterations, - }, - }) - return - } - try { - for (const scenario of creationOrder) { - scenario.check() - } - } finally { - for (const scenario of creationOrder.reverse()) { - scenario.teardown() - } - closeWindow() - } - reply({ kind: 'stopped' }) -} - -process.on('message', (request: WorkerRequest) => { - void handle(request).catch((error: unknown) => { - reply({ - kind: 'error', - message: - error instanceof Error ? error.stack || error.message : String(error), - }) - }) -}) diff --git a/benchmarks/client-nav/link-performance/staging.ts b/benchmarks/client-nav/link-performance/staging.ts deleted file mode 100644 index ac07d34c29..0000000000 --- a/benchmarks/client-nav/link-performance/staging.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { mkdirSync, mkdtempSync } from 'node:fs' -import { resolve } from 'node:path' -import { fileURLToPath } from 'node:url' - -export function createStagingDirectory() { - // SWC skips node_modules, leaving the emitted benchmark JavaScript intact. - const root = fileURLToPath(new URL('./node_modules/.cache/', import.meta.url)) - mkdirSync(root, { recursive: true }) - return mkdtempSync(resolve(root, 'link-performance-')) -} diff --git a/benchmarks/client-nav/link-performance/statistics.test.ts b/benchmarks/client-nav/link-performance/statistics.test.ts deleted file mode 100644 index 8f5f37413b..0000000000 --- a/benchmarks/client-nav/link-performance/statistics.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { expect, test } from 'vitest' -import { classify, mean, summarizeRatios } from './statistics' - -test('summarizes multiplicative paired changes across process replicas', () => { - const result = summarizeRatios([0.9, 0.9, 0.9, 0.9]) - expect(result.changePercent).toBeCloseTo(-10) - expect(result.low95).toBeCloseTo(-10) - expect(result.high95).toBeCloseTo(-10) - expect(result.replicas).toBe(4) -}) - -test('does not turn opposite noisy runs into a conclusive result', () => { - const result = summarizeRatios([0.9, 1.1, 0.95, 1.05]) - expect(result.low95).toBeLessThan(0) - expect(result.high95).toBeGreaterThan(0) - expect(classify(result, result)).toBe('inconclusive') -}) - -test('requires CPU and wall time to corroborate a direction', () => { - const slower = summarizeRatios([1.08, 1.09, 1.08, 1.09]) - const faster = summarizeRatios([0.9, 0.91, 0.9, 0.91]) - expect(classify(slower, slower)).toBe('slower') - expect(classify(faster, faster)).toBe('faster') - expect(classify(slower, faster)).toBe('inconclusive') - expect(classify(summarizeRatios([1, 1, 1]), summarizeRatios([1, 1, 1]))).toBe( - 'within-2%', - ) -}) - -test('rejects incomplete or invalid sampling data', () => { - expect(() => summarizeRatios([1])).toThrow() - expect(() => summarizeRatios([0, 1])).toThrow() - expect(() => summarizeRatios([NaN, 1])).toThrow() - expect(() => mean([])).toThrow() - expect(() => mean([Infinity])).toThrow() -}) diff --git a/benchmarks/client-nav/link-performance/statistics.ts b/benchmarks/client-nav/link-performance/statistics.ts deleted file mode 100644 index 469bdaf65a..0000000000 --- a/benchmarks/client-nav/link-performance/statistics.ts +++ /dev/null @@ -1,57 +0,0 @@ -const critical95 = [ - 12.7062, 4.3027, 3.1824, 2.7764, 2.5706, 2.4469, 2.3646, 2.306, 2.2622, - 2.2281, -] - -export function mean(values: ReadonlyArray) { - if (!values.length || values.some((value) => !Number.isFinite(value))) { - throw new Error('Expected finite, nonempty samples') - } - return values.reduce((sum, value) => sum + value, 0) / values.length -} - -export function summarizeRatios(ratios: ReadonlyArray) { - if ( - ratios.length < 2 || - ratios.length > 11 || - ratios.some((value) => value <= 0) - ) { - throw new Error('Expected 2-11 independent positive process-replica ratios') - } - const logs = ratios.map(Math.log) - const center = mean(logs) - const variance = - logs.reduce((sum, value) => sum + (value - center) ** 2, 0) / - (logs.length - 1) - // Replicas, not the many correlated batches inside a worker, are the samples. - const margin = - critical95[logs.length - 2]! * Math.sqrt(variance / logs.length) - const percent = (value: number) => (Math.exp(value) - 1) * 100 - return { - changePercent: percent(center), - low95: percent(center - margin), - high95: percent(center + margin), - replicas: ratios.length, - } -} - -export function classify( - cpu: ReturnType, - wall: ReturnType, -) { - if (cpu.low95 > 0 && wall.low95 > 0) { - return 'slower' - } - if (cpu.high95 < 0 && wall.high95 < 0) { - return 'faster' - } - if ( - cpu.low95 >= -2 && - cpu.high95 <= 2 && - wall.low95 >= -2 && - wall.high95 <= 2 - ) { - return 'within-2%' - } - return 'inconclusive' -} diff --git a/benchmarks/client-nav/link-performance/tsconfig.json b/benchmarks/client-nav/link-performance/tsconfig.json deleted file mode 100644 index fbf230c977..0000000000 --- a/benchmarks/client-nav/link-performance/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "./**/*.ts", - "./**/*.tsx", - "../scenarios/harness.ts", - "../setup-helpers.ts", - "../vitest.setup.ts" - ] -} diff --git a/benchmarks/client-nav/link-performance/vite.client.config.ts b/benchmarks/client-nav/link-performance/vite.client.config.ts deleted file mode 100644 index 1cd45fc45e..0000000000 --- a/benchmarks/client-nav/link-performance/vite.client.config.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { createLinkPerformanceConfig } from './config' - -export default createLinkPerformanceConfig('client') diff --git a/benchmarks/client-nav/link-performance/vite.ssr.config.ts b/benchmarks/client-nav/link-performance/vite.ssr.config.ts deleted file mode 100644 index f59148eaf6..0000000000 --- a/benchmarks/client-nav/link-performance/vite.ssr.config.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { createLinkPerformanceConfig } from './config' - -export default createLinkPerformanceConfig('ssr') diff --git a/benchmarks/client-nav/link-performance/vitest.config.ts b/benchmarks/client-nav/link-performance/vitest.config.ts deleted file mode 100644 index f8454c819d..0000000000 --- a/benchmarks/client-nav/link-performance/vitest.config.ts +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index 474858a529..0000000000 --- a/benchmarks/client-nav/link-performance/worker-protocol.ts +++ /dev/null @@ -1,28 +0,0 @@ -import type { LinkCaseId } from './cases' - -export type Mode = 'client' | 'ssr' -export type Variant = 0 | 1 - -export type WorkerRequest = - | { - kind: 'init' - mode: Mode - caseId: LinkCaseId - bundle: string - variant: Variant - } - | { kind: 'measure'; iterations: number; variant: Variant } - | { kind: 'stop' } - -export interface BlockSample { - wallMs: number - cpuMs: number - processCpuMs: number - iterations: number -} - -export type WorkerResponse = - | { kind: 'ready'; batchMs: number } - | { kind: 'sample'; sample: BlockSample } - | { kind: 'stopped' } - | { kind: 'error'; message: string } diff --git a/benchmarks/client-nav/package.json b/benchmarks/client-nav/package.json deleted file mode 100644 index 1f878adc67..0000000000 --- a/benchmarks/client-nav/package.json +++ /dev/null @@ -1,245 +0,0 @@ -{ - "name": "@benchmarks/client-nav", - "private": true, - "type": "module", - "scripts": { - "build:react": "NODE_ENV=production vite build --config ./react/vite.config.ts", - "build:solid": "NODE_ENV=production vite build --config ./solid/vite.config.ts", - "build:vue": "NODE_ENV=production vite build --config ./vue/vite.config.ts", - "test:flame:react": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./react/speed.flame.ts", - "test:flame:solid": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./solid/speed.flame.ts", - "test:flame:vue": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./vue/speed.flame.ts", - "test:perf": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.config.ts", - "test:perf:react": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.react.config.ts", - "test:perf:solid": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.solid.config.ts", - "test:perf:vue": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.vue.config.ts", - "test: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", - "test:types:vue": "tsc -p ./vue/tsconfig.json --noEmit" - }, - "dependencies": { - "@tanstack/history": "workspace:^", - "@tanstack/react-router": "workspace:^", - "@tanstack/router-core": "workspace:^", - "@tanstack/solid-router": "workspace:^", - "@tanstack/vue-router": "workspace:^", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "solid-js": "^1.9.10", - "vue": "^3.5.16" - }, - "devDependencies": { - "@platformatic/flame": "^1.6.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": "catalog:" - }, - "nx": { - "targets": { - "build:react": { - "cache": false, - "dependsOn": [ - { - "projects": [ - "@tanstack/react-router" - ], - "target": "build" - }, - { - "projects": [ - "@benchmarks/client-nav-async-pipeline-react", - "@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", - "@benchmarks/client-nav-nested-params-react", - "@benchmarks/client-nav-preload-react", - "@benchmarks/client-nav-rewrites-react", - "@benchmarks/client-nav-route-tree-scale-react", - "@benchmarks/client-nav-search-params-react" - ], - "target": "build:client" - } - ] - }, - "build:solid": { - "cache": false, - "dependsOn": [ - { - "projects": [ - "@tanstack/solid-router" - ], - "target": "build" - }, - { - "projects": [ - "@benchmarks/client-nav-async-pipeline-solid", - "@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", - "@benchmarks/client-nav-nested-params-solid", - "@benchmarks/client-nav-preload-solid", - "@benchmarks/client-nav-rewrites-solid", - "@benchmarks/client-nav-route-tree-scale-solid", - "@benchmarks/client-nav-search-params-solid" - ], - "target": "build:client" - } - ] - }, - "build:vue": { - "cache": false, - "dependsOn": [ - { - "projects": [ - "@tanstack/vue-router" - ], - "target": "build" - }, - { - "projects": [ - "@benchmarks/client-nav-async-pipeline-vue", - "@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", - "@benchmarks/client-nav-nested-params-vue", - "@benchmarks/client-nav-preload-vue", - "@benchmarks/client-nav-rewrites-vue", - "@benchmarks/client-nav-route-tree-scale-vue", - "@benchmarks/client-nav-search-params-vue" - ], - "target": "build:client" - } - ] - }, - "test:perf": { - "cache": false, - "dependsOn": [ - "build:react", - "build:solid", - "build:vue" - ] - }, - "test:flame:react": { - "cache": false, - "dependsOn": [ - "build:react" - ] - }, - "test:flame:solid": { - "cache": false, - "dependsOn": [ - "build:solid" - ] - }, - "test:flame:vue": { - "cache": false, - "dependsOn": [ - "build:vue" - ] - }, - "test:perf:react": { - "cache": false, - "dependsOn": [ - "build:react" - ] - }, - "test:perf:solid": { - "cache": false, - "dependsOn": [ - "build:solid" - ] - }, - "test:perf:vue": { - "cache": false, - "dependsOn": [ - "build:vue" - ] - }, - "test:types": { - "inputs": [ - "default", - "^production", - "{workspaceRoot}/eslint.config.js", - "{workspaceRoot}/benchmarks/cpu-simulation.ts", - "dependentTaskOutputs" - ], - "dependsOn": [ - "^build", - { - "projects": [ - "@benchmarks/client-nav-async-pipeline-react", - "@benchmarks/client-nav-async-pipeline-solid", - "@benchmarks/client-nav-async-pipeline-vue", - "@benchmarks/client-nav-control-flow-react", - "@benchmarks/client-nav-control-flow-solid", - "@benchmarks/client-nav-control-flow-vue", - "@benchmarks/client-nav-head-react", - "@benchmarks/client-nav-head-solid", - "@benchmarks/client-nav-head-vue", - "@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", - "@benchmarks/client-nav-loaders-vue", - "@benchmarks/client-nav-mount-react", - "@benchmarks/client-nav-mount-solid", - "@benchmarks/client-nav-mount-vue", - "@benchmarks/client-nav-nested-params-react", - "@benchmarks/client-nav-nested-params-solid", - "@benchmarks/client-nav-nested-params-vue", - "@benchmarks/client-nav-preload-react", - "@benchmarks/client-nav-preload-solid", - "@benchmarks/client-nav-preload-vue", - "@benchmarks/client-nav-rewrites-react", - "@benchmarks/client-nav-route-tree-scale-react", - "@benchmarks/client-nav-rewrites-solid", - "@benchmarks/client-nav-route-tree-scale-solid", - "@benchmarks/client-nav-rewrites-vue", - "@benchmarks/client-nav-route-tree-scale-vue", - "@benchmarks/client-nav-search-params-react", - "@benchmarks/client-nav-search-params-solid", - "@benchmarks/client-nav-search-params-vue" - ], - "target": "test:types:client" - } - ] - } - } - } -} diff --git a/benchmarks/client-nav/react/app.tsx b/benchmarks/client-nav/react/app.tsx deleted file mode 100644 index cad766e26c..0000000000 --- a/benchmarks/client-nav/react/app.tsx +++ /dev/null @@ -1,385 +0,0 @@ -import { - Link, - Outlet, - RouterProvider, - createMemoryHistory, - createRootRoute, - createRoute, - createRouter, - useParams, - useSearch, -} from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' - -function runPerfSelectorComputation(seed: number) { - let value = Math.trunc(seed) | 0 - - for (let index = 0; index < 40; index++) { - value = (value * 1664525 + 1013904223 + index) >>> 0 - } - - return value -} - -function normalizePage(value: unknown) { - const page = Number(value) - return Number.isFinite(page) && page > 0 ? Math.trunc(page) : 1 -} - -function normalizeFilter(value: unknown) { - return typeof value === 'string' && value.length > 0 ? value : 'all' -} - -const noop = () => {} -const rootSelectors = Array.from({ length: 10 }, (_, index) => index) -const routeSelectors = Array.from({ length: 6 }, (_, index) => index) -const linkGroups = Array.from({ length: 4 }, (_, index) => index) - -function RootParamsSubscriber() { - const params = useParams({ - strict: false, - select: (params) => runPerfSelectorComputation(Number(params.id ?? 0)), - }) - - void runPerfSelectorComputation(params) - return null -} - -function RootSearchSubscriber() { - const search = useSearch({ - strict: false, - select: (search) => runPerfSelectorComputation(Number(search.page ?? 0)), - }) - - void runPerfSelectorComputation(search) - return null -} - -function LinkPanel() { - return ( - <> - {linkGroups.map((groupIndex) => { - const itemsId = groupIndex === 0 ? 1 : groupIndex + 2 - const ctxId = groupIndex + 1 - - return ( -
- - {`Items ${itemsId}`} - - - {`Items 2 alt ${groupIndex}`} - - - {`Search ${groupIndex}`} - - - {`Context ${ctxId}`} - - ({ - page: prev.page + groupIndex + 1, - filter: prev.filter, - junk: `updater-${groupIndex}`, - })} - activeOptions={{ includeSearch: true }} - > - {({ isActive }) => - isActive - ? `Search updater active ${groupIndex}` - : `Search updater inactive ${groupIndex}` - } - -
- ) - })} - - ) -} - -function Root() { - return ( - <> - {rootSelectors.map((selector) => ( - - ))} - {rootSelectors.map((selector) => ( - - ))} - - - - ) -} - -const rootRoute = createRootRoute({ - component: Root, -}) - -const itemsRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/items/$id', - params: { - parse: (params) => ({ - ...params, - id: normalizePage(params.id), - }), - stringify: (params) => ({ - ...params, - id: `${params.id}`, - }), - }, - onEnter: noop, - onStay: noop, - onLeave: noop, - component: ItemsPage, -}) - -const itemDetailsRoute = createRoute({ - getParentRoute: () => itemsRoute, - path: 'details', - component: ItemDetailsPage, -}) - -const searchRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/search', - validateSearch: (search: Record) => ({ - page: normalizePage(search.page), - filter: normalizeFilter(search.filter), - }), - search: { - middlewares: [ - ({ search, next }) => { - const result = next(search) - return { - page: result.page, - filter: result.filter, - } - }, - ], - }, - loaderDeps: ({ search }) => ({ - page: search.page, - filter: search.filter, - }), - loader: ({ deps }) => ({ - seed: deps.page * 31 + deps.filter.length, - checksum: deps.page * 17 + deps.filter.length, - }), - staleTime: 60_000, - gcTime: 60_000, - component: SearchPage, -}) - -const contextRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/ctx/$id', - beforeLoad: ({ params }) => ({ - sectionSeed: Number(params.id) * 13 + 1, - }), - component: ContextPage, -}) - -function ItemParamsSubscriber() { - const params = itemsRoute.useParams({ - select: (params) => runPerfSelectorComputation(params.id), - }) - - void runPerfSelectorComputation(params) - return null -} - -function SearchStateSubscriber() { - const search = searchRoute.useSearch({ - select: (search) => - runPerfSelectorComputation(search.page + search.filter.length), - }) - - void runPerfSelectorComputation(search) - return null -} - -function SearchLoaderDepsSubscriber() { - const loaderDeps = searchRoute.useLoaderDeps({ - select: (loaderDeps) => - runPerfSelectorComputation(loaderDeps.page + loaderDeps.filter.length), - }) - - void runPerfSelectorComputation(loaderDeps) - return null -} - -function SearchLoaderDataSubscriber() { - const loaderData = searchRoute.useLoaderData({ - select: (loaderData) => - runPerfSelectorComputation(loaderData.seed + loaderData.checksum), - }) - - void runPerfSelectorComputation(loaderData) - return null -} - -function ContextParamsSubscriber() { - const params = contextRoute.useParams({ - select: (params) => runPerfSelectorComputation(Number(params.id)), - }) - - void runPerfSelectorComputation(params) - return null -} - -function ContextRouteSubscriber() { - const context = contextRoute.useRouteContext({ - select: (context) => runPerfSelectorComputation(context.sectionSeed), - }) - - void runPerfSelectorComputation(context) - return null -} - -function ItemsPage() { - return ( - <> - {routeSelectors.map((selector) => ( - - ))} - - Details - - - Preserve search on item - - - - ) -} - -function ItemDetailsPage() { - return ( - <> - {routeSelectors.map((selector) => ( - - ))} - - Back to item - - - ) -} - -function SearchPage() { - return ( - <> - {routeSelectors.map((selector) => ( - - ))} - {routeSelectors.map((selector) => ( - - ))} - {routeSelectors.map((selector) => ( - - ))} - ({ - page: prev.page + 1, - filter: prev.filter, - junk: 'local-updater', - })} - activeOptions={{ includeSearch: true }} - activeProps={{ className: 'active-link' }} - inactiveProps={{ className: 'inactive-link' }} - > - Next page - - - ) -} - -function ContextPage() { - return ( - <> - {routeSelectors.map((selector) => ( - - ))} - {routeSelectors.map((selector) => ( - - ))} - - ) -} - -export function mountTestApp(container: Element) { - const router = createRouter({ - history: createMemoryHistory({ - initialEntries: ['/items/0'], - }), - scrollRestoration: true, - routeTree: rootRoute.addChildren([ - itemsRoute.addChildren([itemDetailsRoute]), - searchRoute, - contextRoute, - ]), - }) - - const reactRoot = createRoot(container) - reactRoot.render() - - return { - router, - unmount() { - reactRoot.unmount() - }, - } -} diff --git a/benchmarks/client-nav/react/setup.ts b/benchmarks/client-nav/react/setup.ts deleted file mode 100644 index 11541383ec..0000000000 --- a/benchmarks/client-nav/react/setup.ts +++ /dev/null @@ -1,112 +0,0 @@ -import type { NavigateOptions } from '@tanstack/router-core' -import type * as App from './app' -import { getRequiredLink, waitForRequiredLink } from '../setup-helpers' - -const appModulePath = './dist/app.js' -const { mountTestApp } = (await import( - /* @vite-ignore */ appModulePath -)) as typeof App - -export function setup() { - if (process.env.NODE_ENV !== 'production') { - console.warn( - 'client-nav benchmark is running without NODE_ENV=production; React dev overhead will dominate results.', - ) - } - - let container: HTMLDivElement | undefined = undefined - let unmount: (() => void) | undefined = undefined - let unsub = () => {} - let stepIndex = 0 - let next: () => Promise = () => Promise.reject('Test not initialized') - - async function before() { - stepIndex = 0 - container = document.createElement('div') - document.body.append(container) - - const { router, unmount: dispose } = mountTestApp(container) - unmount = dispose - - let resolveRendered: () => void = () => {} - unsub = router.subscribe('onRendered', () => { - resolveRendered() - }) - - const navigate = (opts: NavigateOptions) => - new Promise((resolveNext) => { - resolveRendered = resolveNext - router.navigate(opts) - }) - - const click = (testId: string, cache?: Map) => - new Promise((resolveNext) => { - resolveRendered = resolveNext - - getRequiredLink(container!, testId, cache).dispatchEvent( - new MouseEvent('click', { - bubbles: true, - cancelable: true, - button: 0, - }), - ) - }) - - await router.load() - - const cachedLinks = new Map() - for (const testId of ['go-items-1', 'go-items-2', 'go-search', 'go-ctx']) { - await waitForRequiredLink(container, testId, cachedLinks) - } - - const steps = [ - () => click('go-items-1', cachedLinks), - () => click('items-details'), - () => - navigate({ - to: '/items/$id/details', - params: { id: 2 }, - replace: true, - }), - () => click('items-parent'), - () => click('go-search', cachedLinks), - () => click('search-next-page'), - () => - navigate({ - to: '/search', - search: { page: 1, filter: 'all' }, - replace: true, - }), - () => click('go-ctx', cachedLinks), - () => - navigate({ - to: '/ctx/$id', - params: { id: 2 }, - replace: true, - }), - () => click('go-items-2', cachedLinks), - ] as const - - next = () => { - const step = steps[stepIndex % steps.length]! - stepIndex += 1 - return step() - } - } - - function after() { - unmount?.() - container?.remove() - unsub() - } - - function tick() { - return next() - } - - return { - before, - tick, - after, - } -} diff --git a/benchmarks/client-nav/react/speed.bench.ts b/benchmarks/client-nav/react/speed.bench.ts deleted file mode 100644 index 944f182734..0000000000 --- a/benchmarks/client-nav/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { setup } from './setup' - -test('client-nav', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-side navigation loop (react)', - { beforeAll: scenario.before, afterAll: scenario.after }, - async () => { - for (let i = 0; i < 10; i++) { - await scenario.tick() - } - }, - ).run({ - warmupIterations: 100, - time: 10_000, - }) -}) diff --git a/benchmarks/client-nav/react/speed.flame.ts b/benchmarks/client-nav/react/speed.flame.ts deleted file mode 100644 index 285ccc63d7..0000000000 --- a/benchmarks/client-nav/react/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/react/tsconfig.json b/benchmarks/client-nav/react/tsconfig.json deleted file mode 100644 index 046a85af51..0000000000 --- a/benchmarks/client-nav/react/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "extends": "../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "allowImportingTsExtensions": true, - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "../jsdom.ts", - "setup.ts", - "vite.config.ts", - "../vitest.setup.ts" - ] -} diff --git a/benchmarks/client-nav/react/vite.config.ts b/benchmarks/client-nav/react/vite.config.ts deleted file mode 100644 index 7df3f80e71..0000000000 --- a/benchmarks/client-nav/react/vite.config.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { cpuSimulationExecArgv } from '../../cpu-simulation' - -// Anchor the project root to the package directory so this config resolves -// identically when run directly and as part of an aggregate `projects` config. -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(), - react(), - ], - build: { - outDir: './react/dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './react/app.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - 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/project.json b/benchmarks/client-nav/scenarios/async-pipeline/react/project.json deleted file mode 100644 index 44ab55ccfe..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-async-pipeline-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/async-pipeline/react/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/setup.ts b/benchmarks/client-nav/scenarios/async-pipeline/react/setup.ts deleted file mode 100644 index 130583b190..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, steps } 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, - assertAfterStep: assertStepResult, - }) -} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/speed.bench.ts b/benchmarks/client-nav/scenarios/async-pipeline/react/speed.bench.ts deleted file mode 100644 index 65dab0781e..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-async-pipeline', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-async-pipeline 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/async-pipeline/react/speed.flame.ts b/benchmarks/client-nav/scenarios/async-pipeline/react/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/src/main.tsx b/benchmarks/client-nav/scenarios/async-pipeline/react/src/main.tsx deleted file mode 100644 index cab86a1272..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/src/main.tsx +++ /dev/null @@ -1,39 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { RouterProvider, createRouter } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - defaultPendingMs: 0, - defaultPendingMinMs: 0, - }) -} - -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/async-pipeline/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routeTree.gen.ts deleted file mode 100644 index 9c79bab826..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routeTree.gen.ts +++ /dev/null @@ -1,140 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const NestedRoute = NestedRouteImport.update({ - id: '/nested', - path: '/nested', - getParentRoute: () => rootRouteImport, -} as any) -const CtxIdRoute = CtxIdRouteImport.update({ - id: '/ctx/$id', - path: '/ctx/$id', - getParentRoute: () => rootRouteImport, -} as any) -const NestedIdRoute = NestedIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => NestedRoute, -} as any) -const SlowIdRoute = SlowIdRouteImport.update({ - id: '/slow/$id', - path: '/slow/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/nested': typeof NestedRouteWithChildren - '/ctx/$id': typeof CtxIdRoute - '/nested/$id': typeof NestedIdRoute - '/slow/$id': typeof SlowIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/nested': typeof NestedRouteWithChildren - '/ctx/$id': typeof CtxIdRoute - '/nested/$id': typeof NestedIdRoute - '/slow/$id': typeof SlowIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/nested': typeof NestedRouteWithChildren - '/ctx/$id': typeof CtxIdRoute - '/nested/$id': typeof NestedIdRoute - '/slow/$id': typeof SlowIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/nested' | '/ctx/$id' | '/nested/$id' | '/slow/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/nested' | '/ctx/$id' | '/nested/$id' | '/slow/$id' - id: '__root__' | '/' | '/nested' | '/ctx/$id' | '/nested/$id' | '/slow/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - NestedRoute: typeof NestedRouteWithChildren - CtxIdRoute: typeof CtxIdRoute - SlowIdRoute: typeof SlowIdRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/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': { - id: '/nested/$id' - path: '/$id' - fullPath: '/nested/$id' - preLoaderRoute: typeof NestedIdRouteImport - parentRoute: typeof NestedRoute - } - '/slow/$id': { - id: '/slow/$id' - path: '/slow/$id' - fullPath: '/slow/$id' - preLoaderRoute: typeof SlowIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -interface NestedRouteChildren { - NestedIdRoute: typeof NestedIdRoute -} - -const NestedRouteChildren: NestedRouteChildren = { - NestedIdRoute: NestedIdRoute, -} - -const NestedRouteWithChildren = - NestedRoute._addFileChildren(NestedRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - NestedRoute: NestedRouteWithChildren, - CtxIdRoute: CtxIdRoute, - SlowIdRoute: SlowIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/__root.tsx deleted file mode 100644 index 1cc8566678..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/__root.tsx +++ /dev/null @@ -1,50 +0,0 @@ -import { Link, Outlet, createRootRoute } from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -const ids = ['1', '2'] - -function RootComponent() { - return ( - <> - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/ctx.$id.tsx b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/ctx.$id.tsx deleted file mode 100644 index d644376b7b..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/ctx.$id.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { - ctxSeedValue, - ctxStateValue, - deferredHops, - hopDelay, -} from '../../../shared' - -export const Route = createFileRoute('/ctx/$id')({ - staleTime: 0, - gcTime: 0, - beforeLoad: async ({ params }) => { - await hopDelay(deferredHops) - return { ctxSeed: ctxSeedValue(params.id) } - }, - loader: ({ params, context }) => { - if (context.ctxSeed !== ctxSeedValue(params.id)) { - throw new Error('beforeLoad context missing in loader') - } - return { value: ctxStateValue(params.id) } - }, - component: CtxPage, -}) - -function CtxPage() { - const data = Route.useLoaderData() - - return
{data.value}
-} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/index.tsx b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/index.tsx deleted file mode 100644 index 5b6d70e744..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/index.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: HomePage, -}) - -function HomePage() { - return ( -
-
home
-
- ) -} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/nested.$id.tsx b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/nested.$id.tsx deleted file mode 100644 index bc002c303f..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/nested.$id.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { deferredHops, hopDelay, nestedStateValue } from '../../../shared' - -export const Route = createFileRoute('/nested/$id')({ - staleTime: 0, - gcTime: 0, - loader: async ({ params }) => { - await hopDelay(deferredHops) - return { value: nestedStateValue(params.id) } - }, - component: NestedPage, -}) - -function NestedPage() { - const data = Route.useLoaderData() - - return
{data.value}
-} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/nested.tsx b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/nested.tsx deleted file mode 100644 index 443f592373..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/nested.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import { deferredHops, hopDelay, nestedLayoutValue } from '../../../shared' - -export const Route = createFileRoute('/nested')({ - staleTime: 0, - gcTime: 0, - loader: async () => { - await hopDelay(deferredHops) - return { value: nestedLayoutValue() } - }, - component: NestedLayout, -}) - -function NestedLayout() { - const data = Route.useLoaderData() - - return ( -
-
{data.value}
- -
- ) -} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/slow.$id.tsx b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/slow.$id.tsx deleted file mode 100644 index 4839b0ca6d..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/slow.$id.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { deferredHops, hopDelay, slowStateValue } from '../../../shared' - -export const Route = createFileRoute('/slow/$id')({ - staleTime: 0, - gcTime: 0, - loader: async ({ params }) => { - await hopDelay(deferredHops) - return { value: slowStateValue(params.id) } - }, - component: SlowPage, -}) - -function SlowPage() { - const data = Route.useLoaderData() - - return
{data.value}
-} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/tsconfig.json b/benchmarks/client-nav/scenarios/async-pipeline/react/tsconfig.json deleted file mode 100644 index 1d59cbb450..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/vite.config.ts b/benchmarks/client-nav/scenarios/async-pipeline/react/vite.config.ts deleted file mode 100644 index e36a5244b1..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/vite.config.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'react', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav async-pipeline (react)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - }, -}) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/shared.ts b/benchmarks/client-nav/scenarios/async-pipeline/shared.ts deleted file mode 100644 index 02123309b2..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/shared.ts +++ /dev/null @@ -1,113 +0,0 @@ -/** - * Shared definition of the `async-pipeline` scenario: the router's async - * load pipeline — fully async loaders (transition-held navigations), async - * `beforeLoad` context building, and parallel nested async loaders. All async - * work resolves through counted 0ms timer hops so the workload is - * deterministic. The three framework apps consume these builders so the - * workload is identical modulo the rendering layer. - * - * Note: component-level deferred consumption (`Await`/Suspense) is - * intentionally NOT covered. React throttles every Suspense reveal (with or - * without a fallback, including `pendingComponent`) by ~300ms of wall-clock - * time, which cannot be made deterministic; the async work is exercised - * through the router's own pipeline instead. - */ -import type { ScenarioStep } from '../harness' - -/** - * Resolves after exactly `hops` chained macrotask turns. Uses `setImmediate` - * rather than `setTimeout(0)`: both are counted, deterministic event-loop - * turns, but timers cost ~3-4 syscalls per hop (timerfd + epoll) and CodSpeed - * excludes syscall time from the measure — inconsistently past a threshold — - * which destabilized the hop-heavy benches. - */ -export function hopDelay(hops: number): Promise { - let promise = Promise.resolve() - for (let i = 0; i < hops; i++) { - promise = promise.then( - () => new Promise((resolve) => setImmediate(() => resolve())), - ) - } - return promise -} - -/** Number of 0ms hops every async loader/beforeLoad takes before resolving. */ -export const deferredHops = 2 - -function checksum(seed: number) { - let value = seed | 0 - for (let index = 0; index < 20; index++) { - value = (value * 1664525 + 1013904223 + index) >>> 0 - } - return value -} - -export function slowStateValue(id: string) { - return `state-${id}-${checksum(Number(id) * 71 + 3)}` -} - -export function ctxSeedValue(id: string) { - return checksum(Number(id) * 13 + 1) -} - -export function ctxStateValue(id: string) { - return `ctx-${id}-${checksum(ctxSeedValue(id) + 5)}` -} - -export function nestedLayoutValue() { - return `layout-${checksum(97)}` -} - -export function nestedStateValue(id: string) { - return `nested-${id}-${checksum(Number(id) * 41 + 11)}` -} - -function markerText(testId: string) { - return ( - document.querySelector(`[data-testid="${testId}"]`)?.textContent ?? - undefined - ) -} - -function step(testId: string, isSettled: () => boolean): ScenarioStep { - return { type: 'click', testId, isSettled } -} - -export const steps: ReadonlyArray = [ - step('go-slow-1', () => markerText('slow-state') === slowStateValue('1')), - step('go-ctx-1', () => markerText('ctx-state') === ctxStateValue('1')), - step( - 'go-nested-1', - () => - markerText('nested-layout') === nestedLayoutValue() && - markerText('nested-state') === nestedStateValue('1'), - ), - step('go-slow-2', () => markerText('slow-state') === slowStateValue('2')), - step('go-ctx-2', () => markerText('ctx-state') === ctxStateValue('2')), - step( - 'go-nested-2', - () => markerText('nested-state') === nestedStateValue('2'), - ), - step('go-home', () => markerText('home-state') === 'home'), -] - -export function assertStepResult(stepIndex: number) { - const current = steps[stepIndex]! - if (typeof current === 'string' || !('isSettled' in current)) { - return - } - if (!current.isSettled!()) { - throw new Error( - `Unexpected document state after async-pipeline step ${stepIndex}`, - ) - } -} - -// Two laps through the 7-step sequence per benchmark iteration. -export const ticksPerIteration = 14 - -export const benchOptions = { - warmupIterations: 100, - time: 10_000, - throws: true, -} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/project.json b/benchmarks/client-nav/scenarios/async-pipeline/solid/project.json deleted file mode 100644 index 2fce426b1e..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-async-pipeline-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/async-pipeline/solid/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/setup.ts b/benchmarks/client-nav/scenarios/async-pipeline/solid/setup.ts deleted file mode 100644 index 6a46971603..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, steps } 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, - assertAfterStep: assertStepResult, - }) -} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.bench.ts deleted file mode 100644 index acef710469..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-async-pipeline', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-async-pipeline 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/async-pipeline/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/main.tsx b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/main.tsx deleted file mode 100644 index 4c6d49f501..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/main.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { render } from 'solid-js/web' -import { RouterProvider, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - defaultPendingMs: 0, - defaultPendingMinMs: 0, - }) -} - -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/async-pipeline/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routeTree.gen.ts deleted file mode 100644 index 27b9498b11..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,140 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const NestedRoute = NestedRouteImport.update({ - id: '/nested', - path: '/nested', - getParentRoute: () => rootRouteImport, -} as any) -const CtxIdRoute = CtxIdRouteImport.update({ - id: '/ctx/$id', - path: '/ctx/$id', - getParentRoute: () => rootRouteImport, -} as any) -const NestedIdRoute = NestedIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => NestedRoute, -} as any) -const SlowIdRoute = SlowIdRouteImport.update({ - id: '/slow/$id', - path: '/slow/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/nested': typeof NestedRouteWithChildren - '/ctx/$id': typeof CtxIdRoute - '/nested/$id': typeof NestedIdRoute - '/slow/$id': typeof SlowIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/nested': typeof NestedRouteWithChildren - '/ctx/$id': typeof CtxIdRoute - '/nested/$id': typeof NestedIdRoute - '/slow/$id': typeof SlowIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/nested': typeof NestedRouteWithChildren - '/ctx/$id': typeof CtxIdRoute - '/nested/$id': typeof NestedIdRoute - '/slow/$id': typeof SlowIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/nested' | '/ctx/$id' | '/nested/$id' | '/slow/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/nested' | '/ctx/$id' | '/nested/$id' | '/slow/$id' - id: '__root__' | '/' | '/nested' | '/ctx/$id' | '/nested/$id' | '/slow/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - NestedRoute: typeof NestedRouteWithChildren - CtxIdRoute: typeof CtxIdRoute - SlowIdRoute: typeof SlowIdRoute -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/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': { - id: '/nested/$id' - path: '/$id' - fullPath: '/nested/$id' - preLoaderRoute: typeof NestedIdRouteImport - parentRoute: typeof NestedRoute - } - '/slow/$id': { - id: '/slow/$id' - path: '/slow/$id' - fullPath: '/slow/$id' - preLoaderRoute: typeof SlowIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -interface NestedRouteChildren { - NestedIdRoute: typeof NestedIdRoute -} - -const NestedRouteChildren: NestedRouteChildren = { - NestedIdRoute: NestedIdRoute, -} - -const NestedRouteWithChildren = - NestedRoute._addFileChildren(NestedRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - NestedRoute: NestedRouteWithChildren, - CtxIdRoute: CtxIdRoute, - SlowIdRoute: SlowIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/__root.tsx deleted file mode 100644 index 7d3647fee8..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/__root.tsx +++ /dev/null @@ -1,46 +0,0 @@ -import { For } from 'solid-js' -import { Link, Outlet, createRootRoute } from '@tanstack/solid-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -const ids = ['1', '2'] - -function RootComponent() { - return ( - <> - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/ctx.$id.tsx b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/ctx.$id.tsx deleted file mode 100644 index e757b57b9d..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/ctx.$id.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { - ctxSeedValue, - ctxStateValue, - deferredHops, - hopDelay, -} from '../../../shared' - -export const Route = createFileRoute('/ctx/$id')({ - staleTime: 0, - gcTime: 0, - beforeLoad: async ({ params }) => { - await hopDelay(deferredHops) - return { ctxSeed: ctxSeedValue(params.id) } - }, - loader: ({ params, context }) => { - if (context.ctxSeed !== ctxSeedValue(params.id)) { - throw new Error('beforeLoad context missing in loader') - } - return { value: ctxStateValue(params.id) } - }, - component: CtxPage, -}) - -function CtxPage() { - const data = Route.useLoaderData() - - return
{data().value}
-} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/index.tsx b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/index.tsx deleted file mode 100644 index 12907d440d..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/index.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/')({ - component: HomePage, -}) - -function HomePage() { - return ( -
-
home
-
- ) -} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/nested.$id.tsx b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/nested.$id.tsx deleted file mode 100644 index 5518ccf498..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/nested.$id.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { deferredHops, hopDelay, nestedStateValue } from '../../../shared' - -export const Route = createFileRoute('/nested/$id')({ - staleTime: 0, - gcTime: 0, - loader: async ({ params }) => { - await hopDelay(deferredHops) - return { value: nestedStateValue(params.id) } - }, - component: NestedPage, -}) - -function NestedPage() { - const data = Route.useLoaderData() - - return
{data().value}
-} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/nested.tsx b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/nested.tsx deleted file mode 100644 index fdc939dc95..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/nested.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' -import { deferredHops, hopDelay, nestedLayoutValue } from '../../../shared' - -export const Route = createFileRoute('/nested')({ - staleTime: 0, - gcTime: 0, - loader: async () => { - await hopDelay(deferredHops) - return { value: nestedLayoutValue() } - }, - component: NestedLayout, -}) - -function NestedLayout() { - const data = Route.useLoaderData() - - return ( -
-
{data().value}
- -
- ) -} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/slow.$id.tsx b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/slow.$id.tsx deleted file mode 100644 index 4c229407e1..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/slow.$id.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { deferredHops, hopDelay, slowStateValue } from '../../../shared' - -export const Route = createFileRoute('/slow/$id')({ - staleTime: 0, - gcTime: 0, - loader: async ({ params }) => { - await hopDelay(deferredHops) - return { value: slowStateValue(params.id) } - }, - component: SlowPage, -}) - -function SlowPage() { - const data = Route.useLoaderData() - - return
{data().value}
-} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/tsconfig.json b/benchmarks/client-nav/scenarios/async-pipeline/solid/tsconfig.json deleted file mode 100644 index 98d76ad6b8..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/vite.config.ts b/benchmarks/client-nav/scenarios/async-pipeline/solid/vite.config.ts deleted file mode 100644 index 214da8042e..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/vite.config.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import solid from 'vite-plugin-solid' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'solid', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - resolve: { - conditions: ['solid', 'browser'], - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav async-pipeline (solid)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/project.json b/benchmarks/client-nav/scenarios/async-pipeline/vue/project.json deleted file mode 100644 index 911bb61e38..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-async-pipeline-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/async-pipeline/vue/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/setup.ts b/benchmarks/client-nav/scenarios/async-pipeline/vue/setup.ts deleted file mode 100644 index 97b74b3892..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, steps } 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, - assertAfterStep: assertStepResult, - }) -} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.bench.ts deleted file mode 100644 index f0fd3e58df..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-async-pipeline', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-async-pipeline 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/async-pipeline/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/main.tsx b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/main.tsx deleted file mode 100644 index e1bfa5965f..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/main.tsx +++ /dev/null @@ -1,43 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import * as Vue from 'vue' -import { RouterProvider, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - defaultPendingMs: 0, - defaultPendingMinMs: 0, - }) -} - -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/async-pipeline/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routeTree.gen.ts deleted file mode 100644 index 66b9efd7aa..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,140 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const NestedRoute = NestedRouteImport.update({ - id: '/nested', - path: '/nested', - getParentRoute: () => rootRouteImport, -} as any) -const CtxIdRoute = CtxIdRouteImport.update({ - id: '/ctx/$id', - path: '/ctx/$id', - getParentRoute: () => rootRouteImport, -} as any) -const NestedIdRoute = NestedIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => NestedRoute, -} as any) -const SlowIdRoute = SlowIdRouteImport.update({ - id: '/slow/$id', - path: '/slow/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/nested': typeof NestedRouteWithChildren - '/ctx/$id': typeof CtxIdRoute - '/nested/$id': typeof NestedIdRoute - '/slow/$id': typeof SlowIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/nested': typeof NestedRouteWithChildren - '/ctx/$id': typeof CtxIdRoute - '/nested/$id': typeof NestedIdRoute - '/slow/$id': typeof SlowIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/nested': typeof NestedRouteWithChildren - '/ctx/$id': typeof CtxIdRoute - '/nested/$id': typeof NestedIdRoute - '/slow/$id': typeof SlowIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/nested' | '/ctx/$id' | '/nested/$id' | '/slow/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/nested' | '/ctx/$id' | '/nested/$id' | '/slow/$id' - id: '__root__' | '/' | '/nested' | '/ctx/$id' | '/nested/$id' | '/slow/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - NestedRoute: typeof NestedRouteWithChildren - CtxIdRoute: typeof CtxIdRoute - SlowIdRoute: typeof SlowIdRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/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': { - id: '/nested/$id' - path: '/$id' - fullPath: '/nested/$id' - preLoaderRoute: typeof NestedIdRouteImport - parentRoute: typeof NestedRoute - } - '/slow/$id': { - id: '/slow/$id' - path: '/slow/$id' - fullPath: '/slow/$id' - preLoaderRoute: typeof SlowIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -interface NestedRouteChildren { - NestedIdRoute: typeof NestedIdRoute -} - -const NestedRouteChildren: NestedRouteChildren = { - NestedIdRoute: NestedIdRoute, -} - -const NestedRouteWithChildren = - NestedRoute._addFileChildren(NestedRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - NestedRoute: NestedRouteWithChildren, - CtxIdRoute: CtxIdRoute, - SlowIdRoute: SlowIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/__root.tsx deleted file mode 100644 index c477ab7e68..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/__root.tsx +++ /dev/null @@ -1,53 +0,0 @@ -import * as Vue from 'vue' -import { Link, Outlet, createRootRoute } from '@tanstack/vue-router' - -const ids = ['1', '2'] - -const RootComponent = Vue.defineComponent({ - setup() { - return () => ( - <> - - - - ) - }, -}) - -export const Route = createRootRoute({ - component: RootComponent, -}) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/ctx.$id.tsx b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/ctx.$id.tsx deleted file mode 100644 index d995f1ff6c..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/ctx.$id.tsx +++ /dev/null @@ -1,32 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' -import { - ctxSeedValue, - ctxStateValue, - deferredHops, - hopDelay, -} from '../../../shared' - -const CtxPage = Vue.defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () =>
{data.value.value}
- }, -}) - -export const Route = createFileRoute('/ctx/$id')({ - staleTime: 0, - gcTime: 0, - beforeLoad: async ({ params }) => { - await hopDelay(deferredHops) - return { ctxSeed: ctxSeedValue(params.id) } - }, - loader: ({ params, context }) => { - if (context.ctxSeed !== ctxSeedValue(params.id)) { - throw new Error('beforeLoad context missing in loader') - } - return { value: ctxStateValue(params.id) } - }, - component: CtxPage, -}) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/index.tsx b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/index.tsx deleted file mode 100644 index 128e132190..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/index.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const HomePage = Vue.defineComponent({ - setup() { - return () => ( -
-
home
-
- ) - }, -}) - -export const Route = createFileRoute('/')({ - component: HomePage, -}) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/nested.$id.tsx b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/nested.$id.tsx deleted file mode 100644 index bbeaaa7dd7..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/nested.$id.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' -import { deferredHops, hopDelay, nestedStateValue } from '../../../shared' - -const NestedPage = Vue.defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () =>
{data.value.value}
- }, -}) - -export const Route = createFileRoute('/nested/$id')({ - staleTime: 0, - gcTime: 0, - loader: async ({ params }) => { - await hopDelay(deferredHops) - return { value: nestedStateValue(params.id) } - }, - component: NestedPage, -}) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/nested.tsx b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/nested.tsx deleted file mode 100644 index 763657dfc6..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/nested.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import * as Vue from 'vue' -import { Outlet, createFileRoute } from '@tanstack/vue-router' -import { deferredHops, hopDelay, nestedLayoutValue } from '../../../shared' - -const NestedLayout = Vue.defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () => ( -
-
{data.value.value}
- -
- ) - }, -}) - -export const Route = createFileRoute('/nested')({ - staleTime: 0, - gcTime: 0, - loader: async () => { - await hopDelay(deferredHops) - return { value: nestedLayoutValue() } - }, - component: NestedLayout, -}) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/slow.$id.tsx b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/slow.$id.tsx deleted file mode 100644 index c9afccba97..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/slow.$id.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' -import { deferredHops, hopDelay, slowStateValue } from '../../../shared' - -const SlowPage = Vue.defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () =>
{data.value.value}
- }, -}) - -export const Route = createFileRoute('/slow/$id')({ - staleTime: 0, - gcTime: 0, - loader: async ({ params }) => { - await hopDelay(deferredHops) - return { value: slowStateValue(params.id) } - }, - component: SlowPage, -}) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/tsconfig.json b/benchmarks/client-nav/scenarios/async-pipeline/vue/tsconfig.json deleted file mode 100644 index 7786fc3da9..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/vite.config.ts b/benchmarks/client-nav/scenarios/async-pipeline/vue/vite.config.ts deleted file mode 100644 index ce4fa7318a..0000000000 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/vite.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'vue', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav async-pipeline (vue)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - }, -}) diff --git a/benchmarks/client-nav/scenarios/control-flow/react/project.json b/benchmarks/client-nav/scenarios/control-flow/react/project.json deleted file mode 100644 index e3e580911f..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-control-flow-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/control-flow/react/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/control-flow/react/setup.ts b/benchmarks/client-nav/scenarios/control-flow/react/setup.ts deleted file mode 100644 index 130583b190..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, steps } 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, - assertAfterStep: assertStepResult, - }) -} diff --git a/benchmarks/client-nav/scenarios/control-flow/react/speed.bench.ts b/benchmarks/client-nav/scenarios/control-flow/react/speed.bench.ts deleted file mode 100644 index d6f2190be7..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-control-flow', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-control-flow 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/control-flow/react/speed.flame.ts b/benchmarks/client-nav/scenarios/control-flow/react/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/control-flow/react/src/main.tsx b/benchmarks/client-nav/scenarios/control-flow/react/src/main.tsx deleted file mode 100644 index da9e63d293..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/src/main.tsx +++ /dev/null @@ -1,39 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { RouterProvider, createRouter } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - // The scenario intentionally throws loader errors every lap; keep React 19's - // default per-caught-error console reporting out of the measured loop. - const reactRoot = createRoot(container, { onCaughtError: () => {} }) - reactRoot.render() - - return { - router, - unmount() { - reactRoot.unmount() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/control-flow/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/control-flow/react/src/routeTree.gen.ts deleted file mode 100644 index 7b6db9b237..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/src/routeTree.gen.ts +++ /dev/null @@ -1,156 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const BrokenRoute = BrokenRouteImport.update({ - id: '/broken', - path: '/broken', - getParentRoute: () => rootRouteImport, -} as any) -const Hop1Route = Hop1RouteImport.update({ - id: '/hop1', - path: '/hop1', - 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({ - id: '/missing/$id', - path: '/missing/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/broken': typeof BrokenRoute - '/hop1': typeof Hop1Route - '/hop2': typeof Hop2Route - '/target': typeof TargetRoute - '/missing/$id': typeof MissingIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/broken': typeof BrokenRoute - '/hop1': typeof Hop1Route - '/hop2': typeof Hop2Route - '/target': typeof TargetRoute - '/missing/$id': typeof MissingIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/broken': typeof BrokenRoute - '/hop1': typeof Hop1Route - '/hop2': typeof Hop2Route - '/target': typeof TargetRoute - '/missing/$id': typeof MissingIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/broken' | '/hop1' | '/hop2' | '/target' | '/missing/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/broken' | '/hop1' | '/hop2' | '/target' | '/missing/$id' - id: - | '__root__' - | '/' - | '/broken' - | '/hop1' - | '/hop2' - | '/target' - | '/missing/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - BrokenRoute: typeof BrokenRoute - Hop1Route: typeof Hop1Route - Hop2Route: typeof Hop2Route - TargetRoute: typeof TargetRoute - MissingIdRoute: typeof MissingIdRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/broken': { - id: '/broken' - path: '/broken' - fullPath: '/broken' - preLoaderRoute: typeof BrokenRouteImport - parentRoute: typeof rootRouteImport - } - '/hop1': { - id: '/hop1' - path: '/hop1' - fullPath: '/hop1' - preLoaderRoute: typeof Hop1RouteImport - 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': { - id: '/missing/$id' - path: '/missing/$id' - fullPath: '/missing/$id' - preLoaderRoute: typeof MissingIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - BrokenRoute: BrokenRoute, - Hop1Route: Hop1Route, - Hop2Route: Hop2Route, - TargetRoute: TargetRoute, - MissingIdRoute: MissingIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/__root.tsx deleted file mode 100644 index 63d5feb901..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/__root.tsx +++ /dev/null @@ -1,52 +0,0 @@ -import { - Link, - Outlet, - createRootRoute, - useLocation, -} from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function LocationMarker() { - const pathname = useLocation({ select: (location) => location.pathname }) - return {pathname} -} - -function RootComponent() { - return ( - <> - - - - - ) -} 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 deleted file mode 100644 index b11bb845bc..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/broken.tsx +++ /dev/null @@ -1,20 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { errorMessage } from '../../../shared' -import type { ErrorComponentProps } from '@tanstack/react-router' - -export const Route = createFileRoute('/broken')({ - staleTime: 0, - gcTime: 0, - loader: () => { - throw new Error(errorMessage) - }, - errorComponent: BrokenError, -}) - -function BrokenError(props: ErrorComponentProps) { - return ( -
- {props.error instanceof Error ? props.error.message : String(props.error)} -
- ) -} diff --git a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/hop1.tsx b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/hop1.tsx deleted file mode 100644 index aacba39384..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/hop1.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute, redirect } from '@tanstack/react-router' - -export const Route = createFileRoute('/hop1')({ - staleTime: 0, - gcTime: 0, - loader: () => { - throw redirect({ to: '/hop2' }) - }, -}) diff --git a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/hop2.tsx b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/hop2.tsx deleted file mode 100644 index db31abe9f3..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/hop2.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute, redirect } from '@tanstack/react-router' - -export const Route = createFileRoute('/hop2')({ - staleTime: 0, - gcTime: 0, - loader: () => { - throw redirect({ to: '/target' }) - }, -}) diff --git a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/index.tsx b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/index.tsx deleted file mode 100644 index 24e856ea15..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: HomePage, -}) - -function HomePage() { - return
home
-} diff --git a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/missing.$id.tsx b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/missing.$id.tsx deleted file mode 100644 index 0c807bb2bc..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/missing.$id.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import { createFileRoute, notFound } from '@tanstack/react-router' - -export const Route = createFileRoute('/missing/$id')({ - staleTime: 0, - gcTime: 0, - loader: ({ params }) => { - if (params.id === 'gone') { - throw notFound() - } - return { id: params.id } - }, - component: MissingPage, - notFoundComponent: MissingNotFound, -}) - -function MissingPage() { - const data = Route.useLoaderData() - return
{data.id}
-} - -function MissingNotFound() { - return
missing not found
-} diff --git a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/target.tsx b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/target.tsx deleted file mode 100644 index 280f65835e..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/target.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/target')({ - component: TargetPage, -}) - -function TargetPage() { - return
target
-} diff --git a/benchmarks/client-nav/scenarios/control-flow/react/tsconfig.json b/benchmarks/client-nav/scenarios/control-flow/react/tsconfig.json deleted file mode 100644 index 1d59cbb450..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/control-flow/react/vite.config.ts b/benchmarks/client-nav/scenarios/control-flow/react/vite.config.ts deleted file mode 100644 index 1eefca0fc3..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/react/vite.config.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'react', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav control-flow (react)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - }, -}) diff --git a/benchmarks/client-nav/scenarios/control-flow/shared.ts b/benchmarks/client-nav/scenarios/control-flow/shared.ts deleted file mode 100644 index c4f368bee1..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/shared.ts +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Shared definition of the `control-flow` scenario: loader-thrown redirects - * (including a 2-hop chain), notFound() rendering, loader errors through the - * route error boundary, and recovery navigation resetting the boundary. - */ -import type { ScenarioStep } from '../harness' - -export const errorMessage = 'bench-error' - -export const steps: ReadonlyArray = [ - { - type: 'click', - testId: 'go-hop1', - // The click lands on /hop1 whose loader chains redirects to /target; wait - // until the post-redirect location is committed before finishing the step. - isSettled: () => - document.querySelector('[data-testid="loc"]')?.textContent === '/target', - }, - 'go-missing-ok', - 'go-missing-gone', - 'go-broken', - 'go-target', - 'go-missing-gone', - 'home', -] - -interface StepExpectation { - loc: string - present: ReadonlyArray - absent?: ReadonlyArray - errorText?: string -} - -const expectations: ReadonlyArray = [ - { loc: '/target', present: ['target-state'] }, - { loc: '/missing/exists', present: ['missing-state'] }, - { - loc: '/missing/gone', - present: ['not-found-state'], - absent: ['missing-state'], - }, - { loc: '/broken', present: ['error-state'], errorText: errorMessage }, - { loc: '/target', present: ['target-state'], absent: ['error-state'] }, - { loc: '/missing/gone', present: ['not-found-state'] }, - { loc: '/', present: ['home-state'] }, -] - -export function assertStepResult(stepIndex: number, container: HTMLElement) { - const expectation = expectations[stepIndex % expectations.length]! - - const loc = container.querySelector('[data-testid="loc"]') - if (loc?.textContent !== expectation.loc) { - throw new Error( - `Expected location "${expectation.loc}" after step ${stepIndex}, received "${loc?.textContent ?? ''}"`, - ) - } - - for (const testId of expectation.present) { - const element = container.querySelector(`[data-testid="${testId}"]`) - if (!element) { - throw new Error( - `Expected [data-testid="${testId}"] after step ${stepIndex}`, - ) - } - if ( - expectation.errorText && - !element.textContent?.includes(expectation.errorText) - ) { - throw new Error( - `Expected [data-testid="${testId}"] to include "${expectation.errorText}", received "${element.textContent}"`, - ) - } - } - - for (const testId of expectation.absent ?? []) { - if (container.querySelector(`[data-testid="${testId}"]`)) { - throw new Error( - `Expected [data-testid="${testId}"] to be absent after step ${stepIndex}`, - ) - } - } -} - -// Two laps through the 7-step sequence per benchmark iteration. -export const ticksPerIteration = 14 - -export const benchOptions = { - warmupIterations: 100, - time: 10_000, - throws: true, -} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/project.json b/benchmarks/client-nav/scenarios/control-flow/solid/project.json deleted file mode 100644 index 2b5154d385..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-control-flow-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/control-flow/solid/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/setup.ts b/benchmarks/client-nav/scenarios/control-flow/solid/setup.ts deleted file mode 100644 index 6a46971603..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, steps } 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, - assertAfterStep: assertStepResult, - }) -} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/control-flow/solid/speed.bench.ts deleted file mode 100644 index d803d2a313..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-control-flow', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-control-flow 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/control-flow/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/control-flow/solid/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/main.tsx b/benchmarks/client-nav/scenarios/control-flow/solid/src/main.tsx deleted file mode 100644 index fa9d239418..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/src/main.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { render } from 'solid-js/web' -import { RouterProvider, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const unmount = render(() => , container) - - return { - router, - unmount, - } -} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/control-flow/solid/src/routeTree.gen.ts deleted file mode 100644 index cd84f99d5d..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,156 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const BrokenRoute = BrokenRouteImport.update({ - id: '/broken', - path: '/broken', - getParentRoute: () => rootRouteImport, -} as any) -const Hop1Route = Hop1RouteImport.update({ - id: '/hop1', - path: '/hop1', - 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({ - id: '/missing/$id', - path: '/missing/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/broken': typeof BrokenRoute - '/hop1': typeof Hop1Route - '/hop2': typeof Hop2Route - '/target': typeof TargetRoute - '/missing/$id': typeof MissingIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/broken': typeof BrokenRoute - '/hop1': typeof Hop1Route - '/hop2': typeof Hop2Route - '/target': typeof TargetRoute - '/missing/$id': typeof MissingIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/broken': typeof BrokenRoute - '/hop1': typeof Hop1Route - '/hop2': typeof Hop2Route - '/target': typeof TargetRoute - '/missing/$id': typeof MissingIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/broken' | '/hop1' | '/hop2' | '/target' | '/missing/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/broken' | '/hop1' | '/hop2' | '/target' | '/missing/$id' - id: - | '__root__' - | '/' - | '/broken' - | '/hop1' - | '/hop2' - | '/target' - | '/missing/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - BrokenRoute: typeof BrokenRoute - Hop1Route: typeof Hop1Route - Hop2Route: typeof Hop2Route - TargetRoute: typeof TargetRoute - MissingIdRoute: typeof MissingIdRoute -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/broken': { - id: '/broken' - path: '/broken' - fullPath: '/broken' - preLoaderRoute: typeof BrokenRouteImport - parentRoute: typeof rootRouteImport - } - '/hop1': { - id: '/hop1' - path: '/hop1' - fullPath: '/hop1' - preLoaderRoute: typeof Hop1RouteImport - 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': { - id: '/missing/$id' - path: '/missing/$id' - fullPath: '/missing/$id' - preLoaderRoute: typeof MissingIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - BrokenRoute: BrokenRoute, - Hop1Route: Hop1Route, - Hop2Route: Hop2Route, - TargetRoute: TargetRoute, - MissingIdRoute: MissingIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/__root.tsx deleted file mode 100644 index 1bce9e8a3e..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/__root.tsx +++ /dev/null @@ -1,52 +0,0 @@ -import { - Link, - Outlet, - createRootRoute, - useLocation, -} from '@tanstack/solid-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function LocationMarker() { - const pathname = useLocation({ select: (location) => location.pathname }) - return {pathname()} -} - -function RootComponent() { - return ( - <> - - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/broken.tsx b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/broken.tsx deleted file mode 100644 index 9931ef9c58..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/broken.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { errorMessage } from '../../../shared' -import type { ErrorComponentProps } from '@tanstack/solid-router' - -export const Route = createFileRoute('/broken')({ - staleTime: 0, - gcTime: 0, - loader: () => { - throw new Error(errorMessage) - }, - errorComponent: BrokenError, -}) - -function BrokenError(props: ErrorComponentProps) { - return
{props.error.message}
-} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/hop1.tsx b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/hop1.tsx deleted file mode 100644 index 1aedb481ec..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/hop1.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute, redirect } from '@tanstack/solid-router' - -export const Route = createFileRoute('/hop1')({ - staleTime: 0, - gcTime: 0, - loader: () => { - throw redirect({ to: '/hop2' }) - }, -}) diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/hop2.tsx b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/hop2.tsx deleted file mode 100644 index 91b601c516..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/hop2.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute, redirect } from '@tanstack/solid-router' - -export const Route = createFileRoute('/hop2')({ - staleTime: 0, - gcTime: 0, - loader: () => { - throw redirect({ to: '/target' }) - }, -}) diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/index.tsx b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/index.tsx deleted file mode 100644 index cc46764de5..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/')({ - component: HomePage, -}) - -function HomePage() { - return
home
-} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/missing.$id.tsx b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/missing.$id.tsx deleted file mode 100644 index 9c0493fb48..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/missing.$id.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import { createFileRoute, notFound } from '@tanstack/solid-router' - -export const Route = createFileRoute('/missing/$id')({ - staleTime: 0, - gcTime: 0, - loader: ({ params }) => { - if (params.id === 'gone') { - throw notFound() - } - return { id: params.id } - }, - component: MissingPage, - notFoundComponent: MissingNotFound, -}) - -function MissingPage() { - const data = Route.useLoaderData() - return
{data().id}
-} - -function MissingNotFound() { - return
missing not found
-} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/target.tsx b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/target.tsx deleted file mode 100644 index 87de4e59a7..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/target.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/target')({ - component: TargetPage, -}) - -function TargetPage() { - return
target
-} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/tsconfig.json b/benchmarks/client-nav/scenarios/control-flow/solid/tsconfig.json deleted file mode 100644 index 98d76ad6b8..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/vite.config.ts b/benchmarks/client-nav/scenarios/control-flow/solid/vite.config.ts deleted file mode 100644 index f4fa916154..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/solid/vite.config.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import solid from 'vite-plugin-solid' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'solid', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - resolve: { - conditions: ['solid', 'browser'], - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav control-flow (solid)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/project.json b/benchmarks/client-nav/scenarios/control-flow/vue/project.json deleted file mode 100644 index 7370687988..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-control-flow-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/control-flow/vue/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/setup.ts b/benchmarks/client-nav/scenarios/control-flow/vue/setup.ts deleted file mode 100644 index 97b74b3892..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, steps } 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, - assertAfterStep: assertStepResult, - }) -} diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/control-flow/vue/speed.bench.ts deleted file mode 100644 index 8a019945c7..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-control-flow', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-control-flow 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/control-flow/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/control-flow/vue/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/main.tsx b/benchmarks/client-nav/scenarios/control-flow/vue/src/main.tsx deleted file mode 100644 index cae9b54f1d..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/src/main.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import * as Vue from 'vue' -import { RouterProvider, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const component = - const app = Vue.createApp({ - render: () => component, - }) - - app.mount(container) - - return { - router, - unmount() { - app.unmount() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/control-flow/vue/src/routeTree.gen.ts deleted file mode 100644 index 6b53a6a203..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,156 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const BrokenRoute = BrokenRouteImport.update({ - id: '/broken', - path: '/broken', - getParentRoute: () => rootRouteImport, -} as any) -const Hop1Route = Hop1RouteImport.update({ - id: '/hop1', - path: '/hop1', - 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({ - id: '/missing/$id', - path: '/missing/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/broken': typeof BrokenRoute - '/hop1': typeof Hop1Route - '/hop2': typeof Hop2Route - '/target': typeof TargetRoute - '/missing/$id': typeof MissingIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/broken': typeof BrokenRoute - '/hop1': typeof Hop1Route - '/hop2': typeof Hop2Route - '/target': typeof TargetRoute - '/missing/$id': typeof MissingIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/broken': typeof BrokenRoute - '/hop1': typeof Hop1Route - '/hop2': typeof Hop2Route - '/target': typeof TargetRoute - '/missing/$id': typeof MissingIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/broken' | '/hop1' | '/hop2' | '/target' | '/missing/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/broken' | '/hop1' | '/hop2' | '/target' | '/missing/$id' - id: - | '__root__' - | '/' - | '/broken' - | '/hop1' - | '/hop2' - | '/target' - | '/missing/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - BrokenRoute: typeof BrokenRoute - Hop1Route: typeof Hop1Route - Hop2Route: typeof Hop2Route - TargetRoute: typeof TargetRoute - MissingIdRoute: typeof MissingIdRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/broken': { - id: '/broken' - path: '/broken' - fullPath: '/broken' - preLoaderRoute: typeof BrokenRouteImport - parentRoute: typeof rootRouteImport - } - '/hop1': { - id: '/hop1' - path: '/hop1' - fullPath: '/hop1' - preLoaderRoute: typeof Hop1RouteImport - 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': { - id: '/missing/$id' - path: '/missing/$id' - fullPath: '/missing/$id' - preLoaderRoute: typeof MissingIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - BrokenRoute: BrokenRoute, - Hop1Route: Hop1Route, - Hop2Route: Hop2Route, - TargetRoute: TargetRoute, - MissingIdRoute: MissingIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/__root.tsx deleted file mode 100644 index 9695c4b32d..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/__root.tsx +++ /dev/null @@ -1,57 +0,0 @@ -import * as Vue from 'vue' -import { - Link, - Outlet, - createRootRoute, - useLocation, -} from '@tanstack/vue-router' - -const LocationMarker = Vue.defineComponent({ - setup() { - const pathname = useLocation({ select: (location) => location.pathname }) - return () => {pathname.value} - }, -}) - -const RootComponent = Vue.defineComponent({ - setup() { - return () => ( - <> - - - - - ) - }, -}) - -export const Route = createRootRoute({ - component: RootComponent, -}) diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/broken.tsx b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/broken.tsx deleted file mode 100644 index c67fa2817e..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/broken.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' -import { errorMessage } from '../../../shared' - -const BrokenError = Vue.defineComponent({ - props: { - error: { type: Error, required: true }, - }, - setup(props) { - return () =>
{props.error.message}
- }, -}) - -export const Route = createFileRoute('/broken')({ - staleTime: 0, - gcTime: 0, - loader: () => { - throw new Error(errorMessage) - }, - errorComponent: BrokenError, -}) diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/hop1.tsx b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/hop1.tsx deleted file mode 100644 index ed00cefe3f..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/hop1.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute, redirect } from '@tanstack/vue-router' - -export const Route = createFileRoute('/hop1')({ - staleTime: 0, - gcTime: 0, - loader: () => { - throw redirect({ to: '/hop2' }) - }, -}) diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/hop2.tsx b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/hop2.tsx deleted file mode 100644 index f6d4b1c1e0..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/hop2.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute, redirect } from '@tanstack/vue-router' - -export const Route = createFileRoute('/hop2')({ - staleTime: 0, - gcTime: 0, - loader: () => { - throw redirect({ to: '/target' }) - }, -}) diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/index.tsx b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/index.tsx deleted file mode 100644 index f3ffc58610..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const HomePage = Vue.defineComponent({ - setup() { - return () =>
home
- }, -}) - -export const Route = createFileRoute('/')({ - component: HomePage, -}) diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/missing.$id.tsx b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/missing.$id.tsx deleted file mode 100644 index 022ea656a6..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/missing.$id.tsx +++ /dev/null @@ -1,28 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute, notFound } from '@tanstack/vue-router' - -const MissingPage = Vue.defineComponent({ - setup() { - const data = Route.useLoaderData() - return () =>
{data.value.id}
- }, -}) - -const MissingNotFound = Vue.defineComponent({ - setup() { - return () =>
missing not found
- }, -}) - -export const Route = createFileRoute('/missing/$id')({ - staleTime: 0, - gcTime: 0, - loader: ({ params }) => { - if (params.id === 'gone') { - throw notFound() - } - return { id: params.id } - }, - component: MissingPage, - notFoundComponent: MissingNotFound, -}) diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/target.tsx b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/target.tsx deleted file mode 100644 index 4e22d0993a..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/target.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const TargetPage = Vue.defineComponent({ - setup() { - return () =>
target
- }, -}) - -export const Route = createFileRoute('/target')({ - component: TargetPage, -}) diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/tsconfig.json b/benchmarks/client-nav/scenarios/control-flow/vue/tsconfig.json deleted file mode 100644 index 7786fc3da9..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/vite.config.ts b/benchmarks/client-nav/scenarios/control-flow/vue/vite.config.ts deleted file mode 100644 index 3c2750d2a6..0000000000 --- a/benchmarks/client-nav/scenarios/control-flow/vue/vite.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'vue', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav control-flow (vue)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - }, -}) diff --git a/benchmarks/client-nav/scenarios/harness.ts b/benchmarks/client-nav/scenarios/harness.ts deleted file mode 100644 index cf3c39c7e6..0000000000 --- a/benchmarks/client-nav/scenarios/harness.ts +++ /dev/null @@ -1,534 +0,0 @@ -import { - createBrowserHistory, - createMemoryHistory, - type RouterHistory, -} from '@tanstack/history' -import { JSDOM } from 'jsdom' -import { getRequiredLink, waitForRequiredLink } from '../setup-helpers' - -export interface ScenarioRouter { - load: () => Promise - subscribe: (eventType: 'onRendered', callback: () => void) => () => void - navigate: (options: any) => Promise - preloadRoute: (options: any) => Promise - invalidate: () => Promise - history: { - back: () => void - forward: () => void - go: (index: number) => void - } -} - -export interface MountedScenarioApp { - router: ScenarioRouter - unmount: () => void -} - -/** - * A single benchmark step. Plain strings are link-click steps (the common - * case). Steps that change the router location (`click`, `navigate`, `back`, - * `forward`, `go`) are awaited through the router's `onRendered` event; steps - * that do background work (`hover`, `preload`, `invalidate`) are awaited - * through a fixed number of 0ms timer hops so the loop stays deterministic. - */ -export type ScenarioStep = - | string - | { - type: 'click' - testId: string - /** - * Optional post-render settle predicate for steps that trigger work - * finishing after `onRendered` (e.g. deferred data resolving through a - * Suspense boundary). The step keeps taking 0ms timer hops until the - * predicate returns true (bounded, throws when exceeded). - */ - isSettled?: () => boolean - } - | { - /** - * Dispatches a single `mouseover` on the link, which triggers - * `preload: 'intent'` exactly once in every adapter: React synthesizes - * `mouseEnter` from `mouseover`, and Solid/Vue attach a native - * `mouseover` preload handler. (Solid/Vue also listen to `mouseenter` — - * dispatching both events would run the preload pipeline twice for them - * but only once for React.) Then settles via counted 0ms hops. - */ - type: 'hover' - testId: string - settleHops?: number - } - | { type: 'navigate'; getOptions: () => object } - | { type: 'preload'; getOptions: () => object; settleHops?: number } - | { type: 'invalidate'; settleHops?: number } - | { type: 'back' } - | { type: 'forward' } - | { type: 'go'; delta: number } - -/** - * One macrotask turn via `setImmediate` rather than `setTimeout(0)`: both - * yield deterministically to the event loop (timers, MessageChannel, React's - * Node scheduler), but a timer costs ~3-4 syscalls (timerfd + epoll) per hop - * while an immediate costs ~1. CodSpeed excludes syscall time from the - * measure — inconsistently past a threshold, which flagged the hop-heavy - * benches as "skipped" — so the loop must stay syscall-lean. - */ -const timerHop = () => - new Promise((resolve) => setImmediate(() => resolve())) - -async function settle(hops: number) { - for (let i = 0; i < hops; i++) { - await timerHop() - } -} - -const MAX_SETTLE_HOPS = 100 -const BATCH_SETTLE_HOPS = 4 - -/** - * Close the batch at a deterministic macrotask boundary. Four fixed hops give - * framework passive effects and scheduler callbacks time to run without - * changing the amount of navigation work in the batch. - */ -async function finishBatch() { - await settle(BATCH_SETTLE_HOPS) -} - -async function settleUntil(isSettled: () => boolean, label: string) { - for (let i = 0; i < MAX_SETTLE_HOPS; i++) { - if (isSettled()) { - return - } - await timerHop() - } - throw new Error( - `Step "${label}" did not settle within ${MAX_SETTLE_HOPS} timer hops`, - ) -} - -/** - * Reroute zero-delay `window.setTimeout` calls onto `setImmediate` for the - * duration of the benchmark. jsdom delivers history traversals through two - * nested `window.setTimeout(0)` tasks; Node clamps those to 1ms of wall - * time, so with nothing else pending the event loop blocks in `epoll_wait` - * until each timer expires — and that blocked wall-time is recorded as - * highly variable syscall time (5-26ms across runs), enough for CodSpeed to - * skip-warn the history benches. Zero-delay timeouts carry no ordering - * semantics a check-phase immediate doesn't satisfy, and the suite's - * conventions already forbid real-delay timers in measured code; non-zero - * delays are passed through untouched. - */ -interface TimerWindow { - setTimeout: typeof window.setTimeout - clearTimeout: typeof window.clearTimeout -} - -function patchZeroDelayTimeouts(targetWindow: TimerWindow) { - const originalSetTimeout = targetWindow.setTimeout.bind(targetWindow) - const originalClearTimeout = targetWindow.clearTimeout.bind(targetWindow) - const immediates = new Map() - // Negative ids cannot collide with real jsdom timer ids. - let nextImmediateId = -2 - - targetWindow.setTimeout = (( - handler: (...handlerArgs: Array) => void, - delay?: number, - ...args: Array - ) => { - if (!delay) { - const id = nextImmediateId-- - immediates.set( - id, - setImmediate(() => { - immediates.delete(id) - handler(...args) - }), - ) - return id - } - return originalSetTimeout(handler, delay, ...args) - }) as typeof targetWindow.setTimeout - - targetWindow.clearTimeout = ((id: number) => { - const immediate = immediates.get(id) - if (immediate) { - clearImmediate(immediate) - immediates.delete(id) - return - } - originalClearTimeout(id) - }) as typeof targetWindow.clearTimeout - - return () => { - targetWindow.setTimeout = - originalSetTimeout as typeof targetWindow.setTimeout - targetWindow.clearTimeout = - originalClearTimeout as typeof targetWindow.clearTimeout - } -} - -interface ListenerTarget { - addEventListener: ( - type: string, - listener: EventListenerOrEventListenerObject | null, - options?: boolean | AddEventListenerOptions, - ) => void - removeEventListener: ( - type: string, - listener: EventListenerOrEventListenerObject | null, - options?: boolean | EventListenerOptions, - ) => void -} - -/** - * Scroll restoration installs page-lifetime listeners without a public router - * dispose operation. Capture just those listeners while the router is created - * so per-invocation routers do not remain reachable after teardown. - */ -function captureScrollRestorationListeners() { - const captured: Array<{ - target: ListenerTarget - type: string - listener: EventListenerOrEventListenerObject | null - options?: boolean | AddEventListenerOptions - }> = [] - const patches: Array<{ - target: ListenerTarget - addEventListener: ListenerTarget['addEventListener'] - }> = [] - - const patch = (target: ListenerTarget, capturedType: string) => { - const originalAddEventListener = target.addEventListener - patches.push({ target, addEventListener: originalAddEventListener }) - - target.addEventListener = function (type, listener, options) { - if (type === capturedType) { - captured.push({ target, type, listener, options }) - } - originalAddEventListener.call(target, type, listener, options) - } - } - - patch(document as unknown as ListenerTarget, 'scroll') - patch(globalThis as unknown as ListenerTarget, 'pagehide') - - let stopped = false - const stop = () => { - if (stopped) { - return - } - stopped = true - for (const entry of patches) { - entry.target.addEventListener = entry.addEventListener - } - } - - return { - stop, - cleanup() { - stop() - for (const { target, type, listener, options } of captured) { - target.removeEventListener(type, listener, options) - } - }, - } -} - -interface ScenarioHistoryResource { - history: RouterHistory - timeoutWindow?: TimerWindow - dispose: () => void -} - -function createScenarioHistory( - mode: NonNullable, - initialUrl: string, -): ScenarioHistoryResource { - if (mode === 'browser') { - const dom = new JSDOM('', { - url: new URL(initialUrl, 'http://localhost').href, - }) - const history = createBrowserHistory({ window: dom.window }) - - return { - history, - timeoutWindow: dom.window as unknown as TimerWindow, - dispose() { - history.destroy() - dom.window.close() - }, - } - } - - const history = createMemoryHistory({ initialEntries: [initialUrl] }) - return { - history, - dispose: history.destroy, - } -} - -export interface ScenarioSetupOptions { - frameworkLabel: string - mount: (container: HTMLElement, history: RouterHistory) => MountedScenarioApp - /** - * Circular sequence of steps advanced by `tick()`. Link steps must target - * links rendered from the start (e.g. in the root layout), no two - * consecutive location-changing steps may target the same location (a - * same-location click never triggers `onRendered`), and the sequence must - * leave the app back on the initial route so the warm-up lap ends in the - * starting state. - */ - steps: ReadonlyArray - /** Sanity check run once per step during the warm-up lap in `before()`. */ - assertAfterStep?: ( - stepIndex: number, - container: HTMLElement, - history: RouterHistory, - ) => void - /** - * URL used to initialize the fresh history before mounting (default '/'). - * Scenarios whose router uses a `basepath` or an input rewrite must start on - * an external URL that maps to their initial route. - */ - initialUrl?: string - /** - * Browser history is reserved for the scenario that explicitly measures - * browser history traversal. All other scenarios use fresh memory history. - */ - historyMode?: 'memory' | 'browser' -} - -function warnAboutDevMode(frameworkLabel: string) { - if (process.env.NODE_ENV !== 'production') { - console.warn( - `client-nav scenario benchmark is running without NODE_ENV=production; ${frameworkLabel} dev overhead will dominate results.`, - ) - } -} - -/** - * Shared scenario runner: mounts the prebuilt app, then advances a circular - * sequence of steps, synchronizing each step so its work is fully part of the - * measured tick and steps cannot overlap. - */ -export function createScenarioSetup(options: ScenarioSetupOptions) { - warnAboutDevMode(options.frameworkLabel) - - let container: HTMLDivElement | undefined = undefined - let unmount: (() => void) | undefined = undefined - let unsub = () => {} - let restoreTimeouts = () => {} - let cleanupScrollRestorationListeners = () => {} - let historyResource: ScenarioHistoryResource | undefined = undefined - let stepIndex = 0 - let next: () => Promise = () => - Promise.reject(new Error('Benchmark not initialized')) - - async function before() { - stepIndex = 0 - historyResource = createScenarioHistory( - options.historyMode ?? 'memory', - options.initialUrl ?? '/', - ) - - const restoreGlobalTimeouts = patchZeroDelayTimeouts(window) - const restoreHistoryTimeouts = historyResource.timeoutWindow - ? patchZeroDelayTimeouts(historyResource.timeoutWindow) - : () => {} - restoreTimeouts = () => { - restoreHistoryTimeouts() - restoreGlobalTimeouts() - } - - container = document.createElement('div') - document.body.append(container) - - const capturedListeners = captureScrollRestorationListeners() - let mounted: MountedScenarioApp - try { - mounted = options.mount(container, historyResource.history) - } finally { - capturedListeners.stop() - cleanupScrollRestorationListeners = capturedListeners.cleanup - } - - const { router, unmount: dispose } = mounted - unmount = dispose - - let resolveRendered: () => void = () => {} - unsub = router.subscribe('onRendered', () => { - resolveRendered() - }) - - const cachedLinks = new Map() - const rendered = () => - new Promise((resolveNext) => { - resolveRendered = resolveNext - }) - - const runStep = async (step: ScenarioStep) => { - if (typeof step === 'string') { - step = { type: 'click', testId: step } - } - - switch (step.type) { - case 'click': { - const renderedPromise = rendered() - getRequiredLink(container!, step.testId, cachedLinks).dispatchEvent( - new MouseEvent('click', { - bubbles: true, - cancelable: true, - button: 0, - }), - ) - await renderedPromise - if (step.isSettled) { - await settleUntil(step.isSettled, `click ${step.testId}`) - } - return - } - case 'hover': { - const link = getRequiredLink(container!, step.testId, cachedLinks) - link.dispatchEvent( - new MouseEvent('mouseover', { bubbles: true, cancelable: true }), - ) - await settle(step.settleHops ?? 4) - return - } - case 'navigate': { - const renderedPromise = rendered() - router.navigate(step.getOptions()) - await renderedPromise - return - } - case 'preload': { - await router.preloadRoute(step.getOptions()) - await settle(step.settleHops ?? 2) - return - } - case 'invalidate': { - await router.invalidate() - await settle(step.settleHops ?? 2) - return - } - case 'back': { - const renderedPromise = rendered() - router.history.back() - await renderedPromise - return - } - case 'forward': { - const renderedPromise = rendered() - router.history.forward() - await renderedPromise - return - } - case 'go': { - const renderedPromise = rendered() - router.history.go(step.delta) - await renderedPromise - return - } - } - } - - await router.load() - - const linkTestIds = new Set() - for (const step of options.steps) { - if (typeof step === 'string') { - linkTestIds.add(step) - } else if (step.type === 'click' || step.type === 'hover') { - linkTestIds.add(step.testId) - } - } - for (const testId of linkTestIds) { - await waitForRequiredLink(container, testId, cachedLinks) - } - - // One warm-up lap that also sanity-checks each step's observable output, - // ending back on the initial route so measurement starts from a known state. - for (const [index, step] of options.steps.entries()) { - await runStep(step) - options.assertAfterStep?.(index, container, historyResource.history) - } - await finishBatch() - - next = () => { - const step = options.steps[stepIndex % options.steps.length]! - stepIndex += 1 - return runStep(step) - } - } - - function after() { - unmount?.() - container?.remove() - unsub() - cleanupScrollRestorationListeners() - restoreTimeouts() - historyResource?.dispose() - restoreTimeouts = () => {} - cleanupScrollRestorationListeners = () => {} - unmount = undefined - container = undefined - historyResource = undefined - } - - function tick() { - return next() - } - - return { - before, - tick, - finishBatch, - after, - } -} - -export interface MountLoopSetupOptions { - frameworkLabel: string - mount: (container: HTMLElement, history: RouterHistory) => MountedScenarioApp - /** Test id that must appear in the container before a mount counts as done. */ - readyTestId: string - assertReady?: (container: HTMLElement) => void -} - -/** - * Mount-loop runner for cold-start scenarios: every tick creates a fresh - * container, mounts the app (router creation included), waits for the initial - * render to commit, then unmounts and cleans up. - */ -export function createMountLoopSetup(options: MountLoopSetupOptions) { - warnAboutDevMode(options.frameworkLabel) - - async function tick() { - const container = document.createElement('div') - document.body.append(container) - const history = createMemoryHistory({ initialEntries: ['/'] }) - - const { router, unmount } = options.mount(container, history) - - try { - await router.load() - await settleUntil( - () => - container.querySelector(`[data-testid="${options.readyTestId}"]`) !== - null, - `mount ${options.readyTestId}`, - ) - options.assertReady?.(container) - } finally { - unmount() - history.destroy() - container.remove() - } - } - - return { - before: async () => {}, - tick, - finishBatch, - after: () => {}, - } -} diff --git a/benchmarks/client-nav/scenarios/head/react/project.json b/benchmarks/client-nav/scenarios/head/react/project.json deleted file mode 100644 index 1becf30fb9..0000000000 --- a/benchmarks/client-nav/scenarios/head/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-head-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/head/react/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/head/react/setup.ts b/benchmarks/client-nav/scenarios/head/react/setup.ts deleted file mode 100644 index 1a28b0ca94..0000000000 --- a/benchmarks/client-nav/scenarios/head/react/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, stepTestIds } 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: stepTestIds, - assertAfterStep: assertStepResult, - }) -} diff --git a/benchmarks/client-nav/scenarios/head/react/speed.bench.ts b/benchmarks/client-nav/scenarios/head/react/speed.bench.ts deleted file mode 100644 index d0d731a09f..0000000000 --- a/benchmarks/client-nav/scenarios/head/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-head', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-head 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/head/react/speed.flame.ts b/benchmarks/client-nav/scenarios/head/react/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/head/react/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/head/react/src/main.tsx b/benchmarks/client-nav/scenarios/head/react/src/main.tsx deleted file mode 100644 index 5febd6f795..0000000000 --- a/benchmarks/client-nav/scenarios/head/react/src/main.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { RouterProvider, createRouter } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const reactRoot = createRoot(container) - reactRoot.render() - - return { - router, - unmount() { - reactRoot.unmount() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/head/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/head/react/src/routeTree.gen.ts deleted file mode 100644 index 88867d9190..0000000000 --- a/benchmarks/client-nav/scenarios/head/react/src/routeTree.gen.ts +++ /dev/null @@ -1,145 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const DocsRoute = DocsRouteImport.update({ - id: '/docs', - path: '/docs', - getParentRoute: () => rootRouteImport, -} as any) -const SettingsRoute = SettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => rootRouteImport, -} as any) -const ArticlesIdRoute = ArticlesIdRouteImport.update({ - id: '/articles/$id', - path: '/articles/$id', - getParentRoute: () => rootRouteImport, -} as any) -const DocsSectionRoute = DocsSectionRouteImport.update({ - id: '/$section', - path: '/$section', - getParentRoute: () => DocsRoute, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/docs': typeof DocsRouteWithChildren - '/settings': typeof SettingsRoute - '/articles/$id': typeof ArticlesIdRoute - '/docs/$section': typeof DocsSectionRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/docs': typeof DocsRouteWithChildren - '/settings': typeof SettingsRoute - '/articles/$id': typeof ArticlesIdRoute - '/docs/$section': typeof DocsSectionRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/docs': typeof DocsRouteWithChildren - '/settings': typeof SettingsRoute - '/articles/$id': typeof ArticlesIdRoute - '/docs/$section': typeof DocsSectionRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/docs' | '/settings' | '/articles/$id' | '/docs/$section' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/docs' | '/settings' | '/articles/$id' | '/docs/$section' - id: - | '__root__' - | '/' - | '/docs' - | '/settings' - | '/articles/$id' - | '/docs/$section' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - DocsRoute: typeof DocsRouteWithChildren - SettingsRoute: typeof SettingsRoute - ArticlesIdRoute: typeof ArticlesIdRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/docs': { - id: '/docs' - path: '/docs' - fullPath: '/docs' - preLoaderRoute: typeof DocsRouteImport - parentRoute: typeof rootRouteImport - } - '/settings': { - id: '/settings' - path: '/settings' - fullPath: '/settings' - preLoaderRoute: typeof SettingsRouteImport - parentRoute: typeof rootRouteImport - } - '/articles/$id': { - id: '/articles/$id' - path: '/articles/$id' - fullPath: '/articles/$id' - preLoaderRoute: typeof ArticlesIdRouteImport - parentRoute: typeof rootRouteImport - } - '/docs/$section': { - id: '/docs/$section' - path: '/$section' - fullPath: '/docs/$section' - preLoaderRoute: typeof DocsSectionRouteImport - parentRoute: typeof DocsRoute - } - } -} - -interface DocsRouteChildren { - DocsSectionRoute: typeof DocsSectionRoute -} - -const DocsRouteChildren: DocsRouteChildren = { - DocsSectionRoute: DocsSectionRoute, -} - -const DocsRouteWithChildren = DocsRoute._addFileChildren(DocsRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - DocsRoute: DocsRouteWithChildren, - SettingsRoute: SettingsRoute, - ArticlesIdRoute: ArticlesIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/head/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/head/react/src/routes/__root.tsx deleted file mode 100644 index 3d61dad0e9..0000000000 --- a/benchmarks/client-nav/scenarios/head/react/src/routes/__root.tsx +++ /dev/null @@ -1,59 +0,0 @@ -import { - HeadContent, - Link, - Outlet, - createRootRoute, -} from '@tanstack/react-router' -import { articleIds, docsSections, rootHead } from '../../../shared' - -export const Route = createRootRoute({ - head: rootHead, - component: RootComponent, -}) - -function RootComponent() { - return ( - <> - - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/head/react/src/routes/articles.$id.tsx b/benchmarks/client-nav/scenarios/head/react/src/routes/articles.$id.tsx deleted file mode 100644 index 6f5b78d60e..0000000000 --- a/benchmarks/client-nav/scenarios/head/react/src/routes/articles.$id.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { articleDescription, articleHead, articleTitle } from '../../../shared' - -export const Route = createFileRoute('/articles/$id')({ - head: ({ params }) => articleHead(params.id), - component: ArticlePage, -}) - -function ArticlePage() { - const params = Route.useParams() - - return ( -
-

{articleTitle(params.id)}

-

{articleDescription(params.id)}

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/head/react/src/routes/docs.$section.tsx b/benchmarks/client-nav/scenarios/head/react/src/routes/docs.$section.tsx deleted file mode 100644 index 6ed1935ada..0000000000 --- a/benchmarks/client-nav/scenarios/head/react/src/routes/docs.$section.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { docsDescription, docsSectionHead, docsTitle } from '../../../shared' - -export const Route = createFileRoute('/docs/$section')({ - head: ({ params }) => docsSectionHead(params.section), - component: DocsSectionPage, -}) - -function DocsSectionPage() { - const params = Route.useParams() - - return ( -
-

{docsTitle(params.section)}

-

{docsDescription(params.section)}

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/head/react/src/routes/docs.tsx b/benchmarks/client-nav/scenarios/head/react/src/routes/docs.tsx deleted file mode 100644 index a2da216ddb..0000000000 --- a/benchmarks/client-nav/scenarios/head/react/src/routes/docs.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import { docsLayoutHead } from '../../../shared' - -export const Route = createFileRoute('/docs')({ - head: docsLayoutHead, - component: DocsLayout, -}) - -function DocsLayout() { - return ( -
-

Docs

- -
- ) -} diff --git a/benchmarks/client-nav/scenarios/head/react/src/routes/index.tsx b/benchmarks/client-nav/scenarios/head/react/src/routes/index.tsx deleted file mode 100644 index 6ac318452f..0000000000 --- a/benchmarks/client-nav/scenarios/head/react/src/routes/index.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { homeHead, homeTitle } from '../../../shared' - -export const Route = createFileRoute('/')({ - head: homeHead, - component: HomePage, -}) - -function HomePage() { - return ( -
-

{homeTitle}

-

Landing page

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/head/react/src/routes/settings.tsx b/benchmarks/client-nav/scenarios/head/react/src/routes/settings.tsx deleted file mode 100644 index cd73902bff..0000000000 --- a/benchmarks/client-nav/scenarios/head/react/src/routes/settings.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { settingsHead, settingsTitle } from '../../../shared' - -export const Route = createFileRoute('/settings')({ - head: settingsHead, - component: SettingsPage, -}) - -function SettingsPage() { - return ( -
-

{settingsTitle}

-

Account settings

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/head/react/tsconfig.json b/benchmarks/client-nav/scenarios/head/react/tsconfig.json deleted file mode 100644 index 1d59cbb450..0000000000 --- a/benchmarks/client-nav/scenarios/head/react/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/head/react/vite.config.ts b/benchmarks/client-nav/scenarios/head/react/vite.config.ts deleted file mode 100644 index 7c8d6d4c15..0000000000 --- a/benchmarks/client-nav/scenarios/head/react/vite.config.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'react', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav head (react)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - }, -}) diff --git a/benchmarks/client-nav/scenarios/head/shared.ts b/benchmarks/client-nav/scenarios/head/shared.ts deleted file mode 100644 index db185d602b..0000000000 --- a/benchmarks/client-nav/scenarios/head/shared.ts +++ /dev/null @@ -1,152 +0,0 @@ -/** - * Shared definition of the `head` scenario: route head() payloads, the click - * sequence, and per-step sanity assertions. The three framework apps consume - * these builders so the workload is identical modulo the rendering layer. - */ - -const siteName = 'Head Bench' - -export const docsSections = ['api', 'guide', 'cli'] as const -export const articleIds = ['1', '2', '3'] as const - -export const homeTitle = `Home | ${siteName}` -export const settingsTitle = `Settings | ${siteName}` - -export function docsTitle(section: string) { - return `Docs ${section} | ${siteName}` -} - -export function docsDescription(section: string) { - return `Documentation for the ${section} section of the head benchmark app.` -} - -export function articleTitle(id: string) { - return `Article ${id} | ${siteName}` -} - -export function articleDescription(id: string) { - return `Long-form article number ${id}, with a description sized like a realistic summary of the page content.` -} - -export function rootHead() { - return { - meta: [ - { charSet: 'utf-8' }, - { name: 'viewport', content: 'width=device-width, initial-scale=1' }, - { name: 'application-name', content: siteName }, - { name: 'description', content: 'Client head-management benchmark' }, - { name: 'theme-color', content: '#111827' }, - { property: 'og:type', content: 'website' }, - { property: 'og:site_name', content: siteName }, - ], - links: [ - { rel: 'icon', href: '/favicon.ico' }, - { rel: 'preconnect', href: 'https://assets.example.com' }, - ], - } -} - -export function homeHead() { - return { - meta: [ - { title: homeTitle }, - { name: 'description', content: 'Landing page of the head benchmark' }, - { property: 'og:title', content: homeTitle }, - ], - links: [{ rel: 'canonical', href: 'https://example.com/' }], - } -} - -export function docsLayoutHead() { - return { - meta: [ - // Overridden by the child section route on every docs navigation, so the - // dedupe path is exercised for both `name` and `property` entries. - { name: 'description', content: 'Documentation hub' }, - { property: 'og:title', content: `Docs | ${siteName}` }, - { name: 'docsearch:index', content: 'head-bench-docs' }, - ], - links: [{ rel: 'search', href: '/docs/opensearch.xml' }], - } -} - -export function docsSectionHead(section: string) { - return { - meta: [ - { title: docsTitle(section) }, - { name: 'description', content: docsDescription(section) }, - { name: 'keywords', content: `docs,${section},router,benchmark` }, - { property: 'og:title', content: docsTitle(section) }, - { property: 'og:description', content: docsDescription(section) }, - { property: 'og:url', content: `https://example.com/docs/${section}` }, - { name: 'twitter:card', content: 'summary' }, - { name: 'twitter:title', content: docsTitle(section) }, - ], - links: [ - { rel: 'canonical', href: `https://example.com/docs/${section}` }, - { rel: 'prev', href: `https://example.com/docs/${section}/intro` }, - ], - } -} - -export function articleHead(id: string) { - return { - meta: [ - { title: articleTitle(id) }, - { name: 'description', content: articleDescription(id) }, - { name: 'author', content: 'Bench Author' }, - { property: 'og:title', content: articleTitle(id) }, - { property: 'og:description', content: articleDescription(id) }, - { property: 'og:url', content: `https://example.com/articles/${id}` }, - { property: 'og:image', content: `https://example.com/covers/${id}.png` }, - { property: 'article:published_time', content: '2026-01-01T00:00:00Z' }, - { name: 'twitter:card', content: 'summary_large_image' }, - { name: 'twitter:title', content: articleTitle(id) }, - ], - links: [{ rel: 'canonical', href: `https://example.com/articles/${id}` }], - } -} - -export function settingsHead() { - return { - meta: [ - { title: settingsTitle }, - // Same names as root entries, so the child-wins dedupe path runs. - { name: 'description', content: 'Account settings' }, - { name: 'theme-color', content: '#f9fafb' }, - { name: 'robots', content: 'noindex' }, - ], - links: [], - } -} - -export const steps = [ - { testId: 'go-docs-api', title: docsTitle('api') }, - { testId: 'go-article-1', title: articleTitle('1') }, - { testId: 'go-docs-guide', title: docsTitle('guide') }, - { testId: 'go-settings', title: settingsTitle }, - { testId: 'go-article-2', title: articleTitle('2') }, - { testId: 'go-docs-cli', title: docsTitle('cli') }, - { testId: 'go-article-3', title: articleTitle('3') }, - { testId: 'go-home', title: homeTitle }, -] as const - -export const stepTestIds = steps.map((step) => step.testId) - -export function assertStepResult(stepIndex: number) { - const expected = steps[stepIndex]!.title - if (document.title !== expected) { - throw new Error( - `Expected document.title to be "${expected}" after step ${stepIndex}, received "${document.title}"`, - ) - } -} - -// Two laps through the 8-step sequence per benchmark iteration. -export const ticksPerIteration = 16 - -export const benchOptions = { - warmupIterations: 100, - time: 10_000, - throws: true, -} diff --git a/benchmarks/client-nav/scenarios/head/solid/project.json b/benchmarks/client-nav/scenarios/head/solid/project.json deleted file mode 100644 index 2575a19b89..0000000000 --- a/benchmarks/client-nav/scenarios/head/solid/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-head-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/head/solid/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/head/solid/setup.ts b/benchmarks/client-nav/scenarios/head/solid/setup.ts deleted file mode 100644 index 4ee924acff..0000000000 --- a/benchmarks/client-nav/scenarios/head/solid/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, stepTestIds } 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: stepTestIds, - assertAfterStep: assertStepResult, - }) -} diff --git a/benchmarks/client-nav/scenarios/head/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/head/solid/speed.bench.ts deleted file mode 100644 index ca156c950b..0000000000 --- a/benchmarks/client-nav/scenarios/head/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-head', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-head 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/head/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/head/solid/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/head/solid/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/head/solid/src/main.tsx b/benchmarks/client-nav/scenarios/head/solid/src/main.tsx deleted file mode 100644 index fa9d239418..0000000000 --- a/benchmarks/client-nav/scenarios/head/solid/src/main.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { render } from 'solid-js/web' -import { RouterProvider, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const unmount = render(() => , container) - - return { - router, - unmount, - } -} diff --git a/benchmarks/client-nav/scenarios/head/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/head/solid/src/routeTree.gen.ts deleted file mode 100644 index b6f217e527..0000000000 --- a/benchmarks/client-nav/scenarios/head/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,145 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const DocsRoute = DocsRouteImport.update({ - id: '/docs', - path: '/docs', - getParentRoute: () => rootRouteImport, -} as any) -const SettingsRoute = SettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => rootRouteImport, -} as any) -const ArticlesIdRoute = ArticlesIdRouteImport.update({ - id: '/articles/$id', - path: '/articles/$id', - getParentRoute: () => rootRouteImport, -} as any) -const DocsSectionRoute = DocsSectionRouteImport.update({ - id: '/$section', - path: '/$section', - getParentRoute: () => DocsRoute, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/docs': typeof DocsRouteWithChildren - '/settings': typeof SettingsRoute - '/articles/$id': typeof ArticlesIdRoute - '/docs/$section': typeof DocsSectionRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/docs': typeof DocsRouteWithChildren - '/settings': typeof SettingsRoute - '/articles/$id': typeof ArticlesIdRoute - '/docs/$section': typeof DocsSectionRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/docs': typeof DocsRouteWithChildren - '/settings': typeof SettingsRoute - '/articles/$id': typeof ArticlesIdRoute - '/docs/$section': typeof DocsSectionRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/docs' | '/settings' | '/articles/$id' | '/docs/$section' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/docs' | '/settings' | '/articles/$id' | '/docs/$section' - id: - | '__root__' - | '/' - | '/docs' - | '/settings' - | '/articles/$id' - | '/docs/$section' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - DocsRoute: typeof DocsRouteWithChildren - SettingsRoute: typeof SettingsRoute - ArticlesIdRoute: typeof ArticlesIdRoute -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/docs': { - id: '/docs' - path: '/docs' - fullPath: '/docs' - preLoaderRoute: typeof DocsRouteImport - parentRoute: typeof rootRouteImport - } - '/settings': { - id: '/settings' - path: '/settings' - fullPath: '/settings' - preLoaderRoute: typeof SettingsRouteImport - parentRoute: typeof rootRouteImport - } - '/articles/$id': { - id: '/articles/$id' - path: '/articles/$id' - fullPath: '/articles/$id' - preLoaderRoute: typeof ArticlesIdRouteImport - parentRoute: typeof rootRouteImport - } - '/docs/$section': { - id: '/docs/$section' - path: '/$section' - fullPath: '/docs/$section' - preLoaderRoute: typeof DocsSectionRouteImport - parentRoute: typeof DocsRoute - } - } -} - -interface DocsRouteChildren { - DocsSectionRoute: typeof DocsSectionRoute -} - -const DocsRouteChildren: DocsRouteChildren = { - DocsSectionRoute: DocsSectionRoute, -} - -const DocsRouteWithChildren = DocsRoute._addFileChildren(DocsRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - DocsRoute: DocsRouteWithChildren, - SettingsRoute: SettingsRoute, - ArticlesIdRoute: ArticlesIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/head/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/head/solid/src/routes/__root.tsx deleted file mode 100644 index 52ca7da373..0000000000 --- a/benchmarks/client-nav/scenarios/head/solid/src/routes/__root.tsx +++ /dev/null @@ -1,58 +0,0 @@ -import { For } from 'solid-js' -import { - HeadContent, - Link, - Outlet, - createRootRoute, -} from '@tanstack/solid-router' -import { articleIds, docsSections, rootHead } from '../../../shared' - -export const Route = createRootRoute({ - head: rootHead, - component: RootComponent, -}) - -function RootComponent() { - return ( - <> - - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/head/solid/src/routes/articles.$id.tsx b/benchmarks/client-nav/scenarios/head/solid/src/routes/articles.$id.tsx deleted file mode 100644 index dab11ada18..0000000000 --- a/benchmarks/client-nav/scenarios/head/solid/src/routes/articles.$id.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { articleDescription, articleHead, articleTitle } from '../../../shared' - -export const Route = createFileRoute('/articles/$id')({ - head: ({ params }) => articleHead(params.id), - component: ArticlePage, -}) - -function ArticlePage() { - const params = Route.useParams() - - return ( -
-

{articleTitle(params().id)}

-

{articleDescription(params().id)}

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/head/solid/src/routes/docs.$section.tsx b/benchmarks/client-nav/scenarios/head/solid/src/routes/docs.$section.tsx deleted file mode 100644 index 7ab1123e7a..0000000000 --- a/benchmarks/client-nav/scenarios/head/solid/src/routes/docs.$section.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { docsDescription, docsSectionHead, docsTitle } from '../../../shared' - -export const Route = createFileRoute('/docs/$section')({ - head: ({ params }) => docsSectionHead(params.section), - component: DocsSectionPage, -}) - -function DocsSectionPage() { - const params = Route.useParams() - - return ( -
-

{docsTitle(params().section)}

-

{docsDescription(params().section)}

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/head/solid/src/routes/docs.tsx b/benchmarks/client-nav/scenarios/head/solid/src/routes/docs.tsx deleted file mode 100644 index 7f84b214d0..0000000000 --- a/benchmarks/client-nav/scenarios/head/solid/src/routes/docs.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' -import { docsLayoutHead } from '../../../shared' - -export const Route = createFileRoute('/docs')({ - head: docsLayoutHead, - component: DocsLayout, -}) - -function DocsLayout() { - return ( -
-

Docs

- -
- ) -} diff --git a/benchmarks/client-nav/scenarios/head/solid/src/routes/index.tsx b/benchmarks/client-nav/scenarios/head/solid/src/routes/index.tsx deleted file mode 100644 index 229eecc8c1..0000000000 --- a/benchmarks/client-nav/scenarios/head/solid/src/routes/index.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { homeHead, homeTitle } from '../../../shared' - -export const Route = createFileRoute('/')({ - head: homeHead, - component: HomePage, -}) - -function HomePage() { - return ( -
-

{homeTitle}

-

Landing page

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/head/solid/src/routes/settings.tsx b/benchmarks/client-nav/scenarios/head/solid/src/routes/settings.tsx deleted file mode 100644 index 88424caef3..0000000000 --- a/benchmarks/client-nav/scenarios/head/solid/src/routes/settings.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { settingsHead, settingsTitle } from '../../../shared' - -export const Route = createFileRoute('/settings')({ - head: settingsHead, - component: SettingsPage, -}) - -function SettingsPage() { - return ( -
-

{settingsTitle}

-

Account settings

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/head/solid/tsconfig.json b/benchmarks/client-nav/scenarios/head/solid/tsconfig.json deleted file mode 100644 index 98d76ad6b8..0000000000 --- a/benchmarks/client-nav/scenarios/head/solid/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/head/solid/vite.config.ts b/benchmarks/client-nav/scenarios/head/solid/vite.config.ts deleted file mode 100644 index 986b2de2b0..0000000000 --- a/benchmarks/client-nav/scenarios/head/solid/vite.config.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import solid from 'vite-plugin-solid' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'solid', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - resolve: { - conditions: ['solid', 'browser'], - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav head (solid)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/client-nav/scenarios/head/vue/project.json b/benchmarks/client-nav/scenarios/head/vue/project.json deleted file mode 100644 index 5ad7909d74..0000000000 --- a/benchmarks/client-nav/scenarios/head/vue/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-head-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/head/vue/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/head/vue/setup.ts b/benchmarks/client-nav/scenarios/head/vue/setup.ts deleted file mode 100644 index 3dd6bc95a5..0000000000 --- a/benchmarks/client-nav/scenarios/head/vue/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, stepTestIds } 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: stepTestIds, - assertAfterStep: assertStepResult, - }) -} diff --git a/benchmarks/client-nav/scenarios/head/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/head/vue/speed.bench.ts deleted file mode 100644 index d188a9dd7a..0000000000 --- a/benchmarks/client-nav/scenarios/head/vue/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-head', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-head 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/head/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/head/vue/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/head/vue/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/head/vue/src/main.tsx b/benchmarks/client-nav/scenarios/head/vue/src/main.tsx deleted file mode 100644 index cae9b54f1d..0000000000 --- a/benchmarks/client-nav/scenarios/head/vue/src/main.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import * as Vue from 'vue' -import { RouterProvider, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const component = - const app = Vue.createApp({ - render: () => component, - }) - - app.mount(container) - - return { - router, - unmount() { - app.unmount() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/head/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/head/vue/src/routeTree.gen.ts deleted file mode 100644 index 161f99a65c..0000000000 --- a/benchmarks/client-nav/scenarios/head/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,145 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const DocsRoute = DocsRouteImport.update({ - id: '/docs', - path: '/docs', - getParentRoute: () => rootRouteImport, -} as any) -const SettingsRoute = SettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => rootRouteImport, -} as any) -const ArticlesIdRoute = ArticlesIdRouteImport.update({ - id: '/articles/$id', - path: '/articles/$id', - getParentRoute: () => rootRouteImport, -} as any) -const DocsSectionRoute = DocsSectionRouteImport.update({ - id: '/$section', - path: '/$section', - getParentRoute: () => DocsRoute, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/docs': typeof DocsRouteWithChildren - '/settings': typeof SettingsRoute - '/articles/$id': typeof ArticlesIdRoute - '/docs/$section': typeof DocsSectionRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/docs': typeof DocsRouteWithChildren - '/settings': typeof SettingsRoute - '/articles/$id': typeof ArticlesIdRoute - '/docs/$section': typeof DocsSectionRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/docs': typeof DocsRouteWithChildren - '/settings': typeof SettingsRoute - '/articles/$id': typeof ArticlesIdRoute - '/docs/$section': typeof DocsSectionRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/docs' | '/settings' | '/articles/$id' | '/docs/$section' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/docs' | '/settings' | '/articles/$id' | '/docs/$section' - id: - | '__root__' - | '/' - | '/docs' - | '/settings' - | '/articles/$id' - | '/docs/$section' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - DocsRoute: typeof DocsRouteWithChildren - SettingsRoute: typeof SettingsRoute - ArticlesIdRoute: typeof ArticlesIdRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/docs': { - id: '/docs' - path: '/docs' - fullPath: '/docs' - preLoaderRoute: typeof DocsRouteImport - parentRoute: typeof rootRouteImport - } - '/settings': { - id: '/settings' - path: '/settings' - fullPath: '/settings' - preLoaderRoute: typeof SettingsRouteImport - parentRoute: typeof rootRouteImport - } - '/articles/$id': { - id: '/articles/$id' - path: '/articles/$id' - fullPath: '/articles/$id' - preLoaderRoute: typeof ArticlesIdRouteImport - parentRoute: typeof rootRouteImport - } - '/docs/$section': { - id: '/docs/$section' - path: '/$section' - fullPath: '/docs/$section' - preLoaderRoute: typeof DocsSectionRouteImport - parentRoute: typeof DocsRoute - } - } -} - -interface DocsRouteChildren { - DocsSectionRoute: typeof DocsSectionRoute -} - -const DocsRouteChildren: DocsRouteChildren = { - DocsSectionRoute: DocsSectionRoute, -} - -const DocsRouteWithChildren = DocsRoute._addFileChildren(DocsRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - DocsRoute: DocsRouteWithChildren, - SettingsRoute: SettingsRoute, - ArticlesIdRoute: ArticlesIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/head/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/head/vue/src/routes/__root.tsx deleted file mode 100644 index ad87699fef..0000000000 --- a/benchmarks/client-nav/scenarios/head/vue/src/routes/__root.tsx +++ /dev/null @@ -1,58 +0,0 @@ -import * as Vue from 'vue' -import { - HeadContent, - Link, - Outlet, - createRootRoute, -} from '@tanstack/vue-router' -import { articleIds, docsSections, rootHead } from '../../../shared' - -const RootComponent = Vue.defineComponent({ - setup() { - return () => ( - <> - - - - - ) - }, -}) - -export const Route = createRootRoute({ - head: rootHead, - component: RootComponent, -}) diff --git a/benchmarks/client-nav/scenarios/head/vue/src/routes/articles.$id.tsx b/benchmarks/client-nav/scenarios/head/vue/src/routes/articles.$id.tsx deleted file mode 100644 index 43a6fade58..0000000000 --- a/benchmarks/client-nav/scenarios/head/vue/src/routes/articles.$id.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' -import { articleDescription, articleHead, articleTitle } from '../../../shared' - -const ArticlePage = Vue.defineComponent({ - setup() { - const params = Route.useParams() - - return () => ( -
-

{articleTitle(params.value.id)}

-

{articleDescription(params.value.id)}

-
- ) - }, -}) - -export const Route = createFileRoute('/articles/$id')({ - head: ({ params }) => articleHead(params.id), - component: ArticlePage, -}) diff --git a/benchmarks/client-nav/scenarios/head/vue/src/routes/docs.$section.tsx b/benchmarks/client-nav/scenarios/head/vue/src/routes/docs.$section.tsx deleted file mode 100644 index ebb59d61a2..0000000000 --- a/benchmarks/client-nav/scenarios/head/vue/src/routes/docs.$section.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' -import { docsDescription, docsSectionHead, docsTitle } from '../../../shared' - -const DocsSectionPage = Vue.defineComponent({ - setup() { - const params = Route.useParams() - - return () => ( -
-

{docsTitle(params.value.section)}

-

{docsDescription(params.value.section)}

-
- ) - }, -}) - -export const Route = createFileRoute('/docs/$section')({ - head: ({ params }) => docsSectionHead(params.section), - component: DocsSectionPage, -}) diff --git a/benchmarks/client-nav/scenarios/head/vue/src/routes/docs.tsx b/benchmarks/client-nav/scenarios/head/vue/src/routes/docs.tsx deleted file mode 100644 index feabbc4d4a..0000000000 --- a/benchmarks/client-nav/scenarios/head/vue/src/routes/docs.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import * as Vue from 'vue' -import { Outlet, createFileRoute } from '@tanstack/vue-router' -import { docsLayoutHead } from '../../../shared' - -const DocsLayout = Vue.defineComponent({ - setup() { - return () => ( -
-

Docs

- -
- ) - }, -}) - -export const Route = createFileRoute('/docs')({ - head: docsLayoutHead, - component: DocsLayout, -}) diff --git a/benchmarks/client-nav/scenarios/head/vue/src/routes/index.tsx b/benchmarks/client-nav/scenarios/head/vue/src/routes/index.tsx deleted file mode 100644 index 421478833f..0000000000 --- a/benchmarks/client-nav/scenarios/head/vue/src/routes/index.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' -import { homeHead, homeTitle } from '../../../shared' - -const HomePage = Vue.defineComponent({ - setup() { - return () => ( -
-

{homeTitle}

-

Landing page

-
- ) - }, -}) - -export const Route = createFileRoute('/')({ - head: homeHead, - component: HomePage, -}) diff --git a/benchmarks/client-nav/scenarios/head/vue/src/routes/settings.tsx b/benchmarks/client-nav/scenarios/head/vue/src/routes/settings.tsx deleted file mode 100644 index 1a519e16c2..0000000000 --- a/benchmarks/client-nav/scenarios/head/vue/src/routes/settings.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' -import { settingsHead, settingsTitle } from '../../../shared' - -const SettingsPage = Vue.defineComponent({ - setup() { - return () => ( -
-

{settingsTitle}

-

Account settings

-
- ) - }, -}) - -export const Route = createFileRoute('/settings')({ - head: settingsHead, - component: SettingsPage, -}) diff --git a/benchmarks/client-nav/scenarios/head/vue/tsconfig.json b/benchmarks/client-nav/scenarios/head/vue/tsconfig.json deleted file mode 100644 index 7786fc3da9..0000000000 --- a/benchmarks/client-nav/scenarios/head/vue/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/head/vue/vite.config.ts b/benchmarks/client-nav/scenarios/head/vue/vite.config.ts deleted file mode 100644 index bb1126d85f..0000000000 --- a/benchmarks/client-nav/scenarios/head/vue/vite.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'vue', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav head (vue)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - }, -}) diff --git a/benchmarks/client-nav/scenarios/history/react/project.json b/benchmarks/client-nav/scenarios/history/react/project.json deleted file mode 100644 index a2fe0001be..0000000000 --- a/benchmarks/client-nav/scenarios/history/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-history-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/history/react/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/history/react/setup.ts b/benchmarks/client-nav/scenarios/history/react/setup.ts deleted file mode 100644 index c26b7ffd08..0000000000 --- a/benchmarks/client-nav/scenarios/history/react/setup.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, steps } 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, - historyMode: 'browser', - steps, - assertAfterStep: assertStepResult, - }) -} diff --git a/benchmarks/client-nav/scenarios/history/react/speed.bench.ts b/benchmarks/client-nav/scenarios/history/react/speed.bench.ts deleted file mode 100644 index 6ec7031857..0000000000 --- a/benchmarks/client-nav/scenarios/history/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-history', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-history 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/history/react/speed.flame.ts b/benchmarks/client-nav/scenarios/history/react/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/history/react/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/history/react/src/main.tsx b/benchmarks/client-nav/scenarios/history/react/src/main.tsx deleted file mode 100644 index 5febd6f795..0000000000 --- a/benchmarks/client-nav/scenarios/history/react/src/main.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { RouterProvider, createRouter } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const reactRoot = createRoot(container) - reactRoot.render() - - return { - router, - unmount() { - reactRoot.unmount() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/history/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/history/react/src/routeTree.gen.ts deleted file mode 100644 index 21bb12ba35..0000000000 --- a/benchmarks/client-nav/scenarios/history/react/src/routeTree.gen.ts +++ /dev/null @@ -1,113 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as GalleryRouteImport } from './routes/gallery' -import { Route as PagesNRouteImport } from './routes/pages.$n' -import { Route as PhotosPhotoIdRouteImport } from './routes/photos.$photoId' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const GalleryRoute = GalleryRouteImport.update({ - id: '/gallery', - path: '/gallery', - getParentRoute: () => rootRouteImport, -} as any) -const PagesNRoute = PagesNRouteImport.update({ - id: '/pages/$n', - path: '/pages/$n', - getParentRoute: () => rootRouteImport, -} as any) -const PhotosPhotoIdRoute = PhotosPhotoIdRouteImport.update({ - id: '/photos/$photoId', - path: '/photos/$photoId', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/gallery': typeof GalleryRoute - '/pages/$n': typeof PagesNRoute - '/photos/$photoId': typeof PhotosPhotoIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/gallery': typeof GalleryRoute - '/pages/$n': typeof PagesNRoute - '/photos/$photoId': typeof PhotosPhotoIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/gallery': typeof GalleryRoute - '/pages/$n': typeof PagesNRoute - '/photos/$photoId': typeof PhotosPhotoIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/gallery' | '/pages/$n' | '/photos/$photoId' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/gallery' | '/pages/$n' | '/photos/$photoId' - id: '__root__' | '/' | '/gallery' | '/pages/$n' | '/photos/$photoId' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - GalleryRoute: typeof GalleryRoute - PagesNRoute: typeof PagesNRoute - PhotosPhotoIdRoute: typeof PhotosPhotoIdRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/gallery': { - id: '/gallery' - path: '/gallery' - fullPath: '/gallery' - preLoaderRoute: typeof GalleryRouteImport - parentRoute: typeof rootRouteImport - } - '/pages/$n': { - id: '/pages/$n' - path: '/pages/$n' - fullPath: '/pages/$n' - preLoaderRoute: typeof PagesNRouteImport - parentRoute: typeof rootRouteImport - } - '/photos/$photoId': { - id: '/photos/$photoId' - path: '/photos/$photoId' - fullPath: '/photos/$photoId' - preLoaderRoute: typeof PhotosPhotoIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - GalleryRoute: GalleryRoute, - PagesNRoute: PagesNRoute, - PhotosPhotoIdRoute: PhotosPhotoIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/history/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/history/react/src/routes/__root.tsx deleted file mode 100644 index 240d8719d4..0000000000 --- a/benchmarks/client-nav/scenarios/history/react/src/routes/__root.tsx +++ /dev/null @@ -1,66 +0,0 @@ -import { - Link, - Outlet, - createRootRoute, - useBlocker, - useCanGoBack, - useLocation, -} from '@tanstack/react-router' -import { maskedPhotoId, shouldBlockFn } from '../../../shared' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - const pathname = useLocation({ select: (location) => location.pathname }) - const canGoBack = useCanGoBack() - - useBlocker({ shouldBlockFn }) - - return ( - <> - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/history/react/src/routes/gallery.tsx b/benchmarks/client-nav/scenarios/history/react/src/routes/gallery.tsx deleted file mode 100644 index 55094556a6..0000000000 --- a/benchmarks/client-nav/scenarios/history/react/src/routes/gallery.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/gallery')({ - component: GalleryPage, -}) - -function GalleryPage() { - return ( -
-

Gallery

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/history/react/src/routes/index.tsx b/benchmarks/client-nav/scenarios/history/react/src/routes/index.tsx deleted file mode 100644 index 932a72f2ef..0000000000 --- a/benchmarks/client-nav/scenarios/history/react/src/routes/index.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: HomePage, -}) - -function HomePage() { - return ( -
-

Home

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/history/react/src/routes/pages.$n.tsx b/benchmarks/client-nav/scenarios/history/react/src/routes/pages.$n.tsx deleted file mode 100644 index b9c5e2f8d0..0000000000 --- a/benchmarks/client-nav/scenarios/history/react/src/routes/pages.$n.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { pageLabel } from '../../../shared' - -export const Route = createFileRoute('/pages/$n')({ - component: PageComponent, -}) - -function PageComponent() { - const params = Route.useParams() - - return ( -
-

{pageLabel(params.n)}

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/history/react/src/routes/photos.$photoId.tsx b/benchmarks/client-nav/scenarios/history/react/src/routes/photos.$photoId.tsx deleted file mode 100644 index 793b531c89..0000000000 --- a/benchmarks/client-nav/scenarios/history/react/src/routes/photos.$photoId.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { photoLabel } from '../../../shared' - -export const Route = createFileRoute('/photos/$photoId')({ - component: PhotoComponent, -}) - -function PhotoComponent() { - const params = Route.useParams() - - return ( -
-

{photoLabel(params.photoId)}

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/history/react/tsconfig.json b/benchmarks/client-nav/scenarios/history/react/tsconfig.json deleted file mode 100644 index 1d59cbb450..0000000000 --- a/benchmarks/client-nav/scenarios/history/react/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/history/react/vite.config.ts b/benchmarks/client-nav/scenarios/history/react/vite.config.ts deleted file mode 100644 index bdbde9c668..0000000000 --- a/benchmarks/client-nav/scenarios/history/react/vite.config.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'react', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav history (react)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - }, -}) diff --git a/benchmarks/client-nav/scenarios/history/shared.ts b/benchmarks/client-nav/scenarios/history/shared.ts deleted file mode 100644 index be6096cea8..0000000000 --- a/benchmarks/client-nav/scenarios/history/shared.ts +++ /dev/null @@ -1,94 +0,0 @@ -/** - * Shared definition of the `history` scenario: push/replace/back/forward - * traversal, location masking, blocker registration overhead (the blocker - * never blocks), and useLocation/useCanGoBack subscriptions. - * - * The step lap is designed to keep the history depth stationary: it ends back - * on the initial entry, so the first push of the next lap truncates the stale - * forward tail and the session history never grows past 4 entries. - */ -import type { ScenarioStep } from '../harness' -import type { RouterHistory } from '@tanstack/history' - -export const pageIds = ['1', '2', '3'] as const -export const maskedPhotoId = '42' - -export function pageLabel(n: string) { - return `Page ${n}` -} - -export function photoLabel(id: string) { - return `Photo ${id}` -} - -/** Registered on every navigation, never blocks. */ -export const shouldBlockFn = () => false - -interface HistoryStepExpectation { - step: ScenarioStep - /** Expected router location pathname (the REAL location, even when masked). */ - pathname: string - /** Expected browser-history pathname when it differs (location masking). */ - windowPathname?: string - /** Marker test id that must be present in the container after the step. */ - marker?: string -} - -export const stepExpectations: ReadonlyArray = [ - { step: 'p-1', pathname: '/pages/1', marker: 'page-state' }, - { step: 'p-2', pathname: '/pages/2', marker: 'page-state' }, - { - step: 'photo-masked', - pathname: `/photos/${maskedPhotoId}`, - windowPathname: '/gallery', - marker: 'photo-state', - }, - { step: { type: 'back' }, pathname: '/pages/2', marker: 'page-state' }, - { step: { type: 'back' }, pathname: '/pages/1', marker: 'page-state' }, - { step: { type: 'forward' }, pathname: '/pages/2', marker: 'page-state' }, - { step: 'p-3-replace', pathname: '/pages/3', marker: 'page-state' }, - { step: { type: 'back' }, pathname: '/pages/1', marker: 'page-state' }, - { step: { type: 'back' }, pathname: '/', marker: 'home-state' }, -] - -export const steps = stepExpectations.map((expectation) => expectation.step) - -export function assertStepResult( - stepIndex: number, - container: HTMLElement, - history: RouterHistory, -) { - const expected = stepExpectations[stepIndex]! - - const loc = container.querySelector('[data-testid="loc"]')?.textContent - if (loc !== expected.pathname) { - throw new Error( - `Expected location marker to be "${expected.pathname}" after step ${stepIndex}, received "${loc}"`, - ) - } - - const windowPathname = expected.windowPathname ?? expected.pathname - if (history.location.pathname !== windowPathname) { - throw new Error( - `Expected history.location.pathname to be "${windowPathname}" after step ${stepIndex}, received "${history.location.pathname}"`, - ) - } - - if ( - expected.marker && - !container.querySelector(`[data-testid="${expected.marker}"]`) - ) { - throw new Error( - `Expected marker "${expected.marker}" to be rendered after step ${stepIndex}`, - ) - } -} - -// Two laps through the 9-step sequence per benchmark iteration. -export const ticksPerIteration = 18 - -export const benchOptions = { - warmupIterations: 100, - time: 10_000, - throws: true, -} diff --git a/benchmarks/client-nav/scenarios/history/solid/project.json b/benchmarks/client-nav/scenarios/history/solid/project.json deleted file mode 100644 index 6f4bba1ca5..0000000000 --- a/benchmarks/client-nav/scenarios/history/solid/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-history-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/history/solid/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/history/solid/setup.ts b/benchmarks/client-nav/scenarios/history/solid/setup.ts deleted file mode 100644 index 4adf55d6df..0000000000 --- a/benchmarks/client-nav/scenarios/history/solid/setup.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, steps } 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, - historyMode: 'browser', - steps, - assertAfterStep: assertStepResult, - }) -} diff --git a/benchmarks/client-nav/scenarios/history/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/history/solid/speed.bench.ts deleted file mode 100644 index 56af035b2b..0000000000 --- a/benchmarks/client-nav/scenarios/history/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-history', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-history 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/history/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/history/solid/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/history/solid/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/history/solid/src/main.tsx b/benchmarks/client-nav/scenarios/history/solid/src/main.tsx deleted file mode 100644 index fa9d239418..0000000000 --- a/benchmarks/client-nav/scenarios/history/solid/src/main.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { render } from 'solid-js/web' -import { RouterProvider, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const unmount = render(() => , container) - - return { - router, - unmount, - } -} diff --git a/benchmarks/client-nav/scenarios/history/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/history/solid/src/routeTree.gen.ts deleted file mode 100644 index af253f4a15..0000000000 --- a/benchmarks/client-nav/scenarios/history/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,113 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as GalleryRouteImport } from './routes/gallery' -import { Route as PagesNRouteImport } from './routes/pages.$n' -import { Route as PhotosPhotoIdRouteImport } from './routes/photos.$photoId' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const GalleryRoute = GalleryRouteImport.update({ - id: '/gallery', - path: '/gallery', - getParentRoute: () => rootRouteImport, -} as any) -const PagesNRoute = PagesNRouteImport.update({ - id: '/pages/$n', - path: '/pages/$n', - getParentRoute: () => rootRouteImport, -} as any) -const PhotosPhotoIdRoute = PhotosPhotoIdRouteImport.update({ - id: '/photos/$photoId', - path: '/photos/$photoId', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/gallery': typeof GalleryRoute - '/pages/$n': typeof PagesNRoute - '/photos/$photoId': typeof PhotosPhotoIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/gallery': typeof GalleryRoute - '/pages/$n': typeof PagesNRoute - '/photos/$photoId': typeof PhotosPhotoIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/gallery': typeof GalleryRoute - '/pages/$n': typeof PagesNRoute - '/photos/$photoId': typeof PhotosPhotoIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/gallery' | '/pages/$n' | '/photos/$photoId' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/gallery' | '/pages/$n' | '/photos/$photoId' - id: '__root__' | '/' | '/gallery' | '/pages/$n' | '/photos/$photoId' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - GalleryRoute: typeof GalleryRoute - PagesNRoute: typeof PagesNRoute - PhotosPhotoIdRoute: typeof PhotosPhotoIdRoute -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/gallery': { - id: '/gallery' - path: '/gallery' - fullPath: '/gallery' - preLoaderRoute: typeof GalleryRouteImport - parentRoute: typeof rootRouteImport - } - '/pages/$n': { - id: '/pages/$n' - path: '/pages/$n' - fullPath: '/pages/$n' - preLoaderRoute: typeof PagesNRouteImport - parentRoute: typeof rootRouteImport - } - '/photos/$photoId': { - id: '/photos/$photoId' - path: '/photos/$photoId' - fullPath: '/photos/$photoId' - preLoaderRoute: typeof PhotosPhotoIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - GalleryRoute: GalleryRoute, - PagesNRoute: PagesNRoute, - PhotosPhotoIdRoute: PhotosPhotoIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/history/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/history/solid/src/routes/__root.tsx deleted file mode 100644 index edf7368929..0000000000 --- a/benchmarks/client-nav/scenarios/history/solid/src/routes/__root.tsx +++ /dev/null @@ -1,66 +0,0 @@ -import { - Link, - Outlet, - createRootRoute, - useBlocker, - useCanGoBack, - useLocation, -} from '@tanstack/solid-router' -import { maskedPhotoId, shouldBlockFn } from '../../../shared' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - const pathname = useLocation({ select: (location) => location.pathname }) - const canGoBack = useCanGoBack() - - useBlocker({ shouldBlockFn }) - - return ( - <> - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/history/solid/src/routes/gallery.tsx b/benchmarks/client-nav/scenarios/history/solid/src/routes/gallery.tsx deleted file mode 100644 index b72d1c6195..0000000000 --- a/benchmarks/client-nav/scenarios/history/solid/src/routes/gallery.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/gallery')({ - component: GalleryPage, -}) - -function GalleryPage() { - return ( -
-

Gallery

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/history/solid/src/routes/index.tsx b/benchmarks/client-nav/scenarios/history/solid/src/routes/index.tsx deleted file mode 100644 index 44a0b8045a..0000000000 --- a/benchmarks/client-nav/scenarios/history/solid/src/routes/index.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/')({ - component: HomePage, -}) - -function HomePage() { - return ( -
-

Home

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/history/solid/src/routes/pages.$n.tsx b/benchmarks/client-nav/scenarios/history/solid/src/routes/pages.$n.tsx deleted file mode 100644 index 1def6674c6..0000000000 --- a/benchmarks/client-nav/scenarios/history/solid/src/routes/pages.$n.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { pageLabel } from '../../../shared' - -export const Route = createFileRoute('/pages/$n')({ - component: PageComponent, -}) - -function PageComponent() { - const params = Route.useParams() - - return ( -
-

{pageLabel(params().n)}

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/history/solid/src/routes/photos.$photoId.tsx b/benchmarks/client-nav/scenarios/history/solid/src/routes/photos.$photoId.tsx deleted file mode 100644 index ab2fe06e3f..0000000000 --- a/benchmarks/client-nav/scenarios/history/solid/src/routes/photos.$photoId.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { photoLabel } from '../../../shared' - -export const Route = createFileRoute('/photos/$photoId')({ - component: PhotoComponent, -}) - -function PhotoComponent() { - const params = Route.useParams() - - return ( -
-

{photoLabel(params().photoId)}

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/history/solid/tsconfig.json b/benchmarks/client-nav/scenarios/history/solid/tsconfig.json deleted file mode 100644 index 98d76ad6b8..0000000000 --- a/benchmarks/client-nav/scenarios/history/solid/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/history/solid/vite.config.ts b/benchmarks/client-nav/scenarios/history/solid/vite.config.ts deleted file mode 100644 index 4da589ff0e..0000000000 --- a/benchmarks/client-nav/scenarios/history/solid/vite.config.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import solid from 'vite-plugin-solid' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'solid', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - resolve: { - conditions: ['solid', 'browser'], - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav history (solid)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/client-nav/scenarios/history/vue/project.json b/benchmarks/client-nav/scenarios/history/vue/project.json deleted file mode 100644 index 17fca887ca..0000000000 --- a/benchmarks/client-nav/scenarios/history/vue/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-history-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/history/vue/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/history/vue/setup.ts b/benchmarks/client-nav/scenarios/history/vue/setup.ts deleted file mode 100644 index df689964e4..0000000000 --- a/benchmarks/client-nav/scenarios/history/vue/setup.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, steps } 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, - historyMode: 'browser', - steps, - assertAfterStep: assertStepResult, - }) -} diff --git a/benchmarks/client-nav/scenarios/history/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/history/vue/speed.bench.ts deleted file mode 100644 index 3d36ac4cfa..0000000000 --- a/benchmarks/client-nav/scenarios/history/vue/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-history', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-history 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/history/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/history/vue/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/history/vue/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/history/vue/src/main.tsx b/benchmarks/client-nav/scenarios/history/vue/src/main.tsx deleted file mode 100644 index cae9b54f1d..0000000000 --- a/benchmarks/client-nav/scenarios/history/vue/src/main.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import * as Vue from 'vue' -import { RouterProvider, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const component = - const app = Vue.createApp({ - render: () => component, - }) - - app.mount(container) - - return { - router, - unmount() { - app.unmount() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/history/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/history/vue/src/routeTree.gen.ts deleted file mode 100644 index 519aef7c8f..0000000000 --- a/benchmarks/client-nav/scenarios/history/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,113 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as GalleryRouteImport } from './routes/gallery' -import { Route as PagesNRouteImport } from './routes/pages.$n' -import { Route as PhotosPhotoIdRouteImport } from './routes/photos.$photoId' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const GalleryRoute = GalleryRouteImport.update({ - id: '/gallery', - path: '/gallery', - getParentRoute: () => rootRouteImport, -} as any) -const PagesNRoute = PagesNRouteImport.update({ - id: '/pages/$n', - path: '/pages/$n', - getParentRoute: () => rootRouteImport, -} as any) -const PhotosPhotoIdRoute = PhotosPhotoIdRouteImport.update({ - id: '/photos/$photoId', - path: '/photos/$photoId', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/gallery': typeof GalleryRoute - '/pages/$n': typeof PagesNRoute - '/photos/$photoId': typeof PhotosPhotoIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/gallery': typeof GalleryRoute - '/pages/$n': typeof PagesNRoute - '/photos/$photoId': typeof PhotosPhotoIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/gallery': typeof GalleryRoute - '/pages/$n': typeof PagesNRoute - '/photos/$photoId': typeof PhotosPhotoIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/gallery' | '/pages/$n' | '/photos/$photoId' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/gallery' | '/pages/$n' | '/photos/$photoId' - id: '__root__' | '/' | '/gallery' | '/pages/$n' | '/photos/$photoId' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - GalleryRoute: typeof GalleryRoute - PagesNRoute: typeof PagesNRoute - PhotosPhotoIdRoute: typeof PhotosPhotoIdRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/gallery': { - id: '/gallery' - path: '/gallery' - fullPath: '/gallery' - preLoaderRoute: typeof GalleryRouteImport - parentRoute: typeof rootRouteImport - } - '/pages/$n': { - id: '/pages/$n' - path: '/pages/$n' - fullPath: '/pages/$n' - preLoaderRoute: typeof PagesNRouteImport - parentRoute: typeof rootRouteImport - } - '/photos/$photoId': { - id: '/photos/$photoId' - path: '/photos/$photoId' - fullPath: '/photos/$photoId' - preLoaderRoute: typeof PhotosPhotoIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - GalleryRoute: GalleryRoute, - PagesNRoute: PagesNRoute, - PhotosPhotoIdRoute: PhotosPhotoIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/history/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/history/vue/src/routes/__root.tsx deleted file mode 100644 index 7f7dff159c..0000000000 --- a/benchmarks/client-nav/scenarios/history/vue/src/routes/__root.tsx +++ /dev/null @@ -1,69 +0,0 @@ -import * as Vue from 'vue' -import { - Link, - Outlet, - createRootRoute, - useBlocker, - useCanGoBack, - useLocation, -} from '@tanstack/vue-router' -import { maskedPhotoId, shouldBlockFn } from '../../../shared' - -const RootComponent = Vue.defineComponent({ - setup() { - const pathname = useLocation({ select: (location) => location.pathname }) - const canGoBack = useCanGoBack() - - useBlocker({ shouldBlockFn }) - - return () => ( - <> - - - - ) - }, -}) - -export const Route = createRootRoute({ - component: RootComponent, -}) diff --git a/benchmarks/client-nav/scenarios/history/vue/src/routes/gallery.tsx b/benchmarks/client-nav/scenarios/history/vue/src/routes/gallery.tsx deleted file mode 100644 index 3a397b1843..0000000000 --- a/benchmarks/client-nav/scenarios/history/vue/src/routes/gallery.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const GalleryPage = Vue.defineComponent({ - setup() { - return () => ( -
-

Gallery

-
- ) - }, -}) - -export const Route = createFileRoute('/gallery')({ - component: GalleryPage, -}) diff --git a/benchmarks/client-nav/scenarios/history/vue/src/routes/index.tsx b/benchmarks/client-nav/scenarios/history/vue/src/routes/index.tsx deleted file mode 100644 index fbc5b957a7..0000000000 --- a/benchmarks/client-nav/scenarios/history/vue/src/routes/index.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const HomePage = Vue.defineComponent({ - setup() { - return () => ( -
-

Home

-
- ) - }, -}) - -export const Route = createFileRoute('/')({ - component: HomePage, -}) diff --git a/benchmarks/client-nav/scenarios/history/vue/src/routes/pages.$n.tsx b/benchmarks/client-nav/scenarios/history/vue/src/routes/pages.$n.tsx deleted file mode 100644 index 560e83ed29..0000000000 --- a/benchmarks/client-nav/scenarios/history/vue/src/routes/pages.$n.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' -import { pageLabel } from '../../../shared' - -const PageComponent = Vue.defineComponent({ - setup() { - const params = Route.useParams() - - return () => ( -
-

{pageLabel(params.value.n)}

-
- ) - }, -}) - -export const Route = createFileRoute('/pages/$n')({ - component: PageComponent, -}) diff --git a/benchmarks/client-nav/scenarios/history/vue/src/routes/photos.$photoId.tsx b/benchmarks/client-nav/scenarios/history/vue/src/routes/photos.$photoId.tsx deleted file mode 100644 index 186566fe72..0000000000 --- a/benchmarks/client-nav/scenarios/history/vue/src/routes/photos.$photoId.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' -import { photoLabel } from '../../../shared' - -const PhotoComponent = Vue.defineComponent({ - setup() { - const params = Route.useParams() - - return () => ( -
-

{photoLabel(params.value.photoId)}

-
- ) - }, -}) - -export const Route = createFileRoute('/photos/$photoId')({ - component: PhotoComponent, -}) diff --git a/benchmarks/client-nav/scenarios/history/vue/tsconfig.json b/benchmarks/client-nav/scenarios/history/vue/tsconfig.json deleted file mode 100644 index 7786fc3da9..0000000000 --- a/benchmarks/client-nav/scenarios/history/vue/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/history/vue/vite.config.ts b/benchmarks/client-nav/scenarios/history/vue/vite.config.ts deleted file mode 100644 index c5f1ca9807..0000000000 --- a/benchmarks/client-nav/scenarios/history/vue/vite.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'vue', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav history (vue)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - }, -}) diff --git a/benchmarks/client-nav/scenarios/hydration/react/fixture.ts b/benchmarks/client-nav/scenarios/hydration/react/fixture.ts deleted file mode 100644 index 950c870a1c..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/fixture.ts +++ /dev/null @@ -1,31 +0,0 @@ -export const ordinaryLinkCount = 192 -export const hashLinkCount = 8 -export const serverUrl = '/teams/team-7/items/item-42?view=summary' -export const clientUrl = `${serverUrl}#details` - -export interface Diagnostics { - beforeLoads: number - loaders: number - mounted: boolean - clicks: number - ordinaryRenders: number - hashRenders: number - countRenders: boolean -} - -export function createDiagnostics(countRenders = false): Diagnostics { - return { - beforeLoads: 0, - loaders: 0, - mounted: false, - clicks: 0, - ordinaryRenders: 0, - hashRenders: 0, - countRenders, - } -} - -export interface FixtureArtifact { - html: string - scripts: Array -} diff --git a/benchmarks/client-nav/scenarios/hydration/react/generate-fixture.mjs b/benchmarks/client-nav/scenarios/hydration/react/generate-fixture.mjs deleted file mode 100644 index fbc67c5a08..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/generate-fixture.mjs +++ /dev/null @@ -1,23 +0,0 @@ -import assert from 'node:assert/strict' -import { writeFile } from 'node:fs/promises' -import { JSDOM } from 'jsdom' - -if (process.env.NODE_ENV !== 'production') { - throw new Error('Generate the hydration fixture in production mode') -} -const { renderFixture } = await import('./dist/server/server.js') -const html = await renderFixture() -const dom = new JSDOM(html) -try { - const scriptElements = [...dom.window.document.querySelectorAll('script')] - assert.ok(scriptElements.length > 0) - assert.ok(scriptElements.every((script) => !script.src)) - const scripts = scriptElements.map((script) => script.textContent) - assert.ok(scripts.some((script) => script.includes('$_TSR'))) - await writeFile( - new URL('./dist/fixture.json', import.meta.url), - JSON.stringify({ html, scripts }), - ) -} finally { - dom.window.close() -} diff --git a/benchmarks/client-nav/scenarios/hydration/react/hydration.test.ts b/benchmarks/client-nav/scenarios/hydration/react/hydration.test.ts deleted file mode 100644 index 7e466cbaed..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/hydration.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { expect, test } from 'vitest' -import { hashLinkCount, ordinaryLinkCount } from './fixture' -import { setup } from './setup' -import { settleHydration } from './settle' - -const turn = () => new Promise((resolve) => setImmediate(resolve)) - -test('restores data and context into fresh DOMs and includes follow-up renders', async () => { - const scenario = setup({ countRenders: true }) - const schedulerTasks = new Set() - for (let iteration = 0; iteration < 3; iteration++) { - await scenario.before() - try { - expect(scenario.snapshot().diagnostics.mounted).toBe(false) - expect(scenario.snapshot().matches).toBeUndefined() - await scenario.run() - schedulerTasks.add(scenario.schedulerTasks()) - const completed = scenario.snapshot() - // Supports both main's extra Link update and the optimized snapshot. - expect([ordinaryLinkCount, ordinaryLinkCount * 2]).toContain( - completed.diagnostics.ordinaryRenders, - ) - expect(completed.diagnostics.hashRenders).toBeGreaterThanOrEqual( - hashLinkCount + hashLinkCount / 2, - ) - for (let index = 0; index < 4; index++) { - await turn() - } - expect(scenario.snapshot()).toEqual(completed) - await expect(scenario.run()).rejects.toThrow('newly prepared sample') - } finally { - await scenario.after() - } - } - // React yields on its pinned clock, never on wall time spent hydrating. - expect(schedulerTasks.size).toBe(1) -}) - -test('rejects an empty measurement and still releases its sample', async () => { - const scenario = setup() - await scenario.before() - await expect(scenario.after()).rejects.toThrow( - 'Hydration sample was not completed', - ) - await scenario.before() - try { - await scenario.run() - } finally { - await scenario.after() - } -}) - -test('waits for a commit and scheduler work lasting more than 100 turns', async () => { - let committed = false - const commit = (async () => { - for (let index = 0; index < 150; index++) { - await turn() - } - committed = true - })() - let remainingCallbacks = 150 - await settleHydration( - commit, - () => { - expect(committed).toBe(true) - return remainingCallbacks-- <= 0 - }, - () => 'delayed commit', - ) - expect(remainingCallbacks).toBeLessThan(0) -}) - -test('retains a watchdog for a commit that never completes', async () => { - await expect( - settleHydration( - new Promise(() => {}), - () => true, - () => 'commit pending', - 10, - ), - ).rejects.toThrow('Hydration did not settle within 10ms: commit pending') -}) - -test('retains a watchdog when scheduler work never becomes idle', async () => { - await expect( - settleHydration( - Promise.resolve(), - () => false, - () => 'callbacks pending', - 10, - ), - ).rejects.toThrow('Hydration did not settle within 10ms: callbacks pending') -}) diff --git a/benchmarks/client-nav/scenarios/hydration/react/project.json b/benchmarks/client-nav/scenarios/hydration/react/project.json deleted file mode 100644 index ca23838c0f..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-hydration-react", - "projectType": "application", - "targets": { - "build:client": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { "projects": ["@tanstack/react-router"], "target": "build" } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.server.config.ts && NODE_ENV=production node {projectRoot}/generate-fixture.mjs && NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:unit": { - "executor": "nx:run-commands", - "dependsOn": ["build:client"], - "options": { - "command": "vitest run --config ./scenarios/hydration/react/vite.config.ts", - "cwd": "benchmarks/client-nav" - } - }, - "test:perf": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": ["build:client"], - "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --run --config ./scenarios/hydration/react/vite.config.ts", - "cwd": "benchmarks/client-nav" - } - }, - "test:types:client": { - "executor": "nx:run-commands", - "dependsOn": [ - { "projects": ["@tanstack/react-router"], "target": "build" } - ], - "options": { "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" } - } - } -} diff --git a/benchmarks/client-nav/scenarios/hydration/react/settle.ts b/benchmarks/client-nav/scenarios/hydration/react/settle.ts deleted file mode 100644 index cc4c09a72d..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/settle.ts +++ /dev/null @@ -1,35 +0,0 @@ -const turn = () => new Promise((resolve) => setImmediate(resolve)) - -export async function settleHydration( - committed: Promise, - isIdle: () => boolean, - describeProgress: () => string, - timeoutMs = 60_000, -) { - let timeoutError: Error | undefined - let watchdog: ReturnType | undefined - const timeout = new Promise((_, reject) => { - watchdog = setTimeout(() => { - timeoutError = new Error( - `Hydration did not settle within ${timeoutMs}ms: ${describeProgress()}`, - ) - reject(timeoutError) - }, timeoutMs) - }) - try { - // Concurrent hydration can need many more scheduler turns under CPU - // instrumentation. Await its commit instead of limiting successful work - // to an arbitrary number of event-loop polls. - await Promise.race([committed, timeout]) - let idleTurns = 0 - while (idleTurns < 2) { - await turn() - if (timeoutError) { - throw timeoutError - } - idleTurns = isIdle() ? idleTurns + 1 : 0 - } - } finally { - clearTimeout(watchdog) - } -} diff --git a/benchmarks/client-nav/scenarios/hydration/react/setup.ts b/benchmarks/client-nav/scenarios/hydration/react/setup.ts deleted file mode 100644 index 7c588af3fd..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/setup.ts +++ /dev/null @@ -1,316 +0,0 @@ -import assert from 'node:assert/strict' -import { readFileSync } from 'node:fs' -import { fileURLToPath } from 'node:url' -import { Script } from 'node:vm' -import { JSDOM, VirtualConsole } from 'jsdom' -import { clientUrl, hashLinkCount, ordinaryLinkCount } from './fixture' -import { settleHydration } from './settle' -import type { FixtureArtifact } from './fixture' -import type * as Client from './src/client' - -type ClientApp = typeof Client -const turn = () => new Promise((resolve) => setImmediate(resolve)) - -// React's scheduler ends a time slice once performance.now() has advanced 5 ms. -// Under CodSpeed's CPU simulation the wall clock advances much further per -// instruction, by a runner-dependent factor, so real time turned identical -// samples into different numbers of yields, scheduler tasks and event-loop -// turns. With a frozen clock React yields only to paint after a commit, as on -// a fast host. 1 s is past React's initial 300 ms fallback throttle. Only the -// window's performance clock is pinned: Date.now(), which the Router uses for -// match timestamps, is unchanged. -const schedulerTime = 1_000 - -export function setup({ countRenders = false } = {}) { - // Compile once, outside measurement. Evaluation below creates fresh objects - // in each window's realm; neither the payload nor module state is reused. - const artifact: FixtureArtifact = JSON.parse( - readFileSync(new URL('./dist/fixture.json', import.meta.url), 'utf8'), - ) - const clientPath = new URL('./dist/client/client.js', import.meta.url) - const clientScript = new Script(readFileSync(clientPath, 'utf8'), { - filename: fileURLToPath(clientPath), - }) - const bootstrapScripts = artifact.scripts.map( - (source, index) => - new Script(source, { - filename: `hydration-bootstrap-${index}.js`, - }), - ) - let current: Awaited> | undefined - - async function prepare() { - const errors: Array = [] - const virtualConsole = new VirtualConsole() - virtualConsole.on('jsdomError', (error) => errors.push(String(error))) - virtualConsole.on('error', (...args) => - errors.push(args.map(String).join(' ')), - ) - const dom = new JSDOM(artifact.html, { - url: `http://localhost${clientUrl}`, - runScripts: 'outside-only', - virtualConsole, - }) - const immediates = new Set() - const scheduler = { tasks: 0 } - try { - Object.assign(dom.window, { - TextEncoder, - TextDecoder, - ReadableStream, - WritableStream, - TransformStream, - // Let React's production scheduler use the same task-turn primitive as - // the existing Node client benchmarks, without a real-delay timer. - setImmediate( - callback: (...args: Array) => void, - ...args: Array - ) { - scheduler.tasks++ - const handle = setImmediate(() => { - immediates.delete(handle) - callback(...args) - }) - immediates.add(handle) - return handle - }, - clearImmediate(handle: NodeJS.Immediate) { - immediates.delete(handle) - clearImmediate(handle) - }, - fetch() { - throw new Error('Hydration attempted a network request') - }, - scrollTo() {}, - }) - dom.window.performance.now = () => schedulerTime - const context = dom.getInternalVMContext() - // jsdom has no layout/scroll implementation; only hydration CPU is measured. - dom.window.HTMLElement.prototype.scrollIntoView = () => {} - clientScript.runInContext(context) - const app = (dom.window as unknown as { HydrationBenchmark: ClientApp }) - .HydrationBenchmark - assert.equal(app.serverEnvironment, false) - const anchors = Array.from(dom.window.document.querySelectorAll('a')) - const scriptElements = Array.from( - dom.window.document.querySelectorAll('script'), - ) - const executingScript = { current: null as HTMLScriptElement | null } - Object.defineProperty(dom.window.document, 'currentScript', { - configurable: true, - get: () => executingScript.current, - }) - assert.equal(anchors.length, ordinaryLinkCount + hashLinkCount) - const content = dom.window.document.getElementById('hydration-content') - assert.ok(content) - // Finish jsdom's initial document lifecycle before opening the measure. - await turn() - assert.equal(dom.window.document.readyState, 'complete') - assert.equal(app.ready(), false) - return { - dom, - context, - app, - anchors, - content, - scriptElements, - executingScript, - immediates, - scheduler, - errors, - started: false, - completed: false, - failed: false, - } - } catch (error) { - for (const handle of immediates) { - clearImmediate(handle) - } - dom.window.close() - throw error - } - } - - async function before() { - if (current) { - throw new Error('Previous hydration sample was not disposed') - } - current = await prepare() - } - - async function run() { - const sample = current - if (!sample || sample.started) { - throw new Error('Hydration requires a newly prepared sample') - } - sample.started = true - try { - // HTML parsing/module evaluation are already done. Payload execution, - // router initialization/restoration and React hydration are measured. - for (let index = 0; index < bootstrapScripts.length; index++) { - // SSR bootstrap scripts remove their own script element after running. - sample.executingScript.current = sample.scriptElements[index]! - try { - bootstrapScripts[index]!.runInContext(sample.context) - } finally { - sample.executingScript.current = null - } - } - await settleHydration( - sample.app.start(countRenders), - () => sample.immediates.size === 0, - () => { - const progress = sample.app.snapshot() - return JSON.stringify({ - diagnostics: progress.diagnostics, - errors: [...sample.errors, ...progress.errors], - restoredMatches: progress.matches?.length, - pendingSchedulerCallbacks: sample.immediates.size, - }) - }, - ) - if (sample.errors.length) { - throw new Error(sample.errors.join('\n')) - } - assert.ok( - sample.app.ready(), - 'Hydration committed without the expected active links', - ) - sample.completed = true - } catch (error) { - sample.failed = true - throw error - } - } - - function snapshot() { - if (!current) { - throw new Error('No hydration sample') - } - // Normalize realm prototypes only for untimed assertions. - return JSON.parse(JSON.stringify(current.app.snapshot())) as ReturnType< - ClientApp['snapshot'] - > - } - - function schedulerTasks() { - if (!current) { - throw new Error('No hydration sample') - } - return current.scheduler.tasks - } - - function validate() { - assert.ok(current?.started) - const { dom, anchors, content, errors } = current - const doc = dom.window.document - const result = snapshot() - assert.deepEqual(errors, []) - assert.deepEqual(result.errors, []) - assert.equal(result.diagnostics.beforeLoads, 0) - assert.equal(result.diagnostics.loaders, 0) - assert.equal(result.diagnostics.mounted, true) - assert.equal(result.location, clientUrl) - assert.equal(result.matches?.length, 3) - for (const match of result.matches) { - assert.equal(match.status, 'success') - assert.deepEqual(match.context.viewer, { - id: 'viewer-3', - name: 'Ada', - role: 'editor', - }) - } - assert.deepEqual(result.matches[1]!.context.team, { - id: 'team-7', - member: 'viewer-3', - }) - assert.deepEqual(result.matches[2]!.context.permissions, { edit: true }) - assert.deepEqual(result.matches[1]!.loaderData, { - title: 'Team team-7', - categories: ['open', 'closed'], - }) - const data = result.matches[2]!.loaderData as { - owner: string - selected: string - rows: Array<{ - id: string - label: string - details: { score: number; open: boolean } - }> - } - assert.equal(data.owner, 'viewer-3') - assert.equal(data.selected, 'item-42') - assert.equal(data.rows.length, ordinaryLinkCount) - assert.equal(doc.getElementById('hydration-content'), content) - assert.equal(doc.querySelectorAll('a').length, anchors.length) - assert.equal(doc.getElementById('viewer')?.textContent, 'Ada') - assert.equal(doc.getElementById('permission')?.textContent, 'Editable') - for (const anchor of anchors) { - assert.equal(doc.getElementById(anchor.id), anchor) - } - for (let index = 0; index < ordinaryLinkCount; index++) { - const anchor = doc.getElementById(`ordinary-item-${index}`)! - assert.equal( - anchor.getAttribute('href'), - `/teams/team-7/items/item-${index}?view=summary`, - ) - assert.equal(anchor.textContent, `Item ${index}`) - assert.equal( - anchor.getAttribute('data-status'), - index === 42 ? 'active' : null, - ) - assert.deepEqual(data.rows[index], { - id: `item-${index}`, - label: `Item ${index}`, - details: { score: index * 3, open: index % 2 === 0 }, - }) - } - for (let index = 0; index < hashLinkCount; index++) { - assert.equal( - doc.getElementById(`hash-${index}`)?.getAttribute('data-status'), - index % 2 === 0 ? 'active' : null, - ) - } - doc - .getElementById('interactive')! - .dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true })) - assert.equal( - current.app.snapshot().diagnostics.clicks, - result.diagnostics.clicks + 1, - ) - } - - async function after() { - const sample = current - if (!sample) { - return - } - try { - if (!sample.failed) { - assert.ok(sample.completed, 'Hydration sample was not completed') - validate() - } - } finally { - current = undefined - try { - sample.app.dispose() - // Unmount work and its scheduled effects stay outside the measure. - await turn() - await turn() - } finally { - for (const handle of sample.immediates) { - clearImmediate(handle) - } - sample.dom.window.close() - } - } - } - - return { - before, - run, - after, - snapshot, - schedulerTasks, - } -} diff --git a/benchmarks/client-nav/scenarios/hydration/react/speed.bench.ts b/benchmarks/client-nav/scenarios/hydration/react/speed.bench.ts deleted file mode 100644 index 643877760e..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { setup } from './setup' - -test('client-hydration', async ({ bench }) => { - const scenario = setup() - - await bench( - 'hydrate restored route state and mixed Links (react)', - { beforeEach: scenario.before, afterEach: scenario.after }, - async () => { - await scenario.run() - }, - ).run({ - time: 5000, - warmupTime: 1000, - warmupIterations: 20, - throws: true, - }) -}) diff --git a/benchmarks/client-nav/scenarios/hydration/react/src/app.tsx b/benchmarks/client-nav/scenarios/hydration/react/src/app.tsx deleted file mode 100644 index e9797f71fa..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/src/app.tsx +++ /dev/null @@ -1,216 +0,0 @@ -import { useEffect } from 'react' -import { - HeadContent, - Link, - Outlet, - Scripts, - createMemoryHistory, - createRootRoute, - createRoute, - createRouter, - useHydrated, -} from '@tanstack/react-router' -import { - clientUrl, - hashLinkCount, - ordinaryLinkCount, - serverUrl, -} from '../fixture' -import type { ReactNode } from 'react' -import type { Diagnostics } from '../fixture' - -export function createFixtureRouter( - server: boolean, - diagnostics: Diagnostics, - onHydrated: () => void = () => {}, -) { - function beforeLoad() { - diagnostics.beforeLoads++ - if (!server) { - throw new Error('Hydration reran beforeLoad instead of restoring context') - } - } - - function loader() { - diagnostics.loaders++ - if (!server) { - throw new Error('Hydration reran a loader instead of restoring data') - } - } - - const root = createRootRoute({ - beforeLoad: () => { - beforeLoad() - return { viewer: { id: 'viewer-3', name: 'Ada', role: 'editor' } } - }, - head: () => ({ - meta: [{ charSet: 'utf-8' }, { title: 'Hydration benchmark' }], - }), - shellComponent: Document, - }) - const team = createRoute({ - getParentRoute: () => root, - path: '/teams/$teamId', - beforeLoad: ({ context, params }) => { - beforeLoad() - return { team: { id: params.teamId, member: context.viewer.id } } - }, - loader: ({ context }) => { - loader() - return { - title: `Team ${context.team.id}`, - categories: ['open', 'closed'], - } - }, - component: Team, - }) - const items = createRoute({ - getParentRoute: () => team, - path: 'items/$itemId', - validateSearch: (search: Record) => ({ - view: search.view === 'details' ? 'details' : 'summary', - }), - beforeLoad: ({ context }) => { - beforeLoad() - return { permissions: { edit: context.viewer.role === 'editor' } } - }, - loader: ({ context, params }) => { - loader() - return { - selected: params.itemId, - owner: context.team.member, - rows: Array.from({ length: ordinaryLinkCount }, (_, index) => ({ - id: `item-${index}`, - label: `Item ${index}`, - details: { score: index * 3, open: index % 2 === 0 }, - })), - } - }, - component: Items, - }) - - function Document({ children }: { children: ReactNode }) { - return ( - - - - - - {children} - - - - ) - } - - function Team() { - const context = team.useRouteContext() - const data = team.useLoaderData() - return ( -
-

{data.title}

-

{context.viewer.name}

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

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

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

{data().title}

-

{context().viewer.name}

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

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

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

{detailMarker(params.id)}

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

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

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

{otherMarker}

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

{detailMarker(params().id)}

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

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

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

{otherMarker}

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

{detailMarker(params.value.id)}

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

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

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

{otherMarker}

-
- ) - }, -}) - -export const Route = createFileRoute('/other')({ - component: OtherPage, -}) diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/tsconfig.json b/benchmarks/client-nav/scenarios/link-churn/vue/tsconfig.json deleted file mode 100644 index 7786fc3da9..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/vite.config.ts b/benchmarks/client-nav/scenarios/link-churn/vue/vite.config.ts deleted file mode 100644 index 8f56734e04..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/vite.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'vue', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav link-churn (vue)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - }, -}) diff --git a/benchmarks/client-nav/scenarios/links/react/project.json b/benchmarks/client-nav/scenarios/links/react/project.json deleted file mode 100644 index 52c9df8a68..0000000000 --- a/benchmarks/client-nav/scenarios/links/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-links-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/links/react/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/links/react/setup.ts b/benchmarks/client-nav/scenarios/links/react/setup.ts deleted file mode 100644 index 5409df903c..0000000000 --- a/benchmarks/client-nav/scenarios/links/react/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, 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, - }) -} diff --git a/benchmarks/client-nav/scenarios/links/react/speed.bench.ts b/benchmarks/client-nav/scenarios/links/react/speed.bench.ts deleted file mode 100644 index 75f5f725d4..0000000000 --- a/benchmarks/client-nav/scenarios/links/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-links', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-links 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/links/react/speed.flame.ts b/benchmarks/client-nav/scenarios/links/react/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/links/react/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/links/react/src/main.tsx b/benchmarks/client-nav/scenarios/links/react/src/main.tsx deleted file mode 100644 index 5febd6f795..0000000000 --- a/benchmarks/client-nav/scenarios/links/react/src/main.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { RouterProvider, createRouter } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const reactRoot = createRoot(container) - reactRoot.render() - - return { - router, - unmount() { - reactRoot.unmount() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/links/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/links/react/src/routeTree.gen.ts deleted file mode 100644 index 6e0c29ca88..0000000000 --- a/benchmarks/client-nav/scenarios/links/react/src/routeTree.gen.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as AboutRouteImport } from './routes/about' -import { Route as ItemsIdRouteImport } from './routes/items.$id' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) -const ItemsIdRoute = ItemsIdRouteImport.update({ - id: '/items/$id', - path: '/items/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/about': typeof AboutRoute - '/items/$id': typeof ItemsIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/about': typeof AboutRoute - '/items/$id': typeof ItemsIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/about': typeof AboutRoute - '/items/$id': typeof ItemsIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/about' | '/items/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/about' | '/items/$id' - id: '__root__' | '/' | '/about' | '/items/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - AboutRoute: typeof AboutRoute - ItemsIdRoute: typeof ItemsIdRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } - '/items/$id': { - id: '/items/$id' - path: '/items/$id' - fullPath: '/items/$id' - preLoaderRoute: typeof ItemsIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - AboutRoute: AboutRoute, - ItemsIdRoute: ItemsIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/links/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/links/react/src/routes/__root.tsx deleted file mode 100644 index 7a48510e8a..0000000000 --- a/benchmarks/client-nav/scenarios/links/react/src/routes/__root.tsx +++ /dev/null @@ -1,104 +0,0 @@ -import { - Link, - Outlet, - createRootRoute, - useMatchRoute, -} from '@tanstack/react-router' -import { - itemIds, - matchProbeIds, - stepItemIds, - variantSearch, -} from '../../../shared' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function StatusPanel() { - const matchRoute = useMatchRoute() - - return ( - - ) -} - -function LinkGrid() { - return ( -
- {itemIds.map((id) => ( -
- - {`Item ${id}`} - - - {`Item ${id} exact`} - - - {`Item ${id} search`} - - - {`Item ${id} hash`} - - - {({ isActive }) => (isActive ? `Item ${id} on` : `Item ${id} off`)} - -
- ))} -
- ) -} - -function RootComponent() { - return ( - <> - - - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/links/react/src/routes/about.tsx b/benchmarks/client-nav/scenarios/links/react/src/routes/about.tsx deleted file mode 100644 index 0e4afc9297..0000000000 --- a/benchmarks/client-nav/scenarios/links/react/src/routes/about.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { aboutMarker } from '../../../shared' - -export const Route = createFileRoute('/about')({ - component: AboutPage, -}) - -function AboutPage() { - return ( -
-

{aboutMarker}

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/links/react/src/routes/index.tsx b/benchmarks/client-nav/scenarios/links/react/src/routes/index.tsx deleted file mode 100644 index 2b8c83ebab..0000000000 --- a/benchmarks/client-nav/scenarios/links/react/src/routes/index.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { homeMarker } from '../../../shared' - -export const Route = createFileRoute('/')({ - component: HomePage, -}) - -function HomePage() { - return ( -
-

{homeMarker}

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/links/react/src/routes/items.$id.tsx b/benchmarks/client-nav/scenarios/links/react/src/routes/items.$id.tsx deleted file mode 100644 index 23121edb5c..0000000000 --- a/benchmarks/client-nav/scenarios/links/react/src/routes/items.$id.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { itemMarker } from '../../../shared' - -export const Route = createFileRoute('/items/$id')({ - component: ItemPage, -}) - -function ItemPage() { - const params = Route.useParams() - - return ( -
-

{itemMarker(params.id)}

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/links/react/tsconfig.json b/benchmarks/client-nav/scenarios/links/react/tsconfig.json deleted file mode 100644 index 1d59cbb450..0000000000 --- a/benchmarks/client-nav/scenarios/links/react/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/links/react/vite.config.ts b/benchmarks/client-nav/scenarios/links/react/vite.config.ts deleted file mode 100644 index 69de10b5b7..0000000000 --- a/benchmarks/client-nav/scenarios/links/react/vite.config.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'react', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav links (react)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - }, -}) diff --git a/benchmarks/client-nav/scenarios/links/shared.ts b/benchmarks/client-nav/scenarios/links/shared.ts deleted file mode 100644 index 6e75ea045c..0000000000 --- a/benchmarks/client-nav/scenarios/links/shared.ts +++ /dev/null @@ -1,133 +0,0 @@ -/** - * Shared definition of the `links` scenario: a large persistent grid of - * ``s in the root layout so every navigation recomputes link props and - * active state across many activeOptions variants, plus `useMatchRoute` / - * `MatchRoute` consumers. The three framework apps consume these constants so - * the workload is identical modulo the rendering layer. - */ -import type { ScenarioStep } from '../harness' - -// 40 item ids x 5 link variants = 200 links mounted in the root layout. -export const LINK_ITEM_COUNT = 40 -export const LINK_VARIANT_COUNT = 5 - -export const itemIds = Array.from({ length: LINK_ITEM_COUNT }, (_, index) => - String(index + 1), -) - -// Static search object attached to the includeSearch:false variant. -export const variantSearch = { tab: 'specs', page: 2 } - -// Item ids that get a `go-item-` test id on their plain variant link. -export const stepItemIds = ['1', '7', '13', '25', '40'] - -// Ids probed by the useMatchRoute checks in the root StatusPanel. -export const matchProbeIds = [ - '1', - '5', - '7', - '13', - '20', - '25', - '30', - '35', - '40', - '2', -] - -export function itemMarker(id: string) { - return `item-${id}` -} - -export const homeMarker = 'home' -export const aboutMarker = 'about' - -interface StepDef { - testId: string - marker: string - /** Expected number of `.active-link` elements after the step. */ - activeCount: number - /** When one link is active, its href must include this substring. */ - activeHrefPart?: string -} - -export const stepDefs: ReadonlyArray = [ - { - testId: 'go-item-1', - marker: itemMarker('1'), - activeCount: 1, - activeHrefPart: '/items/1', - }, - { - testId: 'go-item-7', - marker: itemMarker('7'), - activeCount: 1, - activeHrefPart: '/items/7', - }, - { testId: 'go-about', marker: aboutMarker, activeCount: 0 }, - { - testId: 'go-item-13', - marker: itemMarker('13'), - activeCount: 1, - activeHrefPart: '/items/13', - }, - { - testId: 'go-item-25', - marker: itemMarker('25'), - activeCount: 1, - activeHrefPart: '/items/25', - }, - { - testId: 'go-item-40', - marker: itemMarker('40'), - activeCount: 1, - activeHrefPart: '/items/40', - }, - { - testId: 'go-item-7', - marker: itemMarker('7'), - activeCount: 1, - activeHrefPart: '/items/7', - }, - { testId: 'go-home', marker: homeMarker, activeCount: 0 }, -] - -export const scenarioSteps: ReadonlyArray = stepDefs.map( - (step) => step.testId, -) - -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}`, - ) - } - if (step.activeHrefPart) { - const href = activeLinks[0]!.getAttribute('href') ?? '' - if (!href.includes(step.activeHrefPart)) { - throw new Error( - `Expected the active link href to include "${step.activeHrefPart}" after step ${stepIndex}, received "${href}"`, - ) - } - } -} - -// One lap through the 8-step sequence per benchmark iteration; each step -// recomputes all 200 links plus the match probes. -export const ticksPerIteration = 8 - -export const benchOptions = { - warmupIterations: 50, - time: 10_000, - throws: true, -} diff --git a/benchmarks/client-nav/scenarios/links/solid/project.json b/benchmarks/client-nav/scenarios/links/solid/project.json deleted file mode 100644 index ef1dab4c50..0000000000 --- a/benchmarks/client-nav/scenarios/links/solid/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-links-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/links/solid/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/links/solid/setup.ts b/benchmarks/client-nav/scenarios/links/solid/setup.ts deleted file mode 100644 index 34270fe8a4..0000000000 --- a/benchmarks/client-nav/scenarios/links/solid/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, 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, - }) -} diff --git a/benchmarks/client-nav/scenarios/links/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/links/solid/speed.bench.ts deleted file mode 100644 index fc7f3e71e7..0000000000 --- a/benchmarks/client-nav/scenarios/links/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-links', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-links 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/links/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/links/solid/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/links/solid/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/links/solid/src/main.tsx b/benchmarks/client-nav/scenarios/links/solid/src/main.tsx deleted file mode 100644 index fa9d239418..0000000000 --- a/benchmarks/client-nav/scenarios/links/solid/src/main.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { render } from 'solid-js/web' -import { RouterProvider, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const unmount = render(() => , container) - - return { - router, - unmount, - } -} diff --git a/benchmarks/client-nav/scenarios/links/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/links/solid/src/routeTree.gen.ts deleted file mode 100644 index 0da70513e8..0000000000 --- a/benchmarks/client-nav/scenarios/links/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as AboutRouteImport } from './routes/about' -import { Route as ItemsIdRouteImport } from './routes/items.$id' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) -const ItemsIdRoute = ItemsIdRouteImport.update({ - id: '/items/$id', - path: '/items/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/about': typeof AboutRoute - '/items/$id': typeof ItemsIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/about': typeof AboutRoute - '/items/$id': typeof ItemsIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/about': typeof AboutRoute - '/items/$id': typeof ItemsIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/about' | '/items/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/about' | '/items/$id' - id: '__root__' | '/' | '/about' | '/items/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - AboutRoute: typeof AboutRoute - ItemsIdRoute: typeof ItemsIdRoute -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } - '/items/$id': { - id: '/items/$id' - path: '/items/$id' - fullPath: '/items/$id' - preLoaderRoute: typeof ItemsIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - AboutRoute: AboutRoute, - ItemsIdRoute: ItemsIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/links/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/links/solid/src/routes/__root.tsx deleted file mode 100644 index a889a26854..0000000000 --- a/benchmarks/client-nav/scenarios/links/solid/src/routes/__root.tsx +++ /dev/null @@ -1,119 +0,0 @@ -import { For } from 'solid-js' -import { - Link, - Outlet, - createRootRoute, - useMatchRoute, -} from '@tanstack/solid-router' -import { - itemIds, - matchProbeIds, - stepItemIds, - variantSearch, -} from '../../../shared' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function StatusPanel() { - const matchRoute = useMatchRoute() - - return ( - - ) -} - -function LinkGrid() { - return ( -
- - {(id) => ( -
- - {`Item ${id}`} - - - {`Item ${id} exact`} - - - {`Item ${id} search`} - - - {`Item ${id} hash`} - - - {({ isActive }) => - isActive ? `Item ${id} on` : `Item ${id} off` - } - -
- )} -
-
- ) -} - -function RootComponent() { - return ( - <> - - - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/links/solid/src/routes/about.tsx b/benchmarks/client-nav/scenarios/links/solid/src/routes/about.tsx deleted file mode 100644 index a2a71678b7..0000000000 --- a/benchmarks/client-nav/scenarios/links/solid/src/routes/about.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { aboutMarker } from '../../../shared' - -export const Route = createFileRoute('/about')({ - component: AboutPage, -}) - -function AboutPage() { - return ( -
-

{aboutMarker}

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/links/solid/src/routes/index.tsx b/benchmarks/client-nav/scenarios/links/solid/src/routes/index.tsx deleted file mode 100644 index 72fbfe387a..0000000000 --- a/benchmarks/client-nav/scenarios/links/solid/src/routes/index.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { homeMarker } from '../../../shared' - -export const Route = createFileRoute('/')({ - component: HomePage, -}) - -function HomePage() { - return ( -
-

{homeMarker}

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/links/solid/src/routes/items.$id.tsx b/benchmarks/client-nav/scenarios/links/solid/src/routes/items.$id.tsx deleted file mode 100644 index 64d84f81f4..0000000000 --- a/benchmarks/client-nav/scenarios/links/solid/src/routes/items.$id.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { itemMarker } from '../../../shared' - -export const Route = createFileRoute('/items/$id')({ - component: ItemPage, -}) - -function ItemPage() { - const params = Route.useParams() - - return ( -
-

{itemMarker(params().id)}

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/links/solid/tsconfig.json b/benchmarks/client-nav/scenarios/links/solid/tsconfig.json deleted file mode 100644 index 98d76ad6b8..0000000000 --- a/benchmarks/client-nav/scenarios/links/solid/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/links/solid/vite.config.ts b/benchmarks/client-nav/scenarios/links/solid/vite.config.ts deleted file mode 100644 index e37342ffc3..0000000000 --- a/benchmarks/client-nav/scenarios/links/solid/vite.config.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import solid from 'vite-plugin-solid' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'solid', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - resolve: { - conditions: ['solid', 'browser'], - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav links (solid)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/client-nav/scenarios/links/vue/project.json b/benchmarks/client-nav/scenarios/links/vue/project.json deleted file mode 100644 index fe1e68fad3..0000000000 --- a/benchmarks/client-nav/scenarios/links/vue/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-links-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/links/vue/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/links/vue/setup.ts b/benchmarks/client-nav/scenarios/links/vue/setup.ts deleted file mode 100644 index f70a154909..0000000000 --- a/benchmarks/client-nav/scenarios/links/vue/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, 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, - }) -} diff --git a/benchmarks/client-nav/scenarios/links/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/links/vue/speed.bench.ts deleted file mode 100644 index 2ace7a8409..0000000000 --- a/benchmarks/client-nav/scenarios/links/vue/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-links', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-links 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/links/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/links/vue/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/links/vue/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/links/vue/src/main.tsx b/benchmarks/client-nav/scenarios/links/vue/src/main.tsx deleted file mode 100644 index cae9b54f1d..0000000000 --- a/benchmarks/client-nav/scenarios/links/vue/src/main.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import * as Vue from 'vue' -import { RouterProvider, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const component = - const app = Vue.createApp({ - render: () => component, - }) - - app.mount(container) - - return { - router, - unmount() { - app.unmount() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/links/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/links/vue/src/routeTree.gen.ts deleted file mode 100644 index 7d2b1e9bbb..0000000000 --- a/benchmarks/client-nav/scenarios/links/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as AboutRouteImport } from './routes/about' -import { Route as ItemsIdRouteImport } from './routes/items.$id' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) -const ItemsIdRoute = ItemsIdRouteImport.update({ - id: '/items/$id', - path: '/items/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/about': typeof AboutRoute - '/items/$id': typeof ItemsIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/about': typeof AboutRoute - '/items/$id': typeof ItemsIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/about': typeof AboutRoute - '/items/$id': typeof ItemsIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/about' | '/items/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/about' | '/items/$id' - id: '__root__' | '/' | '/about' | '/items/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - AboutRoute: typeof AboutRoute - ItemsIdRoute: typeof ItemsIdRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } - '/items/$id': { - id: '/items/$id' - path: '/items/$id' - fullPath: '/items/$id' - preLoaderRoute: typeof ItemsIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - AboutRoute: AboutRoute, - ItemsIdRoute: ItemsIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/links/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/links/vue/src/routes/__root.tsx deleted file mode 100644 index 04f99677fd..0000000000 --- a/benchmarks/client-nav/scenarios/links/vue/src/routes/__root.tsx +++ /dev/null @@ -1,120 +0,0 @@ -import * as Vue from 'vue' -import { - Link, - Outlet, - createRootRoute, - useMatchRoute, -} from '@tanstack/vue-router' -import { - itemIds, - matchProbeIds, - stepItemIds, - variantSearch, -} from '../../../shared' - -const StatusPanel = Vue.defineComponent({ - setup() { - const matchRoute = useMatchRoute() - const probes = matchProbeIds.map((id) => ({ - id, - match: matchRoute({ to: '/items/$id', params: { id } }), - })) - // Static probes use the setup-scoped matchRoute instead of : - // vue-router's MatchRoute creates an undisposed watcher per render (one - // leaked subscription per navigation), so all three apps use - // useMatchRoute for cross-framework parity. - const atHome = matchRoute({ to: '/' }) - const atAbout = matchRoute({ to: '/about' }) - const underRoot = matchRoute({ to: '/', fuzzy: true }) - const underAbout = matchRoute({ to: '/about', fuzzy: true }) - const aboutSearch = matchRoute({ to: '/about', includeSearch: true }) - - return () => ( - - ) - }, -}) - -const LinkGrid = Vue.defineComponent({ - setup() { - return () => ( -
- {itemIds.map((id) => ( -
- - {`Item ${id}`} - - - {`Item ${id} exact`} - - - {`Item ${id} search`} - - - {`Item ${id} hash`} - - - {({ isActive }: { isActive: boolean }) => - isActive ? `Item ${id} on` : `Item ${id} off` - } - -
- ))} -
- ) - }, -}) - -const RootComponent = Vue.defineComponent({ - setup() { - return () => ( - <> - - - - - - ) - }, -}) - -export const Route = createRootRoute({ - component: RootComponent, -}) diff --git a/benchmarks/client-nav/scenarios/links/vue/src/routes/about.tsx b/benchmarks/client-nav/scenarios/links/vue/src/routes/about.tsx deleted file mode 100644 index 5cc1473bff..0000000000 --- a/benchmarks/client-nav/scenarios/links/vue/src/routes/about.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' -import { aboutMarker } from '../../../shared' - -const AboutPage = Vue.defineComponent({ - setup() { - return () => ( -
-

{aboutMarker}

-
- ) - }, -}) - -export const Route = createFileRoute('/about')({ - component: AboutPage, -}) diff --git a/benchmarks/client-nav/scenarios/links/vue/src/routes/index.tsx b/benchmarks/client-nav/scenarios/links/vue/src/routes/index.tsx deleted file mode 100644 index f04a9f5796..0000000000 --- a/benchmarks/client-nav/scenarios/links/vue/src/routes/index.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' -import { homeMarker } from '../../../shared' - -const HomePage = Vue.defineComponent({ - setup() { - return () => ( -
-

{homeMarker}

-
- ) - }, -}) - -export const Route = createFileRoute('/')({ - component: HomePage, -}) diff --git a/benchmarks/client-nav/scenarios/links/vue/src/routes/items.$id.tsx b/benchmarks/client-nav/scenarios/links/vue/src/routes/items.$id.tsx deleted file mode 100644 index 0dc5efa3d3..0000000000 --- a/benchmarks/client-nav/scenarios/links/vue/src/routes/items.$id.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' -import { itemMarker } from '../../../shared' - -const ItemPage = Vue.defineComponent({ - setup() { - const params = Route.useParams() - - return () => ( -
-

{itemMarker(params.value.id)}

-
- ) - }, -}) - -export const Route = createFileRoute('/items/$id')({ - component: ItemPage, -}) diff --git a/benchmarks/client-nav/scenarios/links/vue/tsconfig.json b/benchmarks/client-nav/scenarios/links/vue/tsconfig.json deleted file mode 100644 index 7786fc3da9..0000000000 --- a/benchmarks/client-nav/scenarios/links/vue/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/links/vue/vite.config.ts b/benchmarks/client-nav/scenarios/links/vue/vite.config.ts deleted file mode 100644 index ad89a49d70..0000000000 --- a/benchmarks/client-nav/scenarios/links/vue/vite.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'vue', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav links (vue)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - }, -}) diff --git a/benchmarks/client-nav/scenarios/loaders/react/project.json b/benchmarks/client-nav/scenarios/loaders/react/project.json deleted file mode 100644 index d3dbe585d4..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-loaders-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/loaders/react/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/loaders/react/setup.ts b/benchmarks/client-nav/scenarios/loaders/react/setup.ts deleted file mode 100644 index 130583b190..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/react/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, steps } 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, - assertAfterStep: assertStepResult, - }) -} diff --git a/benchmarks/client-nav/scenarios/loaders/react/speed.bench.ts b/benchmarks/client-nav/scenarios/loaders/react/speed.bench.ts deleted file mode 100644 index 8bcc53b88e..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-loaders', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-loaders 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/loaders/react/speed.flame.ts b/benchmarks/client-nav/scenarios/loaders/react/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/react/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/loaders/react/src/main.tsx b/benchmarks/client-nav/scenarios/loaders/react/src/main.tsx deleted file mode 100644 index 5febd6f795..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/react/src/main.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { RouterProvider, createRouter } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const reactRoot = createRoot(container) - reactRoot.render() - - return { - router, - unmount() { - reactRoot.unmount() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/loaders/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/loaders/react/src/routeTree.gen.ts deleted file mode 100644 index 35908a225f..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/react/src/routeTree.gen.ts +++ /dev/null @@ -1,113 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as DepsRouteImport } from './routes/deps' -import { Route as CachedIdRouteImport } from './routes/cached.$id' -import { Route as FreshIdRouteImport } from './routes/fresh.$id' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const DepsRoute = DepsRouteImport.update({ - id: '/deps', - path: '/deps', - getParentRoute: () => rootRouteImport, -} as any) -const CachedIdRoute = CachedIdRouteImport.update({ - id: '/cached/$id', - path: '/cached/$id', - getParentRoute: () => rootRouteImport, -} as any) -const FreshIdRoute = FreshIdRouteImport.update({ - id: '/fresh/$id', - path: '/fresh/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/deps': typeof DepsRoute - '/cached/$id': typeof CachedIdRoute - '/fresh/$id': typeof FreshIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/deps': typeof DepsRoute - '/cached/$id': typeof CachedIdRoute - '/fresh/$id': typeof FreshIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/deps': typeof DepsRoute - '/cached/$id': typeof CachedIdRoute - '/fresh/$id': typeof FreshIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/deps' | '/cached/$id' | '/fresh/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/deps' | '/cached/$id' | '/fresh/$id' - id: '__root__' | '/' | '/deps' | '/cached/$id' | '/fresh/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - DepsRoute: typeof DepsRoute - CachedIdRoute: typeof CachedIdRoute - FreshIdRoute: typeof FreshIdRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/deps': { - id: '/deps' - path: '/deps' - fullPath: '/deps' - preLoaderRoute: typeof DepsRouteImport - parentRoute: typeof rootRouteImport - } - '/cached/$id': { - id: '/cached/$id' - path: '/cached/$id' - fullPath: '/cached/$id' - preLoaderRoute: typeof CachedIdRouteImport - parentRoute: typeof rootRouteImport - } - '/fresh/$id': { - id: '/fresh/$id' - path: '/fresh/$id' - fullPath: '/fresh/$id' - preLoaderRoute: typeof FreshIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - DepsRoute: DepsRoute, - CachedIdRoute: CachedIdRoute, - FreshIdRoute: FreshIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/loaders/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/loaders/react/src/routes/__root.tsx deleted file mode 100644 index 6309763cf3..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/react/src/routes/__root.tsx +++ /dev/null @@ -1,70 +0,0 @@ -import { Link, Outlet, createRootRoute } from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - <> - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/loaders/react/src/routes/cached.$id.tsx b/benchmarks/client-nav/scenarios/loaders/react/src/routes/cached.$id.tsx deleted file mode 100644 index 9b954185cc..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/react/src/routes/cached.$id.tsx +++ /dev/null @@ -1,55 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { computeChecksum, itemsChecksum, makeItems } from '../../../shared' - -export const Route = createFileRoute('/cached/$id')({ - loader: ({ params }) => { - const items = makeItems(`cached-${params.id}`) - return { items, checksum: itemsChecksum(items) } - }, - staleTime: 1e9, - gcTime: 1e9, - component: CachedPage, -}) - -const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) - -function SumSubscriber() { - const value = Route.useLoaderData({ - select: (data) => computeChecksum(data.checksum), - }) - - void computeChecksum(value) - return null -} - -function FirstItemSubscriber() { - const value = Route.useLoaderData({ - select: (data) => computeChecksum(data.items[0]?.value ?? 0), - }) - - void computeChecksum(value) - return null -} - -function CachedPage() { - const params = Route.useParams() - const loaderData = Route.useLoaderData() - - return ( -
- {subscriberIndexes.map((index) => ( - - ))} - {subscriberIndexes.map((index) => ( - - ))} -

Cached

-
{`c-${params.id}-${loaderData.checksum}`}
-
    - {loaderData.items.slice(0, 5).map((item) => ( -
  • {item.name}
  • - ))} -
-
- ) -} diff --git a/benchmarks/client-nav/scenarios/loaders/react/src/routes/deps.tsx b/benchmarks/client-nav/scenarios/loaders/react/src/routes/deps.tsx deleted file mode 100644 index 92afe04a21..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/react/src/routes/deps.tsx +++ /dev/null @@ -1,65 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import type { SearchSchemaInput } from '@tanstack/react-router' -import { - computeChecksum, - itemsChecksum, - makeItems, - normalizePage, -} from '../../../shared' - -export const Route = createFileRoute('/deps')({ - validateSearch: (search: Record & SearchSchemaInput) => ({ - page: normalizePage(search.page), - }), - loaderDeps: ({ search }) => ({ page: search.page }), - loader: ({ deps }) => { - const items = makeItems(`deps-${deps.page}`) - return { items, checksum: itemsChecksum(items) } - }, - staleTime: 1e9, - gcTime: 1e9, - component: DepsPage, -}) - -const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) - -function SumSubscriber() { - const value = Route.useLoaderData({ - select: (data) => computeChecksum(data.checksum), - }) - - void computeChecksum(value) - return null -} - -function DepsSubscriber() { - const value = Route.useLoaderDeps({ - select: (deps) => computeChecksum(deps.page * 17), - }) - - void computeChecksum(value) - return null -} - -function DepsPage() { - const search = Route.useSearch() - const loaderData = Route.useLoaderData() - - return ( -
- {subscriberIndexes.map((index) => ( - - ))} - {subscriberIndexes.map((index) => ( - - ))} -

Deps

-
{`d-${search.page}-${loaderData.checksum}`}
-
    - {loaderData.items.slice(0, 5).map((item) => ( -
  • {item.name}
  • - ))} -
-
- ) -} diff --git a/benchmarks/client-nav/scenarios/loaders/react/src/routes/fresh.$id.tsx b/benchmarks/client-nav/scenarios/loaders/react/src/routes/fresh.$id.tsx deleted file mode 100644 index fb7cbf2f00..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/react/src/routes/fresh.$id.tsx +++ /dev/null @@ -1,55 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { computeChecksum, itemsChecksum, makeItems } from '../../../shared' - -export const Route = createFileRoute('/fresh/$id')({ - loader: ({ params }) => { - const items = makeItems(`fresh-${params.id}`) - return { items, checksum: itemsChecksum(items) } - }, - staleTime: 0, - gcTime: 0, - component: FreshPage, -}) - -const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) - -function SumSubscriber() { - const value = Route.useLoaderData({ - select: (data) => computeChecksum(data.checksum), - }) - - void computeChecksum(value) - return null -} - -function FirstItemSubscriber() { - const value = Route.useLoaderData({ - select: (data) => computeChecksum(data.items[0]?.value ?? 0), - }) - - void computeChecksum(value) - return null -} - -function FreshPage() { - const params = Route.useParams() - const loaderData = Route.useLoaderData() - - return ( -
- {subscriberIndexes.map((index) => ( - - ))} - {subscriberIndexes.map((index) => ( - - ))} -

Fresh

-
{`f-${params.id}-${loaderData.checksum}`}
-
    - {loaderData.items.slice(0, 5).map((item) => ( -
  • {item.name}
  • - ))} -
-
- ) -} diff --git a/benchmarks/client-nav/scenarios/loaders/react/src/routes/index.tsx b/benchmarks/client-nav/scenarios/loaders/react/src/routes/index.tsx deleted file mode 100644 index 9203c00841..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/react/src/routes/index.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: HomePage, -}) - -function HomePage() { - return ( -
-

Loaders Bench

-
home
-
- ) -} diff --git a/benchmarks/client-nav/scenarios/loaders/react/tsconfig.json b/benchmarks/client-nav/scenarios/loaders/react/tsconfig.json deleted file mode 100644 index 1d59cbb450..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/react/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/loaders/react/vite.config.ts b/benchmarks/client-nav/scenarios/loaders/react/vite.config.ts deleted file mode 100644 index 818b224130..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/react/vite.config.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'react', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav loaders (react)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - }, -}) diff --git a/benchmarks/client-nav/scenarios/loaders/shared.ts b/benchmarks/client-nav/scenarios/loaders/shared.ts deleted file mode 100644 index f744246160..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/shared.ts +++ /dev/null @@ -1,134 +0,0 @@ -/** - * Shared definition of the `loaders` scenario: deterministic loader data - * derivation, the click sequence, and per-step sanity assertions. The three - * framework apps consume these builders so the workload is identical modulo - * the rendering layer. - * - * Isolates: client loader dispatch — always-stale re-runs (staleTime 0), - * pure cache hits (staleTime 1e9), loaderDeps-keyed caching, - * router.invalidate(), and useLoaderData selector subscriptions. - */ - -import type { ScenarioStep } from '../harness' - -export function computeChecksum(seed: number) { - let value = Math.trunc(seed) | 0 - - for (let index = 0; index < 40; index++) { - value = (value * 1664525 + 1013904223 + index) >>> 0 - } - - return value -} - -export interface LoaderItem { - id: string - name: string - value: number - flag: boolean -} - -export function makeItems(seedText: string): Array { - let seed = 0 - for (let index = 0; index < seedText.length; index++) { - seed = (seed * 31 + seedText.charCodeAt(index)) >>> 0 - } - - const items: Array = [] - let value = seed - - for (let index = 0; index < 50; index++) { - value = (value * 1664525 + 1013904223) >>> 0 - items.push({ - id: `${seedText}-${index}`, - name: `Item ${index} of ${seedText}`, - value: value % 100000, - flag: value % 3 === 0, - }) - } - - return items -} - -export function itemsChecksum(items: Array) { - let sum = 0 - for (const item of items) { - sum = (sum + item.value + (item.flag ? 1 : 0)) >>> 0 - } - return sum -} - -export function normalizePage(value: unknown) { - const page = Number(value) - return Number.isFinite(page) && page > 0 ? Math.trunc(page) : 1 -} - -export function freshMarkerText(id: string) { - return `f-${id}-${itemsChecksum(makeItems(`fresh-${id}`))}` -} - -export function cachedMarkerText(id: string) { - return `c-${id}-${itemsChecksum(makeItems(`cached-${id}`))}` -} - -export function depsMarkerText(page: number) { - return `d-${page}-${itemsChecksum(makeItems(`deps-${page}`))}` -} - -export const steps: ReadonlyArray = [ - 'go-fresh-1', - 'go-fresh-2', - 'go-cached-1', - 'go-cached-2', - 'go-deps-1', - 'go-deps-2', - // Invalidates the currently matched routes (the deps route), re-running its - // loader with unchanged deps. Note: this also marks the cached fresh/cached - // matches invalid, so each of those loaders re-runs once per lap on its next - // visit — deterministic, identical work every lap. - { type: 'invalidate' }, - 'go-home', -] - -interface ExpectedState { - testId: string - text?: string -} - -const expectedStates: ReadonlyArray = [ - { testId: 'fresh-state', text: freshMarkerText('1') }, - { testId: 'fresh-state', text: freshMarkerText('2') }, - { testId: 'cached-state', text: cachedMarkerText('1') }, - { testId: 'cached-state', text: cachedMarkerText('2') }, - { testId: 'deps-state', text: depsMarkerText(1) }, - { testId: 'deps-state', text: depsMarkerText(2) }, - // After invalidate the deps loader re-ran with the same deps. - { testId: 'deps-state', text: depsMarkerText(2) }, - { testId: 'home-state' }, -] - -export function assertStepResult(stepIndex: number, container: HTMLElement) { - const expected = expectedStates[stepIndex]! - const element = container.querySelector(`[data-testid="${expected.testId}"]`) - - if (!element) { - throw new Error( - `Expected marker "${expected.testId}" to exist after step ${stepIndex}`, - ) - } - - if (expected.text !== undefined && element.textContent !== expected.text) { - throw new Error( - `Expected marker "${expected.testId}" to read "${expected.text}" after step ${stepIndex}, received "${element.textContent}"`, - ) - } -} - -// Two laps through the 8-step sequence per benchmark iteration. -export const ticksPerIteration = 16 - -export const benchOptions = { - warmupIterations: 100, - time: 10_000, - throws: true, -} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/project.json b/benchmarks/client-nav/scenarios/loaders/solid/project.json deleted file mode 100644 index 071e6bc385..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/solid/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-loaders-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/loaders/solid/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/setup.ts b/benchmarks/client-nav/scenarios/loaders/solid/setup.ts deleted file mode 100644 index 6a46971603..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/solid/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, steps } 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, - assertAfterStep: assertStepResult, - }) -} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/loaders/solid/speed.bench.ts deleted file mode 100644 index 953a17b31a..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-loaders', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-loaders 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/loaders/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/loaders/solid/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/solid/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/src/main.tsx b/benchmarks/client-nav/scenarios/loaders/solid/src/main.tsx deleted file mode 100644 index fa9d239418..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/solid/src/main.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { render } from 'solid-js/web' -import { RouterProvider, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const unmount = render(() => , container) - - return { - router, - unmount, - } -} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/loaders/solid/src/routeTree.gen.ts deleted file mode 100644 index fa5d032141..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,113 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as DepsRouteImport } from './routes/deps' -import { Route as CachedIdRouteImport } from './routes/cached.$id' -import { Route as FreshIdRouteImport } from './routes/fresh.$id' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const DepsRoute = DepsRouteImport.update({ - id: '/deps', - path: '/deps', - getParentRoute: () => rootRouteImport, -} as any) -const CachedIdRoute = CachedIdRouteImport.update({ - id: '/cached/$id', - path: '/cached/$id', - getParentRoute: () => rootRouteImport, -} as any) -const FreshIdRoute = FreshIdRouteImport.update({ - id: '/fresh/$id', - path: '/fresh/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/deps': typeof DepsRoute - '/cached/$id': typeof CachedIdRoute - '/fresh/$id': typeof FreshIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/deps': typeof DepsRoute - '/cached/$id': typeof CachedIdRoute - '/fresh/$id': typeof FreshIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/deps': typeof DepsRoute - '/cached/$id': typeof CachedIdRoute - '/fresh/$id': typeof FreshIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/deps' | '/cached/$id' | '/fresh/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/deps' | '/cached/$id' | '/fresh/$id' - id: '__root__' | '/' | '/deps' | '/cached/$id' | '/fresh/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - DepsRoute: typeof DepsRoute - CachedIdRoute: typeof CachedIdRoute - FreshIdRoute: typeof FreshIdRoute -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/deps': { - id: '/deps' - path: '/deps' - fullPath: '/deps' - preLoaderRoute: typeof DepsRouteImport - parentRoute: typeof rootRouteImport - } - '/cached/$id': { - id: '/cached/$id' - path: '/cached/$id' - fullPath: '/cached/$id' - preLoaderRoute: typeof CachedIdRouteImport - parentRoute: typeof rootRouteImport - } - '/fresh/$id': { - id: '/fresh/$id' - path: '/fresh/$id' - fullPath: '/fresh/$id' - preLoaderRoute: typeof FreshIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - DepsRoute: DepsRoute, - CachedIdRoute: CachedIdRoute, - FreshIdRoute: FreshIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/loaders/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/loaders/solid/src/routes/__root.tsx deleted file mode 100644 index 30350f7907..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/solid/src/routes/__root.tsx +++ /dev/null @@ -1,66 +0,0 @@ -import { Link, Outlet, createRootRoute } from '@tanstack/solid-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - <> - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/src/routes/cached.$id.tsx b/benchmarks/client-nav/scenarios/loaders/solid/src/routes/cached.$id.tsx deleted file mode 100644 index aab6be74dc..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/solid/src/routes/cached.$id.tsx +++ /dev/null @@ -1,62 +0,0 @@ -import { For, createRenderEffect } from 'solid-js' -import { createFileRoute } from '@tanstack/solid-router' -import { computeChecksum, itemsChecksum, makeItems } from '../../../shared' - -export const Route = createFileRoute('/cached/$id')({ - loader: ({ params }) => { - const items = makeItems(`cached-${params.id}`) - return { items, checksum: itemsChecksum(items) } - }, - staleTime: 1e9, - gcTime: 1e9, - component: CachedPage, -}) - -const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) - -function PerfValue(props: { value: () => number }) { - createRenderEffect(() => { - void props.value() - }) - - return null -} - -function SumSubscriber() { - const value = Route.useLoaderData({ - select: (data) => computeChecksum(data.checksum), - }) - - return computeChecksum(value())} /> -} - -function FirstItemSubscriber() { - const value = Route.useLoaderData({ - select: (data) => computeChecksum(data.items[0]?.value ?? 0), - }) - - return computeChecksum(value())} /> -} - -function CachedPage() { - const params = Route.useParams() - const loaderData = Route.useLoaderData() - - return ( -
- {subscriberIndexes.map(() => ( - - ))} - {subscriberIndexes.map(() => ( - - ))} -

Cached

-
{`c-${params().id}-${loaderData().checksum}`}
-
    - - {(item) =>
  • {item.name}
  • } -
    -
-
- ) -} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/src/routes/deps.tsx b/benchmarks/client-nav/scenarios/loaders/solid/src/routes/deps.tsx deleted file mode 100644 index 2f23f2d3da..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/solid/src/routes/deps.tsx +++ /dev/null @@ -1,72 +0,0 @@ -import { For, createRenderEffect } from 'solid-js' -import { createFileRoute } from '@tanstack/solid-router' -import type { SearchSchemaInput } from '@tanstack/solid-router' -import { - computeChecksum, - itemsChecksum, - makeItems, - normalizePage, -} from '../../../shared' - -export const Route = createFileRoute('/deps')({ - validateSearch: (search: Record & SearchSchemaInput) => ({ - page: normalizePage(search.page), - }), - loaderDeps: ({ search }) => ({ page: search.page }), - loader: ({ deps }) => { - const items = makeItems(`deps-${deps.page}`) - return { items, checksum: itemsChecksum(items) } - }, - staleTime: 1e9, - gcTime: 1e9, - component: DepsPage, -}) - -const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) - -function PerfValue(props: { value: () => number }) { - createRenderEffect(() => { - void props.value() - }) - - return null -} - -function SumSubscriber() { - const value = Route.useLoaderData({ - select: (data) => computeChecksum(data.checksum), - }) - - return computeChecksum(value())} /> -} - -function DepsSubscriber() { - const value = Route.useLoaderDeps({ - select: (deps) => computeChecksum(deps.page * 17), - }) - - return computeChecksum(value())} /> -} - -function DepsPage() { - const search = Route.useSearch() - const loaderData = Route.useLoaderData() - - return ( -
- {subscriberIndexes.map(() => ( - - ))} - {subscriberIndexes.map(() => ( - - ))} -

Deps

-
{`d-${search().page}-${loaderData().checksum}`}
-
    - - {(item) =>
  • {item.name}
  • } -
    -
-
- ) -} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/src/routes/fresh.$id.tsx b/benchmarks/client-nav/scenarios/loaders/solid/src/routes/fresh.$id.tsx deleted file mode 100644 index acd6a9aa27..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/solid/src/routes/fresh.$id.tsx +++ /dev/null @@ -1,62 +0,0 @@ -import { For, createRenderEffect } from 'solid-js' -import { createFileRoute } from '@tanstack/solid-router' -import { computeChecksum, itemsChecksum, makeItems } from '../../../shared' - -export const Route = createFileRoute('/fresh/$id')({ - loader: ({ params }) => { - const items = makeItems(`fresh-${params.id}`) - return { items, checksum: itemsChecksum(items) } - }, - staleTime: 0, - gcTime: 0, - component: FreshPage, -}) - -const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) - -function PerfValue(props: { value: () => number }) { - createRenderEffect(() => { - void props.value() - }) - - return null -} - -function SumSubscriber() { - const value = Route.useLoaderData({ - select: (data) => computeChecksum(data.checksum), - }) - - return computeChecksum(value())} /> -} - -function FirstItemSubscriber() { - const value = Route.useLoaderData({ - select: (data) => computeChecksum(data.items[0]?.value ?? 0), - }) - - return computeChecksum(value())} /> -} - -function FreshPage() { - const params = Route.useParams() - const loaderData = Route.useLoaderData() - - return ( -
- {subscriberIndexes.map(() => ( - - ))} - {subscriberIndexes.map(() => ( - - ))} -

Fresh

-
{`f-${params().id}-${loaderData().checksum}`}
-
    - - {(item) =>
  • {item.name}
  • } -
    -
-
- ) -} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/src/routes/index.tsx b/benchmarks/client-nav/scenarios/loaders/solid/src/routes/index.tsx deleted file mode 100644 index 7287d47d0a..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/solid/src/routes/index.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/')({ - component: HomePage, -}) - -function HomePage() { - return ( -
-

Loaders Bench

-
home
-
- ) -} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/tsconfig.json b/benchmarks/client-nav/scenarios/loaders/solid/tsconfig.json deleted file mode 100644 index 98d76ad6b8..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/solid/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/vite.config.ts b/benchmarks/client-nav/scenarios/loaders/solid/vite.config.ts deleted file mode 100644 index 90584d3b7e..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/solid/vite.config.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import solid from 'vite-plugin-solid' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'solid', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - resolve: { - conditions: ['solid', 'browser'], - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav loaders (solid)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/client-nav/scenarios/loaders/vue/project.json b/benchmarks/client-nav/scenarios/loaders/vue/project.json deleted file mode 100644 index 69bd95837d..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/vue/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-loaders-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/loaders/vue/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/loaders/vue/setup.ts b/benchmarks/client-nav/scenarios/loaders/vue/setup.ts deleted file mode 100644 index 97b74b3892..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/vue/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, steps } 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, - assertAfterStep: assertStepResult, - }) -} diff --git a/benchmarks/client-nav/scenarios/loaders/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/loaders/vue/speed.bench.ts deleted file mode 100644 index 1ae2f89a56..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/vue/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-loaders', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-loaders 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/loaders/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/loaders/vue/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/vue/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/loaders/vue/src/main.tsx b/benchmarks/client-nav/scenarios/loaders/vue/src/main.tsx deleted file mode 100644 index cae9b54f1d..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/vue/src/main.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import * as Vue from 'vue' -import { RouterProvider, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const component = - const app = Vue.createApp({ - render: () => component, - }) - - app.mount(container) - - return { - router, - unmount() { - app.unmount() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/loaders/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/loaders/vue/src/routeTree.gen.ts deleted file mode 100644 index 10cb8f2aca..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,113 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as DepsRouteImport } from './routes/deps' -import { Route as CachedIdRouteImport } from './routes/cached.$id' -import { Route as FreshIdRouteImport } from './routes/fresh.$id' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const DepsRoute = DepsRouteImport.update({ - id: '/deps', - path: '/deps', - getParentRoute: () => rootRouteImport, -} as any) -const CachedIdRoute = CachedIdRouteImport.update({ - id: '/cached/$id', - path: '/cached/$id', - getParentRoute: () => rootRouteImport, -} as any) -const FreshIdRoute = FreshIdRouteImport.update({ - id: '/fresh/$id', - path: '/fresh/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/deps': typeof DepsRoute - '/cached/$id': typeof CachedIdRoute - '/fresh/$id': typeof FreshIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/deps': typeof DepsRoute - '/cached/$id': typeof CachedIdRoute - '/fresh/$id': typeof FreshIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/deps': typeof DepsRoute - '/cached/$id': typeof CachedIdRoute - '/fresh/$id': typeof FreshIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/deps' | '/cached/$id' | '/fresh/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/deps' | '/cached/$id' | '/fresh/$id' - id: '__root__' | '/' | '/deps' | '/cached/$id' | '/fresh/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - DepsRoute: typeof DepsRoute - CachedIdRoute: typeof CachedIdRoute - FreshIdRoute: typeof FreshIdRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/deps': { - id: '/deps' - path: '/deps' - fullPath: '/deps' - preLoaderRoute: typeof DepsRouteImport - parentRoute: typeof rootRouteImport - } - '/cached/$id': { - id: '/cached/$id' - path: '/cached/$id' - fullPath: '/cached/$id' - preLoaderRoute: typeof CachedIdRouteImport - parentRoute: typeof rootRouteImport - } - '/fresh/$id': { - id: '/fresh/$id' - path: '/fresh/$id' - fullPath: '/fresh/$id' - preLoaderRoute: typeof FreshIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - DepsRoute: DepsRoute, - CachedIdRoute: CachedIdRoute, - FreshIdRoute: FreshIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/loaders/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/loaders/vue/src/routes/__root.tsx deleted file mode 100644 index b9102a92c4..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/vue/src/routes/__root.tsx +++ /dev/null @@ -1,69 +0,0 @@ -import * as Vue from 'vue' -import { Link, Outlet, createRootRoute } from '@tanstack/vue-router' - -const RootComponent = Vue.defineComponent({ - setup() { - return () => ( - <> - - - - ) - }, -}) - -export const Route = createRootRoute({ - component: RootComponent, -}) diff --git a/benchmarks/client-nav/scenarios/loaders/vue/src/routes/cached.$id.tsx b/benchmarks/client-nav/scenarios/loaders/vue/src/routes/cached.$id.tsx deleted file mode 100644 index a426e35765..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/vue/src/routes/cached.$id.tsx +++ /dev/null @@ -1,68 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' -import { computeChecksum, itemsChecksum, makeItems } from '../../../shared' - -const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) - -const SumSubscriber = Vue.defineComponent({ - setup() { - const value = Route.useLoaderData({ - select: (data) => computeChecksum(data.checksum), - }) - - return () => { - void computeChecksum(value.value) - return null - } - }, -}) - -const FirstItemSubscriber = Vue.defineComponent({ - setup() { - const value = Route.useLoaderData({ - select: (data) => computeChecksum(data.items[0]?.value ?? 0), - }) - - return () => { - void computeChecksum(value.value) - return null - } - }, -}) - -const CachedPage = Vue.defineComponent({ - setup() { - const params = Route.useParams() - const loaderData = Route.useLoaderData() - - return () => ( -
- {subscriberIndexes.map((index) => ( - - ))} - {subscriberIndexes.map((index) => ( - - ))} -

Cached

-
- {`c-${params.value.id}-${loaderData.value.checksum}`} -
-
    - {loaderData.value.items.slice(0, 5).map((item) => ( -
  • {item.name}
  • - ))} -
-
- ) - }, -}) - -export const Route = createFileRoute('/cached/$id')({ - loader: ({ params }) => { - const items = makeItems(`cached-${params.id}`) - return { items, checksum: itemsChecksum(items) } - }, - staleTime: 1e9, - gcTime: 1e9, - component: CachedPage, -}) diff --git a/benchmarks/client-nav/scenarios/loaders/vue/src/routes/deps.tsx b/benchmarks/client-nav/scenarios/loaders/vue/src/routes/deps.tsx deleted file mode 100644 index f987d15d34..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/vue/src/routes/deps.tsx +++ /dev/null @@ -1,78 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' -import type { SearchSchemaInput } from '@tanstack/vue-router' -import { - computeChecksum, - itemsChecksum, - makeItems, - normalizePage, -} from '../../../shared' - -const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) - -const SumSubscriber = Vue.defineComponent({ - setup() { - const value = Route.useLoaderData({ - select: (data) => computeChecksum(data.checksum), - }) - - return () => { - void computeChecksum(value.value) - return null - } - }, -}) - -const DepsSubscriber = Vue.defineComponent({ - setup() { - const value = Route.useLoaderDeps({ - select: (deps) => computeChecksum(deps.page * 17), - }) - - return () => { - void computeChecksum(value.value) - return null - } - }, -}) - -const DepsPage = Vue.defineComponent({ - setup() { - const search = Route.useSearch() - const loaderData = Route.useLoaderData() - - return () => ( -
- {subscriberIndexes.map((index) => ( - - ))} - {subscriberIndexes.map((index) => ( - - ))} -

Deps

-
- {`d-${search.value.page}-${loaderData.value.checksum}`} -
-
    - {loaderData.value.items.slice(0, 5).map((item) => ( -
  • {item.name}
  • - ))} -
-
- ) - }, -}) - -export const Route = createFileRoute('/deps')({ - validateSearch: (search: Record & SearchSchemaInput) => ({ - page: normalizePage(search.page), - }), - loaderDeps: ({ search }) => ({ page: search.page }), - loader: ({ deps }) => { - const items = makeItems(`deps-${deps.page}`) - return { items, checksum: itemsChecksum(items) } - }, - staleTime: 1e9, - gcTime: 1e9, - component: DepsPage, -}) diff --git a/benchmarks/client-nav/scenarios/loaders/vue/src/routes/fresh.$id.tsx b/benchmarks/client-nav/scenarios/loaders/vue/src/routes/fresh.$id.tsx deleted file mode 100644 index 64eec85cfa..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/vue/src/routes/fresh.$id.tsx +++ /dev/null @@ -1,68 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' -import { computeChecksum, itemsChecksum, makeItems } from '../../../shared' - -const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) - -const SumSubscriber = Vue.defineComponent({ - setup() { - const value = Route.useLoaderData({ - select: (data) => computeChecksum(data.checksum), - }) - - return () => { - void computeChecksum(value.value) - return null - } - }, -}) - -const FirstItemSubscriber = Vue.defineComponent({ - setup() { - const value = Route.useLoaderData({ - select: (data) => computeChecksum(data.items[0]?.value ?? 0), - }) - - return () => { - void computeChecksum(value.value) - return null - } - }, -}) - -const FreshPage = Vue.defineComponent({ - setup() { - const params = Route.useParams() - const loaderData = Route.useLoaderData() - - return () => ( -
- {subscriberIndexes.map((index) => ( - - ))} - {subscriberIndexes.map((index) => ( - - ))} -

Fresh

-
- {`f-${params.value.id}-${loaderData.value.checksum}`} -
-
    - {loaderData.value.items.slice(0, 5).map((item) => ( -
  • {item.name}
  • - ))} -
-
- ) - }, -}) - -export const Route = createFileRoute('/fresh/$id')({ - loader: ({ params }) => { - const items = makeItems(`fresh-${params.id}`) - return { items, checksum: itemsChecksum(items) } - }, - staleTime: 0, - gcTime: 0, - component: FreshPage, -}) diff --git a/benchmarks/client-nav/scenarios/loaders/vue/src/routes/index.tsx b/benchmarks/client-nav/scenarios/loaders/vue/src/routes/index.tsx deleted file mode 100644 index c9724c90a4..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/vue/src/routes/index.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const HomePage = Vue.defineComponent({ - setup() { - return () => ( -
-

Loaders Bench

-
home
-
- ) - }, -}) - -export const Route = createFileRoute('/')({ - component: HomePage, -}) diff --git a/benchmarks/client-nav/scenarios/loaders/vue/tsconfig.json b/benchmarks/client-nav/scenarios/loaders/vue/tsconfig.json deleted file mode 100644 index 7786fc3da9..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/vue/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/loaders/vue/vite.config.ts b/benchmarks/client-nav/scenarios/loaders/vue/vite.config.ts deleted file mode 100644 index ecf4cce139..0000000000 --- a/benchmarks/client-nav/scenarios/loaders/vue/vite.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'vue', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav loaders (vue)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - }, -}) diff --git a/benchmarks/client-nav/scenarios/mount/react/project.json b/benchmarks/client-nav/scenarios/mount/react/project.json deleted file mode 100644 index 61839943b3..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-mount-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/mount/react/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/mount/react/setup.ts b/benchmarks/client-nav/scenarios/mount/react/setup.ts deleted file mode 100644 index ed0426c696..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createMountLoopSetup } from '../../harness' -import { assertReady, readyTestId } 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 createMountLoopSetup({ - frameworkLabel: 'React', - mount: mountTestApp, - readyTestId, - assertReady, - }) -} diff --git a/benchmarks/client-nav/scenarios/mount/react/speed.bench.ts b/benchmarks/client-nav/scenarios/mount/react/speed.bench.ts deleted file mode 100644 index 6c3a64b026..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-mount', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-mount 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/mount/react/speed.flame.ts b/benchmarks/client-nav/scenarios/mount/react/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/mount/react/src/main.tsx b/benchmarks/client-nav/scenarios/mount/react/src/main.tsx deleted file mode 100644 index 4e45ed7ef3..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/src/main.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import { RouterProvider, createRouter } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { routeTree } from './routeTree.gen' -import type { RouterHistory } from '@tanstack/history' - -/** - * Unlike the other scenarios, this app is mounted and unmounted in a loop, so - * it must not register page-lifetime globals that have no dispose path: - * - the harness injects and destroys a fresh memory history per mount; - * - `scrollRestoration` stays off — enabling it registers per-router - * document/window listeners that retain every router ever created. - */ -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - }) -} - -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/mount/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/mount/react/src/routeTree.gen.ts deleted file mode 100644 index f9b7e5c268..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/src/routeTree.gen.ts +++ /dev/null @@ -1,264 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as AboutRouteImport } from './routes/about' -import { Route as BlogRouteImport } from './routes/blog' -import { Route as SearchRouteImport } from './routes/search' -import { Route as SettingsRouteImport } from './routes/settings' -import { Route as ShopRouteImport } from './routes/shop' -import { Route as BlogIndexRouteImport } from './routes/blog.index' -import { Route as BlogSlugRouteImport } from './routes/blog.$slug' -import { Route as ShopIndexRouteImport } from './routes/shop.index' -import { Route as ShopProductIdRouteImport } from './routes/shop.$productId' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) -const BlogRoute = BlogRouteImport.update({ - id: '/blog', - path: '/blog', - getParentRoute: () => rootRouteImport, -} as any) -const SearchRoute = SearchRouteImport.update({ - id: '/search', - path: '/search', - 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 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 - '/about': typeof AboutRoute - '/blog': typeof BlogRouteWithChildren - '/search': typeof SearchRoute - '/settings': typeof SettingsRoute - '/shop': typeof ShopRouteWithChildren - '/blog/$slug': typeof BlogSlugRoute - '/shop/$productId': typeof ShopProductIdRoute - '/blog/': typeof BlogIndexRoute - '/shop/': typeof ShopIndexRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/about': typeof AboutRoute - '/search': typeof SearchRoute - '/settings': typeof SettingsRoute - '/blog/$slug': typeof BlogSlugRoute - '/shop/$productId': typeof ShopProductIdRoute - '/blog': typeof BlogIndexRoute - '/shop': typeof ShopIndexRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/about': typeof AboutRoute - '/blog': typeof BlogRouteWithChildren - '/search': typeof SearchRoute - '/settings': typeof SettingsRoute - '/shop': typeof ShopRouteWithChildren - '/blog/$slug': typeof BlogSlugRoute - '/shop/$productId': typeof ShopProductIdRoute - '/blog/': typeof BlogIndexRoute - '/shop/': typeof ShopIndexRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/about' - | '/blog' - | '/search' - | '/settings' - | '/shop' - | '/blog/$slug' - | '/shop/$productId' - | '/blog/' - | '/shop/' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/about' - | '/search' - | '/settings' - | '/blog/$slug' - | '/shop/$productId' - | '/blog' - | '/shop' - id: - | '__root__' - | '/' - | '/about' - | '/blog' - | '/search' - | '/settings' - | '/shop' - | '/blog/$slug' - | '/shop/$productId' - | '/blog/' - | '/shop/' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - AboutRoute: typeof AboutRoute - BlogRoute: typeof BlogRouteWithChildren - SearchRoute: typeof SearchRoute - SettingsRoute: typeof SettingsRoute - ShopRoute: typeof ShopRouteWithChildren -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } - '/blog': { - id: '/blog' - path: '/blog' - fullPath: '/blog' - preLoaderRoute: typeof BlogRouteImport - parentRoute: typeof rootRouteImport - } - '/search': { - id: '/search' - path: '/search' - fullPath: '/search' - preLoaderRoute: typeof SearchRouteImport - 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/' - path: '/' - fullPath: '/blog/' - preLoaderRoute: typeof BlogIndexRouteImport - parentRoute: typeof BlogRoute - } - '/blog/$slug': { - id: '/blog/$slug' - path: '/$slug' - fullPath: '/blog/$slug' - 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 - } - } -} - -interface BlogRouteChildren { - BlogSlugRoute: typeof BlogSlugRoute - BlogIndexRoute: typeof BlogIndexRoute -} - -const BlogRouteChildren: BlogRouteChildren = { - BlogSlugRoute: BlogSlugRoute, - BlogIndexRoute: BlogIndexRoute, -} - -const BlogRouteWithChildren = BlogRoute._addFileChildren(BlogRouteChildren) - -interface ShopRouteChildren { - ShopProductIdRoute: typeof ShopProductIdRoute - ShopIndexRoute: typeof ShopIndexRoute -} - -const ShopRouteChildren: ShopRouteChildren = { - ShopProductIdRoute: ShopProductIdRoute, - ShopIndexRoute: ShopIndexRoute, -} - -const ShopRouteWithChildren = ShopRoute._addFileChildren(ShopRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - AboutRoute: AboutRoute, - BlogRoute: BlogRouteWithChildren, - SearchRoute: SearchRoute, - SettingsRoute: SettingsRoute, - ShopRoute: ShopRouteWithChildren, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/mount/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/mount/react/src/routes/__root.tsx deleted file mode 100644 index 0deab171d8..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/src/routes/__root.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import { Link, Outlet, createRootRoute } from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - <> - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/mount/react/src/routes/about.tsx b/benchmarks/client-nav/scenarios/mount/react/src/routes/about.tsx deleted file mode 100644 index 3fedde283b..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/src/routes/about.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/about')({ - component: AboutPage, -}) - -function AboutPage() { - return

About

-} diff --git a/benchmarks/client-nav/scenarios/mount/react/src/routes/blog.$slug.tsx b/benchmarks/client-nav/scenarios/mount/react/src/routes/blog.$slug.tsx deleted file mode 100644 index f995d95d94..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/src/routes/blog.$slug.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { articleData } from '../../../shared' - -export const Route = createFileRoute('/blog/$slug')({ - loader: ({ params }) => articleData(params.slug), - component: ArticlePage, -}) - -function ArticlePage() { - const article = Route.useLoaderData() - - return
{`${article.title} (${article.words} words)`}
-} diff --git a/benchmarks/client-nav/scenarios/mount/react/src/routes/blog.index.tsx b/benchmarks/client-nav/scenarios/mount/react/src/routes/blog.index.tsx deleted file mode 100644 index 437187eb4f..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/src/routes/blog.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/blog/')({ - component: BlogIndexPage, -}) - -function BlogIndexPage() { - return

All articles

-} diff --git a/benchmarks/client-nav/scenarios/mount/react/src/routes/blog.tsx b/benchmarks/client-nav/scenarios/mount/react/src/routes/blog.tsx deleted file mode 100644 index ab4fbeb482..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/src/routes/blog.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import { blogContext } from '../../../shared' - -export const Route = createFileRoute('/blog')({ - beforeLoad: () => blogContext(), - component: BlogLayout, -}) - -function BlogLayout() { - return ( -
-

Blog

- -
- ) -} diff --git a/benchmarks/client-nav/scenarios/mount/react/src/routes/index.tsx b/benchmarks/client-nav/scenarios/mount/react/src/routes/index.tsx deleted file mode 100644 index dbc99d8f66..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/src/routes/index.tsx +++ /dev/null @@ -1,22 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { homeItems, readyTestId } from '../../../shared' - -export const Route = createFileRoute('/')({ - loader: () => homeItems(), - component: HomePage, -}) - -function HomePage() { - const items = Route.useLoaderData() - - return ( -
-

{`Home (${items.length} items)`}

-
    - {items.map((item) => ( -
  • {`${item.label}: ${item.score}`}
  • - ))} -
-
- ) -} diff --git a/benchmarks/client-nav/scenarios/mount/react/src/routes/search.tsx b/benchmarks/client-nav/scenarios/mount/react/src/routes/search.tsx deleted file mode 100644 index faba50fc72..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/src/routes/search.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { normalizePage, normalizeQuery } from '../../../shared' - -export const Route = createFileRoute('/search')({ - validateSearch: (search: Record) => ({ - q: normalizeQuery(search.q), - page: normalizePage(search.page), - }), - component: SearchPage, -}) - -function SearchPage() { - const search = Route.useSearch() - - return

{`Results for "${search.q}" page ${search.page}`}

-} diff --git a/benchmarks/client-nav/scenarios/mount/react/src/routes/settings.tsx b/benchmarks/client-nav/scenarios/mount/react/src/routes/settings.tsx deleted file mode 100644 index 1f46d9d885..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/src/routes/settings.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/settings')({ - component: SettingsPage, -}) - -function SettingsPage() { - return

Settings

-} diff --git a/benchmarks/client-nav/scenarios/mount/react/src/routes/shop.$productId.tsx b/benchmarks/client-nav/scenarios/mount/react/src/routes/shop.$productId.tsx deleted file mode 100644 index 7b729a3dca..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/src/routes/shop.$productId.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { productData } from '../../../shared' - -export const Route = createFileRoute('/shop/$productId')({ - loader: ({ params }) => productData(params.productId), - component: ProductPage, -}) - -function ProductPage() { - const product = Route.useLoaderData() - - return
{`${product.name}: ${product.price}`}
-} diff --git a/benchmarks/client-nav/scenarios/mount/react/src/routes/shop.index.tsx b/benchmarks/client-nav/scenarios/mount/react/src/routes/shop.index.tsx deleted file mode 100644 index dbca94357a..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/src/routes/shop.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/shop/')({ - component: ShopIndexPage, -}) - -function ShopIndexPage() { - return

All products

-} diff --git a/benchmarks/client-nav/scenarios/mount/react/src/routes/shop.tsx b/benchmarks/client-nav/scenarios/mount/react/src/routes/shop.tsx deleted file mode 100644 index 5243d7bb0e..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/src/routes/shop.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import { shopContext } from '../../../shared' - -export const Route = createFileRoute('/shop')({ - beforeLoad: () => shopContext(), - component: ShopLayout, -}) - -function ShopLayout() { - return ( -
-

Shop

- -
- ) -} diff --git a/benchmarks/client-nav/scenarios/mount/react/tsconfig.json b/benchmarks/client-nav/scenarios/mount/react/tsconfig.json deleted file mode 100644 index 1d59cbb450..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/mount/react/vite.config.ts b/benchmarks/client-nav/scenarios/mount/react/vite.config.ts deleted file mode 100644 index e197d33a9e..0000000000 --- a/benchmarks/client-nav/scenarios/mount/react/vite.config.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'react', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav mount (react)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - }, -}) diff --git a/benchmarks/client-nav/scenarios/mount/shared.ts b/benchmarks/client-nav/scenarios/mount/shared.ts deleted file mode 100644 index a8f3d2c7bd..0000000000 --- a/benchmarks/client-nav/scenarios/mount/shared.ts +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Shared definition of the `mount` scenario: cold start of a moderate, - * realistic app — router creation (processRouteTree), first render, initial - * `router.load()`, and unmount. This is the only scenario where router - * construction is inside the measured loop; the wider tree exists as - * realistic route-processing weight even though only the index route loads. - */ - -export const readyTestId = 'mount-ready' - -export const homeItemCount = 5 - -export function homeItems() { - return Array.from({ length: homeItemCount }, (_, index) => ({ - id: `item-${index}`, - label: `Featured item ${index}`, - score: index * 17 + 3, - })) -} - -export const homeReadyText = `Home (${homeItemCount} items)` - -export function shopContext() { - return { shopSeed: 7 } -} - -export function blogContext() { - return { blogSeed: 13 } -} - -export function productData(productId: string) { - return { - id: productId, - name: `Product ${productId}`, - price: productId.length * 100 + 42, - } -} - -export function articleData(slug: string) { - return { - slug, - title: `Article ${slug}`, - words: slug.length * 250, - } -} - -export function normalizePage(value: unknown) { - const page = Number(value) - return Number.isFinite(page) && page > 0 ? Math.trunc(page) : 1 -} - -export function normalizeQuery(value: unknown) { - return typeof value === 'string' ? value : '' -} - -export function assertReady(container: HTMLElement) { - const marker = container.querySelector(`[data-testid="${readyTestId}"]`) - if (marker?.textContent !== homeReadyText) { - throw new Error( - `Expected mount marker to be "${homeReadyText}", received "${marker?.textContent}"`, - ) - } -} - -// Mounts per benchmark iteration. -// 6 mounts per iteration: a single mount simulates to only ~8ms of CPU, and -// very short measures amplify the relative impact of allocator/GC -// quantization; 6 keeps the measure comfortably above ~50ms simulated. -export const ticksPerIteration = 6 - -export const benchOptions = { - warmupIterations: 100, - time: 10_000, - throws: true, -} diff --git a/benchmarks/client-nav/scenarios/mount/solid/project.json b/benchmarks/client-nav/scenarios/mount/solid/project.json deleted file mode 100644 index 4349570654..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-mount-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/mount/solid/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/mount/solid/setup.ts b/benchmarks/client-nav/scenarios/mount/solid/setup.ts deleted file mode 100644 index 810ea38c91..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createMountLoopSetup } from '../../harness' -import { assertReady, readyTestId } 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 createMountLoopSetup({ - frameworkLabel: 'Solid', - mount: mountTestApp, - readyTestId, - assertReady, - }) -} diff --git a/benchmarks/client-nav/scenarios/mount/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/mount/solid/speed.bench.ts deleted file mode 100644 index 236f875f57..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-mount', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-mount 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/mount/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/mount/solid/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/main.tsx b/benchmarks/client-nav/scenarios/mount/solid/src/main.tsx deleted file mode 100644 index 2586872f5c..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/src/main.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import { render } from 'solid-js/web' -import { RouterProvider, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' -import type { RouterHistory } from '@tanstack/history' - -/** - * Unlike the other scenarios, this app is mounted and unmounted in a loop, so - * it must not register page-lifetime globals that have no dispose path: - * - the harness injects and destroys a fresh memory history per mount; - * - `scrollRestoration` stays off — enabling it registers per-router - * document/window listeners that retain every router ever created. - */ -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const dispose = render(() => , container) - - return { - router, - unmount() { - dispose() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/mount/solid/src/routeTree.gen.ts deleted file mode 100644 index 30247636dd..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,264 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as AboutRouteImport } from './routes/about' -import { Route as BlogRouteImport } from './routes/blog' -import { Route as SearchRouteImport } from './routes/search' -import { Route as SettingsRouteImport } from './routes/settings' -import { Route as ShopRouteImport } from './routes/shop' -import { Route as BlogIndexRouteImport } from './routes/blog.index' -import { Route as BlogSlugRouteImport } from './routes/blog.$slug' -import { Route as ShopIndexRouteImport } from './routes/shop.index' -import { Route as ShopProductIdRouteImport } from './routes/shop.$productId' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) -const BlogRoute = BlogRouteImport.update({ - id: '/blog', - path: '/blog', - getParentRoute: () => rootRouteImport, -} as any) -const SearchRoute = SearchRouteImport.update({ - id: '/search', - path: '/search', - 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 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 - '/about': typeof AboutRoute - '/blog': typeof BlogRouteWithChildren - '/search': typeof SearchRoute - '/settings': typeof SettingsRoute - '/shop': typeof ShopRouteWithChildren - '/blog/$slug': typeof BlogSlugRoute - '/shop/$productId': typeof ShopProductIdRoute - '/blog/': typeof BlogIndexRoute - '/shop/': typeof ShopIndexRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/about': typeof AboutRoute - '/search': typeof SearchRoute - '/settings': typeof SettingsRoute - '/blog/$slug': typeof BlogSlugRoute - '/shop/$productId': typeof ShopProductIdRoute - '/blog': typeof BlogIndexRoute - '/shop': typeof ShopIndexRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/about': typeof AboutRoute - '/blog': typeof BlogRouteWithChildren - '/search': typeof SearchRoute - '/settings': typeof SettingsRoute - '/shop': typeof ShopRouteWithChildren - '/blog/$slug': typeof BlogSlugRoute - '/shop/$productId': typeof ShopProductIdRoute - '/blog/': typeof BlogIndexRoute - '/shop/': typeof ShopIndexRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/about' - | '/blog' - | '/search' - | '/settings' - | '/shop' - | '/blog/$slug' - | '/shop/$productId' - | '/blog/' - | '/shop/' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/about' - | '/search' - | '/settings' - | '/blog/$slug' - | '/shop/$productId' - | '/blog' - | '/shop' - id: - | '__root__' - | '/' - | '/about' - | '/blog' - | '/search' - | '/settings' - | '/shop' - | '/blog/$slug' - | '/shop/$productId' - | '/blog/' - | '/shop/' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - AboutRoute: typeof AboutRoute - BlogRoute: typeof BlogRouteWithChildren - SearchRoute: typeof SearchRoute - SettingsRoute: typeof SettingsRoute - ShopRoute: typeof ShopRouteWithChildren -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } - '/blog': { - id: '/blog' - path: '/blog' - fullPath: '/blog' - preLoaderRoute: typeof BlogRouteImport - parentRoute: typeof rootRouteImport - } - '/search': { - id: '/search' - path: '/search' - fullPath: '/search' - preLoaderRoute: typeof SearchRouteImport - 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/' - path: '/' - fullPath: '/blog/' - preLoaderRoute: typeof BlogIndexRouteImport - parentRoute: typeof BlogRoute - } - '/blog/$slug': { - id: '/blog/$slug' - path: '/$slug' - fullPath: '/blog/$slug' - 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 - } - } -} - -interface BlogRouteChildren { - BlogSlugRoute: typeof BlogSlugRoute - BlogIndexRoute: typeof BlogIndexRoute -} - -const BlogRouteChildren: BlogRouteChildren = { - BlogSlugRoute: BlogSlugRoute, - BlogIndexRoute: BlogIndexRoute, -} - -const BlogRouteWithChildren = BlogRoute._addFileChildren(BlogRouteChildren) - -interface ShopRouteChildren { - ShopProductIdRoute: typeof ShopProductIdRoute - ShopIndexRoute: typeof ShopIndexRoute -} - -const ShopRouteChildren: ShopRouteChildren = { - ShopProductIdRoute: ShopProductIdRoute, - ShopIndexRoute: ShopIndexRoute, -} - -const ShopRouteWithChildren = ShopRoute._addFileChildren(ShopRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - AboutRoute: AboutRoute, - BlogRoute: BlogRouteWithChildren, - SearchRoute: SearchRoute, - SettingsRoute: SettingsRoute, - ShopRoute: ShopRouteWithChildren, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/mount/solid/src/routes/__root.tsx deleted file mode 100644 index f5c3be2641..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/src/routes/__root.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import { Link, Outlet, createRootRoute } from '@tanstack/solid-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - <> - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routes/about.tsx b/benchmarks/client-nav/scenarios/mount/solid/src/routes/about.tsx deleted file mode 100644 index f74d85aa06..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/src/routes/about.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/about')({ - component: AboutPage, -}) - -function AboutPage() { - return

About

-} diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routes/blog.$slug.tsx b/benchmarks/client-nav/scenarios/mount/solid/src/routes/blog.$slug.tsx deleted file mode 100644 index 82caee757a..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/src/routes/blog.$slug.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { articleData } from '../../../shared' - -export const Route = createFileRoute('/blog/$slug')({ - loader: ({ params }) => articleData(params.slug), - component: ArticlePage, -}) - -function ArticlePage() { - const article = Route.useLoaderData() - - return
{`${article().title} (${article().words} words)`}
-} diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routes/blog.index.tsx b/benchmarks/client-nav/scenarios/mount/solid/src/routes/blog.index.tsx deleted file mode 100644 index 8e75108aca..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/src/routes/blog.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/blog/')({ - component: BlogIndexPage, -}) - -function BlogIndexPage() { - return

All articles

-} diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routes/blog.tsx b/benchmarks/client-nav/scenarios/mount/solid/src/routes/blog.tsx deleted file mode 100644 index 1e2cfbd019..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/src/routes/blog.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' -import { blogContext } from '../../../shared' - -export const Route = createFileRoute('/blog')({ - beforeLoad: () => blogContext(), - component: BlogLayout, -}) - -function BlogLayout() { - return ( -
-

Blog

- -
- ) -} diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routes/index.tsx b/benchmarks/client-nav/scenarios/mount/solid/src/routes/index.tsx deleted file mode 100644 index 30665ba224..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/src/routes/index.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import { For } from 'solid-js' -import { createFileRoute } from '@tanstack/solid-router' -import { homeItems, readyTestId } from '../../../shared' - -export const Route = createFileRoute('/')({ - loader: () => homeItems(), - component: HomePage, -}) - -function HomePage() { - const items = Route.useLoaderData() - - return ( -
-

{`Home (${items().length} items)`}

-
    - - {(item) =>
  • {`${item.label}: ${item.score}`}
  • } -
    -
-
- ) -} diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routes/search.tsx b/benchmarks/client-nav/scenarios/mount/solid/src/routes/search.tsx deleted file mode 100644 index 3f8b2d9dd7..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/src/routes/search.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { normalizePage, normalizeQuery } from '../../../shared' - -export const Route = createFileRoute('/search')({ - validateSearch: (search: Record) => ({ - q: normalizeQuery(search.q), - page: normalizePage(search.page), - }), - component: SearchPage, -}) - -function SearchPage() { - const search = Route.useSearch() - - return

{`Results for "${search().q}" page ${search().page}`}

-} diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routes/settings.tsx b/benchmarks/client-nav/scenarios/mount/solid/src/routes/settings.tsx deleted file mode 100644 index c6b95424d9..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/src/routes/settings.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/settings')({ - component: SettingsPage, -}) - -function SettingsPage() { - return

Settings

-} diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routes/shop.$productId.tsx b/benchmarks/client-nav/scenarios/mount/solid/src/routes/shop.$productId.tsx deleted file mode 100644 index 71b0411d6b..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/src/routes/shop.$productId.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { productData } from '../../../shared' - -export const Route = createFileRoute('/shop/$productId')({ - loader: ({ params }) => productData(params.productId), - component: ProductPage, -}) - -function ProductPage() { - const product = Route.useLoaderData() - - return
{`${product().name}: ${product().price}`}
-} diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routes/shop.index.tsx b/benchmarks/client-nav/scenarios/mount/solid/src/routes/shop.index.tsx deleted file mode 100644 index e33c8779f9..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/src/routes/shop.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/shop/')({ - component: ShopIndexPage, -}) - -function ShopIndexPage() { - return

All products

-} diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routes/shop.tsx b/benchmarks/client-nav/scenarios/mount/solid/src/routes/shop.tsx deleted file mode 100644 index ff2ca78653..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/src/routes/shop.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' -import { shopContext } from '../../../shared' - -export const Route = createFileRoute('/shop')({ - beforeLoad: () => shopContext(), - component: ShopLayout, -}) - -function ShopLayout() { - return ( -
-

Shop

- -
- ) -} diff --git a/benchmarks/client-nav/scenarios/mount/solid/tsconfig.json b/benchmarks/client-nav/scenarios/mount/solid/tsconfig.json deleted file mode 100644 index 98d76ad6b8..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/mount/solid/vite.config.ts b/benchmarks/client-nav/scenarios/mount/solid/vite.config.ts deleted file mode 100644 index 5b586dd128..0000000000 --- a/benchmarks/client-nav/scenarios/mount/solid/vite.config.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import solid from 'vite-plugin-solid' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'solid', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - resolve: { - conditions: ['solid', 'browser'], - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav mount (solid)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/client-nav/scenarios/mount/vue/project.json b/benchmarks/client-nav/scenarios/mount/vue/project.json deleted file mode 100644 index f2dbd10440..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-mount-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/mount/vue/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/mount/vue/setup.ts b/benchmarks/client-nav/scenarios/mount/vue/setup.ts deleted file mode 100644 index 3976e71c51..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createMountLoopSetup } from '../../harness' -import { assertReady, readyTestId } 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 createMountLoopSetup({ - frameworkLabel: 'Vue', - mount: mountTestApp, - readyTestId, - assertReady, - }) -} diff --git a/benchmarks/client-nav/scenarios/mount/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/mount/vue/speed.bench.ts deleted file mode 100644 index d9268ba91b..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/speed.bench.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-mount', async ({ bench }) => { - const scenario = setup() - - await bench('client-mount loop (vue)', benchLifecycle(scenario), async () => { - for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() - } - await scenario.finishBatch() - }).run(benchOptions) -}) diff --git a/benchmarks/client-nav/scenarios/mount/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/mount/vue/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/main.tsx b/benchmarks/client-nav/scenarios/mount/vue/src/main.tsx deleted file mode 100644 index fc493c10a5..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/src/main.tsx +++ /dev/null @@ -1,42 +0,0 @@ -import * as Vue from 'vue' -import { RouterProvider, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' -import type { RouterHistory } from '@tanstack/history' - -/** - * Unlike the other scenarios, this app is mounted and unmounted in a loop, so - * it must not register page-lifetime globals that have no dispose path: - * - the harness injects and destroys a fresh memory history per mount; - * - `scrollRestoration` stays off — enabling it registers per-router - * document/window listeners that retain every router ever created. - */ -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - }) -} - -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/mount/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/mount/vue/src/routeTree.gen.ts deleted file mode 100644 index cd27c917e1..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,264 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as AboutRouteImport } from './routes/about' -import { Route as BlogRouteImport } from './routes/blog' -import { Route as SearchRouteImport } from './routes/search' -import { Route as SettingsRouteImport } from './routes/settings' -import { Route as ShopRouteImport } from './routes/shop' -import { Route as BlogIndexRouteImport } from './routes/blog.index' -import { Route as BlogSlugRouteImport } from './routes/blog.$slug' -import { Route as ShopIndexRouteImport } from './routes/shop.index' -import { Route as ShopProductIdRouteImport } from './routes/shop.$productId' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) -const BlogRoute = BlogRouteImport.update({ - id: '/blog', - path: '/blog', - getParentRoute: () => rootRouteImport, -} as any) -const SearchRoute = SearchRouteImport.update({ - id: '/search', - path: '/search', - 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 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 - '/about': typeof AboutRoute - '/blog': typeof BlogRouteWithChildren - '/search': typeof SearchRoute - '/settings': typeof SettingsRoute - '/shop': typeof ShopRouteWithChildren - '/blog/$slug': typeof BlogSlugRoute - '/shop/$productId': typeof ShopProductIdRoute - '/blog/': typeof BlogIndexRoute - '/shop/': typeof ShopIndexRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/about': typeof AboutRoute - '/search': typeof SearchRoute - '/settings': typeof SettingsRoute - '/blog/$slug': typeof BlogSlugRoute - '/shop/$productId': typeof ShopProductIdRoute - '/blog': typeof BlogIndexRoute - '/shop': typeof ShopIndexRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/about': typeof AboutRoute - '/blog': typeof BlogRouteWithChildren - '/search': typeof SearchRoute - '/settings': typeof SettingsRoute - '/shop': typeof ShopRouteWithChildren - '/blog/$slug': typeof BlogSlugRoute - '/shop/$productId': typeof ShopProductIdRoute - '/blog/': typeof BlogIndexRoute - '/shop/': typeof ShopIndexRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/about' - | '/blog' - | '/search' - | '/settings' - | '/shop' - | '/blog/$slug' - | '/shop/$productId' - | '/blog/' - | '/shop/' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/about' - | '/search' - | '/settings' - | '/blog/$slug' - | '/shop/$productId' - | '/blog' - | '/shop' - id: - | '__root__' - | '/' - | '/about' - | '/blog' - | '/search' - | '/settings' - | '/shop' - | '/blog/$slug' - | '/shop/$productId' - | '/blog/' - | '/shop/' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - AboutRoute: typeof AboutRoute - BlogRoute: typeof BlogRouteWithChildren - SearchRoute: typeof SearchRoute - SettingsRoute: typeof SettingsRoute - ShopRoute: typeof ShopRouteWithChildren -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } - '/blog': { - id: '/blog' - path: '/blog' - fullPath: '/blog' - preLoaderRoute: typeof BlogRouteImport - parentRoute: typeof rootRouteImport - } - '/search': { - id: '/search' - path: '/search' - fullPath: '/search' - preLoaderRoute: typeof SearchRouteImport - 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/' - path: '/' - fullPath: '/blog/' - preLoaderRoute: typeof BlogIndexRouteImport - parentRoute: typeof BlogRoute - } - '/blog/$slug': { - id: '/blog/$slug' - path: '/$slug' - fullPath: '/blog/$slug' - 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 - } - } -} - -interface BlogRouteChildren { - BlogSlugRoute: typeof BlogSlugRoute - BlogIndexRoute: typeof BlogIndexRoute -} - -const BlogRouteChildren: BlogRouteChildren = { - BlogSlugRoute: BlogSlugRoute, - BlogIndexRoute: BlogIndexRoute, -} - -const BlogRouteWithChildren = BlogRoute._addFileChildren(BlogRouteChildren) - -interface ShopRouteChildren { - ShopProductIdRoute: typeof ShopProductIdRoute - ShopIndexRoute: typeof ShopIndexRoute -} - -const ShopRouteChildren: ShopRouteChildren = { - ShopProductIdRoute: ShopProductIdRoute, - ShopIndexRoute: ShopIndexRoute, -} - -const ShopRouteWithChildren = ShopRoute._addFileChildren(ShopRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - AboutRoute: AboutRoute, - BlogRoute: BlogRouteWithChildren, - SearchRoute: SearchRoute, - SettingsRoute: SettingsRoute, - ShopRoute: ShopRouteWithChildren, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/mount/vue/src/routes/__root.tsx deleted file mode 100644 index 5c2b7b52d0..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/src/routes/__root.tsx +++ /dev/null @@ -1,44 +0,0 @@ -import * as Vue from 'vue' -import { Link, Outlet, createRootRoute } from '@tanstack/vue-router' - -const RootComponent = Vue.defineComponent({ - setup() { - return () => ( - <> - - - - ) - }, -}) - -export const Route = createRootRoute({ - component: RootComponent, -}) diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/routes/about.tsx b/benchmarks/client-nav/scenarios/mount/vue/src/routes/about.tsx deleted file mode 100644 index 254ecca29c..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/src/routes/about.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const AboutPage = Vue.defineComponent({ - setup() { - return () =>

About

- }, -}) - -export const Route = createFileRoute('/about')({ - component: AboutPage, -}) diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/routes/blog.$slug.tsx b/benchmarks/client-nav/scenarios/mount/vue/src/routes/blog.$slug.tsx deleted file mode 100644 index 3b2e855a6e..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/src/routes/blog.$slug.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' -import { articleData } from '../../../shared' - -const ArticlePage = Vue.defineComponent({ - setup() { - const article = Route.useLoaderData() - - return () => ( -
{`${article.value.title} (${article.value.words} words)`}
- ) - }, -}) - -export const Route = createFileRoute('/blog/$slug')({ - loader: ({ params }) => articleData(params.slug), - component: ArticlePage, -}) diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/routes/blog.index.tsx b/benchmarks/client-nav/scenarios/mount/vue/src/routes/blog.index.tsx deleted file mode 100644 index d3c2bd0305..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/src/routes/blog.index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const BlogIndexPage = Vue.defineComponent({ - setup() { - return () =>

All articles

- }, -}) - -export const Route = createFileRoute('/blog/')({ - component: BlogIndexPage, -}) diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/routes/blog.tsx b/benchmarks/client-nav/scenarios/mount/vue/src/routes/blog.tsx deleted file mode 100644 index fe9532cc6f..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/src/routes/blog.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import * as Vue from 'vue' -import { Outlet, createFileRoute } from '@tanstack/vue-router' -import { blogContext } from '../../../shared' - -const BlogLayout = Vue.defineComponent({ - setup() { - return () => ( -
-

Blog

- -
- ) - }, -}) - -export const Route = createFileRoute('/blog')({ - beforeLoad: () => blogContext(), - component: BlogLayout, -}) diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/routes/index.tsx b/benchmarks/client-nav/scenarios/mount/vue/src/routes/index.tsx deleted file mode 100644 index b0be4d78bb..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/src/routes/index.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' -import { homeItems, readyTestId } from '../../../shared' - -const HomePage = Vue.defineComponent({ - setup() { - const items = Route.useLoaderData() - - return () => ( -
-

{`Home (${items.value.length} items)`}

-
    - {items.value.map((item) => ( -
  • {`${item.label}: ${item.score}`}
  • - ))} -
-
- ) - }, -}) - -export const Route = createFileRoute('/')({ - loader: () => homeItems(), - component: HomePage, -}) diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/routes/search.tsx b/benchmarks/client-nav/scenarios/mount/vue/src/routes/search.tsx deleted file mode 100644 index 09fdb29c1e..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/src/routes/search.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' -import { normalizePage, normalizeQuery } from '../../../shared' - -const SearchPage = Vue.defineComponent({ - setup() { - const search = Route.useSearch() - - return () => ( -

{`Results for "${search.value.q}" page ${search.value.page}`}

- ) - }, -}) - -export const Route = createFileRoute('/search')({ - validateSearch: (search: Record) => ({ - q: normalizeQuery(search.q), - page: normalizePage(search.page), - }), - component: SearchPage, -}) diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/routes/settings.tsx b/benchmarks/client-nav/scenarios/mount/vue/src/routes/settings.tsx deleted file mode 100644 index 3fc0485606..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/src/routes/settings.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const SettingsPage = Vue.defineComponent({ - setup() { - return () =>

Settings

- }, -}) - -export const Route = createFileRoute('/settings')({ - component: SettingsPage, -}) diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/routes/shop.$productId.tsx b/benchmarks/client-nav/scenarios/mount/vue/src/routes/shop.$productId.tsx deleted file mode 100644 index 897559599a..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/src/routes/shop.$productId.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' -import { productData } from '../../../shared' - -const ProductPage = Vue.defineComponent({ - setup() { - const product = Route.useLoaderData() - - return () => ( -
{`${product.value.name}: ${product.value.price}`}
- ) - }, -}) - -export const Route = createFileRoute('/shop/$productId')({ - loader: ({ params }) => productData(params.productId), - component: ProductPage, -}) diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/routes/shop.index.tsx b/benchmarks/client-nav/scenarios/mount/vue/src/routes/shop.index.tsx deleted file mode 100644 index 1040520f03..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/src/routes/shop.index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const ShopIndexPage = Vue.defineComponent({ - setup() { - return () =>

All products

- }, -}) - -export const Route = createFileRoute('/shop/')({ - component: ShopIndexPage, -}) diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/routes/shop.tsx b/benchmarks/client-nav/scenarios/mount/vue/src/routes/shop.tsx deleted file mode 100644 index 184807cfa0..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/src/routes/shop.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import * as Vue from 'vue' -import { Outlet, createFileRoute } from '@tanstack/vue-router' -import { shopContext } from '../../../shared' - -const ShopLayout = Vue.defineComponent({ - setup() { - return () => ( -
-

Shop

- -
- ) - }, -}) - -export const Route = createFileRoute('/shop')({ - beforeLoad: () => shopContext(), - component: ShopLayout, -}) diff --git a/benchmarks/client-nav/scenarios/mount/vue/tsconfig.json b/benchmarks/client-nav/scenarios/mount/vue/tsconfig.json deleted file mode 100644 index 7786fc3da9..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/mount/vue/vite.config.ts b/benchmarks/client-nav/scenarios/mount/vue/vite.config.ts deleted file mode 100644 index 8d4005f339..0000000000 --- a/benchmarks/client-nav/scenarios/mount/vue/vite.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'vue', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav mount (vue)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - }, -}) diff --git a/benchmarks/client-nav/scenarios/nested-params/react/project.json b/benchmarks/client-nav/scenarios/nested-params/react/project.json deleted file mode 100644 index 800f8af9a8..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-nested-params-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/nested-params/react/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/setup.ts b/benchmarks/client-nav/scenarios/nested-params/react/setup.ts deleted file mode 100644 index 130583b190..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, steps } 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, - assertAfterStep: assertStepResult, - }) -} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/speed.bench.ts b/benchmarks/client-nav/scenarios/nested-params/react/speed.bench.ts deleted file mode 100644 index fa5809c1fd..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-nested-params', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-nested-params 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/nested-params/react/speed.flame.ts b/benchmarks/client-nav/scenarios/nested-params/react/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/main.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/main.tsx deleted file mode 100644 index 5febd6f795..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/src/main.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { RouterProvider, createRouter } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const reactRoot = createRoot(container) - reactRoot.render() - - return { - router, - unmount() { - reactRoot.unmount() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/nested-params/react/src/routeTree.gen.ts deleted file mode 100644 index 95d4b46623..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/src/routeTree.gen.ts +++ /dev/null @@ -1,291 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as LARouteImport } from './routes/l.$a' -import { Route as LABRouteImport } from './routes/l.$a.$b' -import { Route as LABCRouteImport } from './routes/l.$a.$b.$c' -import { Route as LABCDRouteImport } from './routes/l.$a.$b.$c.$d' -import { Route as LABCDERouteImport } from './routes/l.$a.$b.$c.$d.$e' -import { Route as LABCDEFRouteImport } from './routes/l.$a.$b.$c.$d.$e.$f' -import { Route as LABCDEFGRouteImport } from './routes/l.$a.$b.$c.$d.$e.$f.$g' -import { Route as LABCDEFGHRouteImport } from './routes/l.$a.$b.$c.$d.$e.$f.$g.$h' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const LARoute = LARouteImport.update({ - id: '/l/$a', - path: '/l/$a', - getParentRoute: () => rootRouteImport, -} as any) -const LABRoute = LABRouteImport.update({ - id: '/$b', - path: '/$b', - getParentRoute: () => LARoute, -} as any) -const LABCRoute = LABCRouteImport.update({ - id: '/$c', - path: '/$c', - getParentRoute: () => LABRoute, -} as any) -const LABCDRoute = LABCDRouteImport.update({ - id: '/$d', - path: '/$d', - getParentRoute: () => LABCRoute, -} as any) -const LABCDERoute = LABCDERouteImport.update({ - id: '/$e', - path: '/$e', - getParentRoute: () => LABCDRoute, -} as any) -const LABCDEFRoute = LABCDEFRouteImport.update({ - id: '/$f', - path: '/$f', - getParentRoute: () => LABCDERoute, -} as any) -const LABCDEFGRoute = LABCDEFGRouteImport.update({ - id: '/$g', - path: '/$g', - getParentRoute: () => LABCDEFRoute, -} as any) -const LABCDEFGHRoute = LABCDEFGHRouteImport.update({ - id: '/$h', - path: '/$h', - getParentRoute: () => LABCDEFGRoute, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/l/$a': typeof LARouteWithChildren - '/l/$a/$b': typeof LABRouteWithChildren - '/l/$a/$b/$c': typeof LABCRouteWithChildren - '/l/$a/$b/$c/$d': typeof LABCDRouteWithChildren - '/l/$a/$b/$c/$d/$e': typeof LABCDERouteWithChildren - '/l/$a/$b/$c/$d/$e/$f': typeof LABCDEFRouteWithChildren - '/l/$a/$b/$c/$d/$e/$f/$g': typeof LABCDEFGRouteWithChildren - '/l/$a/$b/$c/$d/$e/$f/$g/$h': typeof LABCDEFGHRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/l/$a': typeof LARouteWithChildren - '/l/$a/$b': typeof LABRouteWithChildren - '/l/$a/$b/$c': typeof LABCRouteWithChildren - '/l/$a/$b/$c/$d': typeof LABCDRouteWithChildren - '/l/$a/$b/$c/$d/$e': typeof LABCDERouteWithChildren - '/l/$a/$b/$c/$d/$e/$f': typeof LABCDEFRouteWithChildren - '/l/$a/$b/$c/$d/$e/$f/$g': typeof LABCDEFGRouteWithChildren - '/l/$a/$b/$c/$d/$e/$f/$g/$h': typeof LABCDEFGHRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/l/$a': typeof LARouteWithChildren - '/l/$a/$b': typeof LABRouteWithChildren - '/l/$a/$b/$c': typeof LABCRouteWithChildren - '/l/$a/$b/$c/$d': typeof LABCDRouteWithChildren - '/l/$a/$b/$c/$d/$e': typeof LABCDERouteWithChildren - '/l/$a/$b/$c/$d/$e/$f': typeof LABCDEFRouteWithChildren - '/l/$a/$b/$c/$d/$e/$f/$g': typeof LABCDEFGRouteWithChildren - '/l/$a/$b/$c/$d/$e/$f/$g/$h': typeof LABCDEFGHRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/l/$a' - | '/l/$a/$b' - | '/l/$a/$b/$c' - | '/l/$a/$b/$c/$d' - | '/l/$a/$b/$c/$d/$e' - | '/l/$a/$b/$c/$d/$e/$f' - | '/l/$a/$b/$c/$d/$e/$f/$g' - | '/l/$a/$b/$c/$d/$e/$f/$g/$h' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/l/$a' - | '/l/$a/$b' - | '/l/$a/$b/$c' - | '/l/$a/$b/$c/$d' - | '/l/$a/$b/$c/$d/$e' - | '/l/$a/$b/$c/$d/$e/$f' - | '/l/$a/$b/$c/$d/$e/$f/$g' - | '/l/$a/$b/$c/$d/$e/$f/$g/$h' - id: - | '__root__' - | '/' - | '/l/$a' - | '/l/$a/$b' - | '/l/$a/$b/$c' - | '/l/$a/$b/$c/$d' - | '/l/$a/$b/$c/$d/$e' - | '/l/$a/$b/$c/$d/$e/$f' - | '/l/$a/$b/$c/$d/$e/$f/$g' - | '/l/$a/$b/$c/$d/$e/$f/$g/$h' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - LARoute: typeof LARouteWithChildren -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/l/$a': { - id: '/l/$a' - path: '/l/$a' - fullPath: '/l/$a' - preLoaderRoute: typeof LARouteImport - parentRoute: typeof rootRouteImport - } - '/l/$a/$b': { - id: '/l/$a/$b' - path: '/$b' - fullPath: '/l/$a/$b' - preLoaderRoute: typeof LABRouteImport - parentRoute: typeof LARoute - } - '/l/$a/$b/$c': { - id: '/l/$a/$b/$c' - path: '/$c' - fullPath: '/l/$a/$b/$c' - preLoaderRoute: typeof LABCRouteImport - parentRoute: typeof LABRoute - } - '/l/$a/$b/$c/$d': { - id: '/l/$a/$b/$c/$d' - path: '/$d' - fullPath: '/l/$a/$b/$c/$d' - preLoaderRoute: typeof LABCDRouteImport - parentRoute: typeof LABCRoute - } - '/l/$a/$b/$c/$d/$e': { - id: '/l/$a/$b/$c/$d/$e' - path: '/$e' - fullPath: '/l/$a/$b/$c/$d/$e' - preLoaderRoute: typeof LABCDERouteImport - parentRoute: typeof LABCDRoute - } - '/l/$a/$b/$c/$d/$e/$f': { - id: '/l/$a/$b/$c/$d/$e/$f' - path: '/$f' - fullPath: '/l/$a/$b/$c/$d/$e/$f' - preLoaderRoute: typeof LABCDEFRouteImport - parentRoute: typeof LABCDERoute - } - '/l/$a/$b/$c/$d/$e/$f/$g': { - id: '/l/$a/$b/$c/$d/$e/$f/$g' - path: '/$g' - fullPath: '/l/$a/$b/$c/$d/$e/$f/$g' - preLoaderRoute: typeof LABCDEFGRouteImport - parentRoute: typeof LABCDEFRoute - } - '/l/$a/$b/$c/$d/$e/$f/$g/$h': { - id: '/l/$a/$b/$c/$d/$e/$f/$g/$h' - path: '/$h' - fullPath: '/l/$a/$b/$c/$d/$e/$f/$g/$h' - preLoaderRoute: typeof LABCDEFGHRouteImport - parentRoute: typeof LABCDEFGRoute - } - } -} - -interface LABCDEFGRouteChildren { - LABCDEFGHRoute: typeof LABCDEFGHRoute -} - -const LABCDEFGRouteChildren: LABCDEFGRouteChildren = { - LABCDEFGHRoute: LABCDEFGHRoute, -} - -const LABCDEFGRouteWithChildren = LABCDEFGRoute._addFileChildren( - LABCDEFGRouteChildren, -) - -interface LABCDEFRouteChildren { - LABCDEFGRoute: typeof LABCDEFGRouteWithChildren -} - -const LABCDEFRouteChildren: LABCDEFRouteChildren = { - LABCDEFGRoute: LABCDEFGRouteWithChildren, -} - -const LABCDEFRouteWithChildren = - LABCDEFRoute._addFileChildren(LABCDEFRouteChildren) - -interface LABCDERouteChildren { - LABCDEFRoute: typeof LABCDEFRouteWithChildren -} - -const LABCDERouteChildren: LABCDERouteChildren = { - LABCDEFRoute: LABCDEFRouteWithChildren, -} - -const LABCDERouteWithChildren = - LABCDERoute._addFileChildren(LABCDERouteChildren) - -interface LABCDRouteChildren { - LABCDERoute: typeof LABCDERouteWithChildren -} - -const LABCDRouteChildren: LABCDRouteChildren = { - LABCDERoute: LABCDERouteWithChildren, -} - -const LABCDRouteWithChildren = LABCDRoute._addFileChildren(LABCDRouteChildren) - -interface LABCRouteChildren { - LABCDRoute: typeof LABCDRouteWithChildren -} - -const LABCRouteChildren: LABCRouteChildren = { - LABCDRoute: LABCDRouteWithChildren, -} - -const LABCRouteWithChildren = LABCRoute._addFileChildren(LABCRouteChildren) - -interface LABRouteChildren { - LABCRoute: typeof LABCRouteWithChildren -} - -const LABRouteChildren: LABRouteChildren = { - LABCRoute: LABCRouteWithChildren, -} - -const LABRouteWithChildren = LABRoute._addFileChildren(LABRouteChildren) - -interface LARouteChildren { - LABRoute: typeof LABRouteWithChildren -} - -const LARouteChildren: LARouteChildren = { - LABRoute: LABRouteWithChildren, -} - -const LARouteWithChildren = LARoute._addFileChildren(LARouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - LARoute: LARouteWithChildren, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/__root.tsx deleted file mode 100644 index ef2c7b1b18..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/__root.tsx +++ /dev/null @@ -1,50 +0,0 @@ -import { Link, Outlet, createRootRoute } from '@tanstack/react-router' -import { leafParamSets, midParams } from '../../../shared' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - <> - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/index.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/index.tsx deleted file mode 100644 index 24e856ea15..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: HomePage, -}) - -function HomePage() { - return
home
-} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx deleted file mode 100644 index 9789e28040..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx +++ /dev/null @@ -1,63 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { normalizeParam, smallHash } from '../../../shared' - -export const Route = createFileRoute('/l/$a/$b/$c/$d/$e/$f/$g/$h')({ - params: { - parse: (params) => ({ ...params, h: normalizeParam(params.h) }), - stringify: (params) => ({ ...params, h: String(params.h) }), - }, - beforeLoad: ({ params }) => ({ ctxH: smallHash(params.h) }), - component: LevelH, -}) - -function ParamsSubscriberOne() { - const value = Route.useParams({ select: (params) => smallHash(params.h) }) - void value - return null -} - -function ParamsSubscriberTwo() { - const value = Route.useParams({ - select: (params) => smallHash(`${params.h}:2`), - }) - void value - return null -} - -function ContextSubscriberOne() { - const value = Route.useRouteContext({ select: (context) => context.ctxH }) - void value - return null -} - -function ContextSubscriberTwo() { - const value = Route.useRouteContext({ - select: (context) => (context.ctxH * 31 + 7) >>> 0, - }) - void value - return null -} - -function LevelH() { - const params = Route.useParams() - return ( - <> - - - - -
- {[ - params.a, - params.b, - params.c, - params.d, - params.e, - params.f, - params.g, - params.h, - ].join('.')} -
- - ) -} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx deleted file mode 100644 index 650b32ce96..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import { normalizeParam, smallHash } from '../../../shared' - -export const Route = createFileRoute('/l/$a/$b/$c/$d/$e/$f/$g')({ - params: { - parse: (params) => ({ ...params, g: normalizeParam(params.g) }), - stringify: (params) => ({ ...params, g: String(params.g) }), - }, - beforeLoad: ({ params }) => ({ ctxG: smallHash(params.g) }), - component: LevelG, -}) - -function ParamsSubscriberOne() { - const value = Route.useParams({ select: (params) => smallHash(params.g) }) - void value - return null -} - -function ParamsSubscriberTwo() { - const value = Route.useParams({ - select: (params) => smallHash(`${params.g}:2`), - }) - void value - return null -} - -function ContextSubscriberOne() { - const value = Route.useRouteContext({ select: (context) => context.ctxG }) - void value - return null -} - -function ContextSubscriberTwo() { - const value = Route.useRouteContext({ - select: (context) => (context.ctxG * 31 + 7) >>> 0, - }) - void value - return null -} - -function LevelG() { - return ( - <> - - - - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.tsx deleted file mode 100644 index ca18e3ccd2..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import { normalizeParam, smallHash } from '../../../shared' - -export const Route = createFileRoute('/l/$a/$b/$c/$d/$e/$f')({ - params: { - parse: (params) => ({ ...params, f: normalizeParam(params.f) }), - stringify: (params) => ({ ...params, f: String(params.f) }), - }, - beforeLoad: ({ params }) => ({ ctxF: smallHash(params.f) }), - component: LevelF, -}) - -function ParamsSubscriberOne() { - const value = Route.useParams({ select: (params) => smallHash(params.f) }) - void value - return null -} - -function ParamsSubscriberTwo() { - const value = Route.useParams({ - select: (params) => smallHash(`${params.f}:2`), - }) - void value - return null -} - -function ContextSubscriberOne() { - const value = Route.useRouteContext({ select: (context) => context.ctxF }) - void value - return null -} - -function ContextSubscriberTwo() { - const value = Route.useRouteContext({ - select: (context) => (context.ctxF * 31 + 7) >>> 0, - }) - void value - return null -} - -function LevelF() { - return ( - <> - - - - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.tsx deleted file mode 100644 index 782c1808c7..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import { normalizeParam, smallHash } from '../../../shared' - -export const Route = createFileRoute('/l/$a/$b/$c/$d/$e')({ - params: { - parse: (params) => ({ ...params, e: normalizeParam(params.e) }), - stringify: (params) => ({ ...params, e: String(params.e) }), - }, - beforeLoad: ({ params }) => ({ ctxE: smallHash(params.e) }), - component: LevelE, -}) - -function ParamsSubscriberOne() { - const value = Route.useParams({ select: (params) => smallHash(params.e) }) - void value - return null -} - -function ParamsSubscriberTwo() { - const value = Route.useParams({ - select: (params) => smallHash(`${params.e}:2`), - }) - void value - return null -} - -function ContextSubscriberOne() { - const value = Route.useRouteContext({ select: (context) => context.ctxE }) - void value - return null -} - -function ContextSubscriberTwo() { - const value = Route.useRouteContext({ - select: (context) => (context.ctxE * 31 + 7) >>> 0, - }) - void value - return null -} - -function LevelE() { - return ( - <> - - - - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.tsx deleted file mode 100644 index a874bbcb63..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.tsx +++ /dev/null @@ -1,55 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import { normalizeParam, smallHash } from '../../../shared' - -export const Route = createFileRoute('/l/$a/$b/$c/$d')({ - params: { - parse: (params) => ({ ...params, d: normalizeParam(params.d) }), - stringify: (params) => ({ ...params, d: String(params.d) }), - }, - beforeLoad: ({ params }) => ({ ctxD: smallHash(params.d) }), - component: LevelD, -}) - -function ParamsSubscriberOne() { - const value = Route.useParams({ select: (params) => smallHash(params.d) }) - void value - return null -} - -function ParamsSubscriberTwo() { - const value = Route.useParams({ - select: (params) => smallHash(`${params.d}:2`), - }) - void value - return null -} - -function ContextSubscriberOne() { - const value = Route.useRouteContext({ select: (context) => context.ctxD }) - void value - return null -} - -function ContextSubscriberTwo() { - const value = Route.useRouteContext({ - select: (context) => (context.ctxD * 31 + 7) >>> 0, - }) - void value - return null -} - -function LevelD() { - const params = Route.useParams() - return ( - <> - - - - -
- {[params.a, params.b, params.c, params.d].join('.')} -
- - - ) -} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.tsx deleted file mode 100644 index 94aba79453..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import { normalizeParam, smallHash } from '../../../shared' - -export const Route = createFileRoute('/l/$a/$b/$c')({ - params: { - parse: (params) => ({ ...params, c: normalizeParam(params.c) }), - stringify: (params) => ({ ...params, c: String(params.c) }), - }, - beforeLoad: ({ params }) => ({ ctxC: smallHash(params.c) }), - component: LevelC, -}) - -function ParamsSubscriberOne() { - const value = Route.useParams({ select: (params) => smallHash(params.c) }) - void value - return null -} - -function ParamsSubscriberTwo() { - const value = Route.useParams({ - select: (params) => smallHash(`${params.c}:2`), - }) - void value - return null -} - -function ContextSubscriberOne() { - const value = Route.useRouteContext({ select: (context) => context.ctxC }) - void value - return null -} - -function ContextSubscriberTwo() { - const value = Route.useRouteContext({ - select: (context) => (context.ctxC * 31 + 7) >>> 0, - }) - void value - return null -} - -function LevelC() { - return ( - <> - - - - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.tsx deleted file mode 100644 index 1960b68276..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import { normalizeParam, smallHash } from '../../../shared' - -export const Route = createFileRoute('/l/$a/$b')({ - params: { - parse: (params) => ({ ...params, b: normalizeParam(params.b) }), - stringify: (params) => ({ ...params, b: String(params.b) }), - }, - beforeLoad: ({ params }) => ({ ctxB: smallHash(params.b) }), - component: LevelB, -}) - -function ParamsSubscriberOne() { - const value = Route.useParams({ select: (params) => smallHash(params.b) }) - void value - return null -} - -function ParamsSubscriberTwo() { - const value = Route.useParams({ - select: (params) => smallHash(`${params.b}:2`), - }) - void value - return null -} - -function ContextSubscriberOne() { - const value = Route.useRouteContext({ select: (context) => context.ctxB }) - void value - return null -} - -function ContextSubscriberTwo() { - const value = Route.useRouteContext({ - select: (context) => (context.ctxB * 31 + 7) >>> 0, - }) - void value - return null -} - -function LevelB() { - return ( - <> - - - - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.tsx deleted file mode 100644 index 85d1de6f68..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import { normalizeParam, smallHash } from '../../../shared' - -export const Route = createFileRoute('/l/$a')({ - params: { - parse: (params) => ({ ...params, a: normalizeParam(params.a) }), - stringify: (params) => ({ ...params, a: String(params.a) }), - }, - beforeLoad: ({ params }) => ({ ctxA: smallHash(params.a) }), - component: LevelA, -}) - -function ParamsSubscriberOne() { - const value = Route.useParams({ select: (params) => smallHash(params.a) }) - void value - return null -} - -function ParamsSubscriberTwo() { - const value = Route.useParams({ - select: (params) => smallHash(`${params.a}:2`), - }) - void value - return null -} - -function ContextSubscriberOne() { - const value = Route.useRouteContext({ select: (context) => context.ctxA }) - void value - return null -} - -function ContextSubscriberTwo() { - const value = Route.useRouteContext({ - select: (context) => (context.ctxA * 31 + 7) >>> 0, - }) - void value - return null -} - -function LevelA() { - return ( - <> - - - - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/tsconfig.json b/benchmarks/client-nav/scenarios/nested-params/react/tsconfig.json deleted file mode 100644 index 1d59cbb450..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/vite.config.ts b/benchmarks/client-nav/scenarios/nested-params/react/vite.config.ts deleted file mode 100644 index a99060bf1c..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/react/vite.config.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'react', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav nested-params (react)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - }, -}) diff --git a/benchmarks/client-nav/scenarios/nested-params/shared.ts b/benchmarks/client-nav/scenarios/nested-params/shared.ts deleted file mode 100644 index 06c968bb18..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/shared.ts +++ /dev/null @@ -1,143 +0,0 @@ -/** - * Shared definition of the `nested-params` scenario: deep dynamic nesting with - * per-level params.parse/stringify, beforeLoad context accumulation, and - * useParams/useRouteContext subscribers at every level. The three framework - * apps consume these builders so the workload is identical modulo the - * rendering layer. - */ - -export interface LeafParams { - a: string - b: string - c: string - d: string - e: string - f: string - g: string - h: string -} - -// Several values need percent-encoding in the URL (spaces, `&`, `%`, `+`, -// unicode) so every navigation exercises the param encode/decode paths, not -// just plain-ASCII interpolation. -const baseParams: LeafParams = { - a: 'alpha', - b: 'bravo & co', - c: 'charlie 100%', - d: 'delta', - e: 'écho-café', - f: 'foxtrot+one', - g: 'golf', - h: 'hôtel', -} - -/** - * set 0: base; set 1: only the deepest param differs (only the leaf re-runs); - * set 2: a mid param differs (levels d..h re-run); set 3: the top param - * differs (every level re-runs). - */ -export const leafParamSets: ReadonlyArray = [ - baseParams, - { ...baseParams, h: 'hilton' }, - { ...baseParams, d: 'dover' }, - { ...baseParams, a: 'axel' }, -] - -export const midParams = { - a: baseParams.a, - b: baseParams.b, - c: baseParams.c, - d: baseParams.d, -} - -export function normalizeParam(value: unknown) { - const raw = String(value) - return raw.length > 24 ? raw.slice(0, 24) : raw -} - -export function smallHash(value: string | number) { - const input = `${value}` - let hash = 5381 - for (let index = 0; index < input.length; index++) { - hash = ((hash * 33) ^ input.charCodeAt(index)) >>> 0 - } - return hash -} - -export function leafMarker(params: LeafParams) { - return [ - params.a, - params.b, - params.c, - params.d, - params.e, - params.f, - params.g, - params.h, - ] - .map(normalizeParam) - .join('.') -} - -export function midMarker(params: typeof midParams) { - return [params.a, params.b, params.c, params.d].map(normalizeParam).join('.') -} - -export const steps = [ - 'leaf-1', - 'leaf-2', - 'leaf-3', - 'leaf-4', - 'mid-4', - 'home', -] as const - -function requireText(container: HTMLElement, testId: string, expected: string) { - const element = container.querySelector(`[data-testid="${testId}"]`) - if (!element || element.textContent !== expected) { - throw new Error( - `Expected [data-testid="${testId}"] to render "${expected}", received "${element?.textContent ?? ''}"`, - ) - } -} - -function requireAbsent(container: HTMLElement, testId: string) { - if (container.querySelector(`[data-testid="${testId}"]`)) { - throw new Error(`Expected [data-testid="${testId}"] to be absent`) - } -} - -export function assertStepResult(stepIndex: number, container: HTMLElement) { - const step = steps[stepIndex % steps.length]! - switch (step) { - case 'leaf-1': - requireText(container, 'leaf-state', leafMarker(leafParamSets[0]!)) - break - case 'leaf-2': - requireText(container, 'leaf-state', leafMarker(leafParamSets[1]!)) - break - case 'leaf-3': - requireText(container, 'leaf-state', leafMarker(leafParamSets[2]!)) - break - case 'leaf-4': - requireText(container, 'leaf-state', leafMarker(leafParamSets[3]!)) - break - case 'mid-4': - requireAbsent(container, 'leaf-state') - requireText(container, 'mid-state', midMarker(midParams)) - break - case 'home': - requireAbsent(container, 'leaf-state') - requireAbsent(container, 'mid-state') - break - } -} - -// Three laps through the 6-step sequence per benchmark iteration. -export const ticksPerIteration = 18 - -export const benchOptions = { - warmupIterations: 100, - time: 10_000, - throws: true, -} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/project.json b/benchmarks/client-nav/scenarios/nested-params/solid/project.json deleted file mode 100644 index eb0b91bd6c..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-nested-params-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/nested-params/solid/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/setup.ts b/benchmarks/client-nav/scenarios/nested-params/solid/setup.ts deleted file mode 100644 index 6a46971603..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, steps } 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, - assertAfterStep: assertStepResult, - }) -} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/nested-params/solid/speed.bench.ts deleted file mode 100644 index 2c64d9a221..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-nested-params', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-nested-params 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/nested-params/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/nested-params/solid/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/main.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/main.tsx deleted file mode 100644 index fa9d239418..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/src/main.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { render } from 'solid-js/web' -import { RouterProvider, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const unmount = render(() => , container) - - return { - router, - unmount, - } -} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/nested-params/solid/src/routeTree.gen.ts deleted file mode 100644 index 9065c9294f..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,291 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as LARouteImport } from './routes/l.$a' -import { Route as LABRouteImport } from './routes/l.$a.$b' -import { Route as LABCRouteImport } from './routes/l.$a.$b.$c' -import { Route as LABCDRouteImport } from './routes/l.$a.$b.$c.$d' -import { Route as LABCDERouteImport } from './routes/l.$a.$b.$c.$d.$e' -import { Route as LABCDEFRouteImport } from './routes/l.$a.$b.$c.$d.$e.$f' -import { Route as LABCDEFGRouteImport } from './routes/l.$a.$b.$c.$d.$e.$f.$g' -import { Route as LABCDEFGHRouteImport } from './routes/l.$a.$b.$c.$d.$e.$f.$g.$h' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const LARoute = LARouteImport.update({ - id: '/l/$a', - path: '/l/$a', - getParentRoute: () => rootRouteImport, -} as any) -const LABRoute = LABRouteImport.update({ - id: '/$b', - path: '/$b', - getParentRoute: () => LARoute, -} as any) -const LABCRoute = LABCRouteImport.update({ - id: '/$c', - path: '/$c', - getParentRoute: () => LABRoute, -} as any) -const LABCDRoute = LABCDRouteImport.update({ - id: '/$d', - path: '/$d', - getParentRoute: () => LABCRoute, -} as any) -const LABCDERoute = LABCDERouteImport.update({ - id: '/$e', - path: '/$e', - getParentRoute: () => LABCDRoute, -} as any) -const LABCDEFRoute = LABCDEFRouteImport.update({ - id: '/$f', - path: '/$f', - getParentRoute: () => LABCDERoute, -} as any) -const LABCDEFGRoute = LABCDEFGRouteImport.update({ - id: '/$g', - path: '/$g', - getParentRoute: () => LABCDEFRoute, -} as any) -const LABCDEFGHRoute = LABCDEFGHRouteImport.update({ - id: '/$h', - path: '/$h', - getParentRoute: () => LABCDEFGRoute, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/l/$a': typeof LARouteWithChildren - '/l/$a/$b': typeof LABRouteWithChildren - '/l/$a/$b/$c': typeof LABCRouteWithChildren - '/l/$a/$b/$c/$d': typeof LABCDRouteWithChildren - '/l/$a/$b/$c/$d/$e': typeof LABCDERouteWithChildren - '/l/$a/$b/$c/$d/$e/$f': typeof LABCDEFRouteWithChildren - '/l/$a/$b/$c/$d/$e/$f/$g': typeof LABCDEFGRouteWithChildren - '/l/$a/$b/$c/$d/$e/$f/$g/$h': typeof LABCDEFGHRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/l/$a': typeof LARouteWithChildren - '/l/$a/$b': typeof LABRouteWithChildren - '/l/$a/$b/$c': typeof LABCRouteWithChildren - '/l/$a/$b/$c/$d': typeof LABCDRouteWithChildren - '/l/$a/$b/$c/$d/$e': typeof LABCDERouteWithChildren - '/l/$a/$b/$c/$d/$e/$f': typeof LABCDEFRouteWithChildren - '/l/$a/$b/$c/$d/$e/$f/$g': typeof LABCDEFGRouteWithChildren - '/l/$a/$b/$c/$d/$e/$f/$g/$h': typeof LABCDEFGHRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/l/$a': typeof LARouteWithChildren - '/l/$a/$b': typeof LABRouteWithChildren - '/l/$a/$b/$c': typeof LABCRouteWithChildren - '/l/$a/$b/$c/$d': typeof LABCDRouteWithChildren - '/l/$a/$b/$c/$d/$e': typeof LABCDERouteWithChildren - '/l/$a/$b/$c/$d/$e/$f': typeof LABCDEFRouteWithChildren - '/l/$a/$b/$c/$d/$e/$f/$g': typeof LABCDEFGRouteWithChildren - '/l/$a/$b/$c/$d/$e/$f/$g/$h': typeof LABCDEFGHRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/l/$a' - | '/l/$a/$b' - | '/l/$a/$b/$c' - | '/l/$a/$b/$c/$d' - | '/l/$a/$b/$c/$d/$e' - | '/l/$a/$b/$c/$d/$e/$f' - | '/l/$a/$b/$c/$d/$e/$f/$g' - | '/l/$a/$b/$c/$d/$e/$f/$g/$h' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/l/$a' - | '/l/$a/$b' - | '/l/$a/$b/$c' - | '/l/$a/$b/$c/$d' - | '/l/$a/$b/$c/$d/$e' - | '/l/$a/$b/$c/$d/$e/$f' - | '/l/$a/$b/$c/$d/$e/$f/$g' - | '/l/$a/$b/$c/$d/$e/$f/$g/$h' - id: - | '__root__' - | '/' - | '/l/$a' - | '/l/$a/$b' - | '/l/$a/$b/$c' - | '/l/$a/$b/$c/$d' - | '/l/$a/$b/$c/$d/$e' - | '/l/$a/$b/$c/$d/$e/$f' - | '/l/$a/$b/$c/$d/$e/$f/$g' - | '/l/$a/$b/$c/$d/$e/$f/$g/$h' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - LARoute: typeof LARouteWithChildren -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/l/$a': { - id: '/l/$a' - path: '/l/$a' - fullPath: '/l/$a' - preLoaderRoute: typeof LARouteImport - parentRoute: typeof rootRouteImport - } - '/l/$a/$b': { - id: '/l/$a/$b' - path: '/$b' - fullPath: '/l/$a/$b' - preLoaderRoute: typeof LABRouteImport - parentRoute: typeof LARoute - } - '/l/$a/$b/$c': { - id: '/l/$a/$b/$c' - path: '/$c' - fullPath: '/l/$a/$b/$c' - preLoaderRoute: typeof LABCRouteImport - parentRoute: typeof LABRoute - } - '/l/$a/$b/$c/$d': { - id: '/l/$a/$b/$c/$d' - path: '/$d' - fullPath: '/l/$a/$b/$c/$d' - preLoaderRoute: typeof LABCDRouteImport - parentRoute: typeof LABCRoute - } - '/l/$a/$b/$c/$d/$e': { - id: '/l/$a/$b/$c/$d/$e' - path: '/$e' - fullPath: '/l/$a/$b/$c/$d/$e' - preLoaderRoute: typeof LABCDERouteImport - parentRoute: typeof LABCDRoute - } - '/l/$a/$b/$c/$d/$e/$f': { - id: '/l/$a/$b/$c/$d/$e/$f' - path: '/$f' - fullPath: '/l/$a/$b/$c/$d/$e/$f' - preLoaderRoute: typeof LABCDEFRouteImport - parentRoute: typeof LABCDERoute - } - '/l/$a/$b/$c/$d/$e/$f/$g': { - id: '/l/$a/$b/$c/$d/$e/$f/$g' - path: '/$g' - fullPath: '/l/$a/$b/$c/$d/$e/$f/$g' - preLoaderRoute: typeof LABCDEFGRouteImport - parentRoute: typeof LABCDEFRoute - } - '/l/$a/$b/$c/$d/$e/$f/$g/$h': { - id: '/l/$a/$b/$c/$d/$e/$f/$g/$h' - path: '/$h' - fullPath: '/l/$a/$b/$c/$d/$e/$f/$g/$h' - preLoaderRoute: typeof LABCDEFGHRouteImport - parentRoute: typeof LABCDEFGRoute - } - } -} - -interface LABCDEFGRouteChildren { - LABCDEFGHRoute: typeof LABCDEFGHRoute -} - -const LABCDEFGRouteChildren: LABCDEFGRouteChildren = { - LABCDEFGHRoute: LABCDEFGHRoute, -} - -const LABCDEFGRouteWithChildren = LABCDEFGRoute._addFileChildren( - LABCDEFGRouteChildren, -) - -interface LABCDEFRouteChildren { - LABCDEFGRoute: typeof LABCDEFGRouteWithChildren -} - -const LABCDEFRouteChildren: LABCDEFRouteChildren = { - LABCDEFGRoute: LABCDEFGRouteWithChildren, -} - -const LABCDEFRouteWithChildren = - LABCDEFRoute._addFileChildren(LABCDEFRouteChildren) - -interface LABCDERouteChildren { - LABCDEFRoute: typeof LABCDEFRouteWithChildren -} - -const LABCDERouteChildren: LABCDERouteChildren = { - LABCDEFRoute: LABCDEFRouteWithChildren, -} - -const LABCDERouteWithChildren = - LABCDERoute._addFileChildren(LABCDERouteChildren) - -interface LABCDRouteChildren { - LABCDERoute: typeof LABCDERouteWithChildren -} - -const LABCDRouteChildren: LABCDRouteChildren = { - LABCDERoute: LABCDERouteWithChildren, -} - -const LABCDRouteWithChildren = LABCDRoute._addFileChildren(LABCDRouteChildren) - -interface LABCRouteChildren { - LABCDRoute: typeof LABCDRouteWithChildren -} - -const LABCRouteChildren: LABCRouteChildren = { - LABCDRoute: LABCDRouteWithChildren, -} - -const LABCRouteWithChildren = LABCRoute._addFileChildren(LABCRouteChildren) - -interface LABRouteChildren { - LABCRoute: typeof LABCRouteWithChildren -} - -const LABRouteChildren: LABRouteChildren = { - LABCRoute: LABCRouteWithChildren, -} - -const LABRouteWithChildren = LABRoute._addFileChildren(LABRouteChildren) - -interface LARouteChildren { - LABRoute: typeof LABRouteWithChildren -} - -const LARouteChildren: LARouteChildren = { - LABRoute: LABRouteWithChildren, -} - -const LARouteWithChildren = LARoute._addFileChildren(LARouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - LARoute: LARouteWithChildren, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/__root.tsx deleted file mode 100644 index 6fe7ab3e3d..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/__root.tsx +++ /dev/null @@ -1,50 +0,0 @@ -import { Link, Outlet, createRootRoute } from '@tanstack/solid-router' -import { leafParamSets, midParams } from '../../../shared' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - <> - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/index.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/index.tsx deleted file mode 100644 index cc46764de5..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/')({ - component: HomePage, -}) - -function HomePage() { - return
home
-} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx deleted file mode 100644 index 7dc55db0e4..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx +++ /dev/null @@ -1,72 +0,0 @@ -import { createRenderEffect } from 'solid-js' -import { createFileRoute } from '@tanstack/solid-router' -import { normalizeParam, smallHash } from '../../../shared' - -export const Route = createFileRoute('/l/$a/$b/$c/$d/$e/$f/$g/$h')({ - params: { - parse: (params) => ({ ...params, h: normalizeParam(params.h) }), - stringify: (params) => ({ ...params, h: String(params.h) }), - }, - beforeLoad: ({ params }) => ({ ctxH: smallHash(params.h) }), - component: LevelH, -}) - -function ParamsSubscriberOne() { - const value = Route.useParams({ select: (params) => smallHash(params.h) }) - createRenderEffect(() => { - void value() - }) - return null -} - -function ParamsSubscriberTwo() { - const value = Route.useParams({ - select: (params) => smallHash(`${params.h}:2`), - }) - createRenderEffect(() => { - void value() - }) - return null -} - -function ContextSubscriberOne() { - const value = Route.useRouteContext({ select: (context) => context.ctxH }) - createRenderEffect(() => { - void value() - }) - return null -} - -function ContextSubscriberTwo() { - const value = Route.useRouteContext({ - select: (context) => (context.ctxH * 31 + 7) >>> 0, - }) - createRenderEffect(() => { - void value() - }) - return null -} - -function LevelH() { - const params = Route.useParams() - return ( - <> - - - - -
- {[ - params().a, - params().b, - params().c, - params().d, - params().e, - params().f, - params().g, - params().h, - ].join('.')} -
- - ) -} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx deleted file mode 100644 index d9c6c9429b..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx +++ /dev/null @@ -1,60 +0,0 @@ -import { createRenderEffect } from 'solid-js' -import { Outlet, createFileRoute } from '@tanstack/solid-router' -import { normalizeParam, smallHash } from '../../../shared' - -export const Route = createFileRoute('/l/$a/$b/$c/$d/$e/$f/$g')({ - params: { - parse: (params) => ({ ...params, g: normalizeParam(params.g) }), - stringify: (params) => ({ ...params, g: String(params.g) }), - }, - beforeLoad: ({ params }) => ({ ctxG: smallHash(params.g) }), - component: LevelG, -}) - -function ParamsSubscriberOne() { - const value = Route.useParams({ select: (params) => smallHash(params.g) }) - createRenderEffect(() => { - void value() - }) - return null -} - -function ParamsSubscriberTwo() { - const value = Route.useParams({ - select: (params) => smallHash(`${params.g}:2`), - }) - createRenderEffect(() => { - void value() - }) - return null -} - -function ContextSubscriberOne() { - const value = Route.useRouteContext({ select: (context) => context.ctxG }) - createRenderEffect(() => { - void value() - }) - return null -} - -function ContextSubscriberTwo() { - const value = Route.useRouteContext({ - select: (context) => (context.ctxG * 31 + 7) >>> 0, - }) - createRenderEffect(() => { - void value() - }) - return null -} - -function LevelG() { - return ( - <> - - - - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.tsx deleted file mode 100644 index 010f89bc4d..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.tsx +++ /dev/null @@ -1,60 +0,0 @@ -import { createRenderEffect } from 'solid-js' -import { Outlet, createFileRoute } from '@tanstack/solid-router' -import { normalizeParam, smallHash } from '../../../shared' - -export const Route = createFileRoute('/l/$a/$b/$c/$d/$e/$f')({ - params: { - parse: (params) => ({ ...params, f: normalizeParam(params.f) }), - stringify: (params) => ({ ...params, f: String(params.f) }), - }, - beforeLoad: ({ params }) => ({ ctxF: smallHash(params.f) }), - component: LevelF, -}) - -function ParamsSubscriberOne() { - const value = Route.useParams({ select: (params) => smallHash(params.f) }) - createRenderEffect(() => { - void value() - }) - return null -} - -function ParamsSubscriberTwo() { - const value = Route.useParams({ - select: (params) => smallHash(`${params.f}:2`), - }) - createRenderEffect(() => { - void value() - }) - return null -} - -function ContextSubscriberOne() { - const value = Route.useRouteContext({ select: (context) => context.ctxF }) - createRenderEffect(() => { - void value() - }) - return null -} - -function ContextSubscriberTwo() { - const value = Route.useRouteContext({ - select: (context) => (context.ctxF * 31 + 7) >>> 0, - }) - createRenderEffect(() => { - void value() - }) - return null -} - -function LevelF() { - return ( - <> - - - - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.tsx deleted file mode 100644 index 08c107f0c6..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.tsx +++ /dev/null @@ -1,60 +0,0 @@ -import { createRenderEffect } from 'solid-js' -import { Outlet, createFileRoute } from '@tanstack/solid-router' -import { normalizeParam, smallHash } from '../../../shared' - -export const Route = createFileRoute('/l/$a/$b/$c/$d/$e')({ - params: { - parse: (params) => ({ ...params, e: normalizeParam(params.e) }), - stringify: (params) => ({ ...params, e: String(params.e) }), - }, - beforeLoad: ({ params }) => ({ ctxE: smallHash(params.e) }), - component: LevelE, -}) - -function ParamsSubscriberOne() { - const value = Route.useParams({ select: (params) => smallHash(params.e) }) - createRenderEffect(() => { - void value() - }) - return null -} - -function ParamsSubscriberTwo() { - const value = Route.useParams({ - select: (params) => smallHash(`${params.e}:2`), - }) - createRenderEffect(() => { - void value() - }) - return null -} - -function ContextSubscriberOne() { - const value = Route.useRouteContext({ select: (context) => context.ctxE }) - createRenderEffect(() => { - void value() - }) - return null -} - -function ContextSubscriberTwo() { - const value = Route.useRouteContext({ - select: (context) => (context.ctxE * 31 + 7) >>> 0, - }) - createRenderEffect(() => { - void value() - }) - return null -} - -function LevelE() { - return ( - <> - - - - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.tsx deleted file mode 100644 index 1b64edd58b..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.tsx +++ /dev/null @@ -1,64 +0,0 @@ -import { createRenderEffect } from 'solid-js' -import { Outlet, createFileRoute } from '@tanstack/solid-router' -import { normalizeParam, smallHash } from '../../../shared' - -export const Route = createFileRoute('/l/$a/$b/$c/$d')({ - params: { - parse: (params) => ({ ...params, d: normalizeParam(params.d) }), - stringify: (params) => ({ ...params, d: String(params.d) }), - }, - beforeLoad: ({ params }) => ({ ctxD: smallHash(params.d) }), - component: LevelD, -}) - -function ParamsSubscriberOne() { - const value = Route.useParams({ select: (params) => smallHash(params.d) }) - createRenderEffect(() => { - void value() - }) - return null -} - -function ParamsSubscriberTwo() { - const value = Route.useParams({ - select: (params) => smallHash(`${params.d}:2`), - }) - createRenderEffect(() => { - void value() - }) - return null -} - -function ContextSubscriberOne() { - const value = Route.useRouteContext({ select: (context) => context.ctxD }) - createRenderEffect(() => { - void value() - }) - return null -} - -function ContextSubscriberTwo() { - const value = Route.useRouteContext({ - select: (context) => (context.ctxD * 31 + 7) >>> 0, - }) - createRenderEffect(() => { - void value() - }) - return null -} - -function LevelD() { - const params = Route.useParams() - return ( - <> - - - - -
- {[params().a, params().b, params().c, params().d].join('.')} -
- - - ) -} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.tsx deleted file mode 100644 index e509ea82c6..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.tsx +++ /dev/null @@ -1,60 +0,0 @@ -import { createRenderEffect } from 'solid-js' -import { Outlet, createFileRoute } from '@tanstack/solid-router' -import { normalizeParam, smallHash } from '../../../shared' - -export const Route = createFileRoute('/l/$a/$b/$c')({ - params: { - parse: (params) => ({ ...params, c: normalizeParam(params.c) }), - stringify: (params) => ({ ...params, c: String(params.c) }), - }, - beforeLoad: ({ params }) => ({ ctxC: smallHash(params.c) }), - component: LevelC, -}) - -function ParamsSubscriberOne() { - const value = Route.useParams({ select: (params) => smallHash(params.c) }) - createRenderEffect(() => { - void value() - }) - return null -} - -function ParamsSubscriberTwo() { - const value = Route.useParams({ - select: (params) => smallHash(`${params.c}:2`), - }) - createRenderEffect(() => { - void value() - }) - return null -} - -function ContextSubscriberOne() { - const value = Route.useRouteContext({ select: (context) => context.ctxC }) - createRenderEffect(() => { - void value() - }) - return null -} - -function ContextSubscriberTwo() { - const value = Route.useRouteContext({ - select: (context) => (context.ctxC * 31 + 7) >>> 0, - }) - createRenderEffect(() => { - void value() - }) - return null -} - -function LevelC() { - return ( - <> - - - - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.tsx deleted file mode 100644 index ada853b845..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.tsx +++ /dev/null @@ -1,60 +0,0 @@ -import { createRenderEffect } from 'solid-js' -import { Outlet, createFileRoute } from '@tanstack/solid-router' -import { normalizeParam, smallHash } from '../../../shared' - -export const Route = createFileRoute('/l/$a/$b')({ - params: { - parse: (params) => ({ ...params, b: normalizeParam(params.b) }), - stringify: (params) => ({ ...params, b: String(params.b) }), - }, - beforeLoad: ({ params }) => ({ ctxB: smallHash(params.b) }), - component: LevelB, -}) - -function ParamsSubscriberOne() { - const value = Route.useParams({ select: (params) => smallHash(params.b) }) - createRenderEffect(() => { - void value() - }) - return null -} - -function ParamsSubscriberTwo() { - const value = Route.useParams({ - select: (params) => smallHash(`${params.b}:2`), - }) - createRenderEffect(() => { - void value() - }) - return null -} - -function ContextSubscriberOne() { - const value = Route.useRouteContext({ select: (context) => context.ctxB }) - createRenderEffect(() => { - void value() - }) - return null -} - -function ContextSubscriberTwo() { - const value = Route.useRouteContext({ - select: (context) => (context.ctxB * 31 + 7) >>> 0, - }) - createRenderEffect(() => { - void value() - }) - return null -} - -function LevelB() { - return ( - <> - - - - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.tsx deleted file mode 100644 index 5ecf004fae..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.tsx +++ /dev/null @@ -1,60 +0,0 @@ -import { createRenderEffect } from 'solid-js' -import { Outlet, createFileRoute } from '@tanstack/solid-router' -import { normalizeParam, smallHash } from '../../../shared' - -export const Route = createFileRoute('/l/$a')({ - params: { - parse: (params) => ({ ...params, a: normalizeParam(params.a) }), - stringify: (params) => ({ ...params, a: String(params.a) }), - }, - beforeLoad: ({ params }) => ({ ctxA: smallHash(params.a) }), - component: LevelA, -}) - -function ParamsSubscriberOne() { - const value = Route.useParams({ select: (params) => smallHash(params.a) }) - createRenderEffect(() => { - void value() - }) - return null -} - -function ParamsSubscriberTwo() { - const value = Route.useParams({ - select: (params) => smallHash(`${params.a}:2`), - }) - createRenderEffect(() => { - void value() - }) - return null -} - -function ContextSubscriberOne() { - const value = Route.useRouteContext({ select: (context) => context.ctxA }) - createRenderEffect(() => { - void value() - }) - return null -} - -function ContextSubscriberTwo() { - const value = Route.useRouteContext({ - select: (context) => (context.ctxA * 31 + 7) >>> 0, - }) - createRenderEffect(() => { - void value() - }) - return null -} - -function LevelA() { - return ( - <> - - - - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/tsconfig.json b/benchmarks/client-nav/scenarios/nested-params/solid/tsconfig.json deleted file mode 100644 index 98d76ad6b8..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/vite.config.ts b/benchmarks/client-nav/scenarios/nested-params/solid/vite.config.ts deleted file mode 100644 index 9897e2c199..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/solid/vite.config.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import solid from 'vite-plugin-solid' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'solid', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - resolve: { - conditions: ['solid', 'browser'], - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav nested-params (solid)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/project.json b/benchmarks/client-nav/scenarios/nested-params/vue/project.json deleted file mode 100644 index 83c234382c..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-nested-params-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/nested-params/vue/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/setup.ts b/benchmarks/client-nav/scenarios/nested-params/vue/setup.ts deleted file mode 100644 index 97b74b3892..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, steps } 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, - assertAfterStep: assertStepResult, - }) -} diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/nested-params/vue/speed.bench.ts deleted file mode 100644 index bd3e82e070..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-nested-params', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-nested-params 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/nested-params/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/nested-params/vue/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/main.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/main.tsx deleted file mode 100644 index cae9b54f1d..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/src/main.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import * as Vue from 'vue' -import { RouterProvider, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const component = - const app = Vue.createApp({ - render: () => component, - }) - - app.mount(container) - - return { - router, - unmount() { - app.unmount() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/nested-params/vue/src/routeTree.gen.ts deleted file mode 100644 index a7d1049b49..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,291 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as LARouteImport } from './routes/l.$a' -import { Route as LABRouteImport } from './routes/l.$a.$b' -import { Route as LABCRouteImport } from './routes/l.$a.$b.$c' -import { Route as LABCDRouteImport } from './routes/l.$a.$b.$c.$d' -import { Route as LABCDERouteImport } from './routes/l.$a.$b.$c.$d.$e' -import { Route as LABCDEFRouteImport } from './routes/l.$a.$b.$c.$d.$e.$f' -import { Route as LABCDEFGRouteImport } from './routes/l.$a.$b.$c.$d.$e.$f.$g' -import { Route as LABCDEFGHRouteImport } from './routes/l.$a.$b.$c.$d.$e.$f.$g.$h' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const LARoute = LARouteImport.update({ - id: '/l/$a', - path: '/l/$a', - getParentRoute: () => rootRouteImport, -} as any) -const LABRoute = LABRouteImport.update({ - id: '/$b', - path: '/$b', - getParentRoute: () => LARoute, -} as any) -const LABCRoute = LABCRouteImport.update({ - id: '/$c', - path: '/$c', - getParentRoute: () => LABRoute, -} as any) -const LABCDRoute = LABCDRouteImport.update({ - id: '/$d', - path: '/$d', - getParentRoute: () => LABCRoute, -} as any) -const LABCDERoute = LABCDERouteImport.update({ - id: '/$e', - path: '/$e', - getParentRoute: () => LABCDRoute, -} as any) -const LABCDEFRoute = LABCDEFRouteImport.update({ - id: '/$f', - path: '/$f', - getParentRoute: () => LABCDERoute, -} as any) -const LABCDEFGRoute = LABCDEFGRouteImport.update({ - id: '/$g', - path: '/$g', - getParentRoute: () => LABCDEFRoute, -} as any) -const LABCDEFGHRoute = LABCDEFGHRouteImport.update({ - id: '/$h', - path: '/$h', - getParentRoute: () => LABCDEFGRoute, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/l/$a': typeof LARouteWithChildren - '/l/$a/$b': typeof LABRouteWithChildren - '/l/$a/$b/$c': typeof LABCRouteWithChildren - '/l/$a/$b/$c/$d': typeof LABCDRouteWithChildren - '/l/$a/$b/$c/$d/$e': typeof LABCDERouteWithChildren - '/l/$a/$b/$c/$d/$e/$f': typeof LABCDEFRouteWithChildren - '/l/$a/$b/$c/$d/$e/$f/$g': typeof LABCDEFGRouteWithChildren - '/l/$a/$b/$c/$d/$e/$f/$g/$h': typeof LABCDEFGHRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/l/$a': typeof LARouteWithChildren - '/l/$a/$b': typeof LABRouteWithChildren - '/l/$a/$b/$c': typeof LABCRouteWithChildren - '/l/$a/$b/$c/$d': typeof LABCDRouteWithChildren - '/l/$a/$b/$c/$d/$e': typeof LABCDERouteWithChildren - '/l/$a/$b/$c/$d/$e/$f': typeof LABCDEFRouteWithChildren - '/l/$a/$b/$c/$d/$e/$f/$g': typeof LABCDEFGRouteWithChildren - '/l/$a/$b/$c/$d/$e/$f/$g/$h': typeof LABCDEFGHRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/l/$a': typeof LARouteWithChildren - '/l/$a/$b': typeof LABRouteWithChildren - '/l/$a/$b/$c': typeof LABCRouteWithChildren - '/l/$a/$b/$c/$d': typeof LABCDRouteWithChildren - '/l/$a/$b/$c/$d/$e': typeof LABCDERouteWithChildren - '/l/$a/$b/$c/$d/$e/$f': typeof LABCDEFRouteWithChildren - '/l/$a/$b/$c/$d/$e/$f/$g': typeof LABCDEFGRouteWithChildren - '/l/$a/$b/$c/$d/$e/$f/$g/$h': typeof LABCDEFGHRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/l/$a' - | '/l/$a/$b' - | '/l/$a/$b/$c' - | '/l/$a/$b/$c/$d' - | '/l/$a/$b/$c/$d/$e' - | '/l/$a/$b/$c/$d/$e/$f' - | '/l/$a/$b/$c/$d/$e/$f/$g' - | '/l/$a/$b/$c/$d/$e/$f/$g/$h' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/l/$a' - | '/l/$a/$b' - | '/l/$a/$b/$c' - | '/l/$a/$b/$c/$d' - | '/l/$a/$b/$c/$d/$e' - | '/l/$a/$b/$c/$d/$e/$f' - | '/l/$a/$b/$c/$d/$e/$f/$g' - | '/l/$a/$b/$c/$d/$e/$f/$g/$h' - id: - | '__root__' - | '/' - | '/l/$a' - | '/l/$a/$b' - | '/l/$a/$b/$c' - | '/l/$a/$b/$c/$d' - | '/l/$a/$b/$c/$d/$e' - | '/l/$a/$b/$c/$d/$e/$f' - | '/l/$a/$b/$c/$d/$e/$f/$g' - | '/l/$a/$b/$c/$d/$e/$f/$g/$h' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - LARoute: typeof LARouteWithChildren -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/l/$a': { - id: '/l/$a' - path: '/l/$a' - fullPath: '/l/$a' - preLoaderRoute: typeof LARouteImport - parentRoute: typeof rootRouteImport - } - '/l/$a/$b': { - id: '/l/$a/$b' - path: '/$b' - fullPath: '/l/$a/$b' - preLoaderRoute: typeof LABRouteImport - parentRoute: typeof LARoute - } - '/l/$a/$b/$c': { - id: '/l/$a/$b/$c' - path: '/$c' - fullPath: '/l/$a/$b/$c' - preLoaderRoute: typeof LABCRouteImport - parentRoute: typeof LABRoute - } - '/l/$a/$b/$c/$d': { - id: '/l/$a/$b/$c/$d' - path: '/$d' - fullPath: '/l/$a/$b/$c/$d' - preLoaderRoute: typeof LABCDRouteImport - parentRoute: typeof LABCRoute - } - '/l/$a/$b/$c/$d/$e': { - id: '/l/$a/$b/$c/$d/$e' - path: '/$e' - fullPath: '/l/$a/$b/$c/$d/$e' - preLoaderRoute: typeof LABCDERouteImport - parentRoute: typeof LABCDRoute - } - '/l/$a/$b/$c/$d/$e/$f': { - id: '/l/$a/$b/$c/$d/$e/$f' - path: '/$f' - fullPath: '/l/$a/$b/$c/$d/$e/$f' - preLoaderRoute: typeof LABCDEFRouteImport - parentRoute: typeof LABCDERoute - } - '/l/$a/$b/$c/$d/$e/$f/$g': { - id: '/l/$a/$b/$c/$d/$e/$f/$g' - path: '/$g' - fullPath: '/l/$a/$b/$c/$d/$e/$f/$g' - preLoaderRoute: typeof LABCDEFGRouteImport - parentRoute: typeof LABCDEFRoute - } - '/l/$a/$b/$c/$d/$e/$f/$g/$h': { - id: '/l/$a/$b/$c/$d/$e/$f/$g/$h' - path: '/$h' - fullPath: '/l/$a/$b/$c/$d/$e/$f/$g/$h' - preLoaderRoute: typeof LABCDEFGHRouteImport - parentRoute: typeof LABCDEFGRoute - } - } -} - -interface LABCDEFGRouteChildren { - LABCDEFGHRoute: typeof LABCDEFGHRoute -} - -const LABCDEFGRouteChildren: LABCDEFGRouteChildren = { - LABCDEFGHRoute: LABCDEFGHRoute, -} - -const LABCDEFGRouteWithChildren = LABCDEFGRoute._addFileChildren( - LABCDEFGRouteChildren, -) - -interface LABCDEFRouteChildren { - LABCDEFGRoute: typeof LABCDEFGRouteWithChildren -} - -const LABCDEFRouteChildren: LABCDEFRouteChildren = { - LABCDEFGRoute: LABCDEFGRouteWithChildren, -} - -const LABCDEFRouteWithChildren = - LABCDEFRoute._addFileChildren(LABCDEFRouteChildren) - -interface LABCDERouteChildren { - LABCDEFRoute: typeof LABCDEFRouteWithChildren -} - -const LABCDERouteChildren: LABCDERouteChildren = { - LABCDEFRoute: LABCDEFRouteWithChildren, -} - -const LABCDERouteWithChildren = - LABCDERoute._addFileChildren(LABCDERouteChildren) - -interface LABCDRouteChildren { - LABCDERoute: typeof LABCDERouteWithChildren -} - -const LABCDRouteChildren: LABCDRouteChildren = { - LABCDERoute: LABCDERouteWithChildren, -} - -const LABCDRouteWithChildren = LABCDRoute._addFileChildren(LABCDRouteChildren) - -interface LABCRouteChildren { - LABCDRoute: typeof LABCDRouteWithChildren -} - -const LABCRouteChildren: LABCRouteChildren = { - LABCDRoute: LABCDRouteWithChildren, -} - -const LABCRouteWithChildren = LABCRoute._addFileChildren(LABCRouteChildren) - -interface LABRouteChildren { - LABCRoute: typeof LABCRouteWithChildren -} - -const LABRouteChildren: LABRouteChildren = { - LABCRoute: LABCRouteWithChildren, -} - -const LABRouteWithChildren = LABRoute._addFileChildren(LABRouteChildren) - -interface LARouteChildren { - LABRoute: typeof LABRouteWithChildren -} - -const LARouteChildren: LARouteChildren = { - LABRoute: LABRouteWithChildren, -} - -const LARouteWithChildren = LARoute._addFileChildren(LARouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - LARoute: LARouteWithChildren, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/__root.tsx deleted file mode 100644 index 28dd4e847a..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/__root.tsx +++ /dev/null @@ -1,53 +0,0 @@ -import * as Vue from 'vue' -import { Link, Outlet, createRootRoute } from '@tanstack/vue-router' -import { leafParamSets, midParams } from '../../../shared' - -const RootComponent = Vue.defineComponent({ - setup() { - return () => ( - <> - - - - ) - }, -}) - -export const Route = createRootRoute({ - component: RootComponent, -}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/index.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/index.tsx deleted file mode 100644 index f3ffc58610..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const HomePage = Vue.defineComponent({ - setup() { - return () =>
home
- }, -}) - -export const Route = createFileRoute('/')({ - component: HomePage, -}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx deleted file mode 100644 index 756c31e1a9..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx +++ /dev/null @@ -1,86 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' -import { normalizeParam, smallHash } from '../../../shared' - -const ParamsSubscriberOne = Vue.defineComponent({ - setup() { - const value = Route.useParams({ - select: (params) => smallHash(params.h), - }) - return () => { - void value.value - return null - } - }, -}) - -const ParamsSubscriberTwo = Vue.defineComponent({ - setup() { - const value = Route.useParams({ - select: (params) => smallHash(`${params.h}:2`), - }) - return () => { - void value.value - return null - } - }, -}) - -const ContextSubscriberOne = Vue.defineComponent({ - setup() { - const value = Route.useRouteContext({ - select: (context) => context.ctxH, - }) - return () => { - void value.value - return null - } - }, -}) - -const ContextSubscriberTwo = Vue.defineComponent({ - setup() { - const value = Route.useRouteContext({ - select: (context) => (context.ctxH * 31 + 7) >>> 0, - }) - return () => { - void value.value - return null - } - }, -}) - -const LevelH = Vue.defineComponent({ - setup() { - const params = Route.useParams() - return () => ( - <> - - - - -
- {[ - params.value.a, - params.value.b, - params.value.c, - params.value.d, - params.value.e, - params.value.f, - params.value.g, - params.value.h, - ].join('.')} -
- - ) - }, -}) - -export const Route = createFileRoute('/l/$a/$b/$c/$d/$e/$f/$g/$h')({ - params: { - parse: (params) => ({ ...params, h: normalizeParam(params.h) }), - stringify: (params) => ({ ...params, h: String(params.h) }), - }, - beforeLoad: ({ params }) => ({ ctxH: smallHash(params.h) }), - component: LevelH, -}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx deleted file mode 100644 index d6b9ccde83..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx +++ /dev/null @@ -1,74 +0,0 @@ -import * as Vue from 'vue' -import { Outlet, createFileRoute } from '@tanstack/vue-router' -import { normalizeParam, smallHash } from '../../../shared' - -const ParamsSubscriberOne = Vue.defineComponent({ - setup() { - const value = Route.useParams({ - select: (params) => smallHash(params.g), - }) - return () => { - void value.value - return null - } - }, -}) - -const ParamsSubscriberTwo = Vue.defineComponent({ - setup() { - const value = Route.useParams({ - select: (params) => smallHash(`${params.g}:2`), - }) - return () => { - void value.value - return null - } - }, -}) - -const ContextSubscriberOne = Vue.defineComponent({ - setup() { - const value = Route.useRouteContext({ - select: (context) => context.ctxG, - }) - return () => { - void value.value - return null - } - }, -}) - -const ContextSubscriberTwo = Vue.defineComponent({ - setup() { - const value = Route.useRouteContext({ - select: (context) => (context.ctxG * 31 + 7) >>> 0, - }) - return () => { - void value.value - return null - } - }, -}) - -const LevelG = Vue.defineComponent({ - setup() { - return () => ( - <> - - - - - - - ) - }, -}) - -export const Route = createFileRoute('/l/$a/$b/$c/$d/$e/$f/$g')({ - params: { - parse: (params) => ({ ...params, g: normalizeParam(params.g) }), - stringify: (params) => ({ ...params, g: String(params.g) }), - }, - beforeLoad: ({ params }) => ({ ctxG: smallHash(params.g) }), - component: LevelG, -}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.tsx deleted file mode 100644 index 76ed24904c..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.tsx +++ /dev/null @@ -1,74 +0,0 @@ -import * as Vue from 'vue' -import { Outlet, createFileRoute } from '@tanstack/vue-router' -import { normalizeParam, smallHash } from '../../../shared' - -const ParamsSubscriberOne = Vue.defineComponent({ - setup() { - const value = Route.useParams({ - select: (params) => smallHash(params.f), - }) - return () => { - void value.value - return null - } - }, -}) - -const ParamsSubscriberTwo = Vue.defineComponent({ - setup() { - const value = Route.useParams({ - select: (params) => smallHash(`${params.f}:2`), - }) - return () => { - void value.value - return null - } - }, -}) - -const ContextSubscriberOne = Vue.defineComponent({ - setup() { - const value = Route.useRouteContext({ - select: (context) => context.ctxF, - }) - return () => { - void value.value - return null - } - }, -}) - -const ContextSubscriberTwo = Vue.defineComponent({ - setup() { - const value = Route.useRouteContext({ - select: (context) => (context.ctxF * 31 + 7) >>> 0, - }) - return () => { - void value.value - return null - } - }, -}) - -const LevelF = Vue.defineComponent({ - setup() { - return () => ( - <> - - - - - - - ) - }, -}) - -export const Route = createFileRoute('/l/$a/$b/$c/$d/$e/$f')({ - params: { - parse: (params) => ({ ...params, f: normalizeParam(params.f) }), - stringify: (params) => ({ ...params, f: String(params.f) }), - }, - beforeLoad: ({ params }) => ({ ctxF: smallHash(params.f) }), - component: LevelF, -}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.tsx deleted file mode 100644 index e24d3dc373..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.tsx +++ /dev/null @@ -1,74 +0,0 @@ -import * as Vue from 'vue' -import { Outlet, createFileRoute } from '@tanstack/vue-router' -import { normalizeParam, smallHash } from '../../../shared' - -const ParamsSubscriberOne = Vue.defineComponent({ - setup() { - const value = Route.useParams({ - select: (params) => smallHash(params.e), - }) - return () => { - void value.value - return null - } - }, -}) - -const ParamsSubscriberTwo = Vue.defineComponent({ - setup() { - const value = Route.useParams({ - select: (params) => smallHash(`${params.e}:2`), - }) - return () => { - void value.value - return null - } - }, -}) - -const ContextSubscriberOne = Vue.defineComponent({ - setup() { - const value = Route.useRouteContext({ - select: (context) => context.ctxE, - }) - return () => { - void value.value - return null - } - }, -}) - -const ContextSubscriberTwo = Vue.defineComponent({ - setup() { - const value = Route.useRouteContext({ - select: (context) => (context.ctxE * 31 + 7) >>> 0, - }) - return () => { - void value.value - return null - } - }, -}) - -const LevelE = Vue.defineComponent({ - setup() { - return () => ( - <> - - - - - - - ) - }, -}) - -export const Route = createFileRoute('/l/$a/$b/$c/$d/$e')({ - params: { - parse: (params) => ({ ...params, e: normalizeParam(params.e) }), - stringify: (params) => ({ ...params, e: String(params.e) }), - }, - beforeLoad: ({ params }) => ({ ctxE: smallHash(params.e) }), - component: LevelE, -}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.tsx deleted file mode 100644 index 7785638ee7..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.tsx +++ /dev/null @@ -1,83 +0,0 @@ -import * as Vue from 'vue' -import { Outlet, createFileRoute } from '@tanstack/vue-router' -import { normalizeParam, smallHash } from '../../../shared' - -const ParamsSubscriberOne = Vue.defineComponent({ - setup() { - const value = Route.useParams({ - select: (params) => smallHash(params.d), - }) - return () => { - void value.value - return null - } - }, -}) - -const ParamsSubscriberTwo = Vue.defineComponent({ - setup() { - const value = Route.useParams({ - select: (params) => smallHash(`${params.d}:2`), - }) - return () => { - void value.value - return null - } - }, -}) - -const ContextSubscriberOne = Vue.defineComponent({ - setup() { - const value = Route.useRouteContext({ - select: (context) => context.ctxD, - }) - return () => { - void value.value - return null - } - }, -}) - -const ContextSubscriberTwo = Vue.defineComponent({ - setup() { - const value = Route.useRouteContext({ - select: (context) => (context.ctxD * 31 + 7) >>> 0, - }) - return () => { - void value.value - return null - } - }, -}) - -const LevelD = Vue.defineComponent({ - setup() { - const params = Route.useParams() - return () => ( - <> - - - - -
- {[ - params.value.a, - params.value.b, - params.value.c, - params.value.d, - ].join('.')} -
- - - ) - }, -}) - -export const Route = createFileRoute('/l/$a/$b/$c/$d')({ - params: { - parse: (params) => ({ ...params, d: normalizeParam(params.d) }), - stringify: (params) => ({ ...params, d: String(params.d) }), - }, - beforeLoad: ({ params }) => ({ ctxD: smallHash(params.d) }), - component: LevelD, -}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.tsx deleted file mode 100644 index 0d0adc65ff..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.tsx +++ /dev/null @@ -1,74 +0,0 @@ -import * as Vue from 'vue' -import { Outlet, createFileRoute } from '@tanstack/vue-router' -import { normalizeParam, smallHash } from '../../../shared' - -const ParamsSubscriberOne = Vue.defineComponent({ - setup() { - const value = Route.useParams({ - select: (params) => smallHash(params.c), - }) - return () => { - void value.value - return null - } - }, -}) - -const ParamsSubscriberTwo = Vue.defineComponent({ - setup() { - const value = Route.useParams({ - select: (params) => smallHash(`${params.c}:2`), - }) - return () => { - void value.value - return null - } - }, -}) - -const ContextSubscriberOne = Vue.defineComponent({ - setup() { - const value = Route.useRouteContext({ - select: (context) => context.ctxC, - }) - return () => { - void value.value - return null - } - }, -}) - -const ContextSubscriberTwo = Vue.defineComponent({ - setup() { - const value = Route.useRouteContext({ - select: (context) => (context.ctxC * 31 + 7) >>> 0, - }) - return () => { - void value.value - return null - } - }, -}) - -const LevelC = Vue.defineComponent({ - setup() { - return () => ( - <> - - - - - - - ) - }, -}) - -export const Route = createFileRoute('/l/$a/$b/$c')({ - params: { - parse: (params) => ({ ...params, c: normalizeParam(params.c) }), - stringify: (params) => ({ ...params, c: String(params.c) }), - }, - beforeLoad: ({ params }) => ({ ctxC: smallHash(params.c) }), - component: LevelC, -}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.tsx deleted file mode 100644 index f013d865af..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.tsx +++ /dev/null @@ -1,74 +0,0 @@ -import * as Vue from 'vue' -import { Outlet, createFileRoute } from '@tanstack/vue-router' -import { normalizeParam, smallHash } from '../../../shared' - -const ParamsSubscriberOne = Vue.defineComponent({ - setup() { - const value = Route.useParams({ - select: (params) => smallHash(params.b), - }) - return () => { - void value.value - return null - } - }, -}) - -const ParamsSubscriberTwo = Vue.defineComponent({ - setup() { - const value = Route.useParams({ - select: (params) => smallHash(`${params.b}:2`), - }) - return () => { - void value.value - return null - } - }, -}) - -const ContextSubscriberOne = Vue.defineComponent({ - setup() { - const value = Route.useRouteContext({ - select: (context) => context.ctxB, - }) - return () => { - void value.value - return null - } - }, -}) - -const ContextSubscriberTwo = Vue.defineComponent({ - setup() { - const value = Route.useRouteContext({ - select: (context) => (context.ctxB * 31 + 7) >>> 0, - }) - return () => { - void value.value - return null - } - }, -}) - -const LevelB = Vue.defineComponent({ - setup() { - return () => ( - <> - - - - - - - ) - }, -}) - -export const Route = createFileRoute('/l/$a/$b')({ - params: { - parse: (params) => ({ ...params, b: normalizeParam(params.b) }), - stringify: (params) => ({ ...params, b: String(params.b) }), - }, - beforeLoad: ({ params }) => ({ ctxB: smallHash(params.b) }), - component: LevelB, -}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.tsx deleted file mode 100644 index d5764c0985..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.tsx +++ /dev/null @@ -1,74 +0,0 @@ -import * as Vue from 'vue' -import { Outlet, createFileRoute } from '@tanstack/vue-router' -import { normalizeParam, smallHash } from '../../../shared' - -const ParamsSubscriberOne = Vue.defineComponent({ - setup() { - const value = Route.useParams({ - select: (params) => smallHash(params.a), - }) - return () => { - void value.value - return null - } - }, -}) - -const ParamsSubscriberTwo = Vue.defineComponent({ - setup() { - const value = Route.useParams({ - select: (params) => smallHash(`${params.a}:2`), - }) - return () => { - void value.value - return null - } - }, -}) - -const ContextSubscriberOne = Vue.defineComponent({ - setup() { - const value = Route.useRouteContext({ - select: (context) => context.ctxA, - }) - return () => { - void value.value - return null - } - }, -}) - -const ContextSubscriberTwo = Vue.defineComponent({ - setup() { - const value = Route.useRouteContext({ - select: (context) => (context.ctxA * 31 + 7) >>> 0, - }) - return () => { - void value.value - return null - } - }, -}) - -const LevelA = Vue.defineComponent({ - setup() { - return () => ( - <> - - - - - - - ) - }, -}) - -export const Route = createFileRoute('/l/$a')({ - params: { - parse: (params) => ({ ...params, a: normalizeParam(params.a) }), - stringify: (params) => ({ ...params, a: String(params.a) }), - }, - beforeLoad: ({ params }) => ({ ctxA: smallHash(params.a) }), - component: LevelA, -}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/tsconfig.json b/benchmarks/client-nav/scenarios/nested-params/vue/tsconfig.json deleted file mode 100644 index 7786fc3da9..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/vite.config.ts b/benchmarks/client-nav/scenarios/nested-params/vue/vite.config.ts deleted file mode 100644 index 0d74eb7a7c..0000000000 --- a/benchmarks/client-nav/scenarios/nested-params/vue/vite.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'vue', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav nested-params (vue)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - }, -}) diff --git a/benchmarks/client-nav/scenarios/preload/react/project.json b/benchmarks/client-nav/scenarios/preload/react/project.json deleted file mode 100644 index f095228746..0000000000 --- a/benchmarks/client-nav/scenarios/preload/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-preload-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/preload/react/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/preload/react/setup.ts b/benchmarks/client-nav/scenarios/preload/react/setup.ts deleted file mode 100644 index 5409df903c..0000000000 --- a/benchmarks/client-nav/scenarios/preload/react/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, 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, - }) -} diff --git a/benchmarks/client-nav/scenarios/preload/react/speed.bench.ts b/benchmarks/client-nav/scenarios/preload/react/speed.bench.ts deleted file mode 100644 index 5c210b2fd7..0000000000 --- a/benchmarks/client-nav/scenarios/preload/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-preload', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-preload interaction 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/preload/react/speed.flame.ts b/benchmarks/client-nav/scenarios/preload/react/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/preload/react/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/preload/react/src/main.tsx b/benchmarks/client-nav/scenarios/preload/react/src/main.tsx deleted file mode 100644 index 395867f674..0000000000 --- a/benchmarks/client-nav/scenarios/preload/react/src/main.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { RouterProvider, createRouter } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - defaultPreload: 'intent', - defaultPreloadDelay: 0, - defaultPreloadStaleTime: 0, - }) -} - -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/preload/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/preload/react/src/routeTree.gen.ts deleted file mode 100644 index 20619341c0..0000000000 --- a/benchmarks/client-nav/scenarios/preload/react/src/routeTree.gen.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as DocsRouteImport } from './routes/docs' -import { Route as SectionsSectionRouteImport } from './routes/sections.$section' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const DocsRoute = DocsRouteImport.update({ - id: '/docs', - path: '/docs', - getParentRoute: () => rootRouteImport, -} as any) -const SectionsSectionRoute = SectionsSectionRouteImport.update({ - id: '/sections/$section', - path: '/sections/$section', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/docs': typeof DocsRoute - '/sections/$section': typeof SectionsSectionRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/docs': typeof DocsRoute - '/sections/$section': typeof SectionsSectionRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/docs': typeof DocsRoute - '/sections/$section': typeof SectionsSectionRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/docs' | '/sections/$section' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/docs' | '/sections/$section' - id: '__root__' | '/' | '/docs' | '/sections/$section' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - DocsRoute: typeof DocsRoute - SectionsSectionRoute: typeof SectionsSectionRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - 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' - fullPath: '/sections/$section' - preLoaderRoute: typeof SectionsSectionRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - DocsRoute: DocsRoute, - SectionsSectionRoute: SectionsSectionRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/preload/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/preload/react/src/routes/__root.tsx deleted file mode 100644 index b659fe4d26..0000000000 --- a/benchmarks/client-nav/scenarios/preload/react/src/routes/__root.tsx +++ /dev/null @@ -1,32 +0,0 @@ -import { Link, Outlet, createRootRoute } from '@tanstack/react-router' -import { sections } from '../../../shared' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - <> - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/preload/react/src/routes/docs.tsx b/benchmarks/client-nav/scenarios/preload/react/src/routes/docs.tsx deleted file mode 100644 index 1f87530bac..0000000000 --- a/benchmarks/client-nav/scenarios/preload/react/src/routes/docs.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { docsMarker } from '../../../shared' - -export const Route = createFileRoute('/docs')({ - component: DocsPage, -}) - -function DocsPage() { - return ( -
-

{docsMarker}

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/preload/react/src/routes/index.tsx b/benchmarks/client-nav/scenarios/preload/react/src/routes/index.tsx deleted file mode 100644 index 2b8c83ebab..0000000000 --- a/benchmarks/client-nav/scenarios/preload/react/src/routes/index.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { homeMarker } from '../../../shared' - -export const Route = createFileRoute('/')({ - component: HomePage, -}) - -function HomePage() { - return ( -
-

{homeMarker}

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/preload/react/src/routes/sections.$section.tsx b/benchmarks/client-nav/scenarios/preload/react/src/routes/sections.$section.tsx deleted file mode 100644 index 42962b8be7..0000000000 --- a/benchmarks/client-nav/scenarios/preload/react/src/routes/sections.$section.tsx +++ /dev/null @@ -1,32 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { sectionItems } from '../../../shared' - -export const Route = createFileRoute('/sections/$section')({ - loader: ({ params }) => { - const items = sectionItems(params.section) - const checksum = items.reduce( - (sum, item) => (sum + item.value) % 1_000_000_007, - 0, - ) - return { items, checksum } - }, - staleTime: 0, - gcTime: 0, - component: SectionPage, -}) - -function SectionPage() { - const params = Route.useParams() - const data = Route.useLoaderData() - - return ( -
-

{`${params.section}:${data.checksum}`}

-
    - {data.items.map((item) => ( -
  • {`${item.name}=${item.value}`}
  • - ))} -
-
- ) -} diff --git a/benchmarks/client-nav/scenarios/preload/react/tsconfig.json b/benchmarks/client-nav/scenarios/preload/react/tsconfig.json deleted file mode 100644 index 1d59cbb450..0000000000 --- a/benchmarks/client-nav/scenarios/preload/react/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/preload/react/vite.config.ts b/benchmarks/client-nav/scenarios/preload/react/vite.config.ts deleted file mode 100644 index 8a41fc8707..0000000000 --- a/benchmarks/client-nav/scenarios/preload/react/vite.config.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'react', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav preload (react)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - }, -}) diff --git a/benchmarks/client-nav/scenarios/preload/shared.ts b/benchmarks/client-nav/scenarios/preload/shared.ts deleted file mode 100644 index d061f99451..0000000000 --- a/benchmarks/client-nav/scenarios/preload/shared.ts +++ /dev/null @@ -1,119 +0,0 @@ -/** - * Shared definition of the `preload` scenario: intent preloading via link - * hover, programmatic `router.preloadRoute`, and commit-time preload-cache - * maintenance. The router is configured with `defaultPreload: 'intent'`, - * `defaultPreloadDelay: 0` (no wall-clock debounce timer) and - * `defaultPreloadStaleTime: 0` — the default 30s wall-clock threshold would - * flip cache-hit behavior mid-run; with 0 every hover re-runs the preload - * work, keeping the loop stationary. - * - * Hover-intent preloading was verified manually per adapter (standalone jsdom - * run inspecting the router's cached matches after dispatching `mouseover` on - * a link). The harness hover step dispatches a single `mouseover`, which - * triggers the preload pipeline exactly once in every adapter: React - * synthesizes mouseEnter from it, Solid/Vue attach a native `mouseover` - * handler. (Solid/Vue also listen to `mouseenter`; dispatching both events - * would preload twice for them but once for React.) - */ -import type { ScenarioStep } from '../harness' - -export const sections = ['a', 'b', 'c', 'd', 'e'] as const - -export const SECTION_ITEM_COUNT = 30 - -/** Deterministic LCG stream seeded from a string — no Math.random. */ -function seededValues(seedText: string, count: number) { - let value = 0 - for (let i = 0; i < seedText.length; i++) { - value = (value * 31 + seedText.charCodeAt(i)) >>> 0 - } - - const values: Array = [] - for (let i = 0; i < count; i++) { - value = (value * 1664525 + 1013904223) >>> 0 - values.push(value % 100_000) - } - return values -} - -export interface SectionItem { - name: string - value: number -} - -export function sectionItems(section: string): Array { - return seededValues(`section-${section}`, SECTION_ITEM_COUNT).map( - (value, index) => ({ - name: `item-${section}-${index}`, - value, - }), - ) -} - -export function sectionChecksum(section: string) { - return sectionItems(section).reduce( - (sum, item) => (sum + item.value) % 1_000_000_007, - 0, - ) -} - -export function sectionMarker(section: string) { - return `${section}:${sectionChecksum(section)}` -} - -export const docsMarker = 'docs' -export const homeMarker = 'home' - -interface StepDef { - step: ScenarioStep - /** Expected page marker after the step; undefined for non-navigation steps. */ - marker?: string -} - -export const stepDefs: ReadonlyArray = [ - { step: { type: 'hover', testId: 's-a' } }, - { step: { type: 'hover', testId: 's-b' } }, - { step: 's-a', marker: sectionMarker('a') }, - { step: { type: 'hover', testId: 's-c' } }, - { step: 's-c', marker: sectionMarker('c') }, - { - step: { - type: 'preload', - getOptions: () => ({ - to: '/sections/$section', - params: { section: 'd' }, - }), - }, - }, - { step: 's-d', marker: sectionMarker('d') }, - { step: { type: 'hover', testId: 's-e' } }, - { step: 'go-docs', marker: docsMarker }, - { step: 'go-home', marker: homeMarker }, -] - -export const scenarioSteps: ReadonlyArray = stepDefs.map( - (def) => def.step, -) - -export function assertStepResult(stepIndex: number, container: HTMLElement) { - const def = stepDefs[stepIndex]! - if (!def.marker) { - return - } - - const marker = container.querySelector('[data-testid="page-state"]') - if (marker?.textContent !== def.marker) { - throw new Error( - `Expected page marker "${def.marker}" after step ${stepIndex}, received "${marker?.textContent}"`, - ) - } -} - -// Two laps through the 10-step sequence per benchmark iteration. -export const ticksPerIteration = 20 - -export const benchOptions = { - warmupIterations: 50, - time: 10_000, - throws: true, -} diff --git a/benchmarks/client-nav/scenarios/preload/solid/project.json b/benchmarks/client-nav/scenarios/preload/solid/project.json deleted file mode 100644 index a186879335..0000000000 --- a/benchmarks/client-nav/scenarios/preload/solid/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-preload-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/preload/solid/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/preload/solid/setup.ts b/benchmarks/client-nav/scenarios/preload/solid/setup.ts deleted file mode 100644 index 34270fe8a4..0000000000 --- a/benchmarks/client-nav/scenarios/preload/solid/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, 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, - }) -} diff --git a/benchmarks/client-nav/scenarios/preload/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/preload/solid/speed.bench.ts deleted file mode 100644 index f835b4a7b9..0000000000 --- a/benchmarks/client-nav/scenarios/preload/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-preload', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-preload interaction 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/preload/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/preload/solid/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/preload/solid/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/preload/solid/src/main.tsx b/benchmarks/client-nav/scenarios/preload/solid/src/main.tsx deleted file mode 100644 index 3791156c64..0000000000 --- a/benchmarks/client-nav/scenarios/preload/solid/src/main.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { render } from 'solid-js/web' -import { RouterProvider, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - defaultPreload: 'intent', - defaultPreloadDelay: 0, - defaultPreloadStaleTime: 0, - }) -} - -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/preload/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/preload/solid/src/routeTree.gen.ts deleted file mode 100644 index 97e215b6da..0000000000 --- a/benchmarks/client-nav/scenarios/preload/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as DocsRouteImport } from './routes/docs' -import { Route as SectionsSectionRouteImport } from './routes/sections.$section' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const DocsRoute = DocsRouteImport.update({ - id: '/docs', - path: '/docs', - getParentRoute: () => rootRouteImport, -} as any) -const SectionsSectionRoute = SectionsSectionRouteImport.update({ - id: '/sections/$section', - path: '/sections/$section', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/docs': typeof DocsRoute - '/sections/$section': typeof SectionsSectionRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/docs': typeof DocsRoute - '/sections/$section': typeof SectionsSectionRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/docs': typeof DocsRoute - '/sections/$section': typeof SectionsSectionRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/docs' | '/sections/$section' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/docs' | '/sections/$section' - id: '__root__' | '/' | '/docs' | '/sections/$section' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - DocsRoute: typeof DocsRoute - SectionsSectionRoute: typeof SectionsSectionRoute -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - 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' - fullPath: '/sections/$section' - preLoaderRoute: typeof SectionsSectionRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - DocsRoute: DocsRoute, - SectionsSectionRoute: SectionsSectionRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/preload/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/preload/solid/src/routes/__root.tsx deleted file mode 100644 index a805ed0feb..0000000000 --- a/benchmarks/client-nav/scenarios/preload/solid/src/routes/__root.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import { For } from 'solid-js' -import { Link, Outlet, createRootRoute } from '@tanstack/solid-router' -import { sections } from '../../../shared' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - <> - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/preload/solid/src/routes/docs.tsx b/benchmarks/client-nav/scenarios/preload/solid/src/routes/docs.tsx deleted file mode 100644 index b077cfd18f..0000000000 --- a/benchmarks/client-nav/scenarios/preload/solid/src/routes/docs.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { docsMarker } from '../../../shared' - -export const Route = createFileRoute('/docs')({ - component: DocsPage, -}) - -function DocsPage() { - return ( -
-

{docsMarker}

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/preload/solid/src/routes/index.tsx b/benchmarks/client-nav/scenarios/preload/solid/src/routes/index.tsx deleted file mode 100644 index 72fbfe387a..0000000000 --- a/benchmarks/client-nav/scenarios/preload/solid/src/routes/index.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { homeMarker } from '../../../shared' - -export const Route = createFileRoute('/')({ - component: HomePage, -}) - -function HomePage() { - return ( -
-

{homeMarker}

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/preload/solid/src/routes/sections.$section.tsx b/benchmarks/client-nav/scenarios/preload/solid/src/routes/sections.$section.tsx deleted file mode 100644 index 2a7fb2ad1b..0000000000 --- a/benchmarks/client-nav/scenarios/preload/solid/src/routes/sections.$section.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import { For } from 'solid-js' -import { createFileRoute } from '@tanstack/solid-router' -import { sectionItems } from '../../../shared' - -export const Route = createFileRoute('/sections/$section')({ - loader: ({ params }) => { - const items = sectionItems(params.section) - const checksum = items.reduce( - (sum, item) => (sum + item.value) % 1_000_000_007, - 0, - ) - return { items, checksum } - }, - staleTime: 0, - gcTime: 0, - component: SectionPage, -}) - -function SectionPage() { - const params = Route.useParams() - const data = Route.useLoaderData() - - return ( -
-

{`${params().section}:${data().checksum}`}

-
    - - {(item) =>
  • {`${item.name}=${item.value}`}
  • } -
    -
-
- ) -} diff --git a/benchmarks/client-nav/scenarios/preload/solid/tsconfig.json b/benchmarks/client-nav/scenarios/preload/solid/tsconfig.json deleted file mode 100644 index 98d76ad6b8..0000000000 --- a/benchmarks/client-nav/scenarios/preload/solid/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/preload/solid/vite.config.ts b/benchmarks/client-nav/scenarios/preload/solid/vite.config.ts deleted file mode 100644 index 07014e6124..0000000000 --- a/benchmarks/client-nav/scenarios/preload/solid/vite.config.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import solid from 'vite-plugin-solid' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'solid', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - resolve: { - conditions: ['solid', 'browser'], - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav preload (solid)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/client-nav/scenarios/preload/vue/project.json b/benchmarks/client-nav/scenarios/preload/vue/project.json deleted file mode 100644 index 404476723d..0000000000 --- a/benchmarks/client-nav/scenarios/preload/vue/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-preload-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/preload/vue/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/preload/vue/setup.ts b/benchmarks/client-nav/scenarios/preload/vue/setup.ts deleted file mode 100644 index f70a154909..0000000000 --- a/benchmarks/client-nav/scenarios/preload/vue/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, 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, - }) -} diff --git a/benchmarks/client-nav/scenarios/preload/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/preload/vue/speed.bench.ts deleted file mode 100644 index e0ec83619b..0000000000 --- a/benchmarks/client-nav/scenarios/preload/vue/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-preload', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-preload interaction 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/preload/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/preload/vue/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/preload/vue/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/preload/vue/src/main.tsx b/benchmarks/client-nav/scenarios/preload/vue/src/main.tsx deleted file mode 100644 index 3da20b2cbf..0000000000 --- a/benchmarks/client-nav/scenarios/preload/vue/src/main.tsx +++ /dev/null @@ -1,44 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import * as Vue from 'vue' -import { RouterProvider, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - defaultPreload: 'intent', - defaultPreloadDelay: 0, - defaultPreloadStaleTime: 0, - }) -} - -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/preload/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/preload/vue/src/routeTree.gen.ts deleted file mode 100644 index 5f95d09da0..0000000000 --- a/benchmarks/client-nav/scenarios/preload/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as DocsRouteImport } from './routes/docs' -import { Route as SectionsSectionRouteImport } from './routes/sections.$section' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const DocsRoute = DocsRouteImport.update({ - id: '/docs', - path: '/docs', - getParentRoute: () => rootRouteImport, -} as any) -const SectionsSectionRoute = SectionsSectionRouteImport.update({ - id: '/sections/$section', - path: '/sections/$section', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/docs': typeof DocsRoute - '/sections/$section': typeof SectionsSectionRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/docs': typeof DocsRoute - '/sections/$section': typeof SectionsSectionRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/docs': typeof DocsRoute - '/sections/$section': typeof SectionsSectionRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/docs' | '/sections/$section' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/docs' | '/sections/$section' - id: '__root__' | '/' | '/docs' | '/sections/$section' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - DocsRoute: typeof DocsRoute - SectionsSectionRoute: typeof SectionsSectionRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - 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' - fullPath: '/sections/$section' - preLoaderRoute: typeof SectionsSectionRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - DocsRoute: DocsRoute, - SectionsSectionRoute: SectionsSectionRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/preload/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/preload/vue/src/routes/__root.tsx deleted file mode 100644 index bf91ba3770..0000000000 --- a/benchmarks/client-nav/scenarios/preload/vue/src/routes/__root.tsx +++ /dev/null @@ -1,35 +0,0 @@ -import * as Vue from 'vue' -import { Link, Outlet, createRootRoute } from '@tanstack/vue-router' -import { sections } from '../../../shared' - -const RootComponent = Vue.defineComponent({ - setup() { - return () => ( - <> - - - - ) - }, -}) - -export const Route = createRootRoute({ - component: RootComponent, -}) diff --git a/benchmarks/client-nav/scenarios/preload/vue/src/routes/docs.tsx b/benchmarks/client-nav/scenarios/preload/vue/src/routes/docs.tsx deleted file mode 100644 index 07d0a989ad..0000000000 --- a/benchmarks/client-nav/scenarios/preload/vue/src/routes/docs.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' -import { docsMarker } from '../../../shared' - -const DocsPage = Vue.defineComponent({ - setup() { - return () => ( -
-

{docsMarker}

-
- ) - }, -}) - -export const Route = createFileRoute('/docs')({ - component: DocsPage, -}) diff --git a/benchmarks/client-nav/scenarios/preload/vue/src/routes/index.tsx b/benchmarks/client-nav/scenarios/preload/vue/src/routes/index.tsx deleted file mode 100644 index f04a9f5796..0000000000 --- a/benchmarks/client-nav/scenarios/preload/vue/src/routes/index.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' -import { homeMarker } from '../../../shared' - -const HomePage = Vue.defineComponent({ - setup() { - return () => ( -
-

{homeMarker}

-
- ) - }, -}) - -export const Route = createFileRoute('/')({ - component: HomePage, -}) diff --git a/benchmarks/client-nav/scenarios/preload/vue/src/routes/sections.$section.tsx b/benchmarks/client-nav/scenarios/preload/vue/src/routes/sections.$section.tsx deleted file mode 100644 index aeb617a86f..0000000000 --- a/benchmarks/client-nav/scenarios/preload/vue/src/routes/sections.$section.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' -import { sectionItems } from '../../../shared' - -const SectionPage = Vue.defineComponent({ - setup() { - const params = Route.useParams() - const data = Route.useLoaderData() - - return () => ( -
-

- {`${params.value.section}:${data.value.checksum}`} -

-
    - {data.value.items.map((item) => ( -
  • {`${item.name}=${item.value}`}
  • - ))} -
-
- ) - }, -}) - -export const Route = createFileRoute('/sections/$section')({ - loader: ({ params }) => { - const items = sectionItems(params.section) - const checksum = items.reduce( - (sum, item) => (sum + item.value) % 1_000_000_007, - 0, - ) - return { items, checksum } - }, - staleTime: 0, - gcTime: 0, - component: SectionPage, -}) diff --git a/benchmarks/client-nav/scenarios/preload/vue/tsconfig.json b/benchmarks/client-nav/scenarios/preload/vue/tsconfig.json deleted file mode 100644 index 7786fc3da9..0000000000 --- a/benchmarks/client-nav/scenarios/preload/vue/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/preload/vue/vite.config.ts b/benchmarks/client-nav/scenarios/preload/vue/vite.config.ts deleted file mode 100644 index 8d00e66378..0000000000 --- a/benchmarks/client-nav/scenarios/preload/vue/vite.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'vue', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav preload (vue)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - }, -}) diff --git a/benchmarks/client-nav/scenarios/rewrites/react/project.json b/benchmarks/client-nav/scenarios/rewrites/react/project.json deleted file mode 100644 index d98c6e1412..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-rewrites-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/rewrites/react/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/rewrites/react/setup.ts b/benchmarks/client-nav/scenarios/rewrites/react/setup.ts deleted file mode 100644 index 0c5df273ed..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/react/setup.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, initialUrl, steps } 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, - assertAfterStep: assertStepResult, - initialUrl, - }) -} diff --git a/benchmarks/client-nav/scenarios/rewrites/react/speed.bench.ts b/benchmarks/client-nav/scenarios/rewrites/react/speed.bench.ts deleted file mode 100644 index dd1b6f3686..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-rewrites', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-rewrites 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/rewrites/react/speed.flame.ts b/benchmarks/client-nav/scenarios/rewrites/react/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/react/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/rewrites/react/src/main.tsx b/benchmarks/client-nav/scenarios/rewrites/react/src/main.tsx deleted file mode 100644 index 28020ce373..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/react/src/main.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { RouterProvider, createRouter } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { routeTree } from './routeTree.gen' -import { basepath, localeRewrite } from '../../shared' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - basepath, - rewrite: localeRewrite, - 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/rewrites/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/rewrites/react/src/routeTree.gen.ts deleted file mode 100644 index b6ab8c8be4..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/react/src/routeTree.gen.ts +++ /dev/null @@ -1,103 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as PARouteImport } from './routes/p.$a' -import { Route as PABRouteImport } from './routes/p.$a.$b' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const PARoute = PARouteImport.update({ - id: '/p/$a', - path: '/p/$a', - getParentRoute: () => rootRouteImport, -} as any) -const PABRoute = PABRouteImport.update({ - id: '/$b', - path: '/$b', - getParentRoute: () => PARoute, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/p/$a': typeof PARouteWithChildren - '/p/$a/$b': typeof PABRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/p/$a': typeof PARouteWithChildren - '/p/$a/$b': typeof PABRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/p/$a': typeof PARouteWithChildren - '/p/$a/$b': typeof PABRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/p/$a' | '/p/$a/$b' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/p/$a' | '/p/$a/$b' - id: '__root__' | '/' | '/p/$a' | '/p/$a/$b' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - PARoute: typeof PARouteWithChildren -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/p/$a': { - id: '/p/$a' - path: '/p/$a' - fullPath: '/p/$a' - preLoaderRoute: typeof PARouteImport - parentRoute: typeof rootRouteImport - } - '/p/$a/$b': { - id: '/p/$a/$b' - path: '/$b' - fullPath: '/p/$a/$b' - preLoaderRoute: typeof PABRouteImport - parentRoute: typeof PARoute - } - } -} - -interface PARouteChildren { - PABRoute: typeof PABRoute -} - -const PARouteChildren: PARouteChildren = { - PABRoute: PABRoute, -} - -const PARouteWithChildren = PARoute._addFileChildren(PARouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - PARoute: PARouteWithChildren, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/rewrites/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/rewrites/react/src/routes/__root.tsx deleted file mode 100644 index ad14ff51f1..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/react/src/routes/__root.tsx +++ /dev/null @@ -1,61 +0,0 @@ -import { - Link, - Outlet, - createRootRoute, - useLocation, -} from '@tanstack/react-router' -import type { SearchSchemaInput } from '@tanstack/react-router' - -export const Route = createRootRoute({ - validateSearch: (search: Record & SearchSchemaInput) => - ({ - _locale: typeof search._locale === 'string' ? search._locale : undefined, - }) as { _locale?: string }, - component: RootComponent, -}) - -function RootComponent() { - const pathname = useLocation({ select: (location) => location.pathname }) - - return ( - <> - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/rewrites/react/src/routes/index.tsx b/benchmarks/client-nav/scenarios/rewrites/react/src/routes/index.tsx deleted file mode 100644 index 821cfe4a7c..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/react/src/routes/index.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: HomePage, -}) - -function HomePage() { - return ( -
-

Home

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/rewrites/react/src/routes/p.$a.$b.tsx b/benchmarks/client-nav/scenarios/rewrites/react/src/routes/p.$a.$b.tsx deleted file mode 100644 index ec1163e5c2..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/react/src/routes/p.$a.$b.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { itemLabel } from '../../../shared' - -export const Route = createFileRoute('/p/$a/$b')({ - component: ItemPage, -}) - -function ItemPage() { - const params = Route.useParams() - - return ( -
-

{itemLabel(params.a, params.b)}

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/rewrites/react/src/routes/p.$a.tsx b/benchmarks/client-nav/scenarios/rewrites/react/src/routes/p.$a.tsx deleted file mode 100644 index f4937494f0..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/react/src/routes/p.$a.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import { sectionLabel } from '../../../shared' - -export const Route = createFileRoute('/p/$a')({ - component: SectionPage, -}) - -function SectionPage() { - const params = Route.useParams() - - return ( -
-

{sectionLabel(params.a)}

- -
- ) -} diff --git a/benchmarks/client-nav/scenarios/rewrites/react/tsconfig.json b/benchmarks/client-nav/scenarios/rewrites/react/tsconfig.json deleted file mode 100644 index 1d59cbb450..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/react/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/rewrites/react/vite.config.ts b/benchmarks/client-nav/scenarios/rewrites/react/vite.config.ts deleted file mode 100644 index e79e8522e9..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/react/vite.config.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'react', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav rewrites (react)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - }, -}) diff --git a/benchmarks/client-nav/scenarios/rewrites/shared.ts b/benchmarks/client-nav/scenarios/rewrites/shared.ts deleted file mode 100644 index 0ca0a7ceb9..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/shared.ts +++ /dev/null @@ -1,106 +0,0 @@ -/** - * Shared definition of the `rewrites` scenario: composed client-side location - * rewrites — router `basepath` plus a locale input/output rewrite (the client - * analog of the SSR `rewrites` scenario). Externally URLs look like - * `/app/{locale}/p/...`; internally the router sees `/p/...` with the locale - * carried in the `_locale` search param. Every navigation runs the composed - * output rewrite when building hrefs/committing and the input rewrite when - * parsing the committed location. - */ -import type { ScenarioStep } from '../harness' -import type { RouterHistory } from '@tanstack/history' - -export const basepath = '/app' -export const defaultLocale = 'en' - -const localePrefixRe = /^\/(fr|de|es)(\/.*)$/ - -// Framework-agnostic rewrite pair consumed by all three apps' createRouter. -export const localeRewrite = { - input: ({ url }: { url: URL }) => { - const match = url.pathname.match(localePrefixRe) - - if (match) { - url.pathname = match[2]! - url.searchParams.set('_locale', match[1]!) - return url - } - - return undefined - }, - output: ({ url }: { url: URL }) => { - const locale = url.searchParams.get('_locale') - - if (locale) { - url.searchParams.delete('_locale') - url.pathname = `/${locale}${url.pathname}` - } - - return url - }, -} - -export function sectionLabel(a: string) { - return `Section ${a}` -} - -export function itemLabel(a: string, b: string) { - return `Item ${a}/${b}` -} - -interface StepDef { - testId: string - /** Internal router pathname expected after the step. */ - routerPath: string - /** External history pathname expected after the step. */ - windowPath: string -} - -// Circular lap: alternates sections, depths, and locales so every step runs -// the composed rewrites in both directions, then returns to the start. -export const stepDefs: ReadonlyArray = [ - { testId: 'go-x', routerPath: '/p/x', windowPath: '/app/p/x' }, - { testId: 'go-x-1-fr', routerPath: '/p/x/1', windowPath: '/app/fr/p/x/1' }, - { testId: 'go-y-de', routerPath: '/p/y', windowPath: '/app/de/p/y' }, - { testId: 'go-y-2', routerPath: '/p/y/2', windowPath: '/app/p/y/2' }, - { testId: 'go-x-es', routerPath: '/p/x', windowPath: '/app/es/p/x' }, - { testId: 'go-home', routerPath: '/', windowPath: '/app/' }, -] as const - -export const steps: ReadonlyArray = stepDefs.map( - (step) => step.testId, -) - -export function assertStepResult( - stepIndex: number, - container: HTMLElement, - history: RouterHistory, -) { - const expected = stepDefs[stepIndex]! - const marker = container.querySelector('[data-testid="loc"]') - const routerPath = marker?.textContent - - if (routerPath !== expected.routerPath) { - throw new Error( - `Expected router pathname "${expected.routerPath}" after step ${stepIndex}, received "${routerPath}"`, - ) - } - - if (history.location.pathname !== expected.windowPath) { - throw new Error( - `Expected history pathname "${expected.windowPath}" after step ${stepIndex}, received "${history.location.pathname}"`, - ) - } -} - -// The app starts on the external root inside the basepath. -export const initialUrl = '/app' - -// Three laps through the 6-step sequence per benchmark iteration. -export const ticksPerIteration = 18 - -export const benchOptions = { - warmupIterations: 100, - time: 10_000, - throws: true, -} diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/project.json b/benchmarks/client-nav/scenarios/rewrites/solid/project.json deleted file mode 100644 index 4b2f763032..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/solid/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-rewrites-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/rewrites/solid/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/setup.ts b/benchmarks/client-nav/scenarios/rewrites/solid/setup.ts deleted file mode 100644 index 5796df712d..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/solid/setup.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, initialUrl, steps } 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, - assertAfterStep: assertStepResult, - initialUrl, - }) -} diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/rewrites/solid/speed.bench.ts deleted file mode 100644 index 9c4313e2ff..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-rewrites', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-rewrites 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/rewrites/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/rewrites/solid/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/solid/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/src/main.tsx b/benchmarks/client-nav/scenarios/rewrites/solid/src/main.tsx deleted file mode 100644 index 31f1d07650..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/solid/src/main.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { render } from 'solid-js/web' -import { RouterProvider, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' -import { basepath, localeRewrite } from '../../shared' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - basepath, - rewrite: localeRewrite, - 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/rewrites/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/rewrites/solid/src/routeTree.gen.ts deleted file mode 100644 index 2d35f899c9..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,103 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as PARouteImport } from './routes/p.$a' -import { Route as PABRouteImport } from './routes/p.$a.$b' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const PARoute = PARouteImport.update({ - id: '/p/$a', - path: '/p/$a', - getParentRoute: () => rootRouteImport, -} as any) -const PABRoute = PABRouteImport.update({ - id: '/$b', - path: '/$b', - getParentRoute: () => PARoute, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/p/$a': typeof PARouteWithChildren - '/p/$a/$b': typeof PABRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/p/$a': typeof PARouteWithChildren - '/p/$a/$b': typeof PABRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/p/$a': typeof PARouteWithChildren - '/p/$a/$b': typeof PABRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/p/$a' | '/p/$a/$b' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/p/$a' | '/p/$a/$b' - id: '__root__' | '/' | '/p/$a' | '/p/$a/$b' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - PARoute: typeof PARouteWithChildren -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/p/$a': { - id: '/p/$a' - path: '/p/$a' - fullPath: '/p/$a' - preLoaderRoute: typeof PARouteImport - parentRoute: typeof rootRouteImport - } - '/p/$a/$b': { - id: '/p/$a/$b' - path: '/$b' - fullPath: '/p/$a/$b' - preLoaderRoute: typeof PABRouteImport - parentRoute: typeof PARoute - } - } -} - -interface PARouteChildren { - PABRoute: typeof PABRoute -} - -const PARouteChildren: PARouteChildren = { - PABRoute: PABRoute, -} - -const PARouteWithChildren = PARoute._addFileChildren(PARouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - PARoute: PARouteWithChildren, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/__root.tsx deleted file mode 100644 index 3a78f2c3cf..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/__root.tsx +++ /dev/null @@ -1,61 +0,0 @@ -import { - Link, - Outlet, - createRootRoute, - useLocation, -} from '@tanstack/solid-router' -import type { SearchSchemaInput } from '@tanstack/solid-router' - -export const Route = createRootRoute({ - validateSearch: (search: Record & SearchSchemaInput) => - ({ - _locale: typeof search._locale === 'string' ? search._locale : undefined, - }) as { _locale?: string }, - component: RootComponent, -}) - -function RootComponent() { - const pathname = useLocation({ select: (location) => location.pathname }) - - return ( - <> - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/index.tsx b/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/index.tsx deleted file mode 100644 index 5ee381ff05..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/index.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/')({ - component: HomePage, -}) - -function HomePage() { - return ( -
-

Home

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/p.$a.$b.tsx b/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/p.$a.$b.tsx deleted file mode 100644 index febcad35e3..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/p.$a.$b.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { itemLabel } from '../../../shared' - -export const Route = createFileRoute('/p/$a/$b')({ - component: ItemPage, -}) - -function ItemPage() { - const params = Route.useParams() - - return ( -
-

{itemLabel(params().a, params().b)}

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/p.$a.tsx b/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/p.$a.tsx deleted file mode 100644 index adfb7bc3b6..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/p.$a.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' -import { sectionLabel } from '../../../shared' - -export const Route = createFileRoute('/p/$a')({ - component: SectionPage, -}) - -function SectionPage() { - const params = Route.useParams() - - return ( -
-

{sectionLabel(params().a)}

- -
- ) -} diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/tsconfig.json b/benchmarks/client-nav/scenarios/rewrites/solid/tsconfig.json deleted file mode 100644 index 98d76ad6b8..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/solid/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/vite.config.ts b/benchmarks/client-nav/scenarios/rewrites/solid/vite.config.ts deleted file mode 100644 index c9e99b7d60..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/solid/vite.config.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import solid from 'vite-plugin-solid' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'solid', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - resolve: { - conditions: ['solid', 'browser'], - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav rewrites (solid)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/project.json b/benchmarks/client-nav/scenarios/rewrites/vue/project.json deleted file mode 100644 index 9b7cb5d198..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/vue/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-rewrites-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/rewrites/vue/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/setup.ts b/benchmarks/client-nav/scenarios/rewrites/vue/setup.ts deleted file mode 100644 index e26b4d05ca..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/vue/setup.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, initialUrl, steps } 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, - assertAfterStep: assertStepResult, - initialUrl, - }) -} diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/rewrites/vue/speed.bench.ts deleted file mode 100644 index e96aff39eb..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/vue/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-rewrites', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-rewrites 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/rewrites/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/rewrites/vue/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/vue/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/src/main.tsx b/benchmarks/client-nav/scenarios/rewrites/vue/src/main.tsx deleted file mode 100644 index 6695e82dbb..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/vue/src/main.tsx +++ /dev/null @@ -1,44 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import * as Vue from 'vue' -import { RouterProvider, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' -import { basepath, localeRewrite } from '../../shared' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - basepath, - rewrite: localeRewrite, - 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/rewrites/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/rewrites/vue/src/routeTree.gen.ts deleted file mode 100644 index 6eca4e8ce5..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,103 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as PARouteImport } from './routes/p.$a' -import { Route as PABRouteImport } from './routes/p.$a.$b' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const PARoute = PARouteImport.update({ - id: '/p/$a', - path: '/p/$a', - getParentRoute: () => rootRouteImport, -} as any) -const PABRoute = PABRouteImport.update({ - id: '/$b', - path: '/$b', - getParentRoute: () => PARoute, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/p/$a': typeof PARouteWithChildren - '/p/$a/$b': typeof PABRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/p/$a': typeof PARouteWithChildren - '/p/$a/$b': typeof PABRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/p/$a': typeof PARouteWithChildren - '/p/$a/$b': typeof PABRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/p/$a' | '/p/$a/$b' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/p/$a' | '/p/$a/$b' - id: '__root__' | '/' | '/p/$a' | '/p/$a/$b' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - PARoute: typeof PARouteWithChildren -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/p/$a': { - id: '/p/$a' - path: '/p/$a' - fullPath: '/p/$a' - preLoaderRoute: typeof PARouteImport - parentRoute: typeof rootRouteImport - } - '/p/$a/$b': { - id: '/p/$a/$b' - path: '/$b' - fullPath: '/p/$a/$b' - preLoaderRoute: typeof PABRouteImport - parentRoute: typeof PARoute - } - } -} - -interface PARouteChildren { - PABRoute: typeof PABRoute -} - -const PARouteChildren: PARouteChildren = { - PABRoute: PABRoute, -} - -const PARouteWithChildren = PARoute._addFileChildren(PARouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - PARoute: PARouteWithChildren, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/__root.tsx deleted file mode 100644 index ae89645005..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/__root.tsx +++ /dev/null @@ -1,64 +0,0 @@ -import * as Vue from 'vue' -import { - Link, - Outlet, - createRootRoute, - useLocation, -} from '@tanstack/vue-router' -import type { SearchSchemaInput } from '@tanstack/vue-router' - -const RootComponent = Vue.defineComponent({ - setup() { - const pathname = useLocation({ select: (location) => location.pathname }) - - return () => ( - <> - - - - ) - }, -}) - -export const Route = createRootRoute({ - validateSearch: (search: Record & SearchSchemaInput) => - ({ - _locale: typeof search._locale === 'string' ? search._locale : undefined, - }) as { _locale?: string }, - component: RootComponent, -}) diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/index.tsx b/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/index.tsx deleted file mode 100644 index d5405b52d2..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/index.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const HomePage = Vue.defineComponent({ - setup() { - return () => ( -
-

Home

-
- ) - }, -}) - -export const Route = createFileRoute('/')({ - component: HomePage, -}) diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/p.$a.$b.tsx b/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/p.$a.$b.tsx deleted file mode 100644 index 062c0903b9..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/p.$a.$b.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' -import { itemLabel } from '../../../shared' - -const ItemPage = Vue.defineComponent({ - setup() { - const params = Route.useParams() - - return () => ( -
-

{itemLabel(params.value.a, params.value.b)}

-
- ) - }, -}) - -export const Route = createFileRoute('/p/$a/$b')({ - component: ItemPage, -}) diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/p.$a.tsx b/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/p.$a.tsx deleted file mode 100644 index 552700d402..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/p.$a.tsx +++ /dev/null @@ -1,20 +0,0 @@ -import * as Vue from 'vue' -import { Outlet, createFileRoute } from '@tanstack/vue-router' -import { sectionLabel } from '../../../shared' - -const SectionPage = Vue.defineComponent({ - setup() { - const params = Route.useParams() - - return () => ( -
-

{sectionLabel(params.value.a)}

- -
- ) - }, -}) - -export const Route = createFileRoute('/p/$a')({ - component: SectionPage, -}) diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/tsconfig.json b/benchmarks/client-nav/scenarios/rewrites/vue/tsconfig.json deleted file mode 100644 index 7786fc3da9..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/vue/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/vite.config.ts b/benchmarks/client-nav/scenarios/rewrites/vue/vite.config.ts deleted file mode 100644 index 1a795a4e1d..0000000000 --- a/benchmarks/client-nav/scenarios/rewrites/vue/vite.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'vue', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav rewrites (vue)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - }, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/project.json b/benchmarks/client-nav/scenarios/route-tree-scale/react/project.json deleted file mode 100644 index 3291738f79..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-route-tree-scale-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/route-tree-scale/react/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/setup.ts b/benchmarks/client-nav/scenarios/route-tree-scale/react/setup.ts deleted file mode 100644 index 130583b190..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, steps } 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, - assertAfterStep: assertStepResult, - }) -} 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 deleted file mode 100644 index 6f4b448775..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-route-tree-scale', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-route-tree-scale 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/route-tree-scale/react/speed.flame.ts b/benchmarks/client-nav/scenarios/route-tree-scale/react/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/main.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/main.tsx deleted file mode 100644 index 5febd6f795..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/main.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { RouterProvider, createRouter } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const reactRoot = createRoot(container) - reactRoot.render() - - return { - router, - unmount() { - reactRoot.unmount() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routeTree.gen.ts deleted file mode 100644 index f8eeb73dda..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routeTree.gen.ts +++ /dev/null @@ -1,881 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', - getParentRoute: () => rootRouteImport, -} as any) -const SecARoute = SecARouteImport.update({ - id: '/sec-a', - path: '/sec-a', - getParentRoute: () => rootRouteImport, -} as any) -const SecBRoute = SecBRouteImport.update({ - id: '/sec-b', - path: '/sec-b', - getParentRoute: () => rootRouteImport, -} as any) -const SecCRoute = SecCRouteImport.update({ - id: '/sec-c', - path: '/sec-c', - getParentRoute: () => rootRouteImport, -} as any) -const SecDRoute = SecDRouteImport.update({ - id: '/sec-d', - path: '/sec-d', - getParentRoute: () => rootRouteImport, -} as any) -const SecERoute = SecERouteImport.update({ - id: '/sec-e', - path: '/sec-e', - getParentRoute: () => rootRouteImport, -} as any) -const SecFRoute = SecFRouteImport.update({ - id: '/sec-f', - path: '/sec-f', - getParentRoute: () => rootRouteImport, -} as any) -const marketingPricingRoute = marketingPricingRouteImport.update({ - id: '/(marketing)/pricing', - path: '/pricing', - getParentRoute: () => rootRouteImport, -} as any) -const marketingPromoRoute = marketingPromoRouteImport.update({ - id: '/(marketing)/promo', - path: '/promo', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutAlphaRoute = LayoutAlphaRouteImport.update({ - id: '/alpha', - path: '/alpha', - getParentRoute: () => LayoutRoute, -} as any) -const LayoutBetaRoute = LayoutBetaRouteImport.update({ - id: '/beta', - path: '/beta', - getParentRoute: () => LayoutRoute, -} as any) -const FilesSplatRoute = FilesSplatRouteImport.update({ - id: '/files/$', - path: '/files/$', - getParentRoute: () => rootRouteImport, -} as any) -const ReleaseVChar123versionChar125Route = - ReleaseVChar123versionChar125RouteImport.update({ - id: '/release/v{$version}', - path: '/release/v{$version}', - getParentRoute: () => rootRouteImport, - } as any) -const SecAIndexRoute = SecAIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecARoute, -} as any) -const SecAIdRoute = SecAIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecARoute, -} as any) -const SecAAboutRoute = SecAAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecARoute, -} as any) -const SecASettingsRoute = SecASettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecARoute, -} as any) -const SecBIndexRoute = SecBIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecBRoute, -} as any) -const SecBIdRoute = SecBIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecBRoute, -} as any) -const SecBAboutRoute = SecBAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecBRoute, -} as any) -const SecBSettingsRoute = SecBSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecBRoute, -} as any) -const SecCIndexRoute = SecCIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecCRoute, -} as any) -const SecCIdRoute = SecCIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecCRoute, -} as any) -const SecCAboutRoute = SecCAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecCRoute, -} as any) -const SecCSettingsRoute = SecCSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecCRoute, -} as any) -const SecDIndexRoute = SecDIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecDRoute, -} as any) -const SecDIdRoute = SecDIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecDRoute, -} as any) -const SecDAboutRoute = SecDAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecDRoute, -} as any) -const SecDSettingsRoute = SecDSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecDRoute, -} as any) -const SecEIndexRoute = SecEIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecERoute, -} as any) -const SecEIdRoute = SecEIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecERoute, -} as any) -const SecEAboutRoute = SecEAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecERoute, -} as any) -const SecESettingsRoute = SecESettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecERoute, -} 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 { - '/': typeof IndexRoute - '/sec-a': typeof SecARouteWithChildren - '/sec-b': typeof SecBRouteWithChildren - '/sec-c': typeof SecCRouteWithChildren - '/sec-d': typeof SecDRouteWithChildren - '/sec-e': typeof SecERouteWithChildren - '/sec-f': typeof SecFRouteWithChildren - '/pricing': typeof marketingPricingRoute - '/promo': typeof marketingPromoRoute - '/alpha': typeof LayoutAlphaRoute - '/beta': typeof LayoutBetaRoute - '/files/$': typeof FilesSplatRoute - '/release/v{$version}': typeof ReleaseVChar123versionChar125Route - '/sec-a/$id': typeof SecAIdRoute - '/sec-a/about': typeof SecAAboutRoute - '/sec-a/settings': typeof SecASettingsRoute - '/sec-b/$id': typeof SecBIdRoute - '/sec-b/about': typeof SecBAboutRoute - '/sec-b/settings': typeof SecBSettingsRoute - '/sec-c/$id': typeof SecCIdRoute - '/sec-c/about': typeof SecCAboutRoute - '/sec-c/settings': typeof SecCSettingsRoute - '/sec-d/$id': typeof SecDIdRoute - '/sec-d/about': typeof SecDAboutRoute - '/sec-d/settings': typeof SecDSettingsRoute - '/sec-e/$id': typeof SecEIdRoute - '/sec-e/about': typeof SecEAboutRoute - '/sec-e/settings': typeof SecESettingsRoute - '/sec-f/$id': typeof SecFIdRoute - '/sec-f/about': typeof SecFAboutRoute - '/sec-f/settings': typeof SecFSettingsRoute - '/sec-a/': typeof SecAIndexRoute - '/sec-b/': typeof SecBIndexRoute - '/sec-c/': typeof SecCIndexRoute - '/sec-d/': typeof SecDIndexRoute - '/sec-e/': typeof SecEIndexRoute - '/sec-f/': typeof SecFIndexRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/pricing': typeof marketingPricingRoute - '/promo': typeof marketingPromoRoute - '/alpha': typeof LayoutAlphaRoute - '/beta': typeof LayoutBetaRoute - '/files/$': typeof FilesSplatRoute - '/release/v{$version}': typeof ReleaseVChar123versionChar125Route - '/sec-a/$id': typeof SecAIdRoute - '/sec-a/about': typeof SecAAboutRoute - '/sec-a/settings': typeof SecASettingsRoute - '/sec-b/$id': typeof SecBIdRoute - '/sec-b/about': typeof SecBAboutRoute - '/sec-b/settings': typeof SecBSettingsRoute - '/sec-c/$id': typeof SecCIdRoute - '/sec-c/about': typeof SecCAboutRoute - '/sec-c/settings': typeof SecCSettingsRoute - '/sec-d/$id': typeof SecDIdRoute - '/sec-d/about': typeof SecDAboutRoute - '/sec-d/settings': typeof SecDSettingsRoute - '/sec-e/$id': typeof SecEIdRoute - '/sec-e/about': typeof SecEAboutRoute - '/sec-e/settings': typeof SecESettingsRoute - '/sec-f/$id': typeof SecFIdRoute - '/sec-f/about': typeof SecFAboutRoute - '/sec-f/settings': typeof SecFSettingsRoute - '/sec-a': typeof SecAIndexRoute - '/sec-b': typeof SecBIndexRoute - '/sec-c': typeof SecCIndexRoute - '/sec-d': typeof SecDIndexRoute - '/sec-e': typeof SecEIndexRoute - '/sec-f': typeof SecFIndexRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/_layout': typeof LayoutRouteWithChildren - '/sec-a': typeof SecARouteWithChildren - '/sec-b': typeof SecBRouteWithChildren - '/sec-c': typeof SecCRouteWithChildren - '/sec-d': typeof SecDRouteWithChildren - '/sec-e': typeof SecERouteWithChildren - '/sec-f': typeof SecFRouteWithChildren - '/(marketing)/pricing': typeof marketingPricingRoute - '/(marketing)/promo': typeof marketingPromoRoute - '/_layout/alpha': typeof LayoutAlphaRoute - '/_layout/beta': typeof LayoutBetaRoute - '/files/$': typeof FilesSplatRoute - '/release/v{$version}': typeof ReleaseVChar123versionChar125Route - '/sec-a/$id': typeof SecAIdRoute - '/sec-a/about': typeof SecAAboutRoute - '/sec-a/settings': typeof SecASettingsRoute - '/sec-b/$id': typeof SecBIdRoute - '/sec-b/about': typeof SecBAboutRoute - '/sec-b/settings': typeof SecBSettingsRoute - '/sec-c/$id': typeof SecCIdRoute - '/sec-c/about': typeof SecCAboutRoute - '/sec-c/settings': typeof SecCSettingsRoute - '/sec-d/$id': typeof SecDIdRoute - '/sec-d/about': typeof SecDAboutRoute - '/sec-d/settings': typeof SecDSettingsRoute - '/sec-e/$id': typeof SecEIdRoute - '/sec-e/about': typeof SecEAboutRoute - '/sec-e/settings': typeof SecESettingsRoute - '/sec-f/$id': typeof SecFIdRoute - '/sec-f/about': typeof SecFAboutRoute - '/sec-f/settings': typeof SecFSettingsRoute - '/sec-a/': typeof SecAIndexRoute - '/sec-b/': typeof SecBIndexRoute - '/sec-c/': typeof SecCIndexRoute - '/sec-d/': typeof SecDIndexRoute - '/sec-e/': typeof SecEIndexRoute - '/sec-f/': typeof SecFIndexRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/sec-a' - | '/sec-b' - | '/sec-c' - | '/sec-d' - | '/sec-e' - | '/sec-f' - | '/pricing' - | '/promo' - | '/alpha' - | '/beta' - | '/files/$' - | '/release/v{$version}' - | '/sec-a/$id' - | '/sec-a/about' - | '/sec-a/settings' - | '/sec-b/$id' - | '/sec-b/about' - | '/sec-b/settings' - | '/sec-c/$id' - | '/sec-c/about' - | '/sec-c/settings' - | '/sec-d/$id' - | '/sec-d/about' - | '/sec-d/settings' - | '/sec-e/$id' - | '/sec-e/about' - | '/sec-e/settings' - | '/sec-f/$id' - | '/sec-f/about' - | '/sec-f/settings' - | '/sec-a/' - | '/sec-b/' - | '/sec-c/' - | '/sec-d/' - | '/sec-e/' - | '/sec-f/' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/pricing' - | '/promo' - | '/alpha' - | '/beta' - | '/files/$' - | '/release/v{$version}' - | '/sec-a/$id' - | '/sec-a/about' - | '/sec-a/settings' - | '/sec-b/$id' - | '/sec-b/about' - | '/sec-b/settings' - | '/sec-c/$id' - | '/sec-c/about' - | '/sec-c/settings' - | '/sec-d/$id' - | '/sec-d/about' - | '/sec-d/settings' - | '/sec-e/$id' - | '/sec-e/about' - | '/sec-e/settings' - | '/sec-f/$id' - | '/sec-f/about' - | '/sec-f/settings' - | '/sec-a' - | '/sec-b' - | '/sec-c' - | '/sec-d' - | '/sec-e' - | '/sec-f' - id: - | '__root__' - | '/' - | '/_layout' - | '/sec-a' - | '/sec-b' - | '/sec-c' - | '/sec-d' - | '/sec-e' - | '/sec-f' - | '/(marketing)/pricing' - | '/(marketing)/promo' - | '/_layout/alpha' - | '/_layout/beta' - | '/files/$' - | '/release/v{$version}' - | '/sec-a/$id' - | '/sec-a/about' - | '/sec-a/settings' - | '/sec-b/$id' - | '/sec-b/about' - | '/sec-b/settings' - | '/sec-c/$id' - | '/sec-c/about' - | '/sec-c/settings' - | '/sec-d/$id' - | '/sec-d/about' - | '/sec-d/settings' - | '/sec-e/$id' - | '/sec-e/about' - | '/sec-e/settings' - | '/sec-f/$id' - | '/sec-f/about' - | '/sec-f/settings' - | '/sec-a/' - | '/sec-b/' - | '/sec-c/' - | '/sec-d/' - | '/sec-e/' - | '/sec-f/' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - LayoutRoute: typeof LayoutRouteWithChildren - SecARoute: typeof SecARouteWithChildren - SecBRoute: typeof SecBRouteWithChildren - SecCRoute: typeof SecCRouteWithChildren - SecDRoute: typeof SecDRouteWithChildren - SecERoute: typeof SecERouteWithChildren - SecFRoute: typeof SecFRouteWithChildren - marketingPricingRoute: typeof marketingPricingRoute - marketingPromoRoute: typeof marketingPromoRoute - FilesSplatRoute: typeof FilesSplatRoute - ReleaseVChar123versionChar125Route: typeof ReleaseVChar123versionChar125Route -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout': { - id: '/_layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-a': { - id: '/sec-a' - path: '/sec-a' - fullPath: '/sec-a' - preLoaderRoute: typeof SecARouteImport - parentRoute: typeof rootRouteImport - } - '/sec-b': { - id: '/sec-b' - path: '/sec-b' - fullPath: '/sec-b' - preLoaderRoute: typeof SecBRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-c': { - id: '/sec-c' - path: '/sec-c' - fullPath: '/sec-c' - preLoaderRoute: typeof SecCRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-d': { - id: '/sec-d' - path: '/sec-d' - fullPath: '/sec-d' - preLoaderRoute: typeof SecDRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-e': { - id: '/sec-e' - path: '/sec-e' - fullPath: '/sec-e' - preLoaderRoute: typeof SecERouteImport - parentRoute: typeof rootRouteImport - } - '/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/' - path: '/' - fullPath: '/sec-a/' - preLoaderRoute: typeof SecAIndexRouteImport - parentRoute: typeof SecARoute - } - '/sec-a/$id': { - id: '/sec-a/$id' - path: '/$id' - fullPath: '/sec-a/$id' - preLoaderRoute: typeof SecAIdRouteImport - parentRoute: typeof SecARoute - } - '/sec-a/about': { - id: '/sec-a/about' - path: '/about' - fullPath: '/sec-a/about' - preLoaderRoute: typeof SecAAboutRouteImport - parentRoute: typeof SecARoute - } - '/sec-a/settings': { - id: '/sec-a/settings' - path: '/settings' - fullPath: '/sec-a/settings' - preLoaderRoute: typeof SecASettingsRouteImport - parentRoute: typeof SecARoute - } - '/sec-b/': { - id: '/sec-b/' - path: '/' - fullPath: '/sec-b/' - preLoaderRoute: typeof SecBIndexRouteImport - parentRoute: typeof SecBRoute - } - '/sec-b/$id': { - id: '/sec-b/$id' - path: '/$id' - fullPath: '/sec-b/$id' - preLoaderRoute: typeof SecBIdRouteImport - parentRoute: typeof SecBRoute - } - '/sec-b/about': { - id: '/sec-b/about' - path: '/about' - fullPath: '/sec-b/about' - preLoaderRoute: typeof SecBAboutRouteImport - parentRoute: typeof SecBRoute - } - '/sec-b/settings': { - id: '/sec-b/settings' - path: '/settings' - fullPath: '/sec-b/settings' - preLoaderRoute: typeof SecBSettingsRouteImport - parentRoute: typeof SecBRoute - } - '/sec-c/': { - id: '/sec-c/' - path: '/' - fullPath: '/sec-c/' - preLoaderRoute: typeof SecCIndexRouteImport - parentRoute: typeof SecCRoute - } - '/sec-c/$id': { - id: '/sec-c/$id' - path: '/$id' - fullPath: '/sec-c/$id' - preLoaderRoute: typeof SecCIdRouteImport - parentRoute: typeof SecCRoute - } - '/sec-c/about': { - id: '/sec-c/about' - path: '/about' - fullPath: '/sec-c/about' - preLoaderRoute: typeof SecCAboutRouteImport - parentRoute: typeof SecCRoute - } - '/sec-c/settings': { - id: '/sec-c/settings' - path: '/settings' - fullPath: '/sec-c/settings' - preLoaderRoute: typeof SecCSettingsRouteImport - parentRoute: typeof SecCRoute - } - '/sec-d/': { - id: '/sec-d/' - path: '/' - fullPath: '/sec-d/' - preLoaderRoute: typeof SecDIndexRouteImport - parentRoute: typeof SecDRoute - } - '/sec-d/$id': { - id: '/sec-d/$id' - path: '/$id' - fullPath: '/sec-d/$id' - preLoaderRoute: typeof SecDIdRouteImport - parentRoute: typeof SecDRoute - } - '/sec-d/about': { - id: '/sec-d/about' - path: '/about' - fullPath: '/sec-d/about' - preLoaderRoute: typeof SecDAboutRouteImport - parentRoute: typeof SecDRoute - } - '/sec-d/settings': { - id: '/sec-d/settings' - path: '/settings' - fullPath: '/sec-d/settings' - preLoaderRoute: typeof SecDSettingsRouteImport - parentRoute: typeof SecDRoute - } - '/sec-e/': { - id: '/sec-e/' - path: '/' - fullPath: '/sec-e/' - preLoaderRoute: typeof SecEIndexRouteImport - parentRoute: typeof SecERoute - } - '/sec-e/$id': { - id: '/sec-e/$id' - path: '/$id' - fullPath: '/sec-e/$id' - preLoaderRoute: typeof SecEIdRouteImport - parentRoute: typeof SecERoute - } - '/sec-e/about': { - id: '/sec-e/about' - path: '/about' - fullPath: '/sec-e/about' - preLoaderRoute: typeof SecEAboutRouteImport - parentRoute: typeof SecERoute - } - '/sec-e/settings': { - id: '/sec-e/settings' - path: '/settings' - fullPath: '/sec-e/settings' - preLoaderRoute: typeof SecESettingsRouteImport - parentRoute: typeof SecERoute - } - '/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 - } - } -} - -interface LayoutRouteChildren { - LayoutAlphaRoute: typeof LayoutAlphaRoute - LayoutBetaRoute: typeof LayoutBetaRoute -} - -const LayoutRouteChildren: LayoutRouteChildren = { - LayoutAlphaRoute: LayoutAlphaRoute, - LayoutBetaRoute: LayoutBetaRoute, -} - -const LayoutRouteWithChildren = - LayoutRoute._addFileChildren(LayoutRouteChildren) - -interface SecARouteChildren { - SecAIdRoute: typeof SecAIdRoute - SecAAboutRoute: typeof SecAAboutRoute - SecASettingsRoute: typeof SecASettingsRoute - SecAIndexRoute: typeof SecAIndexRoute -} - -const SecARouteChildren: SecARouteChildren = { - SecAIdRoute: SecAIdRoute, - SecAAboutRoute: SecAAboutRoute, - SecASettingsRoute: SecASettingsRoute, - SecAIndexRoute: SecAIndexRoute, -} - -const SecARouteWithChildren = SecARoute._addFileChildren(SecARouteChildren) - -interface SecBRouteChildren { - SecBIdRoute: typeof SecBIdRoute - SecBAboutRoute: typeof SecBAboutRoute - SecBSettingsRoute: typeof SecBSettingsRoute - SecBIndexRoute: typeof SecBIndexRoute -} - -const SecBRouteChildren: SecBRouteChildren = { - SecBIdRoute: SecBIdRoute, - SecBAboutRoute: SecBAboutRoute, - SecBSettingsRoute: SecBSettingsRoute, - SecBIndexRoute: SecBIndexRoute, -} - -const SecBRouteWithChildren = SecBRoute._addFileChildren(SecBRouteChildren) - -interface SecCRouteChildren { - SecCIdRoute: typeof SecCIdRoute - SecCAboutRoute: typeof SecCAboutRoute - SecCSettingsRoute: typeof SecCSettingsRoute - SecCIndexRoute: typeof SecCIndexRoute -} - -const SecCRouteChildren: SecCRouteChildren = { - SecCIdRoute: SecCIdRoute, - SecCAboutRoute: SecCAboutRoute, - SecCSettingsRoute: SecCSettingsRoute, - SecCIndexRoute: SecCIndexRoute, -} - -const SecCRouteWithChildren = SecCRoute._addFileChildren(SecCRouteChildren) - -interface SecDRouteChildren { - SecDIdRoute: typeof SecDIdRoute - SecDAboutRoute: typeof SecDAboutRoute - SecDSettingsRoute: typeof SecDSettingsRoute - SecDIndexRoute: typeof SecDIndexRoute -} - -const SecDRouteChildren: SecDRouteChildren = { - SecDIdRoute: SecDIdRoute, - SecDAboutRoute: SecDAboutRoute, - SecDSettingsRoute: SecDSettingsRoute, - SecDIndexRoute: SecDIndexRoute, -} - -const SecDRouteWithChildren = SecDRoute._addFileChildren(SecDRouteChildren) - -interface SecERouteChildren { - SecEIdRoute: typeof SecEIdRoute - SecEAboutRoute: typeof SecEAboutRoute - SecESettingsRoute: typeof SecESettingsRoute - SecEIndexRoute: typeof SecEIndexRoute -} - -const SecERouteChildren: SecERouteChildren = { - SecEIdRoute: SecEIdRoute, - SecEAboutRoute: SecEAboutRoute, - SecESettingsRoute: SecESettingsRoute, - SecEIndexRoute: SecEIndexRoute, -} - -const SecERouteWithChildren = SecERoute._addFileChildren(SecERouteChildren) - -interface SecFRouteChildren { - SecFIdRoute: typeof SecFIdRoute - SecFAboutRoute: typeof SecFAboutRoute - SecFSettingsRoute: typeof SecFSettingsRoute - SecFIndexRoute: typeof SecFIndexRoute -} - -const SecFRouteChildren: SecFRouteChildren = { - SecFIdRoute: SecFIdRoute, - SecFAboutRoute: SecFAboutRoute, - SecFSettingsRoute: SecFSettingsRoute, - SecFIndexRoute: SecFIndexRoute, -} - -const SecFRouteWithChildren = SecFRoute._addFileChildren(SecFRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - LayoutRoute: LayoutRouteWithChildren, - SecARoute: SecARouteWithChildren, - SecBRoute: SecBRouteWithChildren, - SecCRoute: SecCRouteWithChildren, - SecDRoute: SecDRouteWithChildren, - SecERoute: SecERouteWithChildren, - SecFRoute: SecFRouteWithChildren, - marketingPricingRoute: marketingPricingRoute, - marketingPromoRoute: marketingPromoRoute, - FilesSplatRoute: FilesSplatRoute, - ReleaseVChar123versionChar125Route: ReleaseVChar123versionChar125Route, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/(marketing)/pricing.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/(marketing)/pricing.tsx deleted file mode 100644 index ac2a376549..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/(marketing)/pricing.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/(marketing)/pricing')({ - component: Page, -}) - -function Page() { - return
pricing
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/(marketing)/promo.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/(marketing)/promo.tsx deleted file mode 100644 index b71962254e..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/(marketing)/promo.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/(marketing)/promo')({ - component: Page, -}) - -function Page() { - return
promo
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/__root.tsx deleted file mode 100644 index 7ed47da924..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/__root.tsx +++ /dev/null @@ -1,58 +0,0 @@ -import { Link, Outlet, createRootRoute } from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - <> - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.alpha.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.alpha.tsx deleted file mode 100644 index 893419cef5..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.alpha.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/alpha')({ - component: Page, -}) - -function Page() { - return
alpha
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.beta.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.beta.tsx deleted file mode 100644 index d20c6007ee..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.beta.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/beta')({ - component: Page, -}) - -function Page() { - return
beta
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.tsx deleted file mode 100644 index 961feb50f1..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout')({ - component: Layout, -}) - -function Layout() { - return -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/files.$.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/files.$.tsx deleted file mode 100644 index 028aa43d5a..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/files.$.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/files/$')({ - component: Page, -}) - -function Page() { - const params = Route.useParams() - - return
{`files:${params._splat}`}
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/index.tsx deleted file mode 100644 index 8a7ffca9e7..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: Page, -}) - -function Page() { - return
home
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/release.v{$version}.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/release.v{$version}.tsx deleted file mode 100644 index dfe8e31905..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/release.v{$version}.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/release/v{$version}')({ - component: Page, -}) - -function Page() { - const params = Route.useParams() - - return
{`release:${params.version}`}
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.$id.tsx deleted file mode 100644 index 8be053a040..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-a/$id')({ - component: Page, -}) - -function Page() { - const params = Route.useParams() - - return
{`sec-a:${params.id}`}
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.about.tsx deleted file mode 100644 index 54c1b28618..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.about.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-a/about')({ - component: Page, -}) - -function Page() { - return
sec-a:about
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.index.tsx deleted file mode 100644 index 3c793a94f5..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-a/')({ - component: Page, -}) - -function Page() { - return
sec-a:index
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.settings.tsx deleted file mode 100644 index 0037f6463d..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.settings.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-a/settings')({ - component: Page, -}) - -function Page() { - return
sec-a:settings
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.tsx deleted file mode 100644 index 846f96b67b..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-a')({ - component: Layout, -}) - -function Layout() { - return -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.$id.tsx deleted file mode 100644 index 0dd7f94feb..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-b/$id')({ - component: Page, -}) - -function Page() { - const params = Route.useParams() - - return
{`sec-b:${params.id}`}
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.about.tsx deleted file mode 100644 index fde4647472..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.about.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-b/about')({ - component: Page, -}) - -function Page() { - return
sec-b:about
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.index.tsx deleted file mode 100644 index 51b69cf664..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-b/')({ - component: Page, -}) - -function Page() { - return
sec-b:index
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.settings.tsx deleted file mode 100644 index 977b7438b1..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.settings.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-b/settings')({ - component: Page, -}) - -function Page() { - return
sec-b:settings
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.tsx deleted file mode 100644 index 77d7e6475d..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-b')({ - component: Layout, -}) - -function Layout() { - return -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.$id.tsx deleted file mode 100644 index eb3be796c0..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-c/$id')({ - component: Page, -}) - -function Page() { - const params = Route.useParams() - - return
{`sec-c:${params.id}`}
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.about.tsx deleted file mode 100644 index 7910acf332..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.about.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-c/about')({ - component: Page, -}) - -function Page() { - return
sec-c:about
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.index.tsx deleted file mode 100644 index f6ae102f2d..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-c/')({ - component: Page, -}) - -function Page() { - return
sec-c:index
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.settings.tsx deleted file mode 100644 index bf2be30788..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.settings.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-c/settings')({ - component: Page, -}) - -function Page() { - return
sec-c:settings
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.tsx deleted file mode 100644 index 77ac5644c6..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-c')({ - component: Layout, -}) - -function Layout() { - return -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.$id.tsx deleted file mode 100644 index d34aee8972..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-d/$id')({ - component: Page, -}) - -function Page() { - const params = Route.useParams() - - return
{`sec-d:${params.id}`}
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.about.tsx deleted file mode 100644 index 1f095cb2ff..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.about.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-d/about')({ - component: Page, -}) - -function Page() { - return
sec-d:about
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.index.tsx deleted file mode 100644 index 8fc698a4d4..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-d/')({ - component: Page, -}) - -function Page() { - return
sec-d:index
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.settings.tsx deleted file mode 100644 index 76c7a178ea..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.settings.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-d/settings')({ - component: Page, -}) - -function Page() { - return
sec-d:settings
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.tsx deleted file mode 100644 index 5f3d281b5e..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-d')({ - component: Layout, -}) - -function Layout() { - return -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.$id.tsx deleted file mode 100644 index 6e31d0c5d1..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-e/$id')({ - component: Page, -}) - -function Page() { - const params = Route.useParams() - - return
{`sec-e:${params.id}`}
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.about.tsx deleted file mode 100644 index 5a2835917b..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.about.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-e/about')({ - component: Page, -}) - -function Page() { - return
sec-e:about
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.index.tsx deleted file mode 100644 index 0f23b8d484..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-e/')({ - component: Page, -}) - -function Page() { - return
sec-e:index
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.settings.tsx deleted file mode 100644 index b566a1ffaa..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.settings.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-e/settings')({ - component: Page, -}) - -function Page() { - return
sec-e:settings
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.tsx deleted file mode 100644 index e573a71d98..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-e')({ - component: Layout, -}) - -function Layout() { - return -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.$id.tsx deleted file mode 100644 index a71c17f96e..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-f/$id')({ - component: Page, -}) - -function Page() { - const params = Route.useParams() - - return
{`sec-f:${params.id}`}
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.about.tsx deleted file mode 100644 index 06831063ad..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.about.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-f/about')({ - component: Page, -}) - -function Page() { - return
sec-f:about
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.index.tsx deleted file mode 100644 index 4cd54b6a7f..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-f/')({ - component: Page, -}) - -function Page() { - return
sec-f:index
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.settings.tsx deleted file mode 100644 index 92bdca5e44..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.settings.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-f/settings')({ - component: Page, -}) - -function Page() { - return
sec-f:settings
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.tsx deleted file mode 100644 index 2fa27873e8..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/sec-f')({ - component: Layout, -}) - -function Layout() { - return -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/tsconfig.json b/benchmarks/client-nav/scenarios/route-tree-scale/react/tsconfig.json deleted file mode 100644 index 1d59cbb450..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/vite.config.ts b/benchmarks/client-nav/scenarios/route-tree-scale/react/vite.config.ts deleted file mode 100644 index 0f588fda53..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/vite.config.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'react', - // Real file-based apps code-split by default; this scenario keeps it on - // so navigations also exercise lazy route-chunk resolution. - autoCodeSplitting: true, - 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 route-tree-scale (react)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - }, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/shared.ts b/benchmarks/client-nav/scenarios/route-tree-scale/shared.ts deleted file mode 100644 index 8af5996804..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/shared.ts +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Shared definition of the `route-tree-scale` scenario: route matching, - * location building, and link-target resolution over a wide route tree - * (~40 routes) mixing static segments, dynamic params, prefixed params, - * splats, pathless layouts, and route groups. Navigations jump between - * distant branches so matching cannot reuse the previous branch. - */ - -export const sections = [ - 'sec-a', - 'sec-b', - 'sec-c', - 'sec-d', - 'sec-e', - 'sec-f', -] as const - -export const steps = [ - 'go-sec-a-id', - 'go-sec-f-settings', - 'go-files', - 'go-release', - 'go-alpha', - 'go-promo', - 'go-sec-c-id', - 'go-sec-d-about', - 'go-home', -] as const - -// The dynamic ids and the splat carry characters that need percent-encoding -// (spaces, `&`, `%`, `+`, unicode) so matching also exercises the segment -// encode/decode paths. -const expectedMarkers = [ - 'sec-a:item 11%', - 'sec-f:settings', - 'files:x/ü y/z', - 'release:9', - 'alpha', - 'promo', - 'sec-c:q&a+42', - 'sec-d:about', - 'home', -] as const - -export function assertStepResult(stepIndex: number) { - const expected = expectedMarkers[stepIndex]! - const actual = document.querySelector( - '[data-testid="scale-state"]', - )?.textContent - if (actual !== expected) { - throw new Error( - `Expected scale-state marker "${expected}" after step ${stepIndex}, received "${actual}"`, - ) - } -} - -// Three laps through the 9-step sequence per benchmark iteration. -export const ticksPerIteration = 27 - -export const benchOptions = { - warmupIterations: 100, - time: 10_000, - throws: true, -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/project.json b/benchmarks/client-nav/scenarios/route-tree-scale/solid/project.json deleted file mode 100644 index c568e41196..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-route-tree-scale-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/route-tree-scale/solid/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/setup.ts b/benchmarks/client-nav/scenarios/route-tree-scale/solid/setup.ts deleted file mode 100644 index 6a46971603..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, steps } 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, - assertAfterStep: assertStepResult, - }) -} 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 deleted file mode 100644 index 9244ef1350..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-route-tree-scale', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-route-tree-scale 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/route-tree-scale/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/route-tree-scale/solid/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/main.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/main.tsx deleted file mode 100644 index fa9d239418..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/main.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { render } from 'solid-js/web' -import { RouterProvider, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const unmount = render(() => , container) - - return { - router, - unmount, - } -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routeTree.gen.ts deleted file mode 100644 index e6f3596562..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,881 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', - getParentRoute: () => rootRouteImport, -} as any) -const SecARoute = SecARouteImport.update({ - id: '/sec-a', - path: '/sec-a', - getParentRoute: () => rootRouteImport, -} as any) -const SecBRoute = SecBRouteImport.update({ - id: '/sec-b', - path: '/sec-b', - getParentRoute: () => rootRouteImport, -} as any) -const SecCRoute = SecCRouteImport.update({ - id: '/sec-c', - path: '/sec-c', - getParentRoute: () => rootRouteImport, -} as any) -const SecDRoute = SecDRouteImport.update({ - id: '/sec-d', - path: '/sec-d', - getParentRoute: () => rootRouteImport, -} as any) -const SecERoute = SecERouteImport.update({ - id: '/sec-e', - path: '/sec-e', - getParentRoute: () => rootRouteImport, -} as any) -const SecFRoute = SecFRouteImport.update({ - id: '/sec-f', - path: '/sec-f', - getParentRoute: () => rootRouteImport, -} as any) -const marketingPricingRoute = marketingPricingRouteImport.update({ - id: '/(marketing)/pricing', - path: '/pricing', - getParentRoute: () => rootRouteImport, -} as any) -const marketingPromoRoute = marketingPromoRouteImport.update({ - id: '/(marketing)/promo', - path: '/promo', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutAlphaRoute = LayoutAlphaRouteImport.update({ - id: '/alpha', - path: '/alpha', - getParentRoute: () => LayoutRoute, -} as any) -const LayoutBetaRoute = LayoutBetaRouteImport.update({ - id: '/beta', - path: '/beta', - getParentRoute: () => LayoutRoute, -} as any) -const FilesSplatRoute = FilesSplatRouteImport.update({ - id: '/files/$', - path: '/files/$', - getParentRoute: () => rootRouteImport, -} as any) -const ReleaseVChar123versionChar125Route = - ReleaseVChar123versionChar125RouteImport.update({ - id: '/release/v{$version}', - path: '/release/v{$version}', - getParentRoute: () => rootRouteImport, - } as any) -const SecAIndexRoute = SecAIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecARoute, -} as any) -const SecAIdRoute = SecAIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecARoute, -} as any) -const SecAAboutRoute = SecAAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecARoute, -} as any) -const SecASettingsRoute = SecASettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecARoute, -} as any) -const SecBIndexRoute = SecBIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecBRoute, -} as any) -const SecBIdRoute = SecBIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecBRoute, -} as any) -const SecBAboutRoute = SecBAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecBRoute, -} as any) -const SecBSettingsRoute = SecBSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecBRoute, -} as any) -const SecCIndexRoute = SecCIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecCRoute, -} as any) -const SecCIdRoute = SecCIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecCRoute, -} as any) -const SecCAboutRoute = SecCAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecCRoute, -} as any) -const SecCSettingsRoute = SecCSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecCRoute, -} as any) -const SecDIndexRoute = SecDIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecDRoute, -} as any) -const SecDIdRoute = SecDIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecDRoute, -} as any) -const SecDAboutRoute = SecDAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecDRoute, -} as any) -const SecDSettingsRoute = SecDSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecDRoute, -} as any) -const SecEIndexRoute = SecEIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecERoute, -} as any) -const SecEIdRoute = SecEIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecERoute, -} as any) -const SecEAboutRoute = SecEAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecERoute, -} as any) -const SecESettingsRoute = SecESettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecERoute, -} 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 { - '/': typeof IndexRoute - '/sec-a': typeof SecARouteWithChildren - '/sec-b': typeof SecBRouteWithChildren - '/sec-c': typeof SecCRouteWithChildren - '/sec-d': typeof SecDRouteWithChildren - '/sec-e': typeof SecERouteWithChildren - '/sec-f': typeof SecFRouteWithChildren - '/pricing': typeof marketingPricingRoute - '/promo': typeof marketingPromoRoute - '/alpha': typeof LayoutAlphaRoute - '/beta': typeof LayoutBetaRoute - '/files/$': typeof FilesSplatRoute - '/release/v{$version}': typeof ReleaseVChar123versionChar125Route - '/sec-a/$id': typeof SecAIdRoute - '/sec-a/about': typeof SecAAboutRoute - '/sec-a/settings': typeof SecASettingsRoute - '/sec-b/$id': typeof SecBIdRoute - '/sec-b/about': typeof SecBAboutRoute - '/sec-b/settings': typeof SecBSettingsRoute - '/sec-c/$id': typeof SecCIdRoute - '/sec-c/about': typeof SecCAboutRoute - '/sec-c/settings': typeof SecCSettingsRoute - '/sec-d/$id': typeof SecDIdRoute - '/sec-d/about': typeof SecDAboutRoute - '/sec-d/settings': typeof SecDSettingsRoute - '/sec-e/$id': typeof SecEIdRoute - '/sec-e/about': typeof SecEAboutRoute - '/sec-e/settings': typeof SecESettingsRoute - '/sec-f/$id': typeof SecFIdRoute - '/sec-f/about': typeof SecFAboutRoute - '/sec-f/settings': typeof SecFSettingsRoute - '/sec-a/': typeof SecAIndexRoute - '/sec-b/': typeof SecBIndexRoute - '/sec-c/': typeof SecCIndexRoute - '/sec-d/': typeof SecDIndexRoute - '/sec-e/': typeof SecEIndexRoute - '/sec-f/': typeof SecFIndexRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/pricing': typeof marketingPricingRoute - '/promo': typeof marketingPromoRoute - '/alpha': typeof LayoutAlphaRoute - '/beta': typeof LayoutBetaRoute - '/files/$': typeof FilesSplatRoute - '/release/v{$version}': typeof ReleaseVChar123versionChar125Route - '/sec-a/$id': typeof SecAIdRoute - '/sec-a/about': typeof SecAAboutRoute - '/sec-a/settings': typeof SecASettingsRoute - '/sec-b/$id': typeof SecBIdRoute - '/sec-b/about': typeof SecBAboutRoute - '/sec-b/settings': typeof SecBSettingsRoute - '/sec-c/$id': typeof SecCIdRoute - '/sec-c/about': typeof SecCAboutRoute - '/sec-c/settings': typeof SecCSettingsRoute - '/sec-d/$id': typeof SecDIdRoute - '/sec-d/about': typeof SecDAboutRoute - '/sec-d/settings': typeof SecDSettingsRoute - '/sec-e/$id': typeof SecEIdRoute - '/sec-e/about': typeof SecEAboutRoute - '/sec-e/settings': typeof SecESettingsRoute - '/sec-f/$id': typeof SecFIdRoute - '/sec-f/about': typeof SecFAboutRoute - '/sec-f/settings': typeof SecFSettingsRoute - '/sec-a': typeof SecAIndexRoute - '/sec-b': typeof SecBIndexRoute - '/sec-c': typeof SecCIndexRoute - '/sec-d': typeof SecDIndexRoute - '/sec-e': typeof SecEIndexRoute - '/sec-f': typeof SecFIndexRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/_layout': typeof LayoutRouteWithChildren - '/sec-a': typeof SecARouteWithChildren - '/sec-b': typeof SecBRouteWithChildren - '/sec-c': typeof SecCRouteWithChildren - '/sec-d': typeof SecDRouteWithChildren - '/sec-e': typeof SecERouteWithChildren - '/sec-f': typeof SecFRouteWithChildren - '/(marketing)/pricing': typeof marketingPricingRoute - '/(marketing)/promo': typeof marketingPromoRoute - '/_layout/alpha': typeof LayoutAlphaRoute - '/_layout/beta': typeof LayoutBetaRoute - '/files/$': typeof FilesSplatRoute - '/release/v{$version}': typeof ReleaseVChar123versionChar125Route - '/sec-a/$id': typeof SecAIdRoute - '/sec-a/about': typeof SecAAboutRoute - '/sec-a/settings': typeof SecASettingsRoute - '/sec-b/$id': typeof SecBIdRoute - '/sec-b/about': typeof SecBAboutRoute - '/sec-b/settings': typeof SecBSettingsRoute - '/sec-c/$id': typeof SecCIdRoute - '/sec-c/about': typeof SecCAboutRoute - '/sec-c/settings': typeof SecCSettingsRoute - '/sec-d/$id': typeof SecDIdRoute - '/sec-d/about': typeof SecDAboutRoute - '/sec-d/settings': typeof SecDSettingsRoute - '/sec-e/$id': typeof SecEIdRoute - '/sec-e/about': typeof SecEAboutRoute - '/sec-e/settings': typeof SecESettingsRoute - '/sec-f/$id': typeof SecFIdRoute - '/sec-f/about': typeof SecFAboutRoute - '/sec-f/settings': typeof SecFSettingsRoute - '/sec-a/': typeof SecAIndexRoute - '/sec-b/': typeof SecBIndexRoute - '/sec-c/': typeof SecCIndexRoute - '/sec-d/': typeof SecDIndexRoute - '/sec-e/': typeof SecEIndexRoute - '/sec-f/': typeof SecFIndexRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/sec-a' - | '/sec-b' - | '/sec-c' - | '/sec-d' - | '/sec-e' - | '/sec-f' - | '/pricing' - | '/promo' - | '/alpha' - | '/beta' - | '/files/$' - | '/release/v{$version}' - | '/sec-a/$id' - | '/sec-a/about' - | '/sec-a/settings' - | '/sec-b/$id' - | '/sec-b/about' - | '/sec-b/settings' - | '/sec-c/$id' - | '/sec-c/about' - | '/sec-c/settings' - | '/sec-d/$id' - | '/sec-d/about' - | '/sec-d/settings' - | '/sec-e/$id' - | '/sec-e/about' - | '/sec-e/settings' - | '/sec-f/$id' - | '/sec-f/about' - | '/sec-f/settings' - | '/sec-a/' - | '/sec-b/' - | '/sec-c/' - | '/sec-d/' - | '/sec-e/' - | '/sec-f/' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/pricing' - | '/promo' - | '/alpha' - | '/beta' - | '/files/$' - | '/release/v{$version}' - | '/sec-a/$id' - | '/sec-a/about' - | '/sec-a/settings' - | '/sec-b/$id' - | '/sec-b/about' - | '/sec-b/settings' - | '/sec-c/$id' - | '/sec-c/about' - | '/sec-c/settings' - | '/sec-d/$id' - | '/sec-d/about' - | '/sec-d/settings' - | '/sec-e/$id' - | '/sec-e/about' - | '/sec-e/settings' - | '/sec-f/$id' - | '/sec-f/about' - | '/sec-f/settings' - | '/sec-a' - | '/sec-b' - | '/sec-c' - | '/sec-d' - | '/sec-e' - | '/sec-f' - id: - | '__root__' - | '/' - | '/_layout' - | '/sec-a' - | '/sec-b' - | '/sec-c' - | '/sec-d' - | '/sec-e' - | '/sec-f' - | '/(marketing)/pricing' - | '/(marketing)/promo' - | '/_layout/alpha' - | '/_layout/beta' - | '/files/$' - | '/release/v{$version}' - | '/sec-a/$id' - | '/sec-a/about' - | '/sec-a/settings' - | '/sec-b/$id' - | '/sec-b/about' - | '/sec-b/settings' - | '/sec-c/$id' - | '/sec-c/about' - | '/sec-c/settings' - | '/sec-d/$id' - | '/sec-d/about' - | '/sec-d/settings' - | '/sec-e/$id' - | '/sec-e/about' - | '/sec-e/settings' - | '/sec-f/$id' - | '/sec-f/about' - | '/sec-f/settings' - | '/sec-a/' - | '/sec-b/' - | '/sec-c/' - | '/sec-d/' - | '/sec-e/' - | '/sec-f/' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - LayoutRoute: typeof LayoutRouteWithChildren - SecARoute: typeof SecARouteWithChildren - SecBRoute: typeof SecBRouteWithChildren - SecCRoute: typeof SecCRouteWithChildren - SecDRoute: typeof SecDRouteWithChildren - SecERoute: typeof SecERouteWithChildren - SecFRoute: typeof SecFRouteWithChildren - marketingPricingRoute: typeof marketingPricingRoute - marketingPromoRoute: typeof marketingPromoRoute - FilesSplatRoute: typeof FilesSplatRoute - ReleaseVChar123versionChar125Route: typeof ReleaseVChar123versionChar125Route -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout': { - id: '/_layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-a': { - id: '/sec-a' - path: '/sec-a' - fullPath: '/sec-a' - preLoaderRoute: typeof SecARouteImport - parentRoute: typeof rootRouteImport - } - '/sec-b': { - id: '/sec-b' - path: '/sec-b' - fullPath: '/sec-b' - preLoaderRoute: typeof SecBRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-c': { - id: '/sec-c' - path: '/sec-c' - fullPath: '/sec-c' - preLoaderRoute: typeof SecCRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-d': { - id: '/sec-d' - path: '/sec-d' - fullPath: '/sec-d' - preLoaderRoute: typeof SecDRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-e': { - id: '/sec-e' - path: '/sec-e' - fullPath: '/sec-e' - preLoaderRoute: typeof SecERouteImport - parentRoute: typeof rootRouteImport - } - '/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/' - path: '/' - fullPath: '/sec-a/' - preLoaderRoute: typeof SecAIndexRouteImport - parentRoute: typeof SecARoute - } - '/sec-a/$id': { - id: '/sec-a/$id' - path: '/$id' - fullPath: '/sec-a/$id' - preLoaderRoute: typeof SecAIdRouteImport - parentRoute: typeof SecARoute - } - '/sec-a/about': { - id: '/sec-a/about' - path: '/about' - fullPath: '/sec-a/about' - preLoaderRoute: typeof SecAAboutRouteImport - parentRoute: typeof SecARoute - } - '/sec-a/settings': { - id: '/sec-a/settings' - path: '/settings' - fullPath: '/sec-a/settings' - preLoaderRoute: typeof SecASettingsRouteImport - parentRoute: typeof SecARoute - } - '/sec-b/': { - id: '/sec-b/' - path: '/' - fullPath: '/sec-b/' - preLoaderRoute: typeof SecBIndexRouteImport - parentRoute: typeof SecBRoute - } - '/sec-b/$id': { - id: '/sec-b/$id' - path: '/$id' - fullPath: '/sec-b/$id' - preLoaderRoute: typeof SecBIdRouteImport - parentRoute: typeof SecBRoute - } - '/sec-b/about': { - id: '/sec-b/about' - path: '/about' - fullPath: '/sec-b/about' - preLoaderRoute: typeof SecBAboutRouteImport - parentRoute: typeof SecBRoute - } - '/sec-b/settings': { - id: '/sec-b/settings' - path: '/settings' - fullPath: '/sec-b/settings' - preLoaderRoute: typeof SecBSettingsRouteImport - parentRoute: typeof SecBRoute - } - '/sec-c/': { - id: '/sec-c/' - path: '/' - fullPath: '/sec-c/' - preLoaderRoute: typeof SecCIndexRouteImport - parentRoute: typeof SecCRoute - } - '/sec-c/$id': { - id: '/sec-c/$id' - path: '/$id' - fullPath: '/sec-c/$id' - preLoaderRoute: typeof SecCIdRouteImport - parentRoute: typeof SecCRoute - } - '/sec-c/about': { - id: '/sec-c/about' - path: '/about' - fullPath: '/sec-c/about' - preLoaderRoute: typeof SecCAboutRouteImport - parentRoute: typeof SecCRoute - } - '/sec-c/settings': { - id: '/sec-c/settings' - path: '/settings' - fullPath: '/sec-c/settings' - preLoaderRoute: typeof SecCSettingsRouteImport - parentRoute: typeof SecCRoute - } - '/sec-d/': { - id: '/sec-d/' - path: '/' - fullPath: '/sec-d/' - preLoaderRoute: typeof SecDIndexRouteImport - parentRoute: typeof SecDRoute - } - '/sec-d/$id': { - id: '/sec-d/$id' - path: '/$id' - fullPath: '/sec-d/$id' - preLoaderRoute: typeof SecDIdRouteImport - parentRoute: typeof SecDRoute - } - '/sec-d/about': { - id: '/sec-d/about' - path: '/about' - fullPath: '/sec-d/about' - preLoaderRoute: typeof SecDAboutRouteImport - parentRoute: typeof SecDRoute - } - '/sec-d/settings': { - id: '/sec-d/settings' - path: '/settings' - fullPath: '/sec-d/settings' - preLoaderRoute: typeof SecDSettingsRouteImport - parentRoute: typeof SecDRoute - } - '/sec-e/': { - id: '/sec-e/' - path: '/' - fullPath: '/sec-e/' - preLoaderRoute: typeof SecEIndexRouteImport - parentRoute: typeof SecERoute - } - '/sec-e/$id': { - id: '/sec-e/$id' - path: '/$id' - fullPath: '/sec-e/$id' - preLoaderRoute: typeof SecEIdRouteImport - parentRoute: typeof SecERoute - } - '/sec-e/about': { - id: '/sec-e/about' - path: '/about' - fullPath: '/sec-e/about' - preLoaderRoute: typeof SecEAboutRouteImport - parentRoute: typeof SecERoute - } - '/sec-e/settings': { - id: '/sec-e/settings' - path: '/settings' - fullPath: '/sec-e/settings' - preLoaderRoute: typeof SecESettingsRouteImport - parentRoute: typeof SecERoute - } - '/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 - } - } -} - -interface LayoutRouteChildren { - LayoutAlphaRoute: typeof LayoutAlphaRoute - LayoutBetaRoute: typeof LayoutBetaRoute -} - -const LayoutRouteChildren: LayoutRouteChildren = { - LayoutAlphaRoute: LayoutAlphaRoute, - LayoutBetaRoute: LayoutBetaRoute, -} - -const LayoutRouteWithChildren = - LayoutRoute._addFileChildren(LayoutRouteChildren) - -interface SecARouteChildren { - SecAIdRoute: typeof SecAIdRoute - SecAAboutRoute: typeof SecAAboutRoute - SecASettingsRoute: typeof SecASettingsRoute - SecAIndexRoute: typeof SecAIndexRoute -} - -const SecARouteChildren: SecARouteChildren = { - SecAIdRoute: SecAIdRoute, - SecAAboutRoute: SecAAboutRoute, - SecASettingsRoute: SecASettingsRoute, - SecAIndexRoute: SecAIndexRoute, -} - -const SecARouteWithChildren = SecARoute._addFileChildren(SecARouteChildren) - -interface SecBRouteChildren { - SecBIdRoute: typeof SecBIdRoute - SecBAboutRoute: typeof SecBAboutRoute - SecBSettingsRoute: typeof SecBSettingsRoute - SecBIndexRoute: typeof SecBIndexRoute -} - -const SecBRouteChildren: SecBRouteChildren = { - SecBIdRoute: SecBIdRoute, - SecBAboutRoute: SecBAboutRoute, - SecBSettingsRoute: SecBSettingsRoute, - SecBIndexRoute: SecBIndexRoute, -} - -const SecBRouteWithChildren = SecBRoute._addFileChildren(SecBRouteChildren) - -interface SecCRouteChildren { - SecCIdRoute: typeof SecCIdRoute - SecCAboutRoute: typeof SecCAboutRoute - SecCSettingsRoute: typeof SecCSettingsRoute - SecCIndexRoute: typeof SecCIndexRoute -} - -const SecCRouteChildren: SecCRouteChildren = { - SecCIdRoute: SecCIdRoute, - SecCAboutRoute: SecCAboutRoute, - SecCSettingsRoute: SecCSettingsRoute, - SecCIndexRoute: SecCIndexRoute, -} - -const SecCRouteWithChildren = SecCRoute._addFileChildren(SecCRouteChildren) - -interface SecDRouteChildren { - SecDIdRoute: typeof SecDIdRoute - SecDAboutRoute: typeof SecDAboutRoute - SecDSettingsRoute: typeof SecDSettingsRoute - SecDIndexRoute: typeof SecDIndexRoute -} - -const SecDRouteChildren: SecDRouteChildren = { - SecDIdRoute: SecDIdRoute, - SecDAboutRoute: SecDAboutRoute, - SecDSettingsRoute: SecDSettingsRoute, - SecDIndexRoute: SecDIndexRoute, -} - -const SecDRouteWithChildren = SecDRoute._addFileChildren(SecDRouteChildren) - -interface SecERouteChildren { - SecEIdRoute: typeof SecEIdRoute - SecEAboutRoute: typeof SecEAboutRoute - SecESettingsRoute: typeof SecESettingsRoute - SecEIndexRoute: typeof SecEIndexRoute -} - -const SecERouteChildren: SecERouteChildren = { - SecEIdRoute: SecEIdRoute, - SecEAboutRoute: SecEAboutRoute, - SecESettingsRoute: SecESettingsRoute, - SecEIndexRoute: SecEIndexRoute, -} - -const SecERouteWithChildren = SecERoute._addFileChildren(SecERouteChildren) - -interface SecFRouteChildren { - SecFIdRoute: typeof SecFIdRoute - SecFAboutRoute: typeof SecFAboutRoute - SecFSettingsRoute: typeof SecFSettingsRoute - SecFIndexRoute: typeof SecFIndexRoute -} - -const SecFRouteChildren: SecFRouteChildren = { - SecFIdRoute: SecFIdRoute, - SecFAboutRoute: SecFAboutRoute, - SecFSettingsRoute: SecFSettingsRoute, - SecFIndexRoute: SecFIndexRoute, -} - -const SecFRouteWithChildren = SecFRoute._addFileChildren(SecFRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - LayoutRoute: LayoutRouteWithChildren, - SecARoute: SecARouteWithChildren, - SecBRoute: SecBRouteWithChildren, - SecCRoute: SecCRouteWithChildren, - SecDRoute: SecDRouteWithChildren, - SecERoute: SecERouteWithChildren, - SecFRoute: SecFRouteWithChildren, - marketingPricingRoute: marketingPricingRoute, - marketingPromoRoute: marketingPromoRoute, - FilesSplatRoute: FilesSplatRoute, - ReleaseVChar123versionChar125Route: ReleaseVChar123versionChar125Route, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/(marketing)/pricing.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/(marketing)/pricing.tsx deleted file mode 100644 index 0965507de6..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/(marketing)/pricing.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/(marketing)/pricing')({ - component: Page, -}) - -function Page() { - return
pricing
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/(marketing)/promo.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/(marketing)/promo.tsx deleted file mode 100644 index 220bd06a68..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/(marketing)/promo.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/(marketing)/promo')({ - component: Page, -}) - -function Page() { - return
promo
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/__root.tsx deleted file mode 100644 index a4e4113d9a..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/__root.tsx +++ /dev/null @@ -1,58 +0,0 @@ -import { Link, Outlet, createRootRoute } from '@tanstack/solid-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - <> - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.alpha.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.alpha.tsx deleted file mode 100644 index 234b8488a9..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.alpha.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/_layout/alpha')({ - component: Page, -}) - -function Page() { - return
alpha
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.beta.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.beta.tsx deleted file mode 100644 index 39bc716efa..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.beta.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/_layout/beta')({ - component: Page, -}) - -function Page() { - return
beta
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.tsx deleted file mode 100644 index f1e499d3b3..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/_layout')({ - component: Layout, -}) - -function Layout() { - return -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/files.$.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/files.$.tsx deleted file mode 100644 index 47b1a5eea9..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/files.$.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/files/$')({ - component: Page, -}) - -function Page() { - const params = Route.useParams() - - return
{`files:${params()._splat}`}
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/index.tsx deleted file mode 100644 index 25b1c03c1a..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/')({ - component: Page, -}) - -function Page() { - return
home
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/release.v{$version}.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/release.v{$version}.tsx deleted file mode 100644 index 0dbcee35ca..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/release.v{$version}.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/release/v{$version}')({ - component: Page, -}) - -function Page() { - const params = Route.useParams() - - return
{`release:${params().version}`}
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.$id.tsx deleted file mode 100644 index 18731a2844..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-a/$id')({ - component: Page, -}) - -function Page() { - const params = Route.useParams() - - return
{`sec-a:${params().id}`}
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.about.tsx deleted file mode 100644 index 1699360a1c..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.about.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-a/about')({ - component: Page, -}) - -function Page() { - return
sec-a:about
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.index.tsx deleted file mode 100644 index e71e525d07..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-a/')({ - component: Page, -}) - -function Page() { - return
sec-a:index
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.settings.tsx deleted file mode 100644 index 49d470190e..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.settings.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-a/settings')({ - component: Page, -}) - -function Page() { - return
sec-a:settings
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.tsx deleted file mode 100644 index 2861169fb9..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-a')({ - component: Layout, -}) - -function Layout() { - return -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.$id.tsx deleted file mode 100644 index 86fe71d7c0..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-b/$id')({ - component: Page, -}) - -function Page() { - const params = Route.useParams() - - return
{`sec-b:${params().id}`}
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.about.tsx deleted file mode 100644 index 586b829cd0..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.about.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-b/about')({ - component: Page, -}) - -function Page() { - return
sec-b:about
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.index.tsx deleted file mode 100644 index 7098416658..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-b/')({ - component: Page, -}) - -function Page() { - return
sec-b:index
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.settings.tsx deleted file mode 100644 index c2e0f47650..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.settings.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-b/settings')({ - component: Page, -}) - -function Page() { - return
sec-b:settings
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.tsx deleted file mode 100644 index f2905da9ca..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-b')({ - component: Layout, -}) - -function Layout() { - return -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.$id.tsx deleted file mode 100644 index 3e07e8033a..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-c/$id')({ - component: Page, -}) - -function Page() { - const params = Route.useParams() - - return
{`sec-c:${params().id}`}
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.about.tsx deleted file mode 100644 index 86ed5043a3..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.about.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-c/about')({ - component: Page, -}) - -function Page() { - return
sec-c:about
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.index.tsx deleted file mode 100644 index aa9ed2dc6c..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-c/')({ - component: Page, -}) - -function Page() { - return
sec-c:index
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.settings.tsx deleted file mode 100644 index d0dd3e952c..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.settings.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-c/settings')({ - component: Page, -}) - -function Page() { - return
sec-c:settings
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.tsx deleted file mode 100644 index fa53825238..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-c')({ - component: Layout, -}) - -function Layout() { - return -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.$id.tsx deleted file mode 100644 index 3722012d7c..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-d/$id')({ - component: Page, -}) - -function Page() { - const params = Route.useParams() - - return
{`sec-d:${params().id}`}
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.about.tsx deleted file mode 100644 index 860d2b9e5b..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.about.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-d/about')({ - component: Page, -}) - -function Page() { - return
sec-d:about
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.index.tsx deleted file mode 100644 index ec7b8eaf2c..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-d/')({ - component: Page, -}) - -function Page() { - return
sec-d:index
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.settings.tsx deleted file mode 100644 index d83e3885fd..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.settings.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-d/settings')({ - component: Page, -}) - -function Page() { - return
sec-d:settings
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.tsx deleted file mode 100644 index e71391e2a3..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-d')({ - component: Layout, -}) - -function Layout() { - return -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.$id.tsx deleted file mode 100644 index e58d9d77ac..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-e/$id')({ - component: Page, -}) - -function Page() { - const params = Route.useParams() - - return
{`sec-e:${params().id}`}
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.about.tsx deleted file mode 100644 index 3ef4d2c763..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.about.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-e/about')({ - component: Page, -}) - -function Page() { - return
sec-e:about
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.index.tsx deleted file mode 100644 index 88bf7ca271..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-e/')({ - component: Page, -}) - -function Page() { - return
sec-e:index
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.settings.tsx deleted file mode 100644 index 8a9945926d..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.settings.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-e/settings')({ - component: Page, -}) - -function Page() { - return
sec-e:settings
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.tsx deleted file mode 100644 index 8b5ef24519..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-e')({ - component: Layout, -}) - -function Layout() { - return -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.$id.tsx deleted file mode 100644 index 2b81ef96ff..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-f/$id')({ - component: Page, -}) - -function Page() { - const params = Route.useParams() - - return
{`sec-f:${params().id}`}
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.about.tsx deleted file mode 100644 index 1c4e3a5474..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.about.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-f/about')({ - component: Page, -}) - -function Page() { - return
sec-f:about
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.index.tsx deleted file mode 100644 index 65803ee848..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-f/')({ - component: Page, -}) - -function Page() { - return
sec-f:index
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.settings.tsx deleted file mode 100644 index 5761138262..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.settings.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-f/settings')({ - component: Page, -}) - -function Page() { - return
sec-f:settings
-} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.tsx deleted file mode 100644 index c7f25eecdd..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/sec-f')({ - component: Layout, -}) - -function Layout() { - return -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/tsconfig.json b/benchmarks/client-nav/scenarios/route-tree-scale/solid/tsconfig.json deleted file mode 100644 index 98d76ad6b8..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/vite.config.ts b/benchmarks/client-nav/scenarios/route-tree-scale/solid/vite.config.ts deleted file mode 100644 index 542ede131b..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/vite.config.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import solid from 'vite-plugin-solid' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'solid', - // Real file-based apps code-split by default; this scenario keeps it on - // so navigations also exercise lazy route-chunk resolution. - autoCodeSplitting: true, - 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 route-tree-scale (solid)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/project.json b/benchmarks/client-nav/scenarios/route-tree-scale/vue/project.json deleted file mode 100644 index f613070038..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-route-tree-scale-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/route-tree-scale/vue/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/setup.ts b/benchmarks/client-nav/scenarios/route-tree-scale/vue/setup.ts deleted file mode 100644 index 97b74b3892..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, steps } 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, - assertAfterStep: assertStepResult, - }) -} 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 deleted file mode 100644 index 331e8e008f..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-route-tree-scale', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-route-tree-scale 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/route-tree-scale/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/route-tree-scale/vue/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/main.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/main.tsx deleted file mode 100644 index cae9b54f1d..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/main.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import * as Vue from 'vue' -import { RouterProvider, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} - -export function mountTestApp(container: HTMLElement, history: RouterHistory) { - const router = createTestRouter(history) - - const component = - const app = Vue.createApp({ - render: () => component, - }) - - app.mount(container) - - return { - router, - unmount() { - app.unmount() - }, - } -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routeTree.gen.ts deleted file mode 100644 index a12f981bb4..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,881 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', - getParentRoute: () => rootRouteImport, -} as any) -const SecARoute = SecARouteImport.update({ - id: '/sec-a', - path: '/sec-a', - getParentRoute: () => rootRouteImport, -} as any) -const SecBRoute = SecBRouteImport.update({ - id: '/sec-b', - path: '/sec-b', - getParentRoute: () => rootRouteImport, -} as any) -const SecCRoute = SecCRouteImport.update({ - id: '/sec-c', - path: '/sec-c', - getParentRoute: () => rootRouteImport, -} as any) -const SecDRoute = SecDRouteImport.update({ - id: '/sec-d', - path: '/sec-d', - getParentRoute: () => rootRouteImport, -} as any) -const SecERoute = SecERouteImport.update({ - id: '/sec-e', - path: '/sec-e', - getParentRoute: () => rootRouteImport, -} as any) -const SecFRoute = SecFRouteImport.update({ - id: '/sec-f', - path: '/sec-f', - getParentRoute: () => rootRouteImport, -} as any) -const marketingPricingRoute = marketingPricingRouteImport.update({ - id: '/(marketing)/pricing', - path: '/pricing', - getParentRoute: () => rootRouteImport, -} as any) -const marketingPromoRoute = marketingPromoRouteImport.update({ - id: '/(marketing)/promo', - path: '/promo', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutAlphaRoute = LayoutAlphaRouteImport.update({ - id: '/alpha', - path: '/alpha', - getParentRoute: () => LayoutRoute, -} as any) -const LayoutBetaRoute = LayoutBetaRouteImport.update({ - id: '/beta', - path: '/beta', - getParentRoute: () => LayoutRoute, -} as any) -const FilesSplatRoute = FilesSplatRouteImport.update({ - id: '/files/$', - path: '/files/$', - getParentRoute: () => rootRouteImport, -} as any) -const ReleaseVChar123versionChar125Route = - ReleaseVChar123versionChar125RouteImport.update({ - id: '/release/v{$version}', - path: '/release/v{$version}', - getParentRoute: () => rootRouteImport, - } as any) -const SecAIndexRoute = SecAIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecARoute, -} as any) -const SecAIdRoute = SecAIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecARoute, -} as any) -const SecAAboutRoute = SecAAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecARoute, -} as any) -const SecASettingsRoute = SecASettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecARoute, -} as any) -const SecBIndexRoute = SecBIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecBRoute, -} as any) -const SecBIdRoute = SecBIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecBRoute, -} as any) -const SecBAboutRoute = SecBAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecBRoute, -} as any) -const SecBSettingsRoute = SecBSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecBRoute, -} as any) -const SecCIndexRoute = SecCIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecCRoute, -} as any) -const SecCIdRoute = SecCIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecCRoute, -} as any) -const SecCAboutRoute = SecCAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecCRoute, -} as any) -const SecCSettingsRoute = SecCSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecCRoute, -} as any) -const SecDIndexRoute = SecDIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecDRoute, -} as any) -const SecDIdRoute = SecDIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecDRoute, -} as any) -const SecDAboutRoute = SecDAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecDRoute, -} as any) -const SecDSettingsRoute = SecDSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecDRoute, -} as any) -const SecEIndexRoute = SecEIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecERoute, -} as any) -const SecEIdRoute = SecEIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecERoute, -} as any) -const SecEAboutRoute = SecEAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecERoute, -} as any) -const SecESettingsRoute = SecESettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecERoute, -} 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 { - '/': typeof IndexRoute - '/sec-a': typeof SecARouteWithChildren - '/sec-b': typeof SecBRouteWithChildren - '/sec-c': typeof SecCRouteWithChildren - '/sec-d': typeof SecDRouteWithChildren - '/sec-e': typeof SecERouteWithChildren - '/sec-f': typeof SecFRouteWithChildren - '/pricing': typeof marketingPricingRoute - '/promo': typeof marketingPromoRoute - '/alpha': typeof LayoutAlphaRoute - '/beta': typeof LayoutBetaRoute - '/files/$': typeof FilesSplatRoute - '/release/v{$version}': typeof ReleaseVChar123versionChar125Route - '/sec-a/$id': typeof SecAIdRoute - '/sec-a/about': typeof SecAAboutRoute - '/sec-a/settings': typeof SecASettingsRoute - '/sec-b/$id': typeof SecBIdRoute - '/sec-b/about': typeof SecBAboutRoute - '/sec-b/settings': typeof SecBSettingsRoute - '/sec-c/$id': typeof SecCIdRoute - '/sec-c/about': typeof SecCAboutRoute - '/sec-c/settings': typeof SecCSettingsRoute - '/sec-d/$id': typeof SecDIdRoute - '/sec-d/about': typeof SecDAboutRoute - '/sec-d/settings': typeof SecDSettingsRoute - '/sec-e/$id': typeof SecEIdRoute - '/sec-e/about': typeof SecEAboutRoute - '/sec-e/settings': typeof SecESettingsRoute - '/sec-f/$id': typeof SecFIdRoute - '/sec-f/about': typeof SecFAboutRoute - '/sec-f/settings': typeof SecFSettingsRoute - '/sec-a/': typeof SecAIndexRoute - '/sec-b/': typeof SecBIndexRoute - '/sec-c/': typeof SecCIndexRoute - '/sec-d/': typeof SecDIndexRoute - '/sec-e/': typeof SecEIndexRoute - '/sec-f/': typeof SecFIndexRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/pricing': typeof marketingPricingRoute - '/promo': typeof marketingPromoRoute - '/alpha': typeof LayoutAlphaRoute - '/beta': typeof LayoutBetaRoute - '/files/$': typeof FilesSplatRoute - '/release/v{$version}': typeof ReleaseVChar123versionChar125Route - '/sec-a/$id': typeof SecAIdRoute - '/sec-a/about': typeof SecAAboutRoute - '/sec-a/settings': typeof SecASettingsRoute - '/sec-b/$id': typeof SecBIdRoute - '/sec-b/about': typeof SecBAboutRoute - '/sec-b/settings': typeof SecBSettingsRoute - '/sec-c/$id': typeof SecCIdRoute - '/sec-c/about': typeof SecCAboutRoute - '/sec-c/settings': typeof SecCSettingsRoute - '/sec-d/$id': typeof SecDIdRoute - '/sec-d/about': typeof SecDAboutRoute - '/sec-d/settings': typeof SecDSettingsRoute - '/sec-e/$id': typeof SecEIdRoute - '/sec-e/about': typeof SecEAboutRoute - '/sec-e/settings': typeof SecESettingsRoute - '/sec-f/$id': typeof SecFIdRoute - '/sec-f/about': typeof SecFAboutRoute - '/sec-f/settings': typeof SecFSettingsRoute - '/sec-a': typeof SecAIndexRoute - '/sec-b': typeof SecBIndexRoute - '/sec-c': typeof SecCIndexRoute - '/sec-d': typeof SecDIndexRoute - '/sec-e': typeof SecEIndexRoute - '/sec-f': typeof SecFIndexRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/_layout': typeof LayoutRouteWithChildren - '/sec-a': typeof SecARouteWithChildren - '/sec-b': typeof SecBRouteWithChildren - '/sec-c': typeof SecCRouteWithChildren - '/sec-d': typeof SecDRouteWithChildren - '/sec-e': typeof SecERouteWithChildren - '/sec-f': typeof SecFRouteWithChildren - '/(marketing)/pricing': typeof marketingPricingRoute - '/(marketing)/promo': typeof marketingPromoRoute - '/_layout/alpha': typeof LayoutAlphaRoute - '/_layout/beta': typeof LayoutBetaRoute - '/files/$': typeof FilesSplatRoute - '/release/v{$version}': typeof ReleaseVChar123versionChar125Route - '/sec-a/$id': typeof SecAIdRoute - '/sec-a/about': typeof SecAAboutRoute - '/sec-a/settings': typeof SecASettingsRoute - '/sec-b/$id': typeof SecBIdRoute - '/sec-b/about': typeof SecBAboutRoute - '/sec-b/settings': typeof SecBSettingsRoute - '/sec-c/$id': typeof SecCIdRoute - '/sec-c/about': typeof SecCAboutRoute - '/sec-c/settings': typeof SecCSettingsRoute - '/sec-d/$id': typeof SecDIdRoute - '/sec-d/about': typeof SecDAboutRoute - '/sec-d/settings': typeof SecDSettingsRoute - '/sec-e/$id': typeof SecEIdRoute - '/sec-e/about': typeof SecEAboutRoute - '/sec-e/settings': typeof SecESettingsRoute - '/sec-f/$id': typeof SecFIdRoute - '/sec-f/about': typeof SecFAboutRoute - '/sec-f/settings': typeof SecFSettingsRoute - '/sec-a/': typeof SecAIndexRoute - '/sec-b/': typeof SecBIndexRoute - '/sec-c/': typeof SecCIndexRoute - '/sec-d/': typeof SecDIndexRoute - '/sec-e/': typeof SecEIndexRoute - '/sec-f/': typeof SecFIndexRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/sec-a' - | '/sec-b' - | '/sec-c' - | '/sec-d' - | '/sec-e' - | '/sec-f' - | '/pricing' - | '/promo' - | '/alpha' - | '/beta' - | '/files/$' - | '/release/v{$version}' - | '/sec-a/$id' - | '/sec-a/about' - | '/sec-a/settings' - | '/sec-b/$id' - | '/sec-b/about' - | '/sec-b/settings' - | '/sec-c/$id' - | '/sec-c/about' - | '/sec-c/settings' - | '/sec-d/$id' - | '/sec-d/about' - | '/sec-d/settings' - | '/sec-e/$id' - | '/sec-e/about' - | '/sec-e/settings' - | '/sec-f/$id' - | '/sec-f/about' - | '/sec-f/settings' - | '/sec-a/' - | '/sec-b/' - | '/sec-c/' - | '/sec-d/' - | '/sec-e/' - | '/sec-f/' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/pricing' - | '/promo' - | '/alpha' - | '/beta' - | '/files/$' - | '/release/v{$version}' - | '/sec-a/$id' - | '/sec-a/about' - | '/sec-a/settings' - | '/sec-b/$id' - | '/sec-b/about' - | '/sec-b/settings' - | '/sec-c/$id' - | '/sec-c/about' - | '/sec-c/settings' - | '/sec-d/$id' - | '/sec-d/about' - | '/sec-d/settings' - | '/sec-e/$id' - | '/sec-e/about' - | '/sec-e/settings' - | '/sec-f/$id' - | '/sec-f/about' - | '/sec-f/settings' - | '/sec-a' - | '/sec-b' - | '/sec-c' - | '/sec-d' - | '/sec-e' - | '/sec-f' - id: - | '__root__' - | '/' - | '/_layout' - | '/sec-a' - | '/sec-b' - | '/sec-c' - | '/sec-d' - | '/sec-e' - | '/sec-f' - | '/(marketing)/pricing' - | '/(marketing)/promo' - | '/_layout/alpha' - | '/_layout/beta' - | '/files/$' - | '/release/v{$version}' - | '/sec-a/$id' - | '/sec-a/about' - | '/sec-a/settings' - | '/sec-b/$id' - | '/sec-b/about' - | '/sec-b/settings' - | '/sec-c/$id' - | '/sec-c/about' - | '/sec-c/settings' - | '/sec-d/$id' - | '/sec-d/about' - | '/sec-d/settings' - | '/sec-e/$id' - | '/sec-e/about' - | '/sec-e/settings' - | '/sec-f/$id' - | '/sec-f/about' - | '/sec-f/settings' - | '/sec-a/' - | '/sec-b/' - | '/sec-c/' - | '/sec-d/' - | '/sec-e/' - | '/sec-f/' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - LayoutRoute: typeof LayoutRouteWithChildren - SecARoute: typeof SecARouteWithChildren - SecBRoute: typeof SecBRouteWithChildren - SecCRoute: typeof SecCRouteWithChildren - SecDRoute: typeof SecDRouteWithChildren - SecERoute: typeof SecERouteWithChildren - SecFRoute: typeof SecFRouteWithChildren - marketingPricingRoute: typeof marketingPricingRoute - marketingPromoRoute: typeof marketingPromoRoute - FilesSplatRoute: typeof FilesSplatRoute - ReleaseVChar123versionChar125Route: typeof ReleaseVChar123versionChar125Route -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout': { - id: '/_layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-a': { - id: '/sec-a' - path: '/sec-a' - fullPath: '/sec-a' - preLoaderRoute: typeof SecARouteImport - parentRoute: typeof rootRouteImport - } - '/sec-b': { - id: '/sec-b' - path: '/sec-b' - fullPath: '/sec-b' - preLoaderRoute: typeof SecBRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-c': { - id: '/sec-c' - path: '/sec-c' - fullPath: '/sec-c' - preLoaderRoute: typeof SecCRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-d': { - id: '/sec-d' - path: '/sec-d' - fullPath: '/sec-d' - preLoaderRoute: typeof SecDRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-e': { - id: '/sec-e' - path: '/sec-e' - fullPath: '/sec-e' - preLoaderRoute: typeof SecERouteImport - parentRoute: typeof rootRouteImport - } - '/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/' - path: '/' - fullPath: '/sec-a/' - preLoaderRoute: typeof SecAIndexRouteImport - parentRoute: typeof SecARoute - } - '/sec-a/$id': { - id: '/sec-a/$id' - path: '/$id' - fullPath: '/sec-a/$id' - preLoaderRoute: typeof SecAIdRouteImport - parentRoute: typeof SecARoute - } - '/sec-a/about': { - id: '/sec-a/about' - path: '/about' - fullPath: '/sec-a/about' - preLoaderRoute: typeof SecAAboutRouteImport - parentRoute: typeof SecARoute - } - '/sec-a/settings': { - id: '/sec-a/settings' - path: '/settings' - fullPath: '/sec-a/settings' - preLoaderRoute: typeof SecASettingsRouteImport - parentRoute: typeof SecARoute - } - '/sec-b/': { - id: '/sec-b/' - path: '/' - fullPath: '/sec-b/' - preLoaderRoute: typeof SecBIndexRouteImport - parentRoute: typeof SecBRoute - } - '/sec-b/$id': { - id: '/sec-b/$id' - path: '/$id' - fullPath: '/sec-b/$id' - preLoaderRoute: typeof SecBIdRouteImport - parentRoute: typeof SecBRoute - } - '/sec-b/about': { - id: '/sec-b/about' - path: '/about' - fullPath: '/sec-b/about' - preLoaderRoute: typeof SecBAboutRouteImport - parentRoute: typeof SecBRoute - } - '/sec-b/settings': { - id: '/sec-b/settings' - path: '/settings' - fullPath: '/sec-b/settings' - preLoaderRoute: typeof SecBSettingsRouteImport - parentRoute: typeof SecBRoute - } - '/sec-c/': { - id: '/sec-c/' - path: '/' - fullPath: '/sec-c/' - preLoaderRoute: typeof SecCIndexRouteImport - parentRoute: typeof SecCRoute - } - '/sec-c/$id': { - id: '/sec-c/$id' - path: '/$id' - fullPath: '/sec-c/$id' - preLoaderRoute: typeof SecCIdRouteImport - parentRoute: typeof SecCRoute - } - '/sec-c/about': { - id: '/sec-c/about' - path: '/about' - fullPath: '/sec-c/about' - preLoaderRoute: typeof SecCAboutRouteImport - parentRoute: typeof SecCRoute - } - '/sec-c/settings': { - id: '/sec-c/settings' - path: '/settings' - fullPath: '/sec-c/settings' - preLoaderRoute: typeof SecCSettingsRouteImport - parentRoute: typeof SecCRoute - } - '/sec-d/': { - id: '/sec-d/' - path: '/' - fullPath: '/sec-d/' - preLoaderRoute: typeof SecDIndexRouteImport - parentRoute: typeof SecDRoute - } - '/sec-d/$id': { - id: '/sec-d/$id' - path: '/$id' - fullPath: '/sec-d/$id' - preLoaderRoute: typeof SecDIdRouteImport - parentRoute: typeof SecDRoute - } - '/sec-d/about': { - id: '/sec-d/about' - path: '/about' - fullPath: '/sec-d/about' - preLoaderRoute: typeof SecDAboutRouteImport - parentRoute: typeof SecDRoute - } - '/sec-d/settings': { - id: '/sec-d/settings' - path: '/settings' - fullPath: '/sec-d/settings' - preLoaderRoute: typeof SecDSettingsRouteImport - parentRoute: typeof SecDRoute - } - '/sec-e/': { - id: '/sec-e/' - path: '/' - fullPath: '/sec-e/' - preLoaderRoute: typeof SecEIndexRouteImport - parentRoute: typeof SecERoute - } - '/sec-e/$id': { - id: '/sec-e/$id' - path: '/$id' - fullPath: '/sec-e/$id' - preLoaderRoute: typeof SecEIdRouteImport - parentRoute: typeof SecERoute - } - '/sec-e/about': { - id: '/sec-e/about' - path: '/about' - fullPath: '/sec-e/about' - preLoaderRoute: typeof SecEAboutRouteImport - parentRoute: typeof SecERoute - } - '/sec-e/settings': { - id: '/sec-e/settings' - path: '/settings' - fullPath: '/sec-e/settings' - preLoaderRoute: typeof SecESettingsRouteImport - parentRoute: typeof SecERoute - } - '/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 - } - } -} - -interface LayoutRouteChildren { - LayoutAlphaRoute: typeof LayoutAlphaRoute - LayoutBetaRoute: typeof LayoutBetaRoute -} - -const LayoutRouteChildren: LayoutRouteChildren = { - LayoutAlphaRoute: LayoutAlphaRoute, - LayoutBetaRoute: LayoutBetaRoute, -} - -const LayoutRouteWithChildren = - LayoutRoute._addFileChildren(LayoutRouteChildren) - -interface SecARouteChildren { - SecAIdRoute: typeof SecAIdRoute - SecAAboutRoute: typeof SecAAboutRoute - SecASettingsRoute: typeof SecASettingsRoute - SecAIndexRoute: typeof SecAIndexRoute -} - -const SecARouteChildren: SecARouteChildren = { - SecAIdRoute: SecAIdRoute, - SecAAboutRoute: SecAAboutRoute, - SecASettingsRoute: SecASettingsRoute, - SecAIndexRoute: SecAIndexRoute, -} - -const SecARouteWithChildren = SecARoute._addFileChildren(SecARouteChildren) - -interface SecBRouteChildren { - SecBIdRoute: typeof SecBIdRoute - SecBAboutRoute: typeof SecBAboutRoute - SecBSettingsRoute: typeof SecBSettingsRoute - SecBIndexRoute: typeof SecBIndexRoute -} - -const SecBRouteChildren: SecBRouteChildren = { - SecBIdRoute: SecBIdRoute, - SecBAboutRoute: SecBAboutRoute, - SecBSettingsRoute: SecBSettingsRoute, - SecBIndexRoute: SecBIndexRoute, -} - -const SecBRouteWithChildren = SecBRoute._addFileChildren(SecBRouteChildren) - -interface SecCRouteChildren { - SecCIdRoute: typeof SecCIdRoute - SecCAboutRoute: typeof SecCAboutRoute - SecCSettingsRoute: typeof SecCSettingsRoute - SecCIndexRoute: typeof SecCIndexRoute -} - -const SecCRouteChildren: SecCRouteChildren = { - SecCIdRoute: SecCIdRoute, - SecCAboutRoute: SecCAboutRoute, - SecCSettingsRoute: SecCSettingsRoute, - SecCIndexRoute: SecCIndexRoute, -} - -const SecCRouteWithChildren = SecCRoute._addFileChildren(SecCRouteChildren) - -interface SecDRouteChildren { - SecDIdRoute: typeof SecDIdRoute - SecDAboutRoute: typeof SecDAboutRoute - SecDSettingsRoute: typeof SecDSettingsRoute - SecDIndexRoute: typeof SecDIndexRoute -} - -const SecDRouteChildren: SecDRouteChildren = { - SecDIdRoute: SecDIdRoute, - SecDAboutRoute: SecDAboutRoute, - SecDSettingsRoute: SecDSettingsRoute, - SecDIndexRoute: SecDIndexRoute, -} - -const SecDRouteWithChildren = SecDRoute._addFileChildren(SecDRouteChildren) - -interface SecERouteChildren { - SecEIdRoute: typeof SecEIdRoute - SecEAboutRoute: typeof SecEAboutRoute - SecESettingsRoute: typeof SecESettingsRoute - SecEIndexRoute: typeof SecEIndexRoute -} - -const SecERouteChildren: SecERouteChildren = { - SecEIdRoute: SecEIdRoute, - SecEAboutRoute: SecEAboutRoute, - SecESettingsRoute: SecESettingsRoute, - SecEIndexRoute: SecEIndexRoute, -} - -const SecERouteWithChildren = SecERoute._addFileChildren(SecERouteChildren) - -interface SecFRouteChildren { - SecFIdRoute: typeof SecFIdRoute - SecFAboutRoute: typeof SecFAboutRoute - SecFSettingsRoute: typeof SecFSettingsRoute - SecFIndexRoute: typeof SecFIndexRoute -} - -const SecFRouteChildren: SecFRouteChildren = { - SecFIdRoute: SecFIdRoute, - SecFAboutRoute: SecFAboutRoute, - SecFSettingsRoute: SecFSettingsRoute, - SecFIndexRoute: SecFIndexRoute, -} - -const SecFRouteWithChildren = SecFRoute._addFileChildren(SecFRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - LayoutRoute: LayoutRouteWithChildren, - SecARoute: SecARouteWithChildren, - SecBRoute: SecBRouteWithChildren, - SecCRoute: SecCRouteWithChildren, - SecDRoute: SecDRouteWithChildren, - SecERoute: SecERouteWithChildren, - SecFRoute: SecFRouteWithChildren, - marketingPricingRoute: marketingPricingRoute, - marketingPromoRoute: marketingPromoRoute, - FilesSplatRoute: FilesSplatRoute, - ReleaseVChar123versionChar125Route: ReleaseVChar123versionChar125Route, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/(marketing)/pricing.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/(marketing)/pricing.tsx deleted file mode 100644 index f606c10b4b..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/(marketing)/pricing.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - return () =>
pricing
- }, -}) - -export const Route = createFileRoute('/(marketing)/pricing')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/(marketing)/promo.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/(marketing)/promo.tsx deleted file mode 100644 index 61c3eb3ec9..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/(marketing)/promo.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - return () =>
promo
- }, -}) - -export const Route = createFileRoute('/(marketing)/promo')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/__root.tsx deleted file mode 100644 index d2e1483106..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/__root.tsx +++ /dev/null @@ -1,61 +0,0 @@ -import * as Vue from 'vue' -import { Link, Outlet, createRootRoute } from '@tanstack/vue-router' - -const RootComponent = Vue.defineComponent({ - setup() { - return () => ( - <> - - - - ) - }, -}) - -export const Route = createRootRoute({ - component: RootComponent, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.alpha.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.alpha.tsx deleted file mode 100644 index ff6ad5350e..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.alpha.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - return () =>
alpha
- }, -}) - -export const Route = createFileRoute('/_layout/alpha')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.beta.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.beta.tsx deleted file mode 100644 index 2f7cab6c0a..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.beta.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - return () =>
beta
- }, -}) - -export const Route = createFileRoute('/_layout/beta')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.tsx deleted file mode 100644 index e8221f0f65..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { Outlet, createFileRoute } from '@tanstack/vue-router' - -const Layout = Vue.defineComponent({ - setup() { - return () => - }, -}) - -export const Route = createFileRoute('/_layout')({ - component: Layout, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/files.$.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/files.$.tsx deleted file mode 100644 index 221fae01be..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/files.$.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - const params = Route.useParams() - - return () => ( -
{`files:${params.value._splat}`}
- ) - }, -}) - -export const Route = createFileRoute('/files/$')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/index.tsx deleted file mode 100644 index b3e94f37c4..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - return () =>
home
- }, -}) - -export const Route = createFileRoute('/')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/release.v{$version}.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/release.v{$version}.tsx deleted file mode 100644 index 86b1a2c8f0..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/release.v{$version}.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - const params = Route.useParams() - - return () => ( -
{`release:${params.value.version}`}
- ) - }, -}) - -export const Route = createFileRoute('/release/v{$version}')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.$id.tsx deleted file mode 100644 index 864074940d..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.$id.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - const params = Route.useParams() - - return () => ( -
{`sec-a:${params.value.id}`}
- ) - }, -}) - -export const Route = createFileRoute('/sec-a/$id')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.about.tsx deleted file mode 100644 index 715ab9548c..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.about.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - return () =>
sec-a:about
- }, -}) - -export const Route = createFileRoute('/sec-a/about')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.index.tsx deleted file mode 100644 index baef08547c..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - return () =>
sec-a:index
- }, -}) - -export const Route = createFileRoute('/sec-a/')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.settings.tsx deleted file mode 100644 index 9e6a56b913..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.settings.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - return () =>
sec-a:settings
- }, -}) - -export const Route = createFileRoute('/sec-a/settings')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.tsx deleted file mode 100644 index a9fb557aea..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { Outlet, createFileRoute } from '@tanstack/vue-router' - -const Layout = Vue.defineComponent({ - setup() { - return () => - }, -}) - -export const Route = createFileRoute('/sec-a')({ - component: Layout, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.$id.tsx deleted file mode 100644 index 9a03a8fe01..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.$id.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - const params = Route.useParams() - - return () => ( -
{`sec-b:${params.value.id}`}
- ) - }, -}) - -export const Route = createFileRoute('/sec-b/$id')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.about.tsx deleted file mode 100644 index 2ef1100995..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.about.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - return () =>
sec-b:about
- }, -}) - -export const Route = createFileRoute('/sec-b/about')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.index.tsx deleted file mode 100644 index 652e5f895c..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - return () =>
sec-b:index
- }, -}) - -export const Route = createFileRoute('/sec-b/')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.settings.tsx deleted file mode 100644 index e8fa36377e..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.settings.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - return () =>
sec-b:settings
- }, -}) - -export const Route = createFileRoute('/sec-b/settings')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.tsx deleted file mode 100644 index ba31612633..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { Outlet, createFileRoute } from '@tanstack/vue-router' - -const Layout = Vue.defineComponent({ - setup() { - return () => - }, -}) - -export const Route = createFileRoute('/sec-b')({ - component: Layout, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.$id.tsx deleted file mode 100644 index 7f0407d84e..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.$id.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - const params = Route.useParams() - - return () => ( -
{`sec-c:${params.value.id}`}
- ) - }, -}) - -export const Route = createFileRoute('/sec-c/$id')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.about.tsx deleted file mode 100644 index d26776d439..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.about.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - return () =>
sec-c:about
- }, -}) - -export const Route = createFileRoute('/sec-c/about')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.index.tsx deleted file mode 100644 index 1835eff9b7..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - return () =>
sec-c:index
- }, -}) - -export const Route = createFileRoute('/sec-c/')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.settings.tsx deleted file mode 100644 index 1bf85fd6d9..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.settings.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - return () =>
sec-c:settings
- }, -}) - -export const Route = createFileRoute('/sec-c/settings')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.tsx deleted file mode 100644 index 009f814b93..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { Outlet, createFileRoute } from '@tanstack/vue-router' - -const Layout = Vue.defineComponent({ - setup() { - return () => - }, -}) - -export const Route = createFileRoute('/sec-c')({ - component: Layout, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.$id.tsx deleted file mode 100644 index ff5aab05e3..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.$id.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - const params = Route.useParams() - - return () => ( -
{`sec-d:${params.value.id}`}
- ) - }, -}) - -export const Route = createFileRoute('/sec-d/$id')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.about.tsx deleted file mode 100644 index 25a8078626..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.about.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - return () =>
sec-d:about
- }, -}) - -export const Route = createFileRoute('/sec-d/about')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.index.tsx deleted file mode 100644 index cd9b89664a..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - return () =>
sec-d:index
- }, -}) - -export const Route = createFileRoute('/sec-d/')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.settings.tsx deleted file mode 100644 index 8e4309de32..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.settings.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - return () =>
sec-d:settings
- }, -}) - -export const Route = createFileRoute('/sec-d/settings')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.tsx deleted file mode 100644 index 6b12b514da..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { Outlet, createFileRoute } from '@tanstack/vue-router' - -const Layout = Vue.defineComponent({ - setup() { - return () => - }, -}) - -export const Route = createFileRoute('/sec-d')({ - component: Layout, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.$id.tsx deleted file mode 100644 index 4525051967..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.$id.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - const params = Route.useParams() - - return () => ( -
{`sec-e:${params.value.id}`}
- ) - }, -}) - -export const Route = createFileRoute('/sec-e/$id')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.about.tsx deleted file mode 100644 index 71a32bd36b..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.about.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - return () =>
sec-e:about
- }, -}) - -export const Route = createFileRoute('/sec-e/about')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.index.tsx deleted file mode 100644 index 9b467ca53e..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - return () =>
sec-e:index
- }, -}) - -export const Route = createFileRoute('/sec-e/')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.settings.tsx deleted file mode 100644 index a01066488c..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.settings.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - return () =>
sec-e:settings
- }, -}) - -export const Route = createFileRoute('/sec-e/settings')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.tsx deleted file mode 100644 index 38f4da91fb..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { Outlet, createFileRoute } from '@tanstack/vue-router' - -const Layout = Vue.defineComponent({ - setup() { - return () => - }, -}) - -export const Route = createFileRoute('/sec-e')({ - component: Layout, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.$id.tsx deleted file mode 100644 index c740f9d223..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.$id.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - const params = Route.useParams() - - return () => ( -
{`sec-f:${params.value.id}`}
- ) - }, -}) - -export const Route = createFileRoute('/sec-f/$id')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.about.tsx deleted file mode 100644 index 229dab22a2..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.about.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - return () =>
sec-f:about
- }, -}) - -export const Route = createFileRoute('/sec-f/about')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.index.tsx deleted file mode 100644 index 14e3f46a13..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - return () =>
sec-f:index
- }, -}) - -export const Route = createFileRoute('/sec-f/')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.settings.tsx deleted file mode 100644 index da2c7483b9..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.settings.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const Page = Vue.defineComponent({ - setup() { - return () =>
sec-f:settings
- }, -}) - -export const Route = createFileRoute('/sec-f/settings')({ - component: Page, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.tsx deleted file mode 100644 index 3b389c8144..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as Vue from 'vue' -import { Outlet, createFileRoute } from '@tanstack/vue-router' - -const Layout = Vue.defineComponent({ - setup() { - return () => - }, -}) - -export const Route = createFileRoute('/sec-f')({ - component: Layout, -}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/tsconfig.json b/benchmarks/client-nav/scenarios/route-tree-scale/vue/tsconfig.json deleted file mode 100644 index 7786fc3da9..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/vite.config.ts b/benchmarks/client-nav/scenarios/route-tree-scale/vue/vite.config.ts deleted file mode 100644 index 189ba1de99..0000000000 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/vite.config.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'vue', - // Real file-based apps code-split by default; this scenario keeps it on - // so navigations also exercise lazy route-chunk resolution. - autoCodeSplitting: true, - 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 route-tree-scale (vue)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - }, -}) diff --git a/benchmarks/client-nav/scenarios/search-params/react/project.json b/benchmarks/client-nav/scenarios/search-params/react/project.json deleted file mode 100644 index f2d743f5f9..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-search-params-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/search-params/react/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/search-params/react/setup.ts b/benchmarks/client-nav/scenarios/search-params/react/setup.ts deleted file mode 100644 index 130583b190..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/react/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, steps } 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, - assertAfterStep: assertStepResult, - }) -} diff --git a/benchmarks/client-nav/scenarios/search-params/react/speed.bench.ts b/benchmarks/client-nav/scenarios/search-params/react/speed.bench.ts deleted file mode 100644 index 0b38f7bddb..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-search-params', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-search-params 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/search-params/react/speed.flame.ts b/benchmarks/client-nav/scenarios/search-params/react/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/react/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/search-params/react/src/main.tsx b/benchmarks/client-nav/scenarios/search-params/react/src/main.tsx deleted file mode 100644 index b10d53554b..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/react/src/main.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { RouterProvider, createRouter } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - defaultStructuralSharing: true, - }) -} - -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/search-params/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/search-params/react/src/routeTree.gen.ts deleted file mode 100644 index cff9dca167..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/react/src/routeTree.gen.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as CatalogRouteImport } from './routes/catalog' -import { Route as ProductsRouteImport } from './routes/products' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const CatalogRoute = CatalogRouteImport.update({ - id: '/catalog', - path: '/catalog', - getParentRoute: () => rootRouteImport, -} as any) -const ProductsRoute = ProductsRouteImport.update({ - id: '/products', - path: '/products', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/catalog': typeof CatalogRoute - '/products': typeof ProductsRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/catalog': typeof CatalogRoute - '/products': typeof ProductsRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/catalog': typeof CatalogRoute - '/products': typeof ProductsRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/catalog' | '/products' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/catalog' | '/products' - id: '__root__' | '/' | '/catalog' | '/products' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - CatalogRoute: typeof CatalogRoute - ProductsRoute: typeof ProductsRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/catalog': { - id: '/catalog' - path: '/catalog' - fullPath: '/catalog' - preLoaderRoute: typeof CatalogRouteImport - parentRoute: typeof rootRouteImport - } - '/products': { - id: '/products' - path: '/products' - fullPath: '/products' - preLoaderRoute: typeof ProductsRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - CatalogRoute: CatalogRoute, - ProductsRoute: ProductsRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/search-params/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/search-params/react/src/routes/__root.tsx deleted file mode 100644 index 86399d0175..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/react/src/routes/__root.tsx +++ /dev/null @@ -1,116 +0,0 @@ -import { - Link, - Outlet, - createRootRoute, - useSearch, -} from '@tanstack/react-router' -import { - changedCategories, - computeChecksum, - initialProductsSearch, -} from '../../../shared' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -const rootSubscribers = Array.from({ length: 4 }, (_, index) => index) - -function RootSearchSubscriber() { - const value = useSearch({ - strict: false, - select: (search) => computeChecksum(Number(search.page ?? 0)), - }) - - void computeChecksum(value) - return null -} - -function RootComponent() { - return ( - <> - {rootSubscribers.map((index) => ( - - ))} - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/search-params/react/src/routes/catalog.tsx b/benchmarks/client-nav/scenarios/search-params/react/src/routes/catalog.tsx deleted file mode 100644 index 73f59c13b0..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/react/src/routes/catalog.tsx +++ /dev/null @@ -1,42 +0,0 @@ -import { createFileRoute, retainSearchParams } from '@tanstack/react-router' -import type { SearchSchemaInput } from '@tanstack/react-router' -import { - catalogMarkerText, - computeChecksum, - normalizeCatalogSearch, -} from '../../../shared' - -export const Route = createFileRoute('/catalog')({ - validateSearch: (search: Record & SearchSchemaInput) => - normalizeCatalogSearch(search), - search: { - middlewares: [retainSearchParams(['perPage', 'sort'])], - }, - component: CatalogPage, -}) - -const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) - -function ViewSubscriber() { - const value = Route.useSearch({ - select: (search) => - computeChecksum(search.view.length * 5 + search.page * 11), - }) - - void computeChecksum(value) - return null -} - -function CatalogPage() { - const search = Route.useSearch() - - return ( -
- {subscriberIndexes.map((index) => ( - - ))} -

Catalog

-
{catalogMarkerText(search)}
-
- ) -} diff --git a/benchmarks/client-nav/scenarios/search-params/react/src/routes/index.tsx b/benchmarks/client-nav/scenarios/search-params/react/src/routes/index.tsx deleted file mode 100644 index 5879ad518d..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/react/src/routes/index.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: HomePage, -}) - -function HomePage() { - return ( -
-

Search Params Bench

-
home
-
- ) -} diff --git a/benchmarks/client-nav/scenarios/search-params/react/src/routes/products.tsx b/benchmarks/client-nav/scenarios/search-params/react/src/routes/products.tsx deleted file mode 100644 index d22e99c4bf..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/react/src/routes/products.tsx +++ /dev/null @@ -1,91 +0,0 @@ -import { - createFileRoute, - retainSearchParams, - stripSearchParams, -} from '@tanstack/react-router' -import type { SearchSchemaInput } from '@tanstack/react-router' -import { - computeChecksum, - normalizeProductsSearch, - productsLoaderChecksum, - productsMarkerText, -} from '../../../shared' - -export const Route = createFileRoute('/products')({ - validateSearch: (search: Record & SearchSchemaInput) => - normalizeProductsSearch(search), - search: { - middlewares: [ - retainSearchParams(['perPage', 'sort']), - stripSearchParams({ page: 1 }), - ], - }, - loaderDeps: ({ search }) => ({ - page: search.page, - sort: search.sort, - filters: search.filters, - }), - loader: ({ deps }) => ({ - checksum: productsLoaderChecksum(deps), - }), - staleTime: 1e9, - gcTime: 1e9, - component: ProductsPage, -}) - -const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) - -function PageSubscriber() { - const value = Route.useSearch({ - select: (search) => computeChecksum(search.page * 31 + search.perPage), - }) - - void computeChecksum(value) - return null -} - -function FiltersSubscriber() { - const value = Route.useSearch({ - select: (search) => - computeChecksum( - search.filters.categories.length * 7 + - (search.filters.price.max - search.filters.price.min) + - search.filters.tags.length * 3, - ), - }) - - void computeChecksum(value) - return null -} - -function QuerySubscriber() { - const value = Route.useSearch({ - select: (search) => - computeChecksum(search.q.length * 13 + search.sort.length), - }) - - void computeChecksum(value) - return null -} - -function ProductsPage() { - const search = Route.useSearch() - const loaderData = Route.useLoaderData() - - return ( -
- {subscriberIndexes.map((index) => ( - - ))} - {subscriberIndexes.map((index) => ( - - ))} - {subscriberIndexes.map((index) => ( - - ))} -

Products

-
{productsMarkerText(search)}
-

{`checksum ${loaderData.checksum}`}

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/search-params/react/tsconfig.json b/benchmarks/client-nav/scenarios/search-params/react/tsconfig.json deleted file mode 100644 index 1d59cbb450..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/react/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/search-params/react/vite.config.ts b/benchmarks/client-nav/scenarios/search-params/react/vite.config.ts deleted file mode 100644 index 0318a10815..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/react/vite.config.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import react from '@vitejs/plugin-react' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'react', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav search-params (react)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - }, -}) diff --git a/benchmarks/client-nav/scenarios/search-params/shared.ts b/benchmarks/client-nav/scenarios/search-params/shared.ts deleted file mode 100644 index 343e319ded..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/shared.ts +++ /dev/null @@ -1,200 +0,0 @@ -/** - * Shared definition of the `search-params` scenario: search schema - * normalizers, the click sequence, and per-step sanity assertions. The three - * framework apps consume these builders so the workload is identical modulo - * the rendering layer. - * - * Isolates: validateSearch execution, search middlewares - * (retainSearchParams/stripSearchParams), parse/stringify of medium-complex - * search objects, functional search updaters, structural sharing, and - * useSearch selector subscriptions. - */ - -import type { ScenarioStep } from '../harness' - -export function computeChecksum(seed: number) { - let value = Math.trunc(seed) | 0 - - for (let index = 0; index < 40; index++) { - value = (value * 1664525 + 1013904223 + index) >>> 0 - } - - return value -} - -export interface ProductsSearch { - page: number - perPage: number - sort: 'asc' | 'desc' - q: string - filters: { - categories: Array - price: { min: number; max: number } - tags: Array - } -} - -export interface CatalogSearch { - view: 'grid' | 'list' - page: number - perPage: number - sort: 'asc' | 'desc' -} - -function normalizeNumber(value: unknown, fallback: number) { - const num = Number(value) - return Number.isFinite(num) && num >= 0 ? Math.trunc(num) : fallback -} - -function normalizeString(value: unknown, fallback: string) { - return typeof value === 'string' ? value : fallback -} - -function normalizeSort(value: unknown): 'asc' | 'desc' { - return value === 'desc' ? 'desc' : 'asc' -} - -function normalizeStringArray(value: unknown): Array { - if (!Array.isArray(value)) { - return [] - } - return value.filter((entry): entry is string => typeof entry === 'string') -} - -export function normalizeProductsSearch( - search: Record, -): ProductsSearch { - const filters = - typeof search.filters === 'object' && search.filters !== null - ? (search.filters as Record) - : {} - const price = - typeof filters.price === 'object' && filters.price !== null - ? (filters.price as Record) - : {} - - return { - page: Math.max(1, normalizeNumber(search.page, 1)), - perPage: Math.max(1, normalizeNumber(search.perPage, 20)), - sort: normalizeSort(search.sort), - q: normalizeString(search.q, ''), - filters: { - categories: normalizeStringArray(filters.categories), - price: { - min: normalizeNumber(price.min, 0), - max: normalizeNumber(price.max, 1000), - }, - tags: normalizeStringArray(filters.tags), - }, - } -} - -export function normalizeCatalogSearch( - search: Record, -): CatalogSearch { - return { - view: search.view === 'list' ? 'list' : 'grid', - page: Math.max(1, normalizeNumber(search.page, 1)), - perPage: Math.max(1, normalizeNumber(search.perPage, 20)), - sort: normalizeSort(search.sort), - } -} - -export const initialProductsSearch = { - page: 2, - perPage: 50, - sort: 'desc', - q: 'gadget', - filters: { - categories: ['audio', 'video'], - price: { min: 10, max: 200 }, - tags: ['new', 'sale'], - }, -} satisfies ProductsSearch - -export const changedCategories = ['x-ray', 'yield', 'zeta'] - -export function productsMarkerText(search: ProductsSearch) { - return `${search.page}|${search.sort}|${search.filters.categories.join(',')}` -} - -export function catalogMarkerText(search: CatalogSearch) { - return `${search.view}|${search.page}|${search.perPage}|${search.sort}` -} - -export function productsLoaderChecksum(deps: { - page: number - sort: string - filters: ProductsSearch['filters'] -}) { - return computeChecksum( - deps.page * 31 + - deps.sort.length * 7 + - deps.filters.categories.join('').length * 13 + - deps.filters.tags.length * 3 + - (deps.filters.price.max - deps.filters.price.min), - ) -} - -export const steps: ReadonlyArray = [ - 'go-products', - 'products-next-page', - 'products-categories', - 'products-sort', - 'products-reset', - 'go-catalog', - 'catalog-next-page', - 'products-partial', - 'go-home', -] - -interface ExpectedState { - testId: string - text?: string -} - -const expectedStates: ReadonlyArray = [ - // Full search literal from home. - { testId: 'products-state', text: '2|desc|audio,video' }, - // Functional updater bumping the page. - { testId: 'products-state', text: '3|desc|audio,video' }, - // Functional updater replacing filters.categories. - { testId: 'products-state', text: '3|desc|x-ray,yield,zeta' }, - // Functional updater flipping sort desc -> asc. - { testId: 'products-state', text: '3|asc|x-ray,yield,zeta' }, - // Functional updater resetting page to 1 (stripSearchParams removes it). - { testId: 'products-state', text: '1|asc|x-ray,yield,zeta' }, - // search: true carries the current products search into catalog. - { testId: 'catalog-state', text: 'grid|1|50|asc' }, - // Functional updater bumping the catalog page. - { testId: 'catalog-state', text: 'grid|2|50|asc' }, - // Partial search literal; retainSearchParams fills perPage/sort from catalog. - { testId: 'products-state', text: '1|asc|' }, - { testId: 'home-state' }, -] - -export function assertStepResult(stepIndex: number, container: HTMLElement) { - const expected = expectedStates[stepIndex]! - const element = container.querySelector(`[data-testid="${expected.testId}"]`) - - if (!element) { - throw new Error( - `Expected marker "${expected.testId}" to exist after step ${stepIndex}`, - ) - } - - if (expected.text !== undefined && element.textContent !== expected.text) { - throw new Error( - `Expected marker "${expected.testId}" to read "${expected.text}" after step ${stepIndex}, received "${element.textContent}"`, - ) - } -} - -// Two laps through the 9-step sequence per benchmark iteration. -export const ticksPerIteration = 18 - -export const benchOptions = { - warmupIterations: 100, - time: 10_000, - throws: true, -} diff --git a/benchmarks/client-nav/scenarios/search-params/solid/project.json b/benchmarks/client-nav/scenarios/search-params/solid/project.json deleted file mode 100644 index af48217e03..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/solid/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-search-params-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/search-params/solid/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/search-params/solid/setup.ts b/benchmarks/client-nav/scenarios/search-params/solid/setup.ts deleted file mode 100644 index 6a46971603..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/solid/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, steps } 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, - assertAfterStep: assertStepResult, - }) -} diff --git a/benchmarks/client-nav/scenarios/search-params/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/search-params/solid/speed.bench.ts deleted file mode 100644 index caa626c596..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-search-params', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-search-params 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/search-params/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/search-params/solid/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/solid/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/search-params/solid/src/main.tsx b/benchmarks/client-nav/scenarios/search-params/solid/src/main.tsx deleted file mode 100644 index 25071f7979..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/solid/src/main.tsx +++ /dev/null @@ -1,35 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import { render } from 'solid-js/web' -import { RouterProvider, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - defaultStructuralSharing: true, - }) -} - -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/search-params/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/search-params/solid/src/routeTree.gen.ts deleted file mode 100644 index b15beed09b..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as CatalogRouteImport } from './routes/catalog' -import { Route as ProductsRouteImport } from './routes/products' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const CatalogRoute = CatalogRouteImport.update({ - id: '/catalog', - path: '/catalog', - getParentRoute: () => rootRouteImport, -} as any) -const ProductsRoute = ProductsRouteImport.update({ - id: '/products', - path: '/products', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/catalog': typeof CatalogRoute - '/products': typeof ProductsRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/catalog': typeof CatalogRoute - '/products': typeof ProductsRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/catalog': typeof CatalogRoute - '/products': typeof ProductsRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/catalog' | '/products' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/catalog' | '/products' - id: '__root__' | '/' | '/catalog' | '/products' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - CatalogRoute: typeof CatalogRoute - ProductsRoute: typeof ProductsRoute -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/catalog': { - id: '/catalog' - path: '/catalog' - fullPath: '/catalog' - preLoaderRoute: typeof CatalogRouteImport - parentRoute: typeof rootRouteImport - } - '/products': { - id: '/products' - path: '/products' - fullPath: '/products' - preLoaderRoute: typeof ProductsRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - CatalogRoute: CatalogRoute, - ProductsRoute: ProductsRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/search-params/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/search-params/solid/src/routes/__root.tsx deleted file mode 100644 index 30c042f9c5..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/solid/src/routes/__root.tsx +++ /dev/null @@ -1,120 +0,0 @@ -import { createRenderEffect } from 'solid-js' -import { - Link, - Outlet, - createRootRoute, - useSearch, -} from '@tanstack/solid-router' -import { - changedCategories, - computeChecksum, - initialProductsSearch, -} from '../../../shared' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -const rootSubscribers = Array.from({ length: 4 }, (_, index) => index) - -function PerfValue(props: { value: () => number }) { - createRenderEffect(() => { - void props.value() - }) - - return null -} - -function RootSearchSubscriber() { - const value = useSearch({ - strict: false, - select: (search) => computeChecksum(Number(search.page ?? 0)), - }) - - return computeChecksum(value())} /> -} - -function RootComponent() { - return ( - <> - {rootSubscribers.map(() => ( - - ))} - - - - ) -} diff --git a/benchmarks/client-nav/scenarios/search-params/solid/src/routes/catalog.tsx b/benchmarks/client-nav/scenarios/search-params/solid/src/routes/catalog.tsx deleted file mode 100644 index 60cf8e7896..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/solid/src/routes/catalog.tsx +++ /dev/null @@ -1,50 +0,0 @@ -import { createRenderEffect } from 'solid-js' -import { createFileRoute, retainSearchParams } from '@tanstack/solid-router' -import type { SearchSchemaInput } from '@tanstack/solid-router' -import { - catalogMarkerText, - computeChecksum, - normalizeCatalogSearch, -} from '../../../shared' - -export const Route = createFileRoute('/catalog')({ - validateSearch: (search: Record & SearchSchemaInput) => - normalizeCatalogSearch(search), - search: { - middlewares: [retainSearchParams(['perPage', 'sort'])], - }, - component: CatalogPage, -}) - -const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) - -function PerfValue(props: { value: () => number }) { - createRenderEffect(() => { - void props.value() - }) - - return null -} - -function ViewSubscriber() { - const value = Route.useSearch({ - select: (search) => - computeChecksum(search.view.length * 5 + search.page * 11), - }) - - return computeChecksum(value())} /> -} - -function CatalogPage() { - const search = Route.useSearch() - - return ( -
- {subscriberIndexes.map(() => ( - - ))} -

Catalog

-
{catalogMarkerText(search())}
-
- ) -} diff --git a/benchmarks/client-nav/scenarios/search-params/solid/src/routes/index.tsx b/benchmarks/client-nav/scenarios/search-params/solid/src/routes/index.tsx deleted file mode 100644 index 0bbb913d83..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/solid/src/routes/index.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/')({ - component: HomePage, -}) - -function HomePage() { - return ( -
-

Search Params Bench

-
home
-
- ) -} diff --git a/benchmarks/client-nav/scenarios/search-params/solid/src/routes/products.tsx b/benchmarks/client-nav/scenarios/search-params/solid/src/routes/products.tsx deleted file mode 100644 index 8b2a252155..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/solid/src/routes/products.tsx +++ /dev/null @@ -1,97 +0,0 @@ -import { createRenderEffect } from 'solid-js' -import { - createFileRoute, - retainSearchParams, - stripSearchParams, -} from '@tanstack/solid-router' -import type { SearchSchemaInput } from '@tanstack/solid-router' -import { - computeChecksum, - normalizeProductsSearch, - productsLoaderChecksum, - productsMarkerText, -} from '../../../shared' - -export const Route = createFileRoute('/products')({ - validateSearch: (search: Record & SearchSchemaInput) => - normalizeProductsSearch(search), - search: { - middlewares: [ - retainSearchParams(['perPage', 'sort']), - stripSearchParams({ page: 1 }), - ], - }, - loaderDeps: ({ search }) => ({ - page: search.page, - sort: search.sort, - filters: search.filters, - }), - loader: ({ deps }) => ({ - checksum: productsLoaderChecksum(deps), - }), - staleTime: 1e9, - gcTime: 1e9, - component: ProductsPage, -}) - -const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) - -function PerfValue(props: { value: () => number }) { - createRenderEffect(() => { - void props.value() - }) - - return null -} - -function PageSubscriber() { - const value = Route.useSearch({ - select: (search) => computeChecksum(search.page * 31 + search.perPage), - }) - - return computeChecksum(value())} /> -} - -function FiltersSubscriber() { - const value = Route.useSearch({ - select: (search) => - computeChecksum( - search.filters.categories.length * 7 + - (search.filters.price.max - search.filters.price.min) + - search.filters.tags.length * 3, - ), - }) - - return computeChecksum(value())} /> -} - -function QuerySubscriber() { - const value = Route.useSearch({ - select: (search) => - computeChecksum(search.q.length * 13 + search.sort.length), - }) - - return computeChecksum(value())} /> -} - -function ProductsPage() { - const search = Route.useSearch() - const loaderData = Route.useLoaderData() - - return ( -
- {subscriberIndexes.map(() => ( - - ))} - {subscriberIndexes.map(() => ( - - ))} - {subscriberIndexes.map(() => ( - - ))} -

Products

-
{productsMarkerText(search())}
-

{`checksum ${loaderData().checksum}`}

-
- ) -} diff --git a/benchmarks/client-nav/scenarios/search-params/solid/tsconfig.json b/benchmarks/client-nav/scenarios/search-params/solid/tsconfig.json deleted file mode 100644 index 98d76ad6b8..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/solid/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/search-params/solid/vite.config.ts b/benchmarks/client-nav/scenarios/search-params/solid/vite.config.ts deleted file mode 100644 index 511fd49466..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/solid/vite.config.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import solid from 'vite-plugin-solid' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'solid', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - resolve: { - conditions: ['solid', 'browser'], - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav search-params (solid)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/client-nav/scenarios/search-params/vue/project.json b/benchmarks/client-nav/scenarios/search-params/vue/project.json deleted file mode 100644 index 47b9712a2c..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/vue/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "@benchmarks/client-nav-search-params-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/search-params/vue/speed.flame.ts", - "cwd": "benchmarks/client-nav" - } - } - } -} diff --git a/benchmarks/client-nav/scenarios/search-params/vue/setup.ts b/benchmarks/client-nav/scenarios/search-params/vue/setup.ts deleted file mode 100644 index 97b74b3892..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/vue/setup.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createScenarioSetup } from '../../harness' -import { assertStepResult, steps } 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, - assertAfterStep: assertStepResult, - }) -} diff --git a/benchmarks/client-nav/scenarios/search-params/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/search-params/vue/speed.bench.ts deleted file mode 100644 index 728d2779e8..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/vue/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' -import { benchOptions, ticksPerIteration } from '../shared' -import { setup } from './setup' - -test('client-search-params', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-search-params 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/search-params/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/search-params/vue/speed.flame.ts deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/vue/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../../../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/scenarios/search-params/vue/src/main.tsx b/benchmarks/client-nav/scenarios/search-params/vue/src/main.tsx deleted file mode 100644 index 65bade775c..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/vue/src/main.tsx +++ /dev/null @@ -1,42 +0,0 @@ -import type { RouterHistory } from '@tanstack/history' -import * as Vue from 'vue' -import { RouterProvider, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function createTestRouter(history: RouterHistory) { - return createRouter({ - routeTree, - history, - scrollRestoration: true, - // Key the scroll-restoration cache by pathname instead of the default - // random per-entry location key: with push navigations the default mints - // a fresh key per navigation and the module-level cache grows one entry - // per push for the whole run, which is non-stationary. - getScrollRestorationKey: (location) => location.pathname, - defaultStructuralSharing: true, - }) -} - -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/search-params/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/search-params/vue/src/routeTree.gen.ts deleted file mode 100644 index f73b84ebe7..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as CatalogRouteImport } from './routes/catalog' -import { Route as ProductsRouteImport } from './routes/products' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const CatalogRoute = CatalogRouteImport.update({ - id: '/catalog', - path: '/catalog', - getParentRoute: () => rootRouteImport, -} as any) -const ProductsRoute = ProductsRouteImport.update({ - id: '/products', - path: '/products', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/catalog': typeof CatalogRoute - '/products': typeof ProductsRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/catalog': typeof CatalogRoute - '/products': typeof ProductsRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/catalog': typeof CatalogRoute - '/products': typeof ProductsRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/catalog' | '/products' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/catalog' | '/products' - id: '__root__' | '/' | '/catalog' | '/products' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - CatalogRoute: typeof CatalogRoute - ProductsRoute: typeof ProductsRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/catalog': { - id: '/catalog' - path: '/catalog' - fullPath: '/catalog' - preLoaderRoute: typeof CatalogRouteImport - parentRoute: typeof rootRouteImport - } - '/products': { - id: '/products' - path: '/products' - fullPath: '/products' - preLoaderRoute: typeof ProductsRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - CatalogRoute: CatalogRoute, - ProductsRoute: ProductsRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/search-params/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/search-params/vue/src/routes/__root.tsx deleted file mode 100644 index b4cb07f2ae..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/vue/src/routes/__root.tsx +++ /dev/null @@ -1,114 +0,0 @@ -import * as Vue from 'vue' -import { Link, Outlet, createRootRoute, useSearch } from '@tanstack/vue-router' -import { - changedCategories, - computeChecksum, - initialProductsSearch, -} from '../../../shared' - -const rootSubscribers = Array.from({ length: 4 }, (_, index) => index) - -const RootSearchSubscriber = Vue.defineComponent({ - setup() { - const value = useSearch({ - strict: false, - select: (search) => computeChecksum(Number(search.page ?? 0)), - }) - - return () => { - void computeChecksum(value.value) - return null - } - }, -}) - -const RootComponent = Vue.defineComponent({ - setup() { - return () => ( - <> - {rootSubscribers.map((index) => ( - - ))} - - - - ) - }, -}) - -export const Route = createRootRoute({ - component: RootComponent, -}) diff --git a/benchmarks/client-nav/scenarios/search-params/vue/src/routes/catalog.tsx b/benchmarks/client-nav/scenarios/search-params/vue/src/routes/catalog.tsx deleted file mode 100644 index 6a09efdd4a..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/vue/src/routes/catalog.tsx +++ /dev/null @@ -1,49 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute, retainSearchParams } from '@tanstack/vue-router' -import type { SearchSchemaInput } from '@tanstack/vue-router' -import { - catalogMarkerText, - computeChecksum, - normalizeCatalogSearch, -} from '../../../shared' - -const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) - -const ViewSubscriber = Vue.defineComponent({ - setup() { - const value = Route.useSearch({ - select: (search) => - computeChecksum(search.view.length * 5 + search.page * 11), - }) - - return () => { - void computeChecksum(value.value) - return null - } - }, -}) - -const CatalogPage = Vue.defineComponent({ - setup() { - const search = Route.useSearch() - - return () => ( -
- {subscriberIndexes.map((index) => ( - - ))} -

Catalog

-
{catalogMarkerText(search.value)}
-
- ) - }, -}) - -export const Route = createFileRoute('/catalog')({ - validateSearch: (search: Record & SearchSchemaInput) => - normalizeCatalogSearch(search), - search: { - middlewares: [retainSearchParams(['perPage', 'sort'])], - }, - component: CatalogPage, -}) diff --git a/benchmarks/client-nav/scenarios/search-params/vue/src/routes/index.tsx b/benchmarks/client-nav/scenarios/search-params/vue/src/routes/index.tsx deleted file mode 100644 index 081aa7b4fd..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/vue/src/routes/index.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import * as Vue from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const HomePage = Vue.defineComponent({ - setup() { - return () => ( -
-

Search Params Bench

-
home
-
- ) - }, -}) - -export const Route = createFileRoute('/')({ - component: HomePage, -}) diff --git a/benchmarks/client-nav/scenarios/search-params/vue/src/routes/products.tsx b/benchmarks/client-nav/scenarios/search-params/vue/src/routes/products.tsx deleted file mode 100644 index 8be1683e14..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/vue/src/routes/products.tsx +++ /dev/null @@ -1,108 +0,0 @@ -import * as Vue from 'vue' -import { - createFileRoute, - retainSearchParams, - stripSearchParams, -} from '@tanstack/vue-router' -import type { SearchSchemaInput } from '@tanstack/vue-router' -import { - computeChecksum, - normalizeProductsSearch, - productsLoaderChecksum, - productsMarkerText, -} from '../../../shared' - -const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) - -const PageSubscriber = Vue.defineComponent({ - setup() { - const value = Route.useSearch({ - select: (search) => computeChecksum(search.page * 31 + search.perPage), - }) - - return () => { - void computeChecksum(value.value) - return null - } - }, -}) - -const FiltersSubscriber = Vue.defineComponent({ - setup() { - const value = Route.useSearch({ - select: (search) => - computeChecksum( - search.filters.categories.length * 7 + - (search.filters.price.max - search.filters.price.min) + - search.filters.tags.length * 3, - ), - }) - - return () => { - void computeChecksum(value.value) - return null - } - }, -}) - -const QuerySubscriber = Vue.defineComponent({ - setup() { - const value = Route.useSearch({ - select: (search) => - computeChecksum(search.q.length * 13 + search.sort.length), - }) - - return () => { - void computeChecksum(value.value) - return null - } - }, -}) - -const ProductsPage = Vue.defineComponent({ - setup() { - const search = Route.useSearch() - const loaderData = Route.useLoaderData() - - return () => ( -
- {subscriberIndexes.map((index) => ( - - ))} - {subscriberIndexes.map((index) => ( - - ))} - {subscriberIndexes.map((index) => ( - - ))} -

Products

-
- {productsMarkerText(search.value)} -
-

{`checksum ${loaderData.value.checksum}`}

-
- ) - }, -}) - -export const Route = createFileRoute('/products')({ - validateSearch: (search: Record & SearchSchemaInput) => - normalizeProductsSearch(search), - search: { - middlewares: [ - retainSearchParams(['perPage', 'sort']), - stripSearchParams({ page: 1 }), - ], - }, - loaderDeps: ({ search }) => ({ - page: search.page, - sort: search.sort, - filters: search.filters, - }), - loader: ({ deps }) => ({ - checksum: productsLoaderChecksum(deps), - }), - staleTime: 1e9, - gcTime: 1e9, - component: ProductsPage, -}) diff --git a/benchmarks/client-nav/scenarios/search-params/vue/tsconfig.json b/benchmarks/client-nav/scenarios/search-params/vue/tsconfig.json deleted file mode 100644 index 7786fc3da9..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/vue/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "allowImportingTsExtensions": true, - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "setup.ts", - "vite.config.ts", - "../shared.ts", - "../../harness.ts", - "../../../setup-helpers.ts", - "../../../jsdom.ts", - "../../../vitest.setup.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/client-nav/scenarios/search-params/vue/vite.config.ts b/benchmarks/client-nav/scenarios/search-params/vue/vite.config.ts deleted file mode 100644 index 27490b276a..0000000000 --- a/benchmarks/client-nav/scenarios/search-params/vue/vite.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'vue', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav search-params (vue)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - }, -}) diff --git a/benchmarks/client-nav/setup-helpers.ts b/benchmarks/client-nav/setup-helpers.ts deleted file mode 100644 index c070018743..0000000000 --- a/benchmarks/client-nav/setup-helpers.ts +++ /dev/null @@ -1,43 +0,0 @@ -export function getRequiredLink( - container: ParentNode, - testId: string, - cache?: Map, -) { - const cachedLink = cache?.get(testId) - if (cachedLink) { - return cachedLink - } - - const link = container.querySelector( - `[data-testid="${testId}"]`, - ) - if (!link) { - throw new Error(`Unable to find benchmark link: ${testId}`) - } - - cache?.set(testId, link) - return link -} - -export async function waitForRequiredLink( - container: ParentNode, - testId: string, - cache?: Map, -) { - for (let attempt = 0; attempt < 10; attempt++) { - const link = container.querySelector( - `[data-testid="${testId}"]`, - ) - - if (link) { - cache?.set(testId, link) - return link - } - - await new Promise((resolve) => { - requestAnimationFrame(() => resolve()) - }) - } - - return getRequiredLink(container, testId, cache) -} diff --git a/benchmarks/client-nav/solid/app.tsx b/benchmarks/client-nav/solid/app.tsx deleted file mode 100644 index ef90130f5e..0000000000 --- a/benchmarks/client-nav/solid/app.tsx +++ /dev/null @@ -1,367 +0,0 @@ -import { For, createRenderEffect } from 'solid-js' -import { render } from 'solid-js/web' -import { - Link, - Outlet, - RouterProvider, - createMemoryHistory, - createRootRoute, - createRoute, - createRouter, - useParams, - useSearch, -} from '@tanstack/solid-router' - -function runPerfSelectorComputation(seed: number) { - let value = Math.trunc(seed) | 0 - - for (let index = 0; index < 40; index++) { - value = (value * 1664525 + 1013904223 + index) >>> 0 - } - - return value -} - -function normalizePage(value: unknown) { - const page = Number(value) - return Number.isFinite(page) && page > 0 ? Math.trunc(page) : 1 -} - -function normalizeFilter(value: unknown) { - return typeof value === 'string' && value.length > 0 ? value : 'all' -} - -const noop = () => {} -const rootSelectors = Array.from({ length: 10 }, (_, index) => index) -const routeSelectors = Array.from({ length: 6 }, (_, index) => index) -const linkGroups = Array.from({ length: 4 }, (_, index) => index) - -function PerfValue(props: { value: () => number }) { - createRenderEffect(() => { - void props.value() - }) - - return null -} - -function RootParamsSubscriber() { - const params = useParams({ - strict: false, - select: (params) => runPerfSelectorComputation(Number(params.id ?? 0)), - }) - - return runPerfSelectorComputation(params())} /> -} - -function RootSearchSubscriber() { - const search = useSearch({ - strict: false, - select: (search) => runPerfSelectorComputation(Number(search.page ?? 0)), - }) - - return runPerfSelectorComputation(search())} /> -} - -function LinkPanel() { - return ( - <> - - {(groupIndex) => { - const itemsId = groupIndex === 0 ? 1 : groupIndex + 2 - const ctxId = groupIndex + 1 - - return ( -
- - {`Items ${itemsId}`} - - - {`Items 2 alt ${groupIndex}`} - - - {`Search ${groupIndex}`} - - - {`Context ${ctxId}`} - - ({ - page: prev.page + groupIndex + 1, - filter: prev.filter, - junk: `updater-${groupIndex}`, - })} - activeOptions={{ includeSearch: true }} - > - {({ isActive }) => - isActive - ? `Search updater active ${groupIndex}` - : `Search updater inactive ${groupIndex}` - } - -
- ) - }} -
- - ) -} - -function Root() { - return ( - <> - {() => } - {() => } - - - - ) -} - -const rootRoute = createRootRoute({ - component: Root, -}) - -const itemsRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/items/$id', - params: { - parse: (params) => ({ - ...params, - id: normalizePage(params.id), - }), - stringify: (params) => ({ - ...params, - id: `${params.id}`, - }), - }, - onEnter: noop, - onStay: noop, - onLeave: noop, - component: ItemsPage, -}) - -const itemDetailsRoute = createRoute({ - getParentRoute: () => itemsRoute, - path: 'details', - component: ItemDetailsPage, -}) - -const searchRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/search', - validateSearch: (search: Record) => ({ - page: normalizePage(search.page), - filter: normalizeFilter(search.filter), - }), - search: { - middlewares: [ - ({ search, next }) => { - const result = next(search) - return { - page: result.page, - filter: result.filter, - } - }, - ], - }, - loaderDeps: ({ search }) => ({ - page: search.page, - filter: search.filter, - }), - loader: ({ deps }) => ({ - seed: deps.page * 31 + deps.filter.length, - checksum: deps.page * 17 + deps.filter.length, - }), - staleTime: 60_000, - gcTime: 60_000, - component: SearchPage, -}) - -const contextRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/ctx/$id', - beforeLoad: ({ params }) => ({ - sectionSeed: Number(params.id) * 13 + 1, - }), - component: ContextPage, -}) - -function ItemParamsSubscriber() { - const params = itemsRoute.useParams({ - select: (params) => runPerfSelectorComputation(params.id), - }) - - return runPerfSelectorComputation(params())} /> -} - -function SearchStateSubscriber() { - const search = searchRoute.useSearch({ - select: (search) => - runPerfSelectorComputation(search.page + search.filter.length), - }) - - return runPerfSelectorComputation(search())} /> -} - -function SearchLoaderDepsSubscriber() { - const loaderDeps = searchRoute.useLoaderDeps({ - select: (loaderDeps) => - runPerfSelectorComputation(loaderDeps.page + loaderDeps.filter.length), - }) - - return runPerfSelectorComputation(loaderDeps())} /> -} - -function SearchLoaderDataSubscriber() { - const loaderData = searchRoute.useLoaderData({ - select: (loaderData) => - runPerfSelectorComputation(loaderData.seed + loaderData.checksum), - }) - - return runPerfSelectorComputation(loaderData())} /> -} - -function ContextParamsSubscriber() { - const params = contextRoute.useParams({ - select: (params) => runPerfSelectorComputation(Number(params.id)), - }) - - return runPerfSelectorComputation(params())} /> -} - -function ContextRouteSubscriber() { - const context = contextRoute.useRouteContext({ - select: (context) => runPerfSelectorComputation(context.sectionSeed), - }) - - return runPerfSelectorComputation(context())} /> -} - -function ItemsPage() { - return ( - <> - {() => } - - Details - - - Preserve search on item - - - - ) -} - -function ItemDetailsPage() { - return ( - <> - {() => } - - Back to item - - - ) -} - -function SearchPage() { - return ( - <> - {() => } - {() => } - {() => } - ({ - page: prev.page + 1, - filter: prev.filter, - junk: 'local-updater', - })} - activeOptions={{ includeSearch: true }} - activeProps={{ class: 'active-link' }} - inactiveProps={{ class: 'inactive-link' }} - > - Next page - - - ) -} - -function ContextPage() { - return ( - <> - {() => } - {() => } - - ) -} - -export function mountTestApp(container: Element) { - const router = createRouter({ - history: createMemoryHistory({ - initialEntries: ['/items/0'], - }), - scrollRestoration: true, - routeTree: rootRoute.addChildren([ - itemsRoute.addChildren([itemDetailsRoute]), - searchRoute, - contextRoute, - ]), - }) - - const unmount = render(() => , container) - - return { - router, - unmount, - } -} diff --git a/benchmarks/client-nav/solid/setup.ts b/benchmarks/client-nav/solid/setup.ts deleted file mode 100644 index 9b532a466a..0000000000 --- a/benchmarks/client-nav/solid/setup.ts +++ /dev/null @@ -1,112 +0,0 @@ -import type { NavigateOptions } from '@tanstack/router-core' -import type * as App from './app' -import { getRequiredLink, waitForRequiredLink } from '../setup-helpers' - -const appModulePath = './dist/app.js' -const { mountTestApp } = (await import( - /* @vite-ignore */ appModulePath -)) as typeof App - -export function setup() { - if (process.env.NODE_ENV !== 'production') { - console.warn( - 'client-nav benchmark is running without NODE_ENV=production; Solid dev overhead will dominate results.', - ) - } - - let container: HTMLDivElement | undefined = undefined - let unmount: (() => void) | undefined = undefined - let unsub = () => {} - let stepIndex = 0 - let next: () => Promise = () => Promise.reject('Test not initialized') - - async function before() { - stepIndex = 0 - container = document.createElement('div') - document.body.append(container) - - const { router, unmount: dispose } = mountTestApp(container) - unmount = dispose - - let resolveRendered: () => void = () => {} - unsub = router.subscribe('onRendered', () => { - resolveRendered() - }) - - const navigate = (opts: NavigateOptions) => - new Promise((resolveNext) => { - resolveRendered = resolveNext - router.navigate(opts) - }) - - const click = (testId: string, cache?: Map) => - new Promise((resolveNext) => { - resolveRendered = resolveNext - - getRequiredLink(container!, testId, cache).dispatchEvent( - new MouseEvent('click', { - bubbles: true, - cancelable: true, - button: 0, - }), - ) - }) - - await router.load() - - const cachedLinks = new Map() - for (const testId of ['go-items-1', 'go-items-2', 'go-search', 'go-ctx']) { - await waitForRequiredLink(container, testId, cachedLinks) - } - - const steps = [ - () => click('go-items-1', cachedLinks), - () => click('items-details'), - () => - navigate({ - to: '/items/$id/details', - params: { id: 2 }, - replace: true, - }), - () => click('items-parent'), - () => click('go-search', cachedLinks), - () => click('search-next-page'), - () => - navigate({ - to: '/search', - search: { page: 1, filter: 'all' }, - replace: true, - }), - () => click('go-ctx', cachedLinks), - () => - navigate({ - to: '/ctx/$id', - params: { id: 2 }, - replace: true, - }), - () => click('go-items-2', cachedLinks), - ] as const - - next = () => { - const step = steps[stepIndex % steps.length]! - stepIndex += 1 - return step() - } - } - - function after() { - unmount?.() - container?.remove() - unsub() - } - - function tick() { - return next() - } - - return { - before, - tick, - after, - } -} diff --git a/benchmarks/client-nav/solid/speed.bench.ts b/benchmarks/client-nav/solid/speed.bench.ts deleted file mode 100644 index d629da17a8..0000000000 --- a/benchmarks/client-nav/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { setup } from './setup' - -test('client-nav', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-side navigation loop (solid)', - { beforeAll: scenario.before, afterAll: scenario.after }, - async () => { - for (let i = 0; i < 10; i++) { - await scenario.tick() - } - }, - ).run({ - warmupIterations: 100, - time: 10_000, - }) -}) diff --git a/benchmarks/client-nav/solid/speed.flame.ts b/benchmarks/client-nav/solid/speed.flame.ts deleted file mode 100644 index 285ccc63d7..0000000000 --- a/benchmarks/client-nav/solid/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/solid/tsconfig.json b/benchmarks/client-nav/solid/tsconfig.json deleted file mode 100644 index 4c500d0793..0000000000 --- a/benchmarks/client-nav/solid/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "extends": "../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "allowImportingTsExtensions": true, - "jsxImportSource": "solid-js", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "../jsdom.ts", - "setup.ts", - "vite.config.ts", - "../vitest.setup.ts" - ] -} diff --git a/benchmarks/client-nav/solid/vite.config.ts b/benchmarks/client-nav/solid/vite.config.ts deleted file mode 100644 index 0c26b32f5f..0000000000 --- a/benchmarks/client-nav/solid/vite.config.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import solid from 'vite-plugin-solid' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { cpuSimulationExecArgv } from '../../cpu-simulation' - -// Anchor the project root to the package directory so this config resolves -// identically when run directly and as part of an aggregate `projects` config. -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(), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './solid/dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './solid/app.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - resolve: { - 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/tsconfig.json b/benchmarks/client-nav/tsconfig.json deleted file mode 100644 index f657f504d4..0000000000 --- a/benchmarks/client-nav/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "../../tsconfig.json", - "compilerOptions": { - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": ["vitest.setup.ts"] -} diff --git a/benchmarks/client-nav/vitest.config.ts b/benchmarks/client-nav/vitest.config.ts deleted file mode 100644 index 808e7fc724..0000000000 --- a/benchmarks/client-nav/vitest.config.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { defineConfig } from 'vitest/config' - -export default defineConfig({ - test: { - watch: false, - projects: [ - './react/vite.config.ts', - './solid/vite.config.ts', - './vue/vite.config.ts', - './scenarios/*/react/vite.config.ts', - './scenarios/*/solid/vite.config.ts', - './scenarios/*/vue/vite.config.ts', - ], - }, -}) diff --git a/benchmarks/client-nav/vitest.react.config.ts b/benchmarks/client-nav/vitest.react.config.ts deleted file mode 100644 index a397ad929e..0000000000 --- a/benchmarks/client-nav/vitest.react.config.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { defineConfig } from 'vitest/config' - -export default defineConfig({ - test: { - watch: false, - projects: ['./react/vite.config.ts', './scenarios/*/react/vite.config.ts'], - }, -}) diff --git a/benchmarks/client-nav/vitest.setup.ts b/benchmarks/client-nav/vitest.setup.ts deleted file mode 100644 index 9bac58bd41..0000000000 --- a/benchmarks/client-nav/vitest.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { vi } from 'vitest' - -// @ts-expect-error -global.IS_REACT_ACT_ENVIRONMENT = true - -window.scrollTo = vi.fn() diff --git a/benchmarks/client-nav/vitest.solid.config.ts b/benchmarks/client-nav/vitest.solid.config.ts deleted file mode 100644 index b8827b86aa..0000000000 --- a/benchmarks/client-nav/vitest.solid.config.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { defineConfig } from 'vitest/config' - -export default defineConfig({ - test: { - watch: false, - projects: ['./solid/vite.config.ts', './scenarios/*/solid/vite.config.ts'], - }, -}) diff --git a/benchmarks/client-nav/vitest.vue.config.ts b/benchmarks/client-nav/vitest.vue.config.ts deleted file mode 100644 index 17960d7569..0000000000 --- a/benchmarks/client-nav/vitest.vue.config.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { defineConfig } from 'vitest/config' - -export default defineConfig({ - test: { - watch: false, - projects: ['./vue/vite.config.ts', './scenarios/*/vue/vite.config.ts'], - }, -}) diff --git a/benchmarks/client-nav/vue/app.tsx b/benchmarks/client-nav/vue/app.tsx deleted file mode 100644 index f88eee8129..0000000000 --- a/benchmarks/client-nav/vue/app.tsx +++ /dev/null @@ -1,433 +0,0 @@ -import * as Vue from 'vue' -import { - Link, - Outlet, - RouterProvider, - createMemoryHistory, - createRootRoute, - createRoute, - createRouter, - useParams, - useSearch, -} from '@tanstack/vue-router' - -function runPerfSelectorComputation(seed: number) { - let value = Math.trunc(seed) | 0 - - for (let index = 0; index < 40; index++) { - value = (value * 1664525 + 1013904223 + index) >>> 0 - } - - return value -} - -function normalizePage(value: unknown) { - const page = Number(value) - return Number.isFinite(page) && page > 0 ? Math.trunc(page) : 1 -} - -function normalizeFilter(value: unknown) { - return typeof value === 'string' && value.length > 0 ? value : 'all' -} - -const noop = () => {} -const rootSelectors = Array.from({ length: 10 }, (_, index) => index) -const routeSelectors = Array.from({ length: 6 }, (_, index) => index) -const linkGroups = Array.from({ length: 4 }, (_, index) => index) - -const RootParamsSubscriber = Vue.defineComponent({ - setup() { - const params = useParams({ - strict: false, - select: (params) => runPerfSelectorComputation(Number(params.id ?? 0)), - }) - - return () => { - void runPerfSelectorComputation(params.value) - return null - } - }, -}) - -const RootSearchSubscriber = Vue.defineComponent({ - setup() { - const search = useSearch({ - strict: false, - select: (search) => runPerfSelectorComputation(Number(search.page ?? 0)), - }) - - return () => { - void runPerfSelectorComputation(search.value) - return null - } - }, -}) - -const LinkPanel = Vue.defineComponent({ - setup() { - return () => ( - <> - {linkGroups.map((groupIndex) => { - const itemsId = groupIndex === 0 ? 1 : groupIndex + 2 - const ctxId = groupIndex + 1 - - return ( -
- - {`Items ${itemsId}`} - - - {`Items 2 alt ${groupIndex}`} - - - {`Search ${groupIndex}`} - - - {`Context ${ctxId}`} - - ({ - page: prev.page + groupIndex + 1, - filter: prev.filter, - junk: `updater-${groupIndex}`, - })} - activeOptions={{ includeSearch: true }} - > - {({ isActive }: { isActive: boolean }) => - isActive - ? `Search updater active ${groupIndex}` - : `Search updater inactive ${groupIndex}` - } - -
- ) - })} - - ) - }, -}) - -const Root = Vue.defineComponent({ - setup() { - return () => ( - <> - {rootSelectors.map((selector) => ( - - ))} - {rootSelectors.map((selector) => ( - - ))} - - - - ) - }, -}) - -const rootRoute = createRootRoute({ - component: Root, -}) - -const ItemParamsSubscriber = Vue.defineComponent({ - setup() { - const params = itemsRoute.useParams({ - select: (params) => runPerfSelectorComputation(params.id), - }) - - return () => { - void runPerfSelectorComputation(params.value) - return null - } - }, -}) - -const SearchStateSubscriber = Vue.defineComponent({ - setup() { - const search = searchRoute.useSearch({ - select: (search) => - runPerfSelectorComputation(search.page + search.filter.length), - }) - - return () => { - void runPerfSelectorComputation(search.value) - return null - } - }, -}) - -const SearchLoaderDepsSubscriber = Vue.defineComponent({ - setup() { - const loaderDeps = searchRoute.useLoaderDeps({ - select: (loaderDeps) => - runPerfSelectorComputation(loaderDeps.page + loaderDeps.filter.length), - }) - - return () => { - void runPerfSelectorComputation(loaderDeps.value) - return null - } - }, -}) - -const SearchLoaderDataSubscriber = Vue.defineComponent({ - setup() { - const loaderData = searchRoute.useLoaderData({ - select: (loaderData) => - runPerfSelectorComputation(loaderData.seed + loaderData.checksum), - }) - - return () => { - void runPerfSelectorComputation(loaderData.value) - return null - } - }, -}) - -const ContextParamsSubscriber = Vue.defineComponent({ - setup() { - const params = contextRoute.useParams({ - select: (params) => runPerfSelectorComputation(Number(params.id)), - }) - - return () => { - void runPerfSelectorComputation(params.value) - return null - } - }, -}) - -const ContextRouteSubscriber = Vue.defineComponent({ - setup() { - const context = contextRoute.useRouteContext({ - select: (context) => runPerfSelectorComputation(context.sectionSeed), - }) - - return () => { - void runPerfSelectorComputation(context.value) - return null - } - }, -}) - -const ItemsPage = Vue.defineComponent({ - setup() { - return () => ( - <> - {routeSelectors.map((selector) => ( - - ))} - - Details - - - Preserve search on item - - - - ) - }, -}) - -const ItemDetailsPage = Vue.defineComponent({ - setup() { - return () => ( - <> - {routeSelectors.map((selector) => ( - - ))} - - Back to item - - - ) - }, -}) - -const SearchPage = Vue.defineComponent({ - setup() { - return () => ( - <> - {routeSelectors.map((selector) => ( - - ))} - {routeSelectors.map((selector) => ( - - ))} - {routeSelectors.map((selector) => ( - - ))} - ({ - page: prev.page + 1, - filter: prev.filter, - junk: 'local-updater', - })} - activeOptions={{ includeSearch: true }} - activeProps={{ class: 'active-link' }} - inactiveProps={{ class: 'inactive-link' }} - > - Next page - - - ) - }, -}) - -const ContextPage = Vue.defineComponent({ - setup() { - return () => ( - <> - {routeSelectors.map((selector) => ( - - ))} - {routeSelectors.map((selector) => ( - - ))} - - ) - }, -}) - -const itemsRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/items/$id', - params: { - parse: (params) => ({ - ...params, - id: normalizePage(params.id), - }), - stringify: (params) => ({ - ...params, - id: `${params.id}`, - }), - }, - onEnter: noop, - onStay: noop, - onLeave: noop, - component: ItemsPage, -}) - -const itemDetailsRoute = createRoute({ - getParentRoute: () => itemsRoute, - path: 'details', - component: ItemDetailsPage, -}) - -const searchRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/search', - validateSearch: (search: Record) => ({ - page: normalizePage(search.page), - filter: normalizeFilter(search.filter), - }), - search: { - middlewares: [ - ({ search, next }) => { - const result = next(search) - return { - page: result.page, - filter: result.filter, - } - }, - ], - }, - loaderDeps: ({ search }) => ({ - page: search.page, - filter: search.filter, - }), - loader: ({ deps }) => ({ - seed: deps.page * 31 + deps.filter.length, - checksum: deps.page * 17 + deps.filter.length, - }), - staleTime: 60_000, - gcTime: 60_000, - component: SearchPage, -}) - -const contextRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/ctx/$id', - beforeLoad: ({ params }) => ({ - sectionSeed: Number(params.id) * 13 + 1, - }), - component: ContextPage, -}) - -export function mountTestApp(container: Element) { - const router = createRouter({ - history: createMemoryHistory({ - initialEntries: ['/items/0'], - }), - scrollRestoration: true, - routeTree: rootRoute.addChildren([ - itemsRoute.addChildren([itemDetailsRoute]), - searchRoute, - contextRoute, - ]), - }) - - const component = - const app = Vue.createApp({ - render: () => component, - }) - - app.mount(container) - - return { - router, - unmount() { - app.unmount() - }, - } -} diff --git a/benchmarks/client-nav/vue/setup.ts b/benchmarks/client-nav/vue/setup.ts deleted file mode 100644 index 75a633f629..0000000000 --- a/benchmarks/client-nav/vue/setup.ts +++ /dev/null @@ -1,112 +0,0 @@ -import type { NavigateOptions } from '@tanstack/router-core' -import type * as App from './app' -import { getRequiredLink, waitForRequiredLink } from '../setup-helpers' - -const appModulePath = './dist/app.js' -const { mountTestApp } = (await import( - /* @vite-ignore */ appModulePath -)) as typeof App - -export function setup() { - if (process.env.NODE_ENV !== 'production') { - console.warn( - 'client-nav benchmark is running without NODE_ENV=production; Vue dev overhead will dominate results.', - ) - } - - let container: HTMLDivElement | undefined = undefined - let unmount: (() => void) | undefined = undefined - let unsub = () => {} - let stepIndex = 0 - let next: () => Promise = () => Promise.reject('Test not initialized') - - async function before() { - stepIndex = 0 - container = document.createElement('div') - document.body.append(container) - - const { router, unmount: dispose } = mountTestApp(container) - unmount = dispose - - let resolveRendered: () => void = () => {} - unsub = router.subscribe('onRendered', () => { - resolveRendered() - }) - - const navigate = (opts: NavigateOptions) => - new Promise((resolveNext) => { - resolveRendered = resolveNext - router.navigate(opts) - }) - - const click = (testId: string, cache?: Map) => - new Promise((resolveNext) => { - resolveRendered = resolveNext - - getRequiredLink(container!, testId, cache).dispatchEvent( - new MouseEvent('click', { - bubbles: true, - cancelable: true, - button: 0, - }), - ) - }) - - await router.load() - - const cachedLinks = new Map() - for (const testId of ['go-items-1', 'go-items-2', 'go-search', 'go-ctx']) { - await waitForRequiredLink(container, testId, cachedLinks) - } - - const steps = [ - () => click('go-items-1', cachedLinks), - () => click('items-details'), - () => - navigate({ - to: '/items/$id/details', - params: { id: 2 }, - replace: true, - }), - () => click('items-parent'), - () => click('go-search', cachedLinks), - () => click('search-next-page'), - () => - navigate({ - to: '/search', - search: { page: 1, filter: 'all' }, - replace: true, - }), - () => click('go-ctx', cachedLinks), - () => - navigate({ - to: '/ctx/$id', - params: { id: 2 }, - replace: true, - }), - () => click('go-items-2', cachedLinks), - ] as const - - next = () => { - const step = steps[stepIndex % steps.length]! - stepIndex += 1 - return step() - } - } - - function after() { - unmount?.() - container?.remove() - unsub() - } - - function tick() { - return next() - } - - return { - before, - tick, - after, - } -} diff --git a/benchmarks/client-nav/vue/speed.bench.ts b/benchmarks/client-nav/vue/speed.bench.ts deleted file mode 100644 index 503e91e7b7..0000000000 --- a/benchmarks/client-nav/vue/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { setup } from './setup' - -test('client-nav', async ({ bench }) => { - const scenario = setup() - - await bench( - 'client-side navigation loop (vue)', - { beforeAll: scenario.before, afterAll: scenario.after }, - async () => { - for (let i = 0; i < 10; i++) { - await scenario.tick() - } - }, - ).run({ - warmupIterations: 100, - time: 10_000, - }) -}) diff --git a/benchmarks/client-nav/vue/speed.flame.ts b/benchmarks/client-nav/vue/speed.flame.ts deleted file mode 100644 index 285ccc63d7..0000000000 --- a/benchmarks/client-nav/vue/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { window } from '../jsdom.ts' -import { setup } from './setup.ts' - -const DURATION_MS = 10_000 - -const test = setup() - -try { - await test.before() - - const startedAt = performance.now() - while (performance.now() - startedAt < DURATION_MS) { - await test.tick() - } -} finally { - test.after() - window.close() -} diff --git a/benchmarks/client-nav/vue/tsconfig.json b/benchmarks/client-nav/vue/tsconfig.json deleted file mode 100644 index d8c92cfc17..0000000000 --- a/benchmarks/client-nav/vue/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "extends": "../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "allowImportingTsExtensions": true, - "jsxImportSource": "vue", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "speed.flame.ts", - "../jsdom.ts", - "setup.ts", - "vite.config.ts", - "../vitest.setup.ts" - ] -} diff --git a/benchmarks/client-nav/vue/vite.config.ts b/benchmarks/client-nav/vue/vite.config.ts deleted file mode 100644 index 78d8ae5638..0000000000 --- a/benchmarks/client-nav/vue/vite.config.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { 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. -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(), - vue(), - vueJsx(), - ], - build: { - outDir: './vue/dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './vue/app.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - 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 deleted file mode 100644 index 9b8859f74d..0000000000 --- a/benchmarks/cpu-simulation.ts +++ /dev/null @@ -1,53 +0,0 @@ -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 deleted file mode 100644 index 18b68768f9..0000000000 --- a/benchmarks/memory/README.md +++ /dev/null @@ -1,273 +0,0 @@ -# Memory Benchmarks - -Dedicated memory benchmarks for TanStack Router / Start, measured with the -CodSpeed **memory instrument** (`mode: memory` in -`.github/workflows/benchmarks.yml`). The workflow runs on every -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 -flags phantom regressions on every PR until the next run lands. (Falling back -across a docs-only commit is safe: the previous run's benchmark-relevant code -is identical.) Two separate benchmarks: - -- `server/` (`@benchmarks/memory-server`) — React/Solid/Vue Start apps, requests against - the built server handler (`handler.fetch`), Node environment. -- `client/` (`@benchmarks/memory-client`) — router-only React/Solid/Vue apps in jsdom. - -These deliberately do **not** reuse the CPU scenarios in `benchmarks/ssr` and -`benchmarks/client-nav`: memory benches need their own iteration counts, -payload sizes, and route shapes, and tuning those must never shift the CPU -baselines. Each scenario keeps a framework level (`react/`, `solid/`, `vue/`) -so framework ports can be added without renames. - -## Layout - -```text -benchmarks/memory// - package.json Nx targets: build:, test:perf:, test:flame:, test:types - bench-utils.ts memoryBenchOptions, seeded LCG (+ sequential request loop on the server side) - vitest..config.ts aggregates scenarios/*//vite.config.ts - scenarios/// - one isolated app per scenario + setup.ts + memory.bench.ts + memory.flame.ts -``` - -One app per scenario; apps and bench names are stable once landed (CodSpeed -continuity). Never grow an existing scenario for a new case — add a scenario. -`setup.ts` imports the built app and exports the concrete workload; -`memory.bench.ts` registers it with Vitest's `bench` test fixture, and -`memory.flame.ts` runs the same workload through the Flame profiler. - -## How the memory instrument executes a bench - -- The bench function is warmed up, then **measured exactly once**, starting - after a forced GC. Under plain `vitest bench` the suites only smoke-test: - timing output is meaningless; real numbers come from CodSpeed. -- Under CodSpeed the bench fn runs several warmup invocations plus the - measured one. The bench's `beforeEach`/`afterEach` hooks - (`memoryBenchHooks`) run around every invocation, outside the measurement - window: client workloads mount a fresh app before each invocation and tear - it down afterward. This prevents warmup navigation history and caches from - changing the starting state. Plain `vitest bench` runs the same hooks around - its warmup and measured iteration. Module-level counters/LCGs keep generated - URLs unique across invocations. -- Workload `run` functions must be `async` functions. CodSpeed's Vitest 5 - provider awaits only `AsyncFunction`s; a plain function that returns a - promise would be measured only up to its first suspension. -- Worker flags live in `runtime.ts` and apply only to the CodSpeed memory - instrument. They supplement the integration's predictable execution flags; - the retained overrides are described below. -- Before each CodSpeed invocation, the `beforeEach` hook yields to the event - loop, outside the measurement marker and before CodSpeed forces GC. Promise-only - warmup chains can keep WeakRef targets alive through a collection in the same - job. Client app setup also runs before the forced GC. -- Do not force GC inside a measured request loop or poll `heapUsed` to choose - how much work to do. Both introduce allocator activity from the harness into - the measurement. Footprint scenarios run exactly one large request per - invocation; churn scenarios retain their fixed sequential request counts. -- Error-path cases use separate isolated workers so one case's module and - allocator history cannot contaminate the next case. -- Keep each bench under **~1.5M allocations** (instrument overhead grows past - 2M); this is the main constraint when tuning iteration counts. - -## Worker settings - -All scenarios use [`memoryConfig`](./runtime.ts). It adds these flags only in -memory mode: - -- `--no-maglev` -- `--no-flush-bytecode` -- `--no-minor-gc-task` -- `--no-incremental-marking` -- `--initial-old-space-size=512` - -`--jitless` was removed after repeated CI comparisons. Ten unchanged-commit -repetitions with the last four flags kept all 48 peak-memory results within 1% -(worst spread: 0.834%). With JIT enabled, all 16 subsets of the four flags were -tested. Removing bytecode, minor-GC-task, incremental-marking, or heap-budget -overrides from this profile produced worst client peak spreads of 6.616%, 2.714%, -2.109%, and 10.669%, respectively. Smaller combinations also exceeded 1% in at -least one tracked metric. This supports retaining the four-flag profile; it does -not establish that every override is required in every individual scenario. - -A server-only heap-budget profile initially passed five repetitions, but further -confirmation produced a 24.46% server peak outlier. That configuration was -rejected. Allocated bytes and allocation counts remain imperfectly repeatable: -a client confirmation with the retained four flags showed a 6.77% allocated-byte -spread and a 5.91% allocation-count spread. Client peaks remained within 0.834% -across all 15 observations with the retained profile. Experiment details and CI runs are recorded in -[PR #8260](https://github.com/TanStack/router/pull/8260). - -These settings trade production GC behavior for repeatable regression signals. -They suppress bytecode reclamation and change collection scheduling. The 512 MiB -initial/minimum old-generation allocation budget can postpone automatic full -collections. This does not preallocate 512 MiB, and the smallest sufficient budget -was not determined. Results describe this controlled worker profile, not a -production application's absolute memory footprint. - -CodSpeed's `--no-opt` only disables TurboFan on Node 24 (V8 13); Maglev still -compiles. Under CodSpeed's `--predictable` there is no background compilation, -so Maglev compiles run synchronously inside whichever request triggers them, and -the forced GC before the measured call can discard optimized code so recompiles -land inside the measured window. Maglev's malloc'd Zone scratch (32 KiB -segments) then dominates allocation metrics, and its size depends on -per-process feedback state. `--no-maglev` was added for this: the bimodal -+32,792 B / +1 allocation in `mem server error-paths unmatched (react)` was one -Maglev Zone segment allocated while compiling React Fizz's per-request stream -`write` closure, and compiler scratch made up ~97% of that bench's allocated -bytes. Retained-object measurements are unaffected because Zone memory is freed -after each compile. The repeatability figures above predate this flag. - -## Bench shapes and signals - -- **Churn:** a fixed number of sequential operations, measuring native - allocation activity and peak outstanding native allocations. -- **Peak (footprint):** one large operation, measuring its native footprint. - -CodSpeed reports native allocator activity, not individual JavaScript object -allocations or retained JS heap size. V8 can reuse heap pages without a visible -native allocation. These benchmarks can detect native buffering and allocator -regressions, but a flat graph does not establish that route data or JS objects -are collectable. Absolute numbers include Node/framework/jsdom activity under -benchmark-specific V8 settings; compare identical harness versions. - -## Scenarios - -### Server - -| 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 | -| `error-paths` | churn | redirect/notFound/error/unmatched paths pinning contexts | -| `aborted-requests` | churn | dangling streams/listeners after mid-stream client aborts | -| `peak-large-page` | peak | per-request peak scaling with page size | -| `streaming-peak` | peak | streaming buffering O(document) instead of O(chunk) | -| `serialization-payload` | peak | double-buffering / string-copy blowups in dehydration | - -### Client - -| Scenario | Shape | Exercises | -| ------------------------- | ----- | -------------------------------------------------------- | -| `navigation-churn` | churn | per-navigation retention at steady state | -| `unique-location-churn` | churn | unbounded href/search-keyed caches (never-repeated URLs) | -| `preload-churn` | churn | preload-cache eviction not releasing memory | -| `loader-data-retention` | churn | departed routes' loader data staying pinned (gcTime 0) | -| `mount-unmount` | churn | router instances not collectable after dispose | -| `interrupted-navigations` | churn | superseded navigations retaining closures/contexts | - -## Conventions - -- Strictly sequential work: at most one request/navigation in flight; each - server response is fully consumed before the next request. Pairing a single - navigation with its render signal via `Promise.all([navigate, rendered])` - is fine — never overlap distinct work items. -- Randomness only via the seeded LCG in `bench-utils.ts`. Deferred streaming - uses counted zero-delay timer hops to stage work. Timers still depend on the - event loop, so validate repeatability on CI instead of assuming deterministic - ordering from a zero delay alone. -- 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 - `accept: text/html`, server-fn requests send `sec-fetch-site: same-origin` - with bodies precomputed at module level. -- Client apps export `mountTestApp` from `app.tsx`; benches import the built - `dist/app.js`; navigations use `replace: true`; unmount does full teardown - (framework root, `__TSR_ROUTER__`, `history.destroy()`); large loader payloads - are never rendered into the DOM. -- `NODE_ENV=production` everywhere (the Nx targets set it). - -## Run - -Smoke-test the CodSpeed/Vitest benchmark entrypoints and typecheck the -scenarios: - -```bash -pnpm nx run @benchmarks/memory-server:test:perf:react --outputStyle=stream --skipRemoteCache -pnpm nx run @benchmarks/memory-server:test:perf:solid --outputStyle=stream --skipRemoteCache -pnpm nx run @benchmarks/memory-server:test:perf:vue --outputStyle=stream --skipRemoteCache -pnpm nx run @benchmarks/memory-client:test:perf:react --outputStyle=stream --skipRemoteCache -pnpm nx run @benchmarks/memory-client:test:perf:solid --outputStyle=stream --skipRemoteCache -pnpm nx run @benchmarks/memory-client:test:perf:vue --outputStyle=stream --skipRemoteCache -pnpm nx run @benchmarks/memory-server:test:types --outputStyle=stream --skipRemoteCache -pnpm nx run @benchmarks/memory-client:test:types --outputStyle=stream --skipRemoteCache -``` - -Local attribution profiling, without CodSpeed CLI/login/sudo/upload, uses -`@datadog/pprof` heap sampling and `@platformatic/flame` only to render the -captured pprof files as HTML/Markdown. These targets rebuild the scenarios with -`--sourcemap true` so the generated profile reports can point back to source; -the normal CodSpeed benchmark builds are unchanged. Local aggregate scripts run -with `--parallel=1`, and scenario `test:flame` targets opt out of Nx parallelism -so profiling workloads do not overlap and bias each other. The Vitest aggregate -configs also set `fileParallelism: false` so benchmark files run sequentially -inside `test:perf:react`. - -```bash -pnpm benchmark:memory:server:flame -pnpm benchmark:memory:client:flame -pnpm benchmark:memory:server:flame:solid -pnpm benchmark:memory:client:flame:solid -pnpm benchmark:memory:server:flame:vue -pnpm benchmark:memory:client:flame:vue -``` - -To profile one scenario, run its `test:flame` target directly: - -```bash -pnpm nx run @benchmarks/memory-server-request-churn-react:test:flame --outputStyle=stream --skipRemoteCache -pnpm nx run @benchmarks/memory-client-navigation-churn-react:test:flame --outputStyle=stream --skipRemoteCache -``` - -Flame writes reports under the scenario's ignored `.profiles//` -directory, including `heap-profile-*.html` and `heap-profile-*.md`. The -`memory.flame.ts` entrypoints run the same workload shape as `memory.bench.ts` -but manually start profiling after sanity/setup work and stop it after the -measured workload. Treat these profiles as diagnostic heap-sampling attribution; -they are not CodSpeed memory metrics such as peak memory, allocated bytes, or -allocation counts. The heap sampler is stopped before profile conversion and -Flame report generation, so Flame/pprof report-generation work should not appear -as part of the captured workload. Flame runs do not force GC before profiling; -doing so would perturb the workload and still would not make heap sampling -equivalent to CodSpeed memory metrics. - -Clean local Flame profile output with: - -```bash -pnpm --filter @benchmarks/memory-server clean:profiles -pnpm --filter @benchmarks/memory-client clean:profiles -``` - -Client memory benches are useful for regression tracking of router/React/jsdom -integration behavior and native allocation activity. They are not pure -browser-memory measurements, and local Flame attribution can include jsdom, -React DOM, and profiler shutdown frames. - -Real memory measurement, locally (requires the CodSpeed CLI, `codspeed setup` -once to install the memory executor, and sudo; **uploads results to the -CodSpeed dashboard** — local runs do not affect PR baselines): - -```bash -WITH_INSTRUMENTATION=1 codspeed run --mode memory -- pnpm nx run @benchmarks/memory-server:test:perf:react -WITH_INSTRUMENTATION=1 codspeed run --mode memory -- pnpm nx run @benchmarks/memory-server:test:perf:solid -WITH_INSTRUMENTATION=1 codspeed run --mode memory -- pnpm nx run @benchmarks/memory-server:test:perf:vue -WITH_INSTRUMENTATION=1 codspeed run --mode memory -- pnpm nx run @benchmarks/memory-client:test:perf:react -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 deleted file mode 100644 index 785e8fac7f..0000000000 --- a/benchmarks/memory/client/bench-utils.ts +++ /dev/null @@ -1,22 +0,0 @@ -export { memoryBenchHooks } from '../turn' - -export const memoryBenchOptions = { - iterations: 1, - warmupIterations: 1, - time: 0, - warmupTime: 0, - throws: true, -} - -export function createDeterministicRandom(seed: number) { - let state = seed >>> 0 - - return () => { - state = (state * 1664525 + 1013904223) >>> 0 - return state / 0x100000000 - } -} - -export function randomSegment(random: () => number) { - return Math.floor(random() * 1_000_000_000).toString(36) -} diff --git a/benchmarks/memory/client/benchmark.ts b/benchmarks/memory/client/benchmark.ts deleted file mode 100644 index 463047f4d9..0000000000 --- a/benchmarks/memory/client/benchmark.ts +++ /dev/null @@ -1,11 +0,0 @@ -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/flame-runner.ts b/benchmarks/memory/client/flame-runner.ts deleted file mode 100644 index 04941fda67..0000000000 --- a/benchmarks/memory/client/flame-runner.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { profileFlameWorkload } from '../flame-control.ts' -import { window } from './jsdom.ts' -import type { ClientMemoryWorkload } from './benchmark.ts' - -export async function runClientFlameBenchmark(workload: ClientMemoryWorkload) { - try { - await workload.sanity() - await workload.before?.() - await profileFlameWorkload(workload.run, workload.name) - } finally { - await workload.after?.() - window.close() - } -} diff --git a/benchmarks/memory/client/jsdom.ts b/benchmarks/memory/client/jsdom.ts deleted file mode 100644 index 4df480df68..0000000000 --- a/benchmarks/memory/client/jsdom.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { JSDOM } from 'jsdom' - -const dom = new JSDOM('', { - url: 'http://localhost/', -}) - -const { window } = dom - -function setGlobal(name: string, value: unknown) { - Object.defineProperty(globalThis, name, { - value, - configurable: true, - writable: true, - }) -} - -setGlobal('window', window) -setGlobal('document', window.document) -setGlobal('self', window) -setGlobal('navigator', window.navigator) -setGlobal('location', window.location) -setGlobal('history', window.history) -setGlobal('HTMLElement', window.HTMLElement) -setGlobal('Element', window.Element) -setGlobal('SVGElement', window.SVGElement) -setGlobal('DocumentFragment', window.DocumentFragment) -setGlobal('Node', window.Node) -setGlobal('MouseEvent', window.MouseEvent) -setGlobal('MutationObserver', window.MutationObserver) -setGlobal('sessionStorage', window.sessionStorage) -setGlobal('localStorage', window.localStorage) -setGlobal('getComputedStyle', window.getComputedStyle.bind(window)) - -setGlobal( - 'requestAnimationFrame', - window.requestAnimationFrame?.bind(window) ?? - ((callback: (time: number) => void) => - setTimeout(() => callback(performance.now()), 16)), -) - -setGlobal( - 'cancelAnimationFrame', - window.cancelAnimationFrame?.bind(window) ?? - ((handle: number) => clearTimeout(handle)), -) - -const scrollTo = () => {} -window.scrollTo = scrollTo -setGlobal('scrollTo', scrollTo) - -export { window } diff --git a/benchmarks/memory/client/lifecycle.ts b/benchmarks/memory/client/lifecycle.ts deleted file mode 100644 index c4a62f0f96..0000000000 --- a/benchmarks/memory/client/lifecycle.ts +++ /dev/null @@ -1,46 +0,0 @@ -export type Framework = 'react' | 'solid' | 'vue' - -export type MountedApp = { - router: unknown - unmount: () => void -} - -export type MountTestApp = (container: HTMLDivElement) => MountedApp - -const frameworkNames = { - react: 'React', - solid: 'Solid', - vue: 'Vue', -} satisfies Record - -export function noop() {} - -export function warnClientMemoryDevMode(framework: Framework) { - if (process.env.NODE_ENV !== 'production') { - console.warn( - `memory client benchmark is running without NODE_ENV=production; ${frameworkNames[framework]} dev overhead will dominate results.`, - ) - } -} - -export function createBenchContainer() { - const container = document.createElement('div') - document.body.append(container) - - return container -} - -export function removeBenchContainer(container: HTMLDivElement | undefined) { - container?.remove() -} - -export function nextAnimationFrame() { - return new Promise((resolve) => { - requestAnimationFrame(() => resolve()) - }) -} - -export async function drainMicrotasks() { - await Promise.resolve() - await Promise.resolve() -} diff --git a/benchmarks/memory/client/package.json b/benchmarks/memory/client/package.json deleted file mode 100644 index 4dc6246183..0000000000 --- a/benchmarks/memory/client/package.json +++ /dev/null @@ -1,274 +0,0 @@ -{ - "name": "@benchmarks/memory-client", - "private": true, - "type": "module", - "scripts": { - "clean:profiles": "rm -rf scenarios/*/*/.profiles" - }, - "imports": { - "#memory-client/benchmark": "./benchmark.ts", - "#memory-client/bench-utils": "./bench-utils.ts", - "#memory-client/flame-runner": "./flame-runner.ts", - "#memory-client/lifecycle": "./lifecycle.ts" - }, - "dependencies": { - "@tanstack/react-router": "workspace:*", - "@tanstack/router-core": "workspace:*", - "@tanstack/solid-router": "workspace:*", - "@tanstack/vue-router": "workspace:*", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "solid-js": "^1.9.10", - "vue": "^3.5.16" - }, - "devDependencies": { - "@codspeed/vitest-plugin": "^6.0.1", - "@datadog/pprof": "^5.13.2", - "@platformatic/flame": "^1.6.0", - "@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:", - "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": "catalog:" - }, - "nx": { - "targets": { - "build:react": { - "executor": "nx:noop", - "cache": false, - "dependsOn": [ - { - "projects": [ - "@benchmarks/memory-client-navigation-churn-react", - "@benchmarks/memory-client-unique-location-churn-react", - "@benchmarks/memory-client-preload-churn-react", - "@benchmarks/memory-client-loader-data-retention-react", - "@benchmarks/memory-client-mount-unmount-react", - "@benchmarks/memory-client-interrupted-navigations-react" - ], - "target": "build:client" - } - ] - }, - "build:solid": { - "executor": "nx:noop", - "cache": false, - "dependsOn": [ - { - "projects": [ - "@benchmarks/memory-client-navigation-churn-solid", - "@benchmarks/memory-client-unique-location-churn-solid", - "@benchmarks/memory-client-preload-churn-solid", - "@benchmarks/memory-client-loader-data-retention-solid", - "@benchmarks/memory-client-mount-unmount-solid", - "@benchmarks/memory-client-interrupted-navigations-solid" - ], - "target": "build:client" - } - ] - }, - "build:vue": { - "executor": "nx:noop", - "cache": false, - "dependsOn": [ - { - "projects": [ - "@benchmarks/memory-client-navigation-churn-vue", - "@benchmarks/memory-client-unique-location-churn-vue", - "@benchmarks/memory-client-preload-churn-vue", - "@benchmarks/memory-client-loader-data-retention-vue", - "@benchmarks/memory-client-mount-unmount-vue", - "@benchmarks/memory-client-interrupted-navigations-vue" - ], - "target": "build:client" - } - ] - }, - "build:react:flame": { - "executor": "nx:noop", - "cache": false, - "dependsOn": [ - { - "projects": [ - "@benchmarks/memory-client-navigation-churn-react", - "@benchmarks/memory-client-unique-location-churn-react", - "@benchmarks/memory-client-preload-churn-react", - "@benchmarks/memory-client-loader-data-retention-react", - "@benchmarks/memory-client-mount-unmount-react", - "@benchmarks/memory-client-interrupted-navigations-react" - ], - "target": "build:client:flame" - } - ] - }, - "build:solid:flame": { - "executor": "nx:noop", - "cache": false, - "dependsOn": [ - { - "projects": [ - "@benchmarks/memory-client-navigation-churn-solid", - "@benchmarks/memory-client-unique-location-churn-solid", - "@benchmarks/memory-client-preload-churn-solid", - "@benchmarks/memory-client-loader-data-retention-solid", - "@benchmarks/memory-client-mount-unmount-solid", - "@benchmarks/memory-client-interrupted-navigations-solid" - ], - "target": "build:client:flame" - } - ] - }, - "build:vue:flame": { - "executor": "nx:noop", - "cache": false, - "dependsOn": [ - { - "projects": [ - "@benchmarks/memory-client-navigation-churn-vue", - "@benchmarks/memory-client-unique-location-churn-vue", - "@benchmarks/memory-client-preload-churn-vue", - "@benchmarks/memory-client-loader-data-retention-vue", - "@benchmarks/memory-client-mount-unmount-vue", - "@benchmarks/memory-client-interrupted-navigations-vue" - ], - "target": "build:client:flame" - } - ] - }, - "test:flame:react": { - "executor": "nx:noop", - "cache": false, - "dependsOn": [ - { - "projects": [ - "@benchmarks/memory-client-navigation-churn-react", - "@benchmarks/memory-client-unique-location-churn-react", - "@benchmarks/memory-client-preload-churn-react", - "@benchmarks/memory-client-loader-data-retention-react", - "@benchmarks/memory-client-mount-unmount-react", - "@benchmarks/memory-client-interrupted-navigations-react" - ], - "target": "test:flame" - } - ] - }, - "test:flame:solid": { - "executor": "nx:noop", - "cache": false, - "dependsOn": [ - { - "projects": [ - "@benchmarks/memory-client-navigation-churn-solid", - "@benchmarks/memory-client-unique-location-churn-solid", - "@benchmarks/memory-client-preload-churn-solid", - "@benchmarks/memory-client-loader-data-retention-solid", - "@benchmarks/memory-client-mount-unmount-solid", - "@benchmarks/memory-client-interrupted-navigations-solid" - ], - "target": "test:flame" - } - ] - }, - "test:flame:vue": { - "executor": "nx:noop", - "cache": false, - "dependsOn": [ - { - "projects": [ - "@benchmarks/memory-client-navigation-churn-vue", - "@benchmarks/memory-client-unique-location-churn-vue", - "@benchmarks/memory-client-preload-churn-vue", - "@benchmarks/memory-client-loader-data-retention-vue", - "@benchmarks/memory-client-mount-unmount-vue", - "@benchmarks/memory-client-interrupted-navigations-vue" - ], - "target": "test:flame" - } - ] - }, - "test:perf:react": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": [ - "build:react" - ], - "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.react.config.ts", - "cwd": "benchmarks/memory/client" - } - }, - "test:perf:solid": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": [ - "build:solid" - ], - "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.solid.config.ts", - "cwd": "benchmarks/memory/client" - } - }, - "test:perf:vue": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": [ - "build:vue" - ], - "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.vue.config.ts", - "cwd": "benchmarks/memory/client" - } - }, - "test:types": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": [ - "@benchmarks/memory-client-navigation-churn-react", - "@benchmarks/memory-client-unique-location-churn-react", - "@benchmarks/memory-client-preload-churn-react", - "@benchmarks/memory-client-loader-data-retention-react", - "@benchmarks/memory-client-mount-unmount-react", - "@benchmarks/memory-client-interrupted-navigations-react", - "@benchmarks/memory-client-navigation-churn-solid", - "@benchmarks/memory-client-unique-location-churn-solid", - "@benchmarks/memory-client-preload-churn-solid", - "@benchmarks/memory-client-loader-data-retention-solid", - "@benchmarks/memory-client-mount-unmount-solid", - "@benchmarks/memory-client-interrupted-navigations-solid", - "@benchmarks/memory-client-navigation-churn-vue", - "@benchmarks/memory-client-unique-location-churn-vue", - "@benchmarks/memory-client-preload-churn-vue", - "@benchmarks/memory-client-loader-data-retention-vue", - "@benchmarks/memory-client-mount-unmount-vue", - "@benchmarks/memory-client-interrupted-navigations-vue" - ], - "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 deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' -import { workload } from './setup' - -await workload.sanity() - -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) -}) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/react/memory.flame.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/react/memory.flame.ts deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runClientFlameBenchmark } from '#memory-client/flame-runner' -import { workload } from './setup.ts' - -await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/react/project.json b/benchmarks/memory/client/scenarios/interrupted-navigations/react/project.json deleted file mode 100644 index 0ed437c9ca..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-client-interrupted-navigations-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.config.ts" - } - }, - "build:client:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:client:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "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/memory/client/scenarios/interrupted-navigations/react/setup.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/react/setup.ts deleted file mode 100644 index 6e072ad5f3..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/setup.ts +++ /dev/null @@ -1,19 +0,0 @@ -import type { ClientMemoryWorkload } from '#memory-client/benchmark' -import type * as App from './src/app' -import { createWorkload } from '../shared.ts' - -const appModulePath = './dist/app.js' -const { - mountTestApp, - resolveAllSlowLoaders, - resolveSlowLoader, - slowLoaderRegistry, -} = (await import(/* @vite-ignore */ appModulePath)) as typeof App - -export const workload: ClientMemoryWorkload = createWorkload( - 'react', - mountTestApp, - resolveAllSlowLoaders, - resolveSlowLoader, - slowLoaderRegistry, -) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/app.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/app.tsx deleted file mode 100644 index bd605a78ee..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/app.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import { RouterProvider } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { getRouter } from './router' - -export { - resolveAllSlowLoaders, - resolveSlowLoader, - slowLoaderRegistry, -} from '../../slow-loaders' - -export function mountTestApp(container: Element) { - const router = getRouter() - const reactRoot = createRoot(container) - let didUnmount = false - - reactRoot.render() - - // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, - // release the devtools global, and detach history listeners. - return { - router, - unmount() { - if (didUnmount) { - return - } - - didUnmount = true - reactRoot.unmount() - - if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { - self.__TSR_ROUTER__ = undefined - } - - router.history.destroy() - }, - } -} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routeTree.gen.ts deleted file mode 100644 index 475085a433..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routeTree.gen.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as SlowIdRouteImport } from './routes/slow.$id' -import { Route as FastIdRouteImport } from './routes/fast.$id' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const SlowIdRoute = SlowIdRouteImport.update({ - id: '/slow/$id', - path: '/slow/$id', - getParentRoute: () => rootRouteImport, -} as any) -const FastIdRoute = FastIdRouteImport.update({ - id: '/fast/$id', - path: '/fast/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/fast/$id': typeof FastIdRoute - '/slow/$id': typeof SlowIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/fast/$id': typeof FastIdRoute - '/slow/$id': typeof SlowIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/fast/$id': typeof FastIdRoute - '/slow/$id': typeof SlowIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/fast/$id' | '/slow/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/fast/$id' | '/slow/$id' - id: '__root__' | '/' | '/fast/$id' | '/slow/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - FastIdRoute: typeof FastIdRoute - SlowIdRoute: typeof SlowIdRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/slow/$id': { - id: '/slow/$id' - path: '/slow/$id' - fullPath: '/slow/$id' - preLoaderRoute: typeof SlowIdRouteImport - parentRoute: typeof rootRouteImport - } - '/fast/$id': { - id: '/fast/$id' - path: '/fast/$id' - fullPath: '/fast/$id' - preLoaderRoute: typeof FastIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - FastIdRoute: FastIdRoute, - SlowIdRoute: SlowIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/router.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/router.tsx deleted file mode 100644 index ac27b20f79..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/router.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { createMemoryHistory, createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - history: createMemoryHistory({ - initialEntries: ['/'], - }), - routeTree, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routes/__root.tsx deleted file mode 100644 index 889395056b..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createRootRoute } from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return -} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routes/fast.$id.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routes/fast.$id.tsx deleted file mode 100644 index d5fd7ade46..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routes/fast.$id.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { fixedTimestamp } from '../../../slow-loaders' - -export const Route = createFileRoute('/fast/$id')({ - loader: ({ params }) => ({ - id: params.id, - kind: 'fast' as const, - ts: fixedTimestamp, - }), - component: FastComponent, -}) - -function FastComponent() { - const data = Route.useLoaderData() - - return ( -
- {`${data.kind}:${data.id}:${data.ts}`} -
- ) -} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routes/index.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routes/index.tsx deleted file mode 100644 index a425ac79c4..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
shell
-} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routes/slow.$id.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routes/slow.$id.tsx deleted file mode 100644 index 61bbf328b7..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routes/slow.$id.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { getSlowLoaderDeferred } from '../../../slow-loaders' - -export const Route = createFileRoute('/slow/$id')({ - loader: async ({ params }) => { - const deferred = getSlowLoaderDeferred(params.id) - - return await deferred.promise - }, - component: SlowComponent, -}) - -function SlowComponent() { - const data = Route.useLoaderData() - - return ( -
- {`${data.kind}:${data.id}:${data.ts}`} -
- ) -} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/react/tsconfig.json b/benchmarks/memory/client/scenarios/interrupted-navigations/react/tsconfig.json deleted file mode 100644 index ea566061d9..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "allowImportingTsExtensions": true, - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "src/**/*.ts", - "src/**/*.tsx", - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../../../vitest.setup.ts" - ] -} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/react/vite.config.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/react/vite.config.ts deleted file mode 100644 index 0f05cedf40..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/vite.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -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)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/app.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - ...memoryConfig('client'), - name: '@benchmarks/memory-client interrupted-navigations (react)', - watch: false, - environment: 'jsdom', - }, -}) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/shared.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/shared.ts deleted file mode 100644 index 80f234f0c8..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/shared.ts +++ /dev/null @@ -1,297 +0,0 @@ -import { - createDeterministicRandom, - randomSegment, -} from '#memory-client/bench-utils' -import { - createBenchContainer, - drainMicrotasks, - nextAnimationFrame, - noop, - removeBenchContainer, - warnClientMemoryDevMode, -} from '#memory-client/lifecycle' -import type { Framework, MountTestApp } from '#memory-client/lifecycle' - -type NavigationSettlement = - | { - status: 'fulfilled' - value: void - } - | { - status: 'rejected' - reason: unknown - } - -type ResolveAllSlowLoaders = () => void -type ResolveSlowLoader = (id: string) => void -type SlowLoaderRegistry = { - has: (id: string) => boolean -} - -type RenderedEvent = { - toLocation: { - pathname: string - } -} - -type InterruptedNavigationRouter = { - load: () => Promise - navigate: (options: { - to: '/fast/$id' | '/slow/$id' - params: { id: string } - replace: true - }) => Promise - subscribe: ( - event: 'onRendered', - listener: (event: RenderedEvent) => void, - ) => () => void -} - -const interruptedNavigationIterations = 150 -const interruptedNavigationPairs = createInterruptedNavigationPairs( - interruptedNavigationIterations, -) - -const uninitialized = () => - Promise.reject( - new Error('interrupted-navigations benchmark is not initialized'), - ) - -const uninitializedSettlement = () => - Promise.resolve({ - status: 'rejected', - reason: new Error('interrupted-navigations benchmark is not initialized'), - }) - -function createInterruptedNavigationPairs(iterations: number) { - const random = createDeterministicRandom(13) - - return Array.from({ length: iterations }, (_, index) => ({ - slowId: `slow-${index}-${randomSegment(random)}`, - fastId: `fast-${index}-${randomSegment(random)}`, - })) -} - -function formatReason(reason: unknown) { - if (reason instanceof Error) { - return `${reason.name}: ${reason.message}` - } - - return String(reason) -} - -function assertSlowNavigationSettlement(settlement: NavigationSettlement) { - if (settlement.status === 'fulfilled') { - if (settlement.value !== undefined) { - throw new Error('Expected slow navigation to fulfill with undefined') - } - - return - } - - if ( - reasonHasAbortShape(settlement.reason) || - reasonHasCancellationShape(settlement.reason) - ) { - return - } - - throw new Error( - `Expected slow navigation to settle as void or cancellation, got ${formatReason( - settlement.reason, - )}`, - ) -} - -function reasonHasAbortShape(reason: unknown) { - return reason instanceof DOMException && reason.name === 'AbortError' -} - -function reasonHasCancellationShape(reason: unknown) { - return ( - reason instanceof Error && - (reason.name === 'AbortError' || reason.name === 'CancelledError') - ) -} - -export function createWorkload( - framework: Framework, - mountTestApp: MountTestApp, - resolveAllSlowLoaders: ResolveAllSlowLoaders, - resolveSlowLoader: ResolveSlowLoader, - slowLoaderRegistry: SlowLoaderRegistry, -) { - warnClientMemoryDevMode(framework) - - let container: HTMLDivElement | undefined = undefined - let unmount = noop - let unsub = noop - let resolveRendered: () => void = noop - let expectedRenderedPath: string | undefined = undefined - let navigateFast: (id: string) => Promise = uninitialized - let startSlowNavigation: (id: string) => Promise = - uninitializedSettlement - - function assertRenderedPage(page: 'shell' | 'fast', id?: string) { - const element = container?.querySelector('[data-bench-page]') - const actualPage = element?.dataset.benchPage - const actualId = element?.dataset.benchId - - if (actualPage !== page) { - throw new Error(`Expected rendered page ${page}, got ${actualPage}`) - } - - if (id !== undefined && actualId !== id) { - throw new Error(`Expected rendered id ${id}, got ${actualId}`) - } - } - - async function waitForRenderedPage(page: 'shell' | 'fast', id?: string) { - for (let attempt = 0; attempt < 10; attempt++) { - try { - assertRenderedPage(page, id) - return - } catch { - await nextAnimationFrame() - } - } - - assertRenderedPage(page, id) - } - - async function waitForSlowLoader(id: string) { - for (let attempt = 0; attempt < 20; attempt++) { - if (slowLoaderRegistry.has(id)) { - return - } - - await drainMicrotasks() - } - - throw new Error(`Slow loader was not registered for id: ${id}`) - } - - function waitForNextRender(pathname: string) { - expectedRenderedPath = pathname - - return new Promise((resolve) => { - resolveRendered = resolve - }) - } - - async function before() { - if (container) { - after() - } - - container = createBenchContainer() - - const mounted = mountTestApp(container) - const router = mounted.router as InterruptedNavigationRouter - unmount = mounted.unmount - - unsub = router.subscribe('onRendered', (event) => { - if ( - expectedRenderedPath && - event.toLocation.pathname !== expectedRenderedPath - ) { - return - } - - const resolve = resolveRendered - resolveRendered = noop - expectedRenderedPath = undefined - resolve() - }) - - navigateFast = async (id) => { - const rendered = waitForNextRender(`/fast/${id}`) - await Promise.all([ - router.navigate({ - to: '/fast/$id', - params: { id }, - replace: true, - }), - rendered, - ]) - } - - startSlowNavigation = (id) => { - const navigation = router.navigate({ - to: '/slow/$id', - params: { id }, - replace: true, - }) - - return navigation - .then((value): NavigationSettlement => ({ status: 'fulfilled', value })) - .catch( - (reason: unknown): NavigationSettlement => ({ - status: 'rejected', - reason, - }), - ) - } - - await router.load() - await waitForRenderedPage('shell') - } - - function after() { - resolveAllSlowLoaders() - unmount() - removeBenchContainer(container) - unsub() - - container = undefined - unmount = noop - unsub = noop - resolveRendered = noop - expectedRenderedPath = undefined - navigateFast = uninitialized - startSlowNavigation = uninitializedSettlement - } - - async function interrupt( - slowId: string, - fastId: string, - assertSettlement = true, - ) { - const slowNavigation = startSlowNavigation(slowId) - - await waitForSlowLoader(slowId) - await navigateFast(fastId) - resolveSlowLoader(slowId) - - const settlement = await slowNavigation - - if (assertSettlement) { - assertSlowNavigationSettlement(settlement) - } - - await drainMicrotasks() - } - - return { - name: `mem client interrupted-navigations (${framework})`, - before, - interrupt, - async run() { - for (const pair of interruptedNavigationPairs) { - await interrupt(pair.slowId, pair.fastId) - } - }, - async sanity() { - await before() - - try { - assertRenderedPage('shell') - await interrupt('sanity-slow', 'sanity-fast', false) - assertRenderedPage('fast', 'sanity-fast') - } finally { - after() - } - }, - after, - } -} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/slow-loaders.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/slow-loaders.ts deleted file mode 100644 index c70ccac3da..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/slow-loaders.ts +++ /dev/null @@ -1,54 +0,0 @@ -export const fixedTimestamp = 1_700_000_000_000 - -type SlowLoaderPayload = { - id: string - kind: 'slow' - ts: number -} - -type SlowLoaderDeferred = { - promise: Promise - resolve: () => void -} - -export const slowLoaderRegistry = new Map() - -export function getSlowLoaderDeferred(id: string) { - const existing = slowLoaderRegistry.get(id) - - if (existing) { - return existing - } - - let resolvePromise!: (payload: SlowLoaderPayload) => void - const promise = new Promise((resolve) => { - resolvePromise = resolve - }) - - const deferred: SlowLoaderDeferred = { - promise, - resolve() { - slowLoaderRegistry.delete(id) - resolvePromise({ id, kind: 'slow', ts: fixedTimestamp }) - }, - } - - slowLoaderRegistry.set(id, deferred) - return deferred -} - -export function resolveSlowLoader(id: string) { - const deferred = slowLoaderRegistry.get(id) - - if (!deferred) { - throw new Error(`No pending slow loader for id: ${id}`) - } - - deferred.resolve() -} - -export function resolveAllSlowLoaders() { - for (const id of Array.from(slowLoaderRegistry.keys())) { - resolveSlowLoader(id) - } -} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/memory.bench.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/memory.bench.ts deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' -import { workload } from './setup' - -await workload.sanity() - -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) -}) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/memory.flame.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/memory.flame.ts deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runClientFlameBenchmark } from '#memory-client/flame-runner' -import { workload } from './setup.ts' - -await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/project.json b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/project.json deleted file mode 100644 index 4aff39500e..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-client-interrupted-navigations-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.config.ts" - } - }, - "build:client:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:client:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "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/memory/client/scenarios/interrupted-navigations/solid/setup.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/setup.ts deleted file mode 100644 index e736111663..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/setup.ts +++ /dev/null @@ -1,19 +0,0 @@ -import type { ClientMemoryWorkload } from '#memory-client/benchmark' -import type * as App from './src/app' -import { createWorkload } from '../shared.ts' - -const appModulePath = './dist/app.js' -const { - mountTestApp, - resolveAllSlowLoaders, - resolveSlowLoader, - slowLoaderRegistry, -} = (await import(/* @vite-ignore */ appModulePath)) as typeof App - -export const workload: ClientMemoryWorkload = createWorkload( - 'solid', - mountTestApp, - resolveAllSlowLoaders, - resolveSlowLoader, - slowLoaderRegistry, -) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/app.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/app.tsx deleted file mode 100644 index 6288b5fab1..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/app.tsx +++ /dev/null @@ -1,35 +0,0 @@ -import { RouterProvider } from '@tanstack/solid-router' -import { render } from 'solid-js/web' -import { getRouter } from './router' - -export { - resolveAllSlowLoaders, - resolveSlowLoader, - slowLoaderRegistry, -} from '../../slow-loaders' - -export function mountTestApp(container: Element) { - const router = getRouter() - const dispose = render(() => , container) - let didUnmount = false - - // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, - // release the devtools global, and detach history listeners. - return { - router, - unmount() { - if (didUnmount) { - return - } - - didUnmount = true - dispose() - - if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { - self.__TSR_ROUTER__ = undefined - } - - router.history.destroy() - }, - } -} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routeTree.gen.ts deleted file mode 100644 index f42255963c..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as SlowIdRouteImport } from './routes/slow.$id' -import { Route as FastIdRouteImport } from './routes/fast.$id' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const SlowIdRoute = SlowIdRouteImport.update({ - id: '/slow/$id', - path: '/slow/$id', - getParentRoute: () => rootRouteImport, -} as any) -const FastIdRoute = FastIdRouteImport.update({ - id: '/fast/$id', - path: '/fast/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/fast/$id': typeof FastIdRoute - '/slow/$id': typeof SlowIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/fast/$id': typeof FastIdRoute - '/slow/$id': typeof SlowIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/fast/$id': typeof FastIdRoute - '/slow/$id': typeof SlowIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/fast/$id' | '/slow/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/fast/$id' | '/slow/$id' - id: '__root__' | '/' | '/fast/$id' | '/slow/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - FastIdRoute: typeof FastIdRoute - SlowIdRoute: typeof SlowIdRoute -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/slow/$id': { - id: '/slow/$id' - path: '/slow/$id' - fullPath: '/slow/$id' - preLoaderRoute: typeof SlowIdRouteImport - parentRoute: typeof rootRouteImport - } - '/fast/$id': { - id: '/fast/$id' - path: '/fast/$id' - fullPath: '/fast/$id' - preLoaderRoute: typeof FastIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - FastIdRoute: FastIdRoute, - SlowIdRoute: SlowIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/router.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/router.tsx deleted file mode 100644 index 884aa3438f..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/router.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { createMemoryHistory, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - history: createMemoryHistory({ - initialEntries: ['/'], - }), - routeTree, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routes/__root.tsx deleted file mode 100644 index cb8d5a688d..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createRootRoute } from '@tanstack/solid-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return -} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routes/fast.$id.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routes/fast.$id.tsx deleted file mode 100644 index 511e4712b7..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routes/fast.$id.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { fixedTimestamp } from '../../../slow-loaders' - -export const Route = createFileRoute('/fast/$id')({ - loader: ({ params }) => ({ - id: params.id, - kind: 'fast' as const, - ts: fixedTimestamp, - }), - component: FastComponent, -}) - -function FastComponent() { - const data = Route.useLoaderData() - - return ( -
- {`${data().kind}:${data().id}:${data().ts}`} -
- ) -} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routes/index.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routes/index.tsx deleted file mode 100644 index 592b2d666e..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
shell
-} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routes/slow.$id.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routes/slow.$id.tsx deleted file mode 100644 index 9aaaef5568..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routes/slow.$id.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { getSlowLoaderDeferred } from '../../../slow-loaders' - -export const Route = createFileRoute('/slow/$id')({ - loader: async ({ params }) => { - const deferred = getSlowLoaderDeferred(params.id) - - return await deferred.promise - }, - component: SlowComponent, -}) - -function SlowComponent() { - const data = Route.useLoaderData() - - return ( -
- {`${data().kind}:${data().id}:${data().ts}`} -
- ) -} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/tsconfig.json b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/tsconfig.json deleted file mode 100644 index b12dcb7ade..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "allowImportingTsExtensions": true, - "jsxImportSource": "solid-js", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "src/**/*.ts", - "src/**/*.tsx", - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../../../vitest.setup.ts" - ] -} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/vite.config.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/vite.config.ts deleted file mode 100644 index 26ff0b5c8c..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/vite.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -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)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/app.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - ...memoryConfig('client'), - name: '@benchmarks/memory-client interrupted-navigations (solid)', - watch: false, - environment: 'jsdom', - }, -}) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/memory.bench.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/memory.bench.ts deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' -import { workload } from './setup' - -await workload.sanity() - -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) -}) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/memory.flame.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/memory.flame.ts deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runClientFlameBenchmark } from '#memory-client/flame-runner' -import { workload } from './setup.ts' - -await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/project.json b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/project.json deleted file mode 100644 index 01288cb235..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-client-interrupted-navigations-vue", - "projectType": "application", - "targets": { - "build:client": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "build:client:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:client:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "test:types:client": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/vue-router"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/setup.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/setup.ts deleted file mode 100644 index 260e45b64b..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/setup.ts +++ /dev/null @@ -1,19 +0,0 @@ -import type { ClientMemoryWorkload } from '#memory-client/benchmark' -import type * as App from './src/app' -import { createWorkload } from '../shared.ts' - -const appModulePath = './dist/app.js' -const { - mountTestApp, - resolveAllSlowLoaders, - resolveSlowLoader, - slowLoaderRegistry, -} = (await import(/* @vite-ignore */ appModulePath)) as typeof App - -export const workload: ClientMemoryWorkload = createWorkload( - 'vue', - mountTestApp, - resolveAllSlowLoaders, - resolveSlowLoader, - slowLoaderRegistry, -) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/app.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/app.tsx deleted file mode 100644 index 1abb4410dc..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/app.tsx +++ /dev/null @@ -1,42 +0,0 @@ -import { RouterProvider } from '@tanstack/vue-router' -import { createApp } from 'vue' -import { getRouter } from './router' -import type {} from '@tanstack/router-core' - -export { - resolveAllSlowLoaders, - resolveSlowLoader, - slowLoaderRegistry, -} from '../../slow-loaders' - -export function mountTestApp(container: Element) { - const router = getRouter() - const vueApp = createApp({ - setup() { - return () => - }, - }) - let didUnmount = false - - vueApp.mount(container) - - // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, - // release the devtools global, and detach history listeners. - return { - router, - unmount() { - if (didUnmount) { - return - } - - didUnmount = true - vueApp.unmount() - - if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { - self.__TSR_ROUTER__ = undefined - } - - router.history.destroy() - }, - } -} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routeTree.gen.ts deleted file mode 100644 index 5ea61a89a3..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as SlowIdRouteImport } from './routes/slow.$id' -import { Route as FastIdRouteImport } from './routes/fast.$id' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const SlowIdRoute = SlowIdRouteImport.update({ - id: '/slow/$id', - path: '/slow/$id', - getParentRoute: () => rootRouteImport, -} as any) -const FastIdRoute = FastIdRouteImport.update({ - id: '/fast/$id', - path: '/fast/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/fast/$id': typeof FastIdRoute - '/slow/$id': typeof SlowIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/fast/$id': typeof FastIdRoute - '/slow/$id': typeof SlowIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/fast/$id': typeof FastIdRoute - '/slow/$id': typeof SlowIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/fast/$id' | '/slow/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/fast/$id' | '/slow/$id' - id: '__root__' | '/' | '/fast/$id' | '/slow/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - FastIdRoute: typeof FastIdRoute - SlowIdRoute: typeof SlowIdRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/slow/$id': { - id: '/slow/$id' - path: '/slow/$id' - fullPath: '/slow/$id' - preLoaderRoute: typeof SlowIdRouteImport - parentRoute: typeof rootRouteImport - } - '/fast/$id': { - id: '/fast/$id' - path: '/fast/$id' - fullPath: '/fast/$id' - preLoaderRoute: typeof FastIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - FastIdRoute: FastIdRoute, - SlowIdRoute: SlowIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/router.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/router.tsx deleted file mode 100644 index 4655fe8424..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/router.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { createMemoryHistory, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - history: createMemoryHistory({ - initialEntries: ['/'], - }), - routeTree, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/__root.tsx deleted file mode 100644 index 91296e6f84..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createRootRoute } from '@tanstack/vue-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return -} 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 deleted file mode 100644 index f6dc9ac3bd..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/fast.$id.tsx +++ /dev/null @@ -1,24 +0,0 @@ -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, - kind: 'fast' as const, - ts: fixedTimestamp, - }), - component: FastComponent, -}) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/index.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/index.tsx deleted file mode 100644 index c30a51e1e5..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
shell
-} 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 deleted file mode 100644 index 3b5bb75ede..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/slow.$id.tsx +++ /dev/null @@ -1,24 +0,0 @@ -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) - - return await deferred.promise - }, - component: SlowComponent, -}) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/tsconfig.json b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/tsconfig.json deleted file mode 100644 index 9a5872a4c0..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "allowImportingTsExtensions": true, - "jsxImportSource": "vue", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "src/**/*.ts", - "src/**/*.tsx", - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../../../vitest.setup.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 deleted file mode 100644 index 02574908d2..0000000000 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/app.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - ...memoryConfig('client'), - name: '@benchmarks/memory-client interrupted-navigations (vue)', - watch: false, - environment: 'jsdom', - }, -}) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/loader-data.ts b/benchmarks/memory/client/scenarios/loader-data-retention/loader-data.ts deleted file mode 100644 index 3bd59c82ef..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/loader-data.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { - createDeterministicRandom, - randomSegment, -} from '#memory-client/bench-utils' - -export const loaderPayloadRecordCount = 512 - -const loaderPayloadCharsPerRecord = 1024 - -type LoaderRecord = { - key: string - value: string -} - -export function createLoaderData(id: string) { - const random = createDeterministicRandom(hashId(id)) - const records: Array = [] - - for (let index = 0; index < loaderPayloadRecordCount; index++) { - records.push({ - key: `${id}:${index}:${randomSegment(random)}`, - value: createRecordValue(id, index, random), - }) - } - - return { id, records } -} - -function createRecordValue(id: string, index: number, random: () => number) { - const firstSegment = randomSegment(random) - const secondSegment = randomSegment(random) - const segment = `${id}:${index}:${firstSegment}:${secondSegment}:` - - return segment - .repeat(Math.ceil(loaderPayloadCharsPerRecord / segment.length)) - .slice(0, loaderPayloadCharsPerRecord) -} - -function hashId(id: string) { - let hash = 2166136261 - - for (let index = 0; index < id.length; index++) { - hash ^= id.charCodeAt(index) - hash = Math.imul(hash, 16777619) - } - - return hash >>> 0 -} 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 deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' -import { workload } from './setup' - -await workload.sanity() - -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) -}) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/react/memory.flame.ts b/benchmarks/memory/client/scenarios/loader-data-retention/react/memory.flame.ts deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runClientFlameBenchmark } from '#memory-client/flame-runner' -import { workload } from './setup.ts' - -await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/react/project.json b/benchmarks/memory/client/scenarios/loader-data-retention/react/project.json deleted file mode 100644 index 713038e20f..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-client-loader-data-retention-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.config.ts" - } - }, - "build:client:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:client:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "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/memory/client/scenarios/loader-data-retention/react/setup.ts b/benchmarks/memory/client/scenarios/loader-data-retention/react/setup.ts deleted file mode 100644 index fafaf13e6f..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ClientMemoryWorkload } from '#memory-client/benchmark' -import type * as App from './src/app' -import { createWorkload } from '../shared.ts' - -const appModulePath = './dist/app.js' -const { loaderPayloadRecordCount, mountTestApp } = (await import( - /* @vite-ignore */ appModulePath -)) as typeof App - -export const workload: ClientMemoryWorkload = createWorkload( - 'react', - mountTestApp, - loaderPayloadRecordCount, -) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/react/src/app.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/react/src/app.tsx deleted file mode 100644 index 5eef150c2c..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/src/app.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import { RouterProvider } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { getRouter } from './router' - -export { loaderPayloadRecordCount } from '../../loader-data' - -export function mountTestApp(container: Element) { - const router = getRouter() - const reactRoot = createRoot(container) - let didUnmount = false - - reactRoot.render() - - // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, - // release the devtools global, and detach history listeners. - return { - router, - unmount() { - if (didUnmount) { - return - } - - didUnmount = true - reactRoot.unmount() - - if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { - self.__TSR_ROUTER__ = undefined - } - - router.history.destroy() - }, - } -} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routeTree.gen.ts deleted file mode 100644 index ea96d809c8..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routeTree.gen.ts +++ /dev/null @@ -1,102 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as ShellRouteImport } from './routes/shell' -import { Route as PageIdRouteImport } from './routes/page.$id' -import { Route as ShellIndexRouteImport } from './routes/shell.index' - -const ShellRoute = ShellRouteImport.update({ - id: '/shell', - path: '/shell', - getParentRoute: () => rootRouteImport, -} as any) -const PageIdRoute = PageIdRouteImport.update({ - id: '/page/$id', - path: '/page/$id', - getParentRoute: () => rootRouteImport, -} as any) -const ShellIndexRoute = ShellIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => ShellRoute, -} as any) - -export interface FileRoutesByFullPath { - '/shell': typeof ShellRouteWithChildren - '/page/$id': typeof PageIdRoute - '/shell/': typeof ShellIndexRoute -} -export interface FileRoutesByTo { - '/page/$id': typeof PageIdRoute - '/shell': typeof ShellIndexRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/shell': typeof ShellRouteWithChildren - '/page/$id': typeof PageIdRoute - '/shell/': typeof ShellIndexRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/shell' | '/page/$id' | '/shell/' - fileRoutesByTo: FileRoutesByTo - to: '/page/$id' | '/shell' - id: '__root__' | '/shell' | '/page/$id' | '/shell/' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - ShellRoute: typeof ShellRouteWithChildren - PageIdRoute: typeof PageIdRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/shell': { - id: '/shell' - path: '/shell' - fullPath: '/shell' - preLoaderRoute: typeof ShellRouteImport - parentRoute: typeof rootRouteImport - } - '/page/$id': { - id: '/page/$id' - path: '/page/$id' - fullPath: '/page/$id' - preLoaderRoute: typeof PageIdRouteImport - parentRoute: typeof rootRouteImport - } - '/shell/': { - id: '/shell/' - path: '/' - fullPath: '/shell/' - preLoaderRoute: typeof ShellIndexRouteImport - parentRoute: typeof ShellRoute - } - } -} - -interface ShellRouteChildren { - ShellIndexRoute: typeof ShellIndexRoute -} - -const ShellRouteChildren: ShellRouteChildren = { - ShellIndexRoute: ShellIndexRoute, -} - -const ShellRouteWithChildren = ShellRoute._addFileChildren(ShellRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - ShellRoute: ShellRouteWithChildren, - PageIdRoute: PageIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/react/src/router.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/react/src/router.tsx deleted file mode 100644 index 5a5c8210d9..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/src/router.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import { createMemoryHistory, createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - history: createMemoryHistory({ - initialEntries: ['/shell'], - }), - routeTree, - defaultGcTime: 0, - defaultPreloadGcTime: 0, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routes/__root.tsx deleted file mode 100644 index 889395056b..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createRootRoute } from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return -} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routes/page.$id.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routes/page.$id.tsx deleted file mode 100644 index 63af9ed429..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routes/page.$id.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { createLoaderData } from '../../../loader-data' - -export const Route = createFileRoute('/page/$id')({ - loader: ({ params }) => createLoaderData(params.id), - component: PageComponent, -}) - -function PageComponent() { - const data = Route.useLoaderData() - - return ( -
- {`${data.id}:${data.records.length}`} -
- ) -} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routes/shell.index.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routes/shell.index.tsx deleted file mode 100644 index d78bb8bfb9..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routes/shell.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/shell/')({ - component: ShellIndexComponent, -}) - -function ShellIndexComponent() { - return
ready
-} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routes/shell.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routes/shell.tsx deleted file mode 100644 index 024a58c243..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routes/shell.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/shell')({ - component: ShellComponent, -}) - -function ShellComponent() { - return -} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/react/tsconfig.json b/benchmarks/memory/client/scenarios/loader-data-retention/react/tsconfig.json deleted file mode 100644 index ea566061d9..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "allowImportingTsExtensions": true, - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "src/**/*.ts", - "src/**/*.tsx", - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../../../vitest.setup.ts" - ] -} 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 deleted file mode 100644 index 8630417936..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/vite.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -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)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/app.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - ...memoryConfig('client'), - name: '@benchmarks/memory-client loader-data-retention (react)', - watch: false, - environment: 'jsdom', - }, -}) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/shared.ts b/benchmarks/memory/client/scenarios/loader-data-retention/shared.ts deleted file mode 100644 index bd90c023f0..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/shared.ts +++ /dev/null @@ -1,187 +0,0 @@ -import { - createDeterministicRandom, - randomSegment, -} from '#memory-client/bench-utils' -import { - createBenchContainer, - nextAnimationFrame, - noop, - removeBenchContainer, - warnClientMemoryDevMode, -} from '#memory-client/lifecycle' -import type { Framework, MountTestApp } from '#memory-client/lifecycle' - -type RenderEvent = { - toLocation: { - pathname: string - } -} - -type LoaderDataRouter = { - load: () => Promise - navigate: (options: { - to: '/page/$id' - params: { id: string } - replace: true - }) => Promise - subscribe: ( - event: 'onRendered', - listener: (event: RenderEvent) => void, - ) => () => void -} - -const loaderDataRetentionNavigationCount = 20 -const pageIds = createPageIds() - -const uninitialized = () => - Promise.reject( - new Error('loader-data-retention benchmark is not initialized'), - ) - -function createPageIds() { - const random = createDeterministicRandom(11) - - return Array.from( - { length: loaderDataRetentionNavigationCount }, - (_, index) => `${index}-${randomSegment(random)}`, - ) -} - -export function createWorkload( - framework: Framework, - mountTestApp: MountTestApp, - loaderPayloadRecordCount: number, -) { - warnClientMemoryDevMode(framework) - - let container: HTMLDivElement | undefined = undefined - let unmount = noop - let unsub = noop - let resolveRendered: () => void = noop - let expectedRenderedPath: string | undefined = undefined - let navigateTo: (id: string) => Promise = uninitialized - - function assertRenderedShell() { - const actual = - container?.querySelector('[data-bench-page]')?.dataset - .benchPage - - if (actual !== 'shell') { - throw new Error(`Expected rendered shell page, got ${actual}`) - } - } - - function assertRenderedPage(id: string) { - const page = container?.querySelector( - '[data-bench-page="page"]', - ) - const actualId = page?.dataset.benchId - const actualCount = page?.dataset.benchCount - const expectedCount = String(loaderPayloadRecordCount) - - if (actualId !== id || actualCount !== expectedCount) { - throw new Error( - `Expected rendered page ${id}:${expectedCount}, got ${actualId}:${actualCount}`, - ) - } - } - - async function waitForRenderedShell() { - for (let attempt = 0; attempt < 10; attempt++) { - try { - assertRenderedShell() - return - } catch { - await nextAnimationFrame() - } - } - - assertRenderedShell() - } - - function waitForNextRender(pathname: string) { - expectedRenderedPath = pathname - - return new Promise((resolve) => { - resolveRendered = resolve - }) - } - - async function before() { - if (container) { - after() - } - - container = createBenchContainer() - - const mounted = mountTestApp(container) - const router = mounted.router as LoaderDataRouter - unmount = mounted.unmount - - unsub = router.subscribe('onRendered', (event) => { - if ( - expectedRenderedPath && - event.toLocation.pathname !== expectedRenderedPath - ) { - return - } - - const resolve = resolveRendered - resolveRendered = noop - expectedRenderedPath = undefined - resolve() - }) - - navigateTo = async (id) => { - const pathname = `/page/${id}` - const rendered = waitForNextRender(pathname) - - await router.navigate({ - to: '/page/$id', - params: { id }, - replace: true, - }) - await rendered - assertRenderedPage(id) - } - - await router.load() - await waitForRenderedShell() - } - - function after() { - unmount() - removeBenchContainer(container) - unsub() - - container = undefined - unmount = noop - unsub = noop - resolveRendered = noop - expectedRenderedPath = undefined - navigateTo = uninitialized - } - - return { - name: `mem client loader-data-retention (${framework})`, - before, - navigate: (id: string) => navigateTo(id), - async run() { - for (const id of pageIds) { - await navigateTo(id) - } - }, - async sanity() { - await before() - - try { - assertRenderedShell() - await navigateTo('sanity-a') - assertRenderedPage('sanity-a') - } finally { - after() - } - }, - after, - } -} 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 deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' -import { workload } from './setup' - -await workload.sanity() - -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) -}) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/solid/memory.flame.ts b/benchmarks/memory/client/scenarios/loader-data-retention/solid/memory.flame.ts deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runClientFlameBenchmark } from '#memory-client/flame-runner' -import { workload } from './setup.ts' - -await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/solid/project.json b/benchmarks/memory/client/scenarios/loader-data-retention/solid/project.json deleted file mode 100644 index 6c85f51896..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-client-loader-data-retention-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.config.ts" - } - }, - "build:client:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:client:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "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/memory/client/scenarios/loader-data-retention/solid/setup.ts b/benchmarks/memory/client/scenarios/loader-data-retention/solid/setup.ts deleted file mode 100644 index b7c80a3e49..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ClientMemoryWorkload } from '#memory-client/benchmark' -import type * as App from './src/app' -import { createWorkload } from '../shared.ts' - -const appModulePath = './dist/app.js' -const { loaderPayloadRecordCount, mountTestApp } = (await import( - /* @vite-ignore */ appModulePath -)) as typeof App - -export const workload: ClientMemoryWorkload = createWorkload( - 'solid', - mountTestApp, - loaderPayloadRecordCount, -) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/app.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/app.tsx deleted file mode 100644 index 4315a4b15c..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/app.tsx +++ /dev/null @@ -1,31 +0,0 @@ -import { RouterProvider } from '@tanstack/solid-router' -import { render } from 'solid-js/web' -import { getRouter } from './router' - -export { loaderPayloadRecordCount } from '../../loader-data' - -export function mountTestApp(container: Element) { - const router = getRouter() - const dispose = render(() => , container) - let didUnmount = false - - // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, - // release the devtools global, and detach history listeners. - return { - router, - unmount() { - if (didUnmount) { - return - } - - didUnmount = true - dispose() - - if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { - self.__TSR_ROUTER__ = undefined - } - - router.history.destroy() - }, - } -} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routeTree.gen.ts deleted file mode 100644 index a1946d187d..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,102 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as ShellRouteImport } from './routes/shell' -import { Route as ShellIndexRouteImport } from './routes/shell.index' -import { Route as PageIdRouteImport } from './routes/page.$id' - -const ShellRoute = ShellRouteImport.update({ - id: '/shell', - path: '/shell', - getParentRoute: () => rootRouteImport, -} as any) -const ShellIndexRoute = ShellIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => ShellRoute, -} as any) -const PageIdRoute = PageIdRouteImport.update({ - id: '/page/$id', - path: '/page/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/shell': typeof ShellRouteWithChildren - '/page/$id': typeof PageIdRoute - '/shell/': typeof ShellIndexRoute -} -export interface FileRoutesByTo { - '/page/$id': typeof PageIdRoute - '/shell': typeof ShellIndexRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/shell': typeof ShellRouteWithChildren - '/page/$id': typeof PageIdRoute - '/shell/': typeof ShellIndexRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/shell' | '/page/$id' | '/shell/' - fileRoutesByTo: FileRoutesByTo - to: '/page/$id' | '/shell' - id: '__root__' | '/shell' | '/page/$id' | '/shell/' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - ShellRoute: typeof ShellRouteWithChildren - PageIdRoute: typeof PageIdRoute -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/shell': { - id: '/shell' - path: '/shell' - fullPath: '/shell' - preLoaderRoute: typeof ShellRouteImport - parentRoute: typeof rootRouteImport - } - '/shell/': { - id: '/shell/' - path: '/' - fullPath: '/shell/' - preLoaderRoute: typeof ShellIndexRouteImport - parentRoute: typeof ShellRoute - } - '/page/$id': { - id: '/page/$id' - path: '/page/$id' - fullPath: '/page/$id' - preLoaderRoute: typeof PageIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -interface ShellRouteChildren { - ShellIndexRoute: typeof ShellIndexRoute -} - -const ShellRouteChildren: ShellRouteChildren = { - ShellIndexRoute: ShellIndexRoute, -} - -const ShellRouteWithChildren = ShellRoute._addFileChildren(ShellRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - ShellRoute: ShellRouteWithChildren, - PageIdRoute: PageIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/router.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/router.tsx deleted file mode 100644 index 06afdb10d3..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/router.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import { createMemoryHistory, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - history: createMemoryHistory({ - initialEntries: ['/shell'], - }), - routeTree, - defaultGcTime: 0, - defaultPreloadGcTime: 0, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routes/__root.tsx deleted file mode 100644 index cb8d5a688d..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createRootRoute } from '@tanstack/solid-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return -} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routes/page.$id.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routes/page.$id.tsx deleted file mode 100644 index fb6c438fa5..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routes/page.$id.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { createLoaderData } from '../../../loader-data' - -export const Route = createFileRoute('/page/$id')({ - loader: ({ params }) => createLoaderData(params.id), - component: PageComponent, -}) - -function PageComponent() { - const data = Route.useLoaderData() - - return ( -
- {`${data().id}:${data().records.length}`} -
- ) -} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routes/shell.index.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routes/shell.index.tsx deleted file mode 100644 index 2f4f5daee2..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routes/shell.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/shell/')({ - component: ShellIndexComponent, -}) - -function ShellIndexComponent() { - return
ready
-} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routes/shell.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routes/shell.tsx deleted file mode 100644 index c1e38a1aaf..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routes/shell.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/shell')({ - component: ShellComponent, -}) - -function ShellComponent() { - return -} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/solid/tsconfig.json b/benchmarks/memory/client/scenarios/loader-data-retention/solid/tsconfig.json deleted file mode 100644 index b12dcb7ade..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "allowImportingTsExtensions": true, - "jsxImportSource": "solid-js", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "src/**/*.ts", - "src/**/*.tsx", - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../../../vitest.setup.ts" - ] -} 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 deleted file mode 100644 index 5dfd5b53fe..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/vite.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -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)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/app.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - ...memoryConfig('client'), - name: '@benchmarks/memory-client loader-data-retention (solid)', - watch: false, - environment: 'jsdom', - }, -}) 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 deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' -import { workload } from './setup' - -await workload.sanity() - -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) -}) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/vue/memory.flame.ts b/benchmarks/memory/client/scenarios/loader-data-retention/vue/memory.flame.ts deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runClientFlameBenchmark } from '#memory-client/flame-runner' -import { workload } from './setup.ts' - -await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/vue/project.json b/benchmarks/memory/client/scenarios/loader-data-retention/vue/project.json deleted file mode 100644 index 22504c906f..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-client-loader-data-retention-vue", - "projectType": "application", - "targets": { - "build:client": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "build:client:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:client:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "test:types:client": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/vue-router"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/vue/setup.ts b/benchmarks/memory/client/scenarios/loader-data-retention/vue/setup.ts deleted file mode 100644 index a83a1f70d1..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ClientMemoryWorkload } from '#memory-client/benchmark' -import type * as App from './src/app' -import { createWorkload } from '../shared.ts' - -const appModulePath = './dist/app.js' -const { loaderPayloadRecordCount, mountTestApp } = (await import( - /* @vite-ignore */ appModulePath -)) as typeof App - -export const workload: ClientMemoryWorkload = createWorkload( - 'vue', - mountTestApp, - loaderPayloadRecordCount, -) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/app.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/app.tsx deleted file mode 100644 index c843b4feb5..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/app.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import { RouterProvider } from '@tanstack/vue-router' -import { createApp } from 'vue' -import { getRouter } from './router' -import type {} from '@tanstack/router-core' - -export { loaderPayloadRecordCount } from '../../loader-data' - -export function mountTestApp(container: Element) { - const router = getRouter() - const vueApp = createApp({ - setup() { - return () => - }, - }) - let didUnmount = false - - vueApp.mount(container) - - // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, - // release the devtools global, and detach history listeners. - return { - router, - unmount() { - if (didUnmount) { - return - } - - didUnmount = true - vueApp.unmount() - - if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { - self.__TSR_ROUTER__ = undefined - } - - router.history.destroy() - }, - } -} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routeTree.gen.ts deleted file mode 100644 index 5b09d365e7..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,102 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as ShellRouteImport } from './routes/shell' -import { Route as PageIdRouteImport } from './routes/page.$id' -import { Route as ShellIndexRouteImport } from './routes/shell.index' - -const ShellRoute = ShellRouteImport.update({ - id: '/shell', - path: '/shell', - getParentRoute: () => rootRouteImport, -} as any) -const PageIdRoute = PageIdRouteImport.update({ - id: '/page/$id', - path: '/page/$id', - getParentRoute: () => rootRouteImport, -} as any) -const ShellIndexRoute = ShellIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => ShellRoute, -} as any) - -export interface FileRoutesByFullPath { - '/shell': typeof ShellRouteWithChildren - '/page/$id': typeof PageIdRoute - '/shell/': typeof ShellIndexRoute -} -export interface FileRoutesByTo { - '/page/$id': typeof PageIdRoute - '/shell': typeof ShellIndexRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/shell': typeof ShellRouteWithChildren - '/page/$id': typeof PageIdRoute - '/shell/': typeof ShellIndexRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/shell' | '/page/$id' | '/shell/' - fileRoutesByTo: FileRoutesByTo - to: '/page/$id' | '/shell' - id: '__root__' | '/shell' | '/page/$id' | '/shell/' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - ShellRoute: typeof ShellRouteWithChildren - PageIdRoute: typeof PageIdRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/shell': { - id: '/shell' - path: '/shell' - fullPath: '/shell' - preLoaderRoute: typeof ShellRouteImport - parentRoute: typeof rootRouteImport - } - '/page/$id': { - id: '/page/$id' - path: '/page/$id' - fullPath: '/page/$id' - preLoaderRoute: typeof PageIdRouteImport - parentRoute: typeof rootRouteImport - } - '/shell/': { - id: '/shell/' - path: '/' - fullPath: '/shell/' - preLoaderRoute: typeof ShellIndexRouteImport - parentRoute: typeof ShellRoute - } - } -} - -interface ShellRouteChildren { - ShellIndexRoute: typeof ShellIndexRoute -} - -const ShellRouteChildren: ShellRouteChildren = { - ShellIndexRoute: ShellIndexRoute, -} - -const ShellRouteWithChildren = ShellRoute._addFileChildren(ShellRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - ShellRoute: ShellRouteWithChildren, - PageIdRoute: PageIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/router.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/router.tsx deleted file mode 100644 index 84286e1dae..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/router.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import { createMemoryHistory, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - history: createMemoryHistory({ - initialEntries: ['/shell'], - }), - routeTree, - defaultGcTime: 0, - defaultPreloadGcTime: 0, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/__root.tsx deleted file mode 100644 index 91296e6f84..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createRootRoute } from '@tanstack/vue-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return -} 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 deleted file mode 100644 index 38f1d2614c..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/page.$id.tsx +++ /dev/null @@ -1,25 +0,0 @@ -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, -}) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/shell.index.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/shell.index.tsx deleted file mode 100644 index 640ffeeb5c..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/shell.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' - -export const Route = createFileRoute('/shell/')({ - component: ShellIndexComponent, -}) - -function ShellIndexComponent() { - return
ready
-} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/shell.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/shell.tsx deleted file mode 100644 index f8a598bc34..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/shell.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/vue-router' - -export const Route = createFileRoute('/shell')({ - component: ShellComponent, -}) - -function ShellComponent() { - return -} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/vue/tsconfig.json b/benchmarks/memory/client/scenarios/loader-data-retention/vue/tsconfig.json deleted file mode 100644 index 9a5872a4c0..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "allowImportingTsExtensions": true, - "jsxImportSource": "vue", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "src/**/*.ts", - "src/**/*.tsx", - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../../../vitest.setup.ts" - ] -} 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 deleted file mode 100644 index 006636eaa0..0000000000 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/app.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - ...memoryConfig('client'), - name: '@benchmarks/memory-client loader-data-retention (vue)', - watch: false, - environment: 'jsdom', - }, -}) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/react/memory.bench.ts b/benchmarks/memory/client/scenarios/mount-unmount/react/memory.bench.ts deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/react/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' -import { workload } from './setup' - -await workload.sanity() - -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) -}) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/react/memory.flame.ts b/benchmarks/memory/client/scenarios/mount-unmount/react/memory.flame.ts deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/react/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runClientFlameBenchmark } from '#memory-client/flame-runner' -import { workload } from './setup.ts' - -await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/react/project.json b/benchmarks/memory/client/scenarios/mount-unmount/react/project.json deleted file mode 100644 index 05d8aaa4bf..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/react/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-client-mount-unmount-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.config.ts" - } - }, - "build:client:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:client:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "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/memory/client/scenarios/mount-unmount/react/setup.ts b/benchmarks/memory/client/scenarios/mount-unmount/react/setup.ts deleted file mode 100644 index 70603b5c34..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/react/setup.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { ClientMemoryWorkload } from '#memory-client/benchmark' -import type * as App from './src/app' -import { createWorkload } from '../shared.ts' - -const appModulePath = './dist/app.js' -const { mountTestApp } = (await import( - /* @vite-ignore */ appModulePath -)) as typeof App - -export const workload: ClientMemoryWorkload = createWorkload( - 'react', - mountTestApp, -) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/react/src/app.tsx b/benchmarks/memory/client/scenarios/mount-unmount/react/src/app.tsx deleted file mode 100644 index bdf76eaa24..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/react/src/app.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { RouterProvider } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { getRouter } from './router' - -export function mountTestApp(container: Element) { - const router = getRouter() - const reactRoot = createRoot(container) - let didUnmount = false - - reactRoot.render() - - return { - router, - unmount() { - if (didUnmount) { - return - } - - didUnmount = true - reactRoot.unmount() - - if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { - self.__TSR_ROUTER__ = undefined - } - - router.history.destroy() - }, - } -} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/react/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/mount-unmount/react/src/routeTree.gen.ts deleted file mode 100644 index 5efcb2cf72..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/react/src/routeTree.gen.ts +++ /dev/null @@ -1,59 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as ARouteImport } from './routes/a' - -const ARoute = ARouteImport.update({ - id: '/a', - path: '/a', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/a': typeof ARoute -} -export interface FileRoutesByTo { - '/a': typeof ARoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/a': typeof ARoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/a' - fileRoutesByTo: FileRoutesByTo - to: '/a' - id: '__root__' | '/a' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - ARoute: typeof ARoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/a': { - id: '/a' - path: '/a' - fullPath: '/a' - preLoaderRoute: typeof ARouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - ARoute: ARoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/mount-unmount/react/src/router.tsx b/benchmarks/memory/client/scenarios/mount-unmount/react/src/router.tsx deleted file mode 100644 index 9cb85c5a1b..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/react/src/router.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { createMemoryHistory, createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - history: createMemoryHistory({ - initialEntries: ['/a'], - }), - routeTree, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/react/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/mount-unmount/react/src/routes/__root.tsx deleted file mode 100644 index 889395056b..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/react/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createRootRoute } from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return -} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/react/src/routes/a.tsx b/benchmarks/memory/client/scenarios/mount-unmount/react/src/routes/a.tsx deleted file mode 100644 index 1e268d3c42..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/react/src/routes/a.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/a')({ - loader: () => ({ id: 'a' }), - component: AComponent, -}) - -function AComponent() { - const data = Route.useLoaderData() - - return
{data.id}
-} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/react/tsconfig.json b/benchmarks/memory/client/scenarios/mount-unmount/react/tsconfig.json deleted file mode 100644 index ea566061d9..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/react/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "allowImportingTsExtensions": true, - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "src/**/*.ts", - "src/**/*.tsx", - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../../../vitest.setup.ts" - ] -} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/react/vite.config.ts b/benchmarks/memory/client/scenarios/mount-unmount/react/vite.config.ts deleted file mode 100644 index a08352a837..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/react/vite.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -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)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/app.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - ...memoryConfig('client'), - name: '@benchmarks/memory-client mount-unmount (react)', - watch: false, - environment: 'jsdom', - }, -}) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/shared.ts b/benchmarks/memory/client/scenarios/mount-unmount/shared.ts deleted file mode 100644 index 01cfe8c46a..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/shared.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { - createBenchContainer, - drainMicrotasks, - noop, - removeBenchContainer, - warnClientMemoryDevMode, -} from '#memory-client/lifecycle' -import type { Framework, MountTestApp } from '#memory-client/lifecycle' - -type RenderRouter = { - load: () => Promise - subscribe: (event: 'onRendered', listener: () => void) => () => void -} - -const mountUnmountIterations = 100 - -function assertEmptyBody() { - if (document.body.childNodes.length !== 0) { - throw new Error( - `Expected document.body to be empty, found ${document.body.childNodes.length} child node(s)`, - ) - } -} - -export function createWorkload( - framework: Framework, - mountTestApp: MountTestApp, -) { - warnClientMemoryDevMode(framework) - - async function cycle() { - const container = createBenchContainer() - - let unmount = noop - let unsubscribe = noop - - try { - const mounted = mountTestApp(container) - const router = mounted.router as RenderRouter - unmount = mounted.unmount - - const rendered = new Promise((resolve) => { - unsubscribe = router.subscribe('onRendered', () => { - resolve() - }) - }) - - await router.load() - await rendered - unsubscribe() - unsubscribe = noop - } finally { - unmount() - removeBenchContainer(container) - unsubscribe() - await drainMicrotasks() - } - } - - return { - name: `mem client mount-unmount (${framework})`, - cycle, - async run() { - for (let index = 0; index < mountUnmountIterations; index++) { - await cycle() - } - }, - async sanity() { - assertEmptyBody() - await cycle() - assertEmptyBody() - }, - } -} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/solid/memory.bench.ts b/benchmarks/memory/client/scenarios/mount-unmount/solid/memory.bench.ts deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/solid/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' -import { workload } from './setup' - -await workload.sanity() - -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) -}) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/solid/memory.flame.ts b/benchmarks/memory/client/scenarios/mount-unmount/solid/memory.flame.ts deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/solid/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runClientFlameBenchmark } from '#memory-client/flame-runner' -import { workload } from './setup.ts' - -await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/solid/project.json b/benchmarks/memory/client/scenarios/mount-unmount/solid/project.json deleted file mode 100644 index 63e8e950db..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/solid/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-client-mount-unmount-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.config.ts" - } - }, - "build:client:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:client:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "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/memory/client/scenarios/mount-unmount/solid/setup.ts b/benchmarks/memory/client/scenarios/mount-unmount/solid/setup.ts deleted file mode 100644 index 493425c6a2..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/solid/setup.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { ClientMemoryWorkload } from '#memory-client/benchmark' -import type * as App from './src/app' -import { createWorkload } from '../shared.ts' - -const appModulePath = './dist/app.js' -const { mountTestApp } = (await import( - /* @vite-ignore */ appModulePath -)) as typeof App - -export const workload: ClientMemoryWorkload = createWorkload( - 'solid', - mountTestApp, -) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/solid/src/app.tsx b/benchmarks/memory/client/scenarios/mount-unmount/solid/src/app.tsx deleted file mode 100644 index b23bc126d5..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/solid/src/app.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import { RouterProvider } from '@tanstack/solid-router' -import { render } from 'solid-js/web' -import { getRouter } from './router' - -export function mountTestApp(container: Element) { - const router = getRouter() - const dispose = render(() => , container) - let didUnmount = false - - return { - router, - unmount() { - if (didUnmount) { - return - } - - didUnmount = true - dispose() - - if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { - self.__TSR_ROUTER__ = undefined - } - - router.history.destroy() - }, - } -} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/solid/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/mount-unmount/solid/src/routeTree.gen.ts deleted file mode 100644 index a3f9739290..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,59 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as ARouteImport } from './routes/a' - -const ARoute = ARouteImport.update({ - id: '/a', - path: '/a', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/a': typeof ARoute -} -export interface FileRoutesByTo { - '/a': typeof ARoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/a': typeof ARoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/a' - fileRoutesByTo: FileRoutesByTo - to: '/a' - id: '__root__' | '/a' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - ARoute: typeof ARoute -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/a': { - id: '/a' - path: '/a' - fullPath: '/a' - preLoaderRoute: typeof ARouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - ARoute: ARoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/mount-unmount/solid/src/router.tsx b/benchmarks/memory/client/scenarios/mount-unmount/solid/src/router.tsx deleted file mode 100644 index e8c14f12f6..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/solid/src/router.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { createMemoryHistory, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - history: createMemoryHistory({ - initialEntries: ['/a'], - }), - routeTree, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/solid/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/mount-unmount/solid/src/routes/__root.tsx deleted file mode 100644 index cb8d5a688d..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/solid/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createRootRoute } from '@tanstack/solid-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return -} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/solid/src/routes/a.tsx b/benchmarks/memory/client/scenarios/mount-unmount/solid/src/routes/a.tsx deleted file mode 100644 index 36c4be538c..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/solid/src/routes/a.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/a')({ - loader: () => ({ id: 'a' }), - component: AComponent, -}) - -function AComponent() { - const data = Route.useLoaderData() - - return
{data().id}
-} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/solid/tsconfig.json b/benchmarks/memory/client/scenarios/mount-unmount/solid/tsconfig.json deleted file mode 100644 index b12dcb7ade..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/solid/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "allowImportingTsExtensions": true, - "jsxImportSource": "solid-js", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "src/**/*.ts", - "src/**/*.tsx", - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../../../vitest.setup.ts" - ] -} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/solid/vite.config.ts b/benchmarks/memory/client/scenarios/mount-unmount/solid/vite.config.ts deleted file mode 100644 index 33699639de..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/solid/vite.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -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)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/app.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - ...memoryConfig('client'), - name: '@benchmarks/memory-client mount-unmount (solid)', - watch: false, - environment: 'jsdom', - }, -}) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/vue/memory.bench.ts b/benchmarks/memory/client/scenarios/mount-unmount/vue/memory.bench.ts deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' -import { workload } from './setup' - -await workload.sanity() - -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) -}) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/vue/memory.flame.ts b/benchmarks/memory/client/scenarios/mount-unmount/vue/memory.flame.ts deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runClientFlameBenchmark } from '#memory-client/flame-runner' -import { workload } from './setup.ts' - -await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/vue/project.json b/benchmarks/memory/client/scenarios/mount-unmount/vue/project.json deleted file mode 100644 index 157673cf16..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-client-mount-unmount-vue", - "projectType": "application", - "targets": { - "build:client": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "build:client:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:client:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "test:types:client": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/vue-router"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/vue/setup.ts b/benchmarks/memory/client/scenarios/mount-unmount/vue/setup.ts deleted file mode 100644 index a38df04788..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/setup.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { ClientMemoryWorkload } from '#memory-client/benchmark' -import type * as App from './src/app' -import { createWorkload } from '../shared.ts' - -const appModulePath = './dist/app.js' -const { mountTestApp } = (await import( - /* @vite-ignore */ appModulePath -)) as typeof App - -export const workload: ClientMemoryWorkload = createWorkload( - 'vue', - mountTestApp, -) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/vue/src/app.tsx b/benchmarks/memory/client/scenarios/mount-unmount/vue/src/app.tsx deleted file mode 100644 index 27b82fcbe1..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/src/app.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import { RouterProvider } from '@tanstack/vue-router' -import { createApp } from 'vue' -import { getRouter } from './router' -import type {} from '@tanstack/router-core' - -export function mountTestApp(container: Element) { - const router = getRouter() - const vueApp = createApp({ - setup() { - return () => - }, - }) - let didUnmount = false - - vueApp.mount(container) - - return { - router, - unmount() { - if (didUnmount) { - return - } - - didUnmount = true - vueApp.unmount() - - if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { - self.__TSR_ROUTER__ = undefined - } - - router.history.destroy() - }, - } -} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/vue/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/mount-unmount/vue/src/routeTree.gen.ts deleted file mode 100644 index 1a54b81033..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,59 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as ARouteImport } from './routes/a' - -const ARoute = ARouteImport.update({ - id: '/a', - path: '/a', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/a': typeof ARoute -} -export interface FileRoutesByTo { - '/a': typeof ARoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/a': typeof ARoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/a' - fileRoutesByTo: FileRoutesByTo - to: '/a' - id: '__root__' | '/a' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - ARoute: typeof ARoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/a': { - id: '/a' - path: '/a' - fullPath: '/a' - preLoaderRoute: typeof ARouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - ARoute: ARoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/mount-unmount/vue/src/router.tsx b/benchmarks/memory/client/scenarios/mount-unmount/vue/src/router.tsx deleted file mode 100644 index e083495cd2..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/src/router.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { createMemoryHistory, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - history: createMemoryHistory({ - initialEntries: ['/a'], - }), - routeTree, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/vue/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/mount-unmount/vue/src/routes/__root.tsx deleted file mode 100644 index 91296e6f84..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createRootRoute } from '@tanstack/vue-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return -} 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 deleted file mode 100644 index 0dd650e1dd..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/src/routes/a.tsx +++ /dev/null @@ -1,15 +0,0 @@ -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, -}) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/vue/tsconfig.json b/benchmarks/memory/client/scenarios/mount-unmount/vue/tsconfig.json deleted file mode 100644 index 9a5872a4c0..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "allowImportingTsExtensions": true, - "jsxImportSource": "vue", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "src/**/*.ts", - "src/**/*.tsx", - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../../../vitest.setup.ts" - ] -} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/vue/vite.config.ts b/benchmarks/memory/client/scenarios/mount-unmount/vue/vite.config.ts deleted file mode 100644 index a3f0eeaa8c..0000000000 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/app.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - ...memoryConfig('client'), - name: '@benchmarks/memory-client mount-unmount (vue)', - watch: false, - environment: 'jsdom', - }, -}) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/react/memory.bench.ts b/benchmarks/memory/client/scenarios/navigation-churn/react/memory.bench.ts deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' -import { workload } from './setup' - -await workload.sanity() - -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) -}) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/react/memory.flame.ts b/benchmarks/memory/client/scenarios/navigation-churn/react/memory.flame.ts deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runClientFlameBenchmark } from '#memory-client/flame-runner' -import { workload } from './setup.ts' - -await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/react/project.json b/benchmarks/memory/client/scenarios/navigation-churn/react/project.json deleted file mode 100644 index b424277bc6..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-client-navigation-churn-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.config.ts" - } - }, - "build:client:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:client:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "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/memory/client/scenarios/navigation-churn/react/setup.ts b/benchmarks/memory/client/scenarios/navigation-churn/react/setup.ts deleted file mode 100644 index 70603b5c34..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/setup.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { ClientMemoryWorkload } from '#memory-client/benchmark' -import type * as App from './src/app' -import { createWorkload } from '../shared.ts' - -const appModulePath = './dist/app.js' -const { mountTestApp } = (await import( - /* @vite-ignore */ appModulePath -)) as typeof App - -export const workload: ClientMemoryWorkload = createWorkload( - 'react', - mountTestApp, -) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/react/src/app.tsx b/benchmarks/memory/client/scenarios/navigation-churn/react/src/app.tsx deleted file mode 100644 index d714e7bfdd..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/src/app.tsx +++ /dev/null @@ -1,31 +0,0 @@ -import { RouterProvider } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { getRouter } from './router' - -export function mountTestApp(container: Element) { - const router = getRouter() - const reactRoot = createRoot(container) - let didUnmount = false - - reactRoot.render() - - // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, - // release the devtools global, and detach history listeners. - return { - router, - unmount() { - if (didUnmount) { - return - } - - didUnmount = true - reactRoot.unmount() - - if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { - self.__TSR_ROUTER__ = undefined - } - - router.history.destroy() - }, - } -} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/react/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/navigation-churn/react/src/routeTree.gen.ts deleted file mode 100644 index 3cca81cabb..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/src/routeTree.gen.ts +++ /dev/null @@ -1,77 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as BRouteImport } from './routes/b' -import { Route as ARouteImport } from './routes/a' - -const BRoute = BRouteImport.update({ - id: '/b', - path: '/b', - getParentRoute: () => rootRouteImport, -} as any) -const ARoute = ARouteImport.update({ - id: '/a', - path: '/a', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/a': typeof ARoute - '/b': typeof BRoute -} -export interface FileRoutesByTo { - '/a': typeof ARoute - '/b': typeof BRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/a': typeof ARoute - '/b': typeof BRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/a' | '/b' - fileRoutesByTo: FileRoutesByTo - to: '/a' | '/b' - id: '__root__' | '/a' | '/b' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - ARoute: typeof ARoute - BRoute: typeof BRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/b': { - id: '/b' - path: '/b' - fullPath: '/b' - preLoaderRoute: typeof BRouteImport - parentRoute: typeof rootRouteImport - } - '/a': { - id: '/a' - path: '/a' - fullPath: '/a' - preLoaderRoute: typeof ARouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - ARoute: ARoute, - BRoute: BRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/navigation-churn/react/src/router.tsx b/benchmarks/memory/client/scenarios/navigation-churn/react/src/router.tsx deleted file mode 100644 index 9cb85c5a1b..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/src/router.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { createMemoryHistory, createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - history: createMemoryHistory({ - initialEntries: ['/a'], - }), - routeTree, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/react/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/navigation-churn/react/src/routes/__root.tsx deleted file mode 100644 index 889395056b..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createRootRoute } from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return -} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/react/src/routes/a.tsx b/benchmarks/memory/client/scenarios/navigation-churn/react/src/routes/a.tsx deleted file mode 100644 index bdd32d0b81..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/src/routes/a.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -const fixedTimestamp = 1_700_000_000_000 - -export const Route = createFileRoute('/a')({ - loader: () => ({ name: 'a', ts: fixedTimestamp }), - component: AComponent, -}) - -function AComponent() { - const data = Route.useLoaderData() - - return
{`${data.name}:${data.ts}`}
-} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/react/src/routes/b.tsx b/benchmarks/memory/client/scenarios/navigation-churn/react/src/routes/b.tsx deleted file mode 100644 index 05deef729d..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/src/routes/b.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -const fixedTimestamp = 1_700_000_000_000 - -export const Route = createFileRoute('/b')({ - loader: () => ({ name: 'b', ts: fixedTimestamp }), - component: BComponent, -}) - -function BComponent() { - const data = Route.useLoaderData() - - return
{`${data.name}:${data.ts}`}
-} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/react/tsconfig.json b/benchmarks/memory/client/scenarios/navigation-churn/react/tsconfig.json deleted file mode 100644 index ea566061d9..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "allowImportingTsExtensions": true, - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "src/**/*.ts", - "src/**/*.tsx", - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../../../vitest.setup.ts" - ] -} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/react/vite.config.ts b/benchmarks/memory/client/scenarios/navigation-churn/react/vite.config.ts deleted file mode 100644 index eef60a658e..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/vite.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -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)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/app.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - ...memoryConfig('client'), - name: '@benchmarks/memory-client navigation-churn (react)', - watch: false, - environment: 'jsdom', - }, -}) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/shared.ts b/benchmarks/memory/client/scenarios/navigation-churn/shared.ts deleted file mode 100644 index 7eaf1a8b66..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/shared.ts +++ /dev/null @@ -1,129 +0,0 @@ -import { - createBenchContainer, - nextAnimationFrame, - noop, - removeBenchContainer, - warnClientMemoryDevMode, -} from '#memory-client/lifecycle' -import type { Framework, MountTestApp } from '#memory-client/lifecycle' - -type Target = '/a' | '/b' - -type NavigationRouter = { - load: () => Promise - navigate: (options: { to: Target; replace: true }) => Promise - subscribe: (event: 'onRendered', listener: () => void) => () => void -} - -const navigationChurnIterations = 300 - -const uninitialized = () => - Promise.reject(new Error('navigation-churn benchmark is not initialized')) - -export function createWorkload( - framework: Framework, - mountTestApp: MountTestApp, -) { - warnClientMemoryDevMode(framework) - - let container: HTMLDivElement | undefined = undefined - let unmount = noop - let unsub = noop - let resolveRendered: () => void = noop - let navigateTo: (target: Target) => Promise = uninitialized - - function assertRenderedPage(target: Target) { - const expected = target.slice(1) - const actual = - container?.querySelector('[data-bench-page]')?.dataset - .benchPage - - if (actual !== expected) { - throw new Error(`Expected rendered page ${expected}, got ${actual}`) - } - } - - async function waitForRenderedPage(target: Target) { - for (let attempt = 0; attempt < 10; attempt++) { - try { - assertRenderedPage(target) - return - } catch { - await nextAnimationFrame() - } - } - - assertRenderedPage(target) - } - - function waitForNextRender() { - return new Promise((resolve) => { - resolveRendered = resolve - }) - } - - async function before() { - if (container) { - after() - } - - container = createBenchContainer() - - const mounted = mountTestApp(container) - const router = mounted.router as NavigationRouter - unmount = mounted.unmount - - unsub = router.subscribe('onRendered', () => { - resolveRendered() - }) - - navigateTo = async (target) => { - const rendered = waitForNextRender() - await Promise.all([ - router.navigate({ - to: target, - replace: true, - }), - rendered, - ]) - } - - await router.load() - await waitForRenderedPage('/a') - } - - function after() { - unmount() - removeBenchContainer(container) - unsub() - - container = undefined - unmount = noop - unsub = noop - resolveRendered = noop - navigateTo = uninitialized - } - - return { - name: `mem client navigation-churn (${framework})`, - before, - navigate: (target: Target) => navigateTo(target), - async run() { - for (let index = 0; index < navigationChurnIterations; index++) { - await navigateTo(index % 2 === 0 ? '/b' : '/a') - } - }, - async sanity() { - await before() - - try { - assertRenderedPage('/a') - await navigateTo('/b') - assertRenderedPage('/b') - } finally { - after() - } - }, - after, - } -} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/solid/memory.bench.ts b/benchmarks/memory/client/scenarios/navigation-churn/solid/memory.bench.ts deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' -import { workload } from './setup' - -await workload.sanity() - -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) -}) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/solid/memory.flame.ts b/benchmarks/memory/client/scenarios/navigation-churn/solid/memory.flame.ts deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runClientFlameBenchmark } from '#memory-client/flame-runner' -import { workload } from './setup.ts' - -await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/solid/project.json b/benchmarks/memory/client/scenarios/navigation-churn/solid/project.json deleted file mode 100644 index 2c581e6188..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-client-navigation-churn-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.config.ts" - } - }, - "build:client:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:client:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "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/memory/client/scenarios/navigation-churn/solid/setup.ts b/benchmarks/memory/client/scenarios/navigation-churn/solid/setup.ts deleted file mode 100644 index 493425c6a2..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/setup.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { ClientMemoryWorkload } from '#memory-client/benchmark' -import type * as App from './src/app' -import { createWorkload } from '../shared.ts' - -const appModulePath = './dist/app.js' -const { mountTestApp } = (await import( - /* @vite-ignore */ appModulePath -)) as typeof App - -export const workload: ClientMemoryWorkload = createWorkload( - 'solid', - mountTestApp, -) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/solid/src/app.tsx b/benchmarks/memory/client/scenarios/navigation-churn/solid/src/app.tsx deleted file mode 100644 index 16000c90a1..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/src/app.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { RouterProvider } from '@tanstack/solid-router' -import { render } from 'solid-js/web' -import { getRouter } from './router' - -export function mountTestApp(container: Element) { - const router = getRouter() - const dispose = render(() => , container) - let didUnmount = false - - // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, - // release the devtools global, and detach history listeners. - return { - router, - unmount() { - if (didUnmount) { - return - } - - didUnmount = true - dispose() - - if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { - self.__TSR_ROUTER__ = undefined - } - - router.history.destroy() - }, - } -} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/solid/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/navigation-churn/solid/src/routeTree.gen.ts deleted file mode 100644 index 59d7fad058..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,77 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as BRouteImport } from './routes/b' -import { Route as ARouteImport } from './routes/a' - -const BRoute = BRouteImport.update({ - id: '/b', - path: '/b', - getParentRoute: () => rootRouteImport, -} as any) -const ARoute = ARouteImport.update({ - id: '/a', - path: '/a', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/a': typeof ARoute - '/b': typeof BRoute -} -export interface FileRoutesByTo { - '/a': typeof ARoute - '/b': typeof BRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/a': typeof ARoute - '/b': typeof BRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/a' | '/b' - fileRoutesByTo: FileRoutesByTo - to: '/a' | '/b' - id: '__root__' | '/a' | '/b' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - ARoute: typeof ARoute - BRoute: typeof BRoute -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/b': { - id: '/b' - path: '/b' - fullPath: '/b' - preLoaderRoute: typeof BRouteImport - parentRoute: typeof rootRouteImport - } - '/a': { - id: '/a' - path: '/a' - fullPath: '/a' - preLoaderRoute: typeof ARouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - ARoute: ARoute, - BRoute: BRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/navigation-churn/solid/src/router.tsx b/benchmarks/memory/client/scenarios/navigation-churn/solid/src/router.tsx deleted file mode 100644 index e8c14f12f6..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/src/router.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { createMemoryHistory, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - history: createMemoryHistory({ - initialEntries: ['/a'], - }), - routeTree, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/solid/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/navigation-churn/solid/src/routes/__root.tsx deleted file mode 100644 index cb8d5a688d..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createRootRoute } from '@tanstack/solid-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return -} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/solid/src/routes/a.tsx b/benchmarks/memory/client/scenarios/navigation-churn/solid/src/routes/a.tsx deleted file mode 100644 index 0b7838fdbe..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/src/routes/a.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -const fixedTimestamp = 1_700_000_000_000 - -export const Route = createFileRoute('/a')({ - loader: () => ({ name: 'a', ts: fixedTimestamp }), - component: AComponent, -}) - -function AComponent() { - const data = Route.useLoaderData() - - return
{`${data().name}:${data().ts}`}
-} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/solid/src/routes/b.tsx b/benchmarks/memory/client/scenarios/navigation-churn/solid/src/routes/b.tsx deleted file mode 100644 index ec9b513ba9..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/src/routes/b.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -const fixedTimestamp = 1_700_000_000_000 - -export const Route = createFileRoute('/b')({ - loader: () => ({ name: 'b', ts: fixedTimestamp }), - component: BComponent, -}) - -function BComponent() { - const data = Route.useLoaderData() - - return
{`${data().name}:${data().ts}`}
-} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/solid/tsconfig.json b/benchmarks/memory/client/scenarios/navigation-churn/solid/tsconfig.json deleted file mode 100644 index b12dcb7ade..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "allowImportingTsExtensions": true, - "jsxImportSource": "solid-js", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "src/**/*.ts", - "src/**/*.tsx", - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../../../vitest.setup.ts" - ] -} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/solid/vite.config.ts b/benchmarks/memory/client/scenarios/navigation-churn/solid/vite.config.ts deleted file mode 100644 index 7dfb186b2e..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/vite.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -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)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/app.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - ...memoryConfig('client'), - name: '@benchmarks/memory-client navigation-churn (solid)', - watch: false, - environment: 'jsdom', - }, -}) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/vue/memory.bench.ts b/benchmarks/memory/client/scenarios/navigation-churn/vue/memory.bench.ts deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' -import { workload } from './setup' - -await workload.sanity() - -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) -}) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/vue/memory.flame.ts b/benchmarks/memory/client/scenarios/navigation-churn/vue/memory.flame.ts deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runClientFlameBenchmark } from '#memory-client/flame-runner' -import { workload } from './setup.ts' - -await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/vue/project.json b/benchmarks/memory/client/scenarios/navigation-churn/vue/project.json deleted file mode 100644 index f96d03d7d3..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-client-navigation-churn-vue", - "projectType": "application", - "targets": { - "build:client": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "build:client:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:client:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "test:types:client": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/vue-router"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/vue/setup.ts b/benchmarks/memory/client/scenarios/navigation-churn/vue/setup.ts deleted file mode 100644 index a38df04788..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/setup.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { ClientMemoryWorkload } from '#memory-client/benchmark' -import type * as App from './src/app' -import { createWorkload } from '../shared.ts' - -const appModulePath = './dist/app.js' -const { mountTestApp } = (await import( - /* @vite-ignore */ appModulePath -)) as typeof App - -export const workload: ClientMemoryWorkload = createWorkload( - 'vue', - mountTestApp, -) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/app.tsx b/benchmarks/memory/client/scenarios/navigation-churn/vue/src/app.tsx deleted file mode 100644 index fad2251cc0..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/app.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import { RouterProvider } from '@tanstack/vue-router' -import { createApp } from 'vue' -import { getRouter } from './router' -import type {} from '@tanstack/router-core' - -export function mountTestApp(container: Element) { - const router = getRouter() - const vueApp = createApp({ - setup() { - return () => - }, - }) - let didUnmount = false - - vueApp.mount(container) - - // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, - // release the devtools global, and detach history listeners. - return { - router, - unmount() { - if (didUnmount) { - return - } - - didUnmount = true - vueApp.unmount() - - if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { - self.__TSR_ROUTER__ = undefined - } - - router.history.destroy() - }, - } -} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routeTree.gen.ts deleted file mode 100644 index 12c9640358..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,77 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as BRouteImport } from './routes/b' -import { Route as ARouteImport } from './routes/a' - -const BRoute = BRouteImport.update({ - id: '/b', - path: '/b', - getParentRoute: () => rootRouteImport, -} as any) -const ARoute = ARouteImport.update({ - id: '/a', - path: '/a', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/a': typeof ARoute - '/b': typeof BRoute -} -export interface FileRoutesByTo { - '/a': typeof ARoute - '/b': typeof BRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/a': typeof ARoute - '/b': typeof BRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/a' | '/b' - fileRoutesByTo: FileRoutesByTo - to: '/a' | '/b' - id: '__root__' | '/a' | '/b' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - ARoute: typeof ARoute - BRoute: typeof BRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/b': { - id: '/b' - path: '/b' - fullPath: '/b' - preLoaderRoute: typeof BRouteImport - parentRoute: typeof rootRouteImport - } - '/a': { - id: '/a' - path: '/a' - fullPath: '/a' - preLoaderRoute: typeof ARouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - ARoute: ARoute, - BRoute: BRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/router.tsx b/benchmarks/memory/client/scenarios/navigation-churn/vue/src/router.tsx deleted file mode 100644 index e083495cd2..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/router.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { createMemoryHistory, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - history: createMemoryHistory({ - initialEntries: ['/a'], - }), - routeTree, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/__root.tsx deleted file mode 100644 index 91296e6f84..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createRootRoute } from '@tanstack/vue-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return -} 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 deleted file mode 100644 index c1a9cfb244..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/a.tsx +++ /dev/null @@ -1,19 +0,0 @@ -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, -}) 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 deleted file mode 100644 index 3a20799f3b..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/b.tsx +++ /dev/null @@ -1,19 +0,0 @@ -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, -}) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/vue/tsconfig.json b/benchmarks/memory/client/scenarios/navigation-churn/vue/tsconfig.json deleted file mode 100644 index 9a5872a4c0..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "allowImportingTsExtensions": true, - "jsxImportSource": "vue", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "src/**/*.ts", - "src/**/*.tsx", - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../../../vitest.setup.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 deleted file mode 100644 index b3bdd39dd2..0000000000 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/app.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - ...memoryConfig('client'), - name: '@benchmarks/memory-client navigation-churn (vue)', - watch: false, - environment: 'jsdom', - }, -}) diff --git a/benchmarks/memory/client/scenarios/preload-churn/item-payload.ts b/benchmarks/memory/client/scenarios/preload-churn/item-payload.ts deleted file mode 100644 index 4a86ea7244..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/item-payload.ts +++ /dev/null @@ -1,51 +0,0 @@ -const payloadByteLength = 20 * 1024 -const payloadChunkCount = 32 -const payloadChunkSize = payloadByteLength / payloadChunkCount -const trackedLoaderIdPrefix = 'sanity-' -const trackedItemLoaderCalls = new Map() - -export function createItemPayload(id: string) { - let seed = hashId(id) - const chunks = new Array(payloadChunkCount) - - for (let index = 0; index < payloadChunkCount; index++) { - seed = (seed * 1664525 + 1013904223) >>> 0 - chunks[index] = createPayloadChunk(id, index, seed) - } - - return { - id, - chunks, - byteLength: payloadByteLength, - } -} - -export function trackItemLoaderCall(id: string) { - if (!id.startsWith(trackedLoaderIdPrefix)) { - return - } - - trackedItemLoaderCalls.set(id, (trackedItemLoaderCalls.get(id) ?? 0) + 1) -} - -export function getTrackedItemLoaderCount(id: string) { - return trackedItemLoaderCalls.get(id) ?? 0 -} - -function createPayloadChunk(id: string, index: number, seed: number) { - const token = `${id}:${index.toString(36)}:${seed.toString(36)}:` - const repeatCount = Math.ceil(payloadChunkSize / token.length) - - return token.repeat(repeatCount).slice(0, payloadChunkSize) -} - -function hashId(id: string) { - let hash = 2166136261 - - for (let index = 0; index < id.length; index++) { - hash ^= id.charCodeAt(index) - hash = Math.imul(hash, 16777619) - } - - return hash >>> 0 -} diff --git a/benchmarks/memory/client/scenarios/preload-churn/react/memory.bench.ts b/benchmarks/memory/client/scenarios/preload-churn/react/memory.bench.ts deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/react/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' -import { workload } from './setup' - -await workload.sanity() - -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) -}) diff --git a/benchmarks/memory/client/scenarios/preload-churn/react/memory.flame.ts b/benchmarks/memory/client/scenarios/preload-churn/react/memory.flame.ts deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/react/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runClientFlameBenchmark } from '#memory-client/flame-runner' -import { workload } from './setup.ts' - -await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/preload-churn/react/project.json b/benchmarks/memory/client/scenarios/preload-churn/react/project.json deleted file mode 100644 index 238d98c816..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/react/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-client-preload-churn-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.config.ts" - } - }, - "build:client:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:client:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "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/memory/client/scenarios/preload-churn/react/setup.ts b/benchmarks/memory/client/scenarios/preload-churn/react/setup.ts deleted file mode 100644 index 31cd97d135..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/react/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ClientMemoryWorkload } from '#memory-client/benchmark' -import type * as App from './src/app' -import { createWorkload } from '../shared.ts' - -const appModulePath = './dist/app.js' -const { getTrackedItemLoaderCount, mountTestApp } = (await import( - /* @vite-ignore */ appModulePath -)) as typeof App - -export const workload: ClientMemoryWorkload = createWorkload( - 'react', - mountTestApp, - getTrackedItemLoaderCount, -) diff --git a/benchmarks/memory/client/scenarios/preload-churn/react/src/app.tsx b/benchmarks/memory/client/scenarios/preload-churn/react/src/app.tsx deleted file mode 100644 index b75d1fe34d..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/react/src/app.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import { RouterProvider } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { getRouter } from './router' - -export { getTrackedItemLoaderCount } from '../../item-payload' - -export function mountTestApp(container: Element) { - const router = getRouter() - const reactRoot = createRoot(container) - let didUnmount = false - - reactRoot.render() - - // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, - // release the devtools global, and detach history listeners. - return { - router, - unmount() { - if (didUnmount) { - return - } - - didUnmount = true - reactRoot.unmount() - - if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { - self.__TSR_ROUTER__ = undefined - } - - router.history.destroy() - }, - } -} diff --git a/benchmarks/memory/client/scenarios/preload-churn/react/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/preload-churn/react/src/routeTree.gen.ts deleted file mode 100644 index 84aaebb9c9..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/react/src/routeTree.gen.ts +++ /dev/null @@ -1,77 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as ItemsIdRouteImport } from './routes/items.$id' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ItemsIdRoute = ItemsIdRouteImport.update({ - id: '/items/$id', - path: '/items/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/items/$id': typeof ItemsIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/items/$id': typeof ItemsIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/items/$id': typeof ItemsIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/items/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/items/$id' - id: '__root__' | '/' | '/items/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ItemsIdRoute: typeof ItemsIdRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/items/$id': { - id: '/items/$id' - path: '/items/$id' - fullPath: '/items/$id' - preLoaderRoute: typeof ItemsIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ItemsIdRoute: ItemsIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/preload-churn/react/src/router.tsx b/benchmarks/memory/client/scenarios/preload-churn/react/src/router.tsx deleted file mode 100644 index 69e3180173..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/react/src/router.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { createMemoryHistory, createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - history: createMemoryHistory({ - initialEntries: ['/'], - }), - routeTree, - defaultPreloadGcTime: 0, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/client/scenarios/preload-churn/react/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/preload-churn/react/src/routes/__root.tsx deleted file mode 100644 index 889395056b..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/react/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createRootRoute } from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return -} diff --git a/benchmarks/memory/client/scenarios/preload-churn/react/src/routes/index.tsx b/benchmarks/memory/client/scenarios/preload-churn/react/src/routes/index.tsx deleted file mode 100644 index af735d705b..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/react/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
index
-} diff --git a/benchmarks/memory/client/scenarios/preload-churn/react/src/routes/items.$id.tsx b/benchmarks/memory/client/scenarios/preload-churn/react/src/routes/items.$id.tsx deleted file mode 100644 index 2f52acd528..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/react/src/routes/items.$id.tsx +++ /dev/null @@ -1,20 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { createItemPayload, trackItemLoaderCall } from '../../../item-payload' - -export const Route = createFileRoute('/items/$id')({ - loader: ({ params }) => { - trackItemLoaderCall(params.id) - return createItemPayload(params.id) - }, - component: ItemComponent, -}) - -function ItemComponent() { - const data = Route.useLoaderData() - - return ( -
- {`${data.id}:${data.byteLength}`} -
- ) -} diff --git a/benchmarks/memory/client/scenarios/preload-churn/react/tsconfig.json b/benchmarks/memory/client/scenarios/preload-churn/react/tsconfig.json deleted file mode 100644 index ea566061d9..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/react/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "allowImportingTsExtensions": true, - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "src/**/*.ts", - "src/**/*.tsx", - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../../../vitest.setup.ts" - ] -} diff --git a/benchmarks/memory/client/scenarios/preload-churn/react/vite.config.ts b/benchmarks/memory/client/scenarios/preload-churn/react/vite.config.ts deleted file mode 100644 index c12995f68e..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/react/vite.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -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)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/app.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - ...memoryConfig('client'), - name: '@benchmarks/memory-client preload-churn (react)', - watch: false, - environment: 'jsdom', - }, -}) diff --git a/benchmarks/memory/client/scenarios/preload-churn/shared.ts b/benchmarks/memory/client/scenarios/preload-churn/shared.ts deleted file mode 100644 index 68fdfedd3f..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/shared.ts +++ /dev/null @@ -1,216 +0,0 @@ -import { - createDeterministicRandom, - randomSegment, -} from '#memory-client/bench-utils' -import { - createBenchContainer, - drainMicrotasks, - nextAnimationFrame, - noop, - removeBenchContainer, - warnClientMemoryDevMode, -} from '#memory-client/lifecycle' -import type { Framework, MountTestApp } from '#memory-client/lifecycle' - -type GetTrackedItemLoaderCount = (id: string) => number - -type PreloadRouter = { - load: () => Promise - preloadRoute: (options: { - to: '/items/$id' - params: { id: string } - }) => Promise - navigate: ( - options: - | { - to: '/items/$id' - params: { id: string } - replace: true - } - | { - to: '/' - replace: true - }, - ) => Promise - subscribe: (event: 'onRendered', listener: () => void) => () => void -} - -// 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. Interleave navigation to exercise eviction. -const preloadsPerEvictionNavigation = 10 -// Keep generated URLs unique across warmup and measured invocations. -const benchmarkRandom = createDeterministicRandom(0x706c6f61) -let preloadCounter = 0 - -const uninitialized = async (_id: string) => { - throw new Error('preload-churn benchmark is not initialized') -} - -export function createWorkload( - framework: Framework, - mountTestApp: MountTestApp, - getTrackedItemLoaderCount: GetTrackedItemLoaderCount, -) { - warnClientMemoryDevMode(framework) - - let container: HTMLDivElement | undefined = undefined - let router: PreloadRouter | undefined = undefined - let unmount = noop - let unsub = noop - let resolveRendered = noop - let evictionParity = 0 - let preloadItem: (id: string) => Promise = uninitialized - let navigateToItem: (id: string) => Promise = uninitialized - let navigateToIndex: () => Promise = () => - uninitialized('navigate-to-index') - - function assertRenderedIndex() { - const actual = - container?.querySelector('[data-bench-page]')?.dataset - .benchPage - - if (actual !== 'index') { - throw new Error(`Expected rendered index page, got ${actual}`) - } - } - - async function waitForRenderedIndex() { - for (let attempt = 0; attempt < 10; attempt++) { - try { - assertRenderedIndex() - return - } catch { - await nextAnimationFrame() - } - } - - assertRenderedIndex() - } - - function waitForNextRender() { - return new Promise((resolve) => { - resolveRendered = resolve - }) - } - - async function before() { - if (container) { - after() - } - - container = createBenchContainer() - - const mounted = mountTestApp(container) - router = mounted.router as PreloadRouter - unmount = mounted.unmount - - unsub = router.subscribe('onRendered', () => { - resolveRendered() - }) - - preloadItem = async (id) => { - await router!.preloadRoute({ - to: '/items/$id', - params: { id }, - }) - await drainMicrotasks() - } - - navigateToItem = async (id) => { - const rendered = waitForNextRender() - await Promise.all([ - router!.navigate({ - to: '/items/$id', - params: { id }, - replace: true, - }), - rendered, - ]) - } - - navigateToIndex = async () => { - const rendered = waitForNextRender() - await Promise.all([ - router!.navigate({ - to: '/', - replace: true, - }), - rendered, - ]) - } - - await router.load() - await waitForRenderedIndex() - } - - function after() { - unmount() - removeBenchContainer(container) - unsub() - - container = undefined - router = undefined - unmount = noop - unsub = noop - resolveRendered = noop - evictionParity = 0 - preloadItem = uninitialized - navigateToItem = uninitialized - navigateToIndex = () => uninitialized('navigate-to-index') - } - - // Alternate between two distinct locations so every eviction navigation - // changes the href (a same-href navigate would never commit or render). - async function evictPreloads() { - evictionParity = (evictionParity + 1) % 2 - - if (evictionParity === 1) { - await navigateToItem(evictionItemId) - } else { - await navigateToIndex() - } - } - - return { - name: `mem client preload-churn (${framework})`, - before, - preload: (id: string) => preloadItem(id), - evictPreloads, - async run() { - for (let index = 0; index < preloadChurnIterations; index++) { - await preloadItem( - `${(preloadCounter++).toString(36)}-${randomSegment(benchmarkRandom)}`, - ) - - if ((index + 1) % preloadsPerEvictionNavigation === 0) { - await evictPreloads() - } - } - }, - async sanity() { - await before() - - try { - assertRenderedIndex() - - const id = 'sanity-preloaded-item' - const initialLoaderCount = getTrackedItemLoaderCount(id) - await preloadItem(id) - - const preloadedLoaderCount = getTrackedItemLoaderCount(id) - if (preloadedLoaderCount !== initialLoaderCount + 1) { - throw new Error( - `Expected preload to run item loader once, got ${preloadedLoaderCount - initialLoaderCount}`, - ) - } - } finally { - after() - } - }, - after, - } -} diff --git a/benchmarks/memory/client/scenarios/preload-churn/solid/memory.bench.ts b/benchmarks/memory/client/scenarios/preload-churn/solid/memory.bench.ts deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' -import { workload } from './setup' - -await workload.sanity() - -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) -}) diff --git a/benchmarks/memory/client/scenarios/preload-churn/solid/memory.flame.ts b/benchmarks/memory/client/scenarios/preload-churn/solid/memory.flame.ts deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runClientFlameBenchmark } from '#memory-client/flame-runner' -import { workload } from './setup.ts' - -await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/preload-churn/solid/project.json b/benchmarks/memory/client/scenarios/preload-churn/solid/project.json deleted file mode 100644 index 16ef8af968..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-client-preload-churn-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.config.ts" - } - }, - "build:client:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:client:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "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/memory/client/scenarios/preload-churn/solid/setup.ts b/benchmarks/memory/client/scenarios/preload-churn/solid/setup.ts deleted file mode 100644 index 4db457f561..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ClientMemoryWorkload } from '#memory-client/benchmark' -import type * as App from './src/app' -import { createWorkload } from '../shared.ts' - -const appModulePath = './dist/app.js' -const { getTrackedItemLoaderCount, mountTestApp } = (await import( - /* @vite-ignore */ appModulePath -)) as typeof App - -export const workload: ClientMemoryWorkload = createWorkload( - 'solid', - mountTestApp, - getTrackedItemLoaderCount, -) diff --git a/benchmarks/memory/client/scenarios/preload-churn/solid/src/app.tsx b/benchmarks/memory/client/scenarios/preload-churn/solid/src/app.tsx deleted file mode 100644 index 18ad5b97e4..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/src/app.tsx +++ /dev/null @@ -1,31 +0,0 @@ -import { RouterProvider } from '@tanstack/solid-router' -import { render } from 'solid-js/web' -import { getRouter } from './router' - -export { getTrackedItemLoaderCount } from '../../item-payload' - -export function mountTestApp(container: Element) { - const router = getRouter() - const dispose = render(() => , container) - let didUnmount = false - - // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, - // release the devtools global, and detach history listeners. - return { - router, - unmount() { - if (didUnmount) { - return - } - - didUnmount = true - dispose() - - if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { - self.__TSR_ROUTER__ = undefined - } - - router.history.destroy() - }, - } -} diff --git a/benchmarks/memory/client/scenarios/preload-churn/solid/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/preload-churn/solid/src/routeTree.gen.ts deleted file mode 100644 index 27749ab2af..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,77 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as ItemsIdRouteImport } from './routes/items.$id' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ItemsIdRoute = ItemsIdRouteImport.update({ - id: '/items/$id', - path: '/items/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/items/$id': typeof ItemsIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/items/$id': typeof ItemsIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/items/$id': typeof ItemsIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/items/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/items/$id' - id: '__root__' | '/' | '/items/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ItemsIdRoute: typeof ItemsIdRoute -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/items/$id': { - id: '/items/$id' - path: '/items/$id' - fullPath: '/items/$id' - preLoaderRoute: typeof ItemsIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ItemsIdRoute: ItemsIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/preload-churn/solid/src/router.tsx b/benchmarks/memory/client/scenarios/preload-churn/solid/src/router.tsx deleted file mode 100644 index faed87f1f4..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/src/router.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { createMemoryHistory, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - history: createMemoryHistory({ - initialEntries: ['/'], - }), - routeTree, - defaultPreloadGcTime: 0, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/client/scenarios/preload-churn/solid/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/preload-churn/solid/src/routes/__root.tsx deleted file mode 100644 index cb8d5a688d..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createRootRoute } from '@tanstack/solid-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return -} diff --git a/benchmarks/memory/client/scenarios/preload-churn/solid/src/routes/index.tsx b/benchmarks/memory/client/scenarios/preload-churn/solid/src/routes/index.tsx deleted file mode 100644 index b870b8bfd5..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
index
-} diff --git a/benchmarks/memory/client/scenarios/preload-churn/solid/src/routes/items.$id.tsx b/benchmarks/memory/client/scenarios/preload-churn/solid/src/routes/items.$id.tsx deleted file mode 100644 index 15fa2a34ab..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/src/routes/items.$id.tsx +++ /dev/null @@ -1,20 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { createItemPayload, trackItemLoaderCall } from '../../../item-payload' - -export const Route = createFileRoute('/items/$id')({ - loader: ({ params }) => { - trackItemLoaderCall(params.id) - return createItemPayload(params.id) - }, - component: ItemComponent, -}) - -function ItemComponent() { - const data = Route.useLoaderData() - - return ( -
- {`${data().id}:${data().byteLength}`} -
- ) -} diff --git a/benchmarks/memory/client/scenarios/preload-churn/solid/tsconfig.json b/benchmarks/memory/client/scenarios/preload-churn/solid/tsconfig.json deleted file mode 100644 index b12dcb7ade..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "allowImportingTsExtensions": true, - "jsxImportSource": "solid-js", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "src/**/*.ts", - "src/**/*.tsx", - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../../../vitest.setup.ts" - ] -} diff --git a/benchmarks/memory/client/scenarios/preload-churn/solid/vite.config.ts b/benchmarks/memory/client/scenarios/preload-churn/solid/vite.config.ts deleted file mode 100644 index efc75d2b93..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/vite.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -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)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/app.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - ...memoryConfig('client'), - name: '@benchmarks/memory-client preload-churn (solid)', - watch: false, - environment: 'jsdom', - }, -}) diff --git a/benchmarks/memory/client/scenarios/preload-churn/vue/memory.bench.ts b/benchmarks/memory/client/scenarios/preload-churn/vue/memory.bench.ts deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' -import { workload } from './setup' - -await workload.sanity() - -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) -}) diff --git a/benchmarks/memory/client/scenarios/preload-churn/vue/memory.flame.ts b/benchmarks/memory/client/scenarios/preload-churn/vue/memory.flame.ts deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runClientFlameBenchmark } from '#memory-client/flame-runner' -import { workload } from './setup.ts' - -await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/preload-churn/vue/project.json b/benchmarks/memory/client/scenarios/preload-churn/vue/project.json deleted file mode 100644 index e13388890f..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-client-preload-churn-vue", - "projectType": "application", - "targets": { - "build:client": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "build:client:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:client:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "test:types:client": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/vue-router"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/memory/client/scenarios/preload-churn/vue/setup.ts b/benchmarks/memory/client/scenarios/preload-churn/vue/setup.ts deleted file mode 100644 index 4aad4af31e..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ClientMemoryWorkload } from '#memory-client/benchmark' -import type * as App from './src/app' -import { createWorkload } from '../shared.ts' - -const appModulePath = './dist/app.js' -const { getTrackedItemLoaderCount, mountTestApp } = (await import( - /* @vite-ignore */ appModulePath -)) as typeof App - -export const workload: ClientMemoryWorkload = createWorkload( - 'vue', - mountTestApp, - getTrackedItemLoaderCount, -) diff --git a/benchmarks/memory/client/scenarios/preload-churn/vue/src/app.tsx b/benchmarks/memory/client/scenarios/preload-churn/vue/src/app.tsx deleted file mode 100644 index 890447d88b..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/src/app.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import { RouterProvider } from '@tanstack/vue-router' -import { createApp } from 'vue' -import { getRouter } from './router' -import type {} from '@tanstack/router-core' - -export { getTrackedItemLoaderCount } from '../../item-payload' - -export function mountTestApp(container: Element) { - const router = getRouter() - const vueApp = createApp({ - setup() { - return () => - }, - }) - let didUnmount = false - - vueApp.mount(container) - - // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, - // release the devtools global, and detach history listeners. - return { - router, - unmount() { - if (didUnmount) { - return - } - - didUnmount = true - vueApp.unmount() - - if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { - self.__TSR_ROUTER__ = undefined - } - - router.history.destroy() - }, - } -} diff --git a/benchmarks/memory/client/scenarios/preload-churn/vue/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/preload-churn/vue/src/routeTree.gen.ts deleted file mode 100644 index a2216f2b67..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,77 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as ItemsIdRouteImport } from './routes/items.$id' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ItemsIdRoute = ItemsIdRouteImport.update({ - id: '/items/$id', - path: '/items/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/items/$id': typeof ItemsIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/items/$id': typeof ItemsIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/items/$id': typeof ItemsIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/items/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/items/$id' - id: '__root__' | '/' | '/items/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ItemsIdRoute: typeof ItemsIdRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/items/$id': { - id: '/items/$id' - path: '/items/$id' - fullPath: '/items/$id' - preLoaderRoute: typeof ItemsIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ItemsIdRoute: ItemsIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/preload-churn/vue/src/router.tsx b/benchmarks/memory/client/scenarios/preload-churn/vue/src/router.tsx deleted file mode 100644 index 86534112d7..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/src/router.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { createMemoryHistory, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - history: createMemoryHistory({ - initialEntries: ['/'], - }), - routeTree, - defaultPreloadGcTime: 0, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/client/scenarios/preload-churn/vue/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/preload-churn/vue/src/routes/__root.tsx deleted file mode 100644 index 91296e6f84..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createRootRoute } from '@tanstack/vue-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return -} diff --git a/benchmarks/memory/client/scenarios/preload-churn/vue/src/routes/index.tsx b/benchmarks/memory/client/scenarios/preload-churn/vue/src/routes/index.tsx deleted file mode 100644 index b4f871306c..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
index
-} 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 deleted file mode 100644 index 08254e173e..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/src/routes/items.$id.tsx +++ /dev/null @@ -1,23 +0,0 @@ -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) - return createItemPayload(params.id) - }, - component: ItemComponent, -}) diff --git a/benchmarks/memory/client/scenarios/preload-churn/vue/tsconfig.json b/benchmarks/memory/client/scenarios/preload-churn/vue/tsconfig.json deleted file mode 100644 index 9a5872a4c0..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "allowImportingTsExtensions": true, - "jsxImportSource": "vue", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "src/**/*.ts", - "src/**/*.tsx", - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../../../vitest.setup.ts" - ] -} diff --git a/benchmarks/memory/client/scenarios/preload-churn/vue/vite.config.ts b/benchmarks/memory/client/scenarios/preload-churn/vue/vite.config.ts deleted file mode 100644 index 3d56089ba7..0000000000 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/app.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - ...memoryConfig('client'), - name: '@benchmarks/memory-client preload-churn (vue)', - watch: false, - environment: 'jsdom', - }, -}) 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 deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/react/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' -import { workload } from './setup' - -await workload.sanity() - -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) -}) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/react/memory.flame.ts b/benchmarks/memory/client/scenarios/unique-location-churn/react/memory.flame.ts deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/react/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runClientFlameBenchmark } from '#memory-client/flame-runner' -import { workload } from './setup.ts' - -await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/react/project.json b/benchmarks/memory/client/scenarios/unique-location-churn/react/project.json deleted file mode 100644 index 1572552650..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/react/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-client-unique-location-churn-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.config.ts" - } - }, - "build:client:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:client:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "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/memory/client/scenarios/unique-location-churn/react/setup.ts b/benchmarks/memory/client/scenarios/unique-location-churn/react/setup.ts deleted file mode 100644 index 70603b5c34..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/react/setup.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { ClientMemoryWorkload } from '#memory-client/benchmark' -import type * as App from './src/app' -import { createWorkload } from '../shared.ts' - -const appModulePath = './dist/app.js' -const { mountTestApp } = (await import( - /* @vite-ignore */ appModulePath -)) as typeof App - -export const workload: ClientMemoryWorkload = createWorkload( - 'react', - mountTestApp, -) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/react/src/app.tsx b/benchmarks/memory/client/scenarios/unique-location-churn/react/src/app.tsx deleted file mode 100644 index d714e7bfdd..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/react/src/app.tsx +++ /dev/null @@ -1,31 +0,0 @@ -import { RouterProvider } from '@tanstack/react-router' -import { createRoot } from 'react-dom/client' -import { getRouter } from './router' - -export function mountTestApp(container: Element) { - const router = getRouter() - const reactRoot = createRoot(container) - let didUnmount = false - - reactRoot.render() - - // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, - // release the devtools global, and detach history listeners. - return { - router, - unmount() { - if (didUnmount) { - return - } - - didUnmount = true - reactRoot.unmount() - - if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { - self.__TSR_ROUTER__ = undefined - } - - router.history.destroy() - }, - } -} diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/react/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/unique-location-churn/react/src/routeTree.gen.ts deleted file mode 100644 index 1165f57523..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/react/src/routeTree.gen.ts +++ /dev/null @@ -1,59 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as ItemsIdRouteImport } from './routes/items.$id' - -const ItemsIdRoute = ItemsIdRouteImport.update({ - id: '/items/$id', - path: '/items/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/items/$id': typeof ItemsIdRoute -} -export interface FileRoutesByTo { - '/items/$id': typeof ItemsIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/items/$id': typeof ItemsIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/items/$id' - fileRoutesByTo: FileRoutesByTo - to: '/items/$id' - id: '__root__' | '/items/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - ItemsIdRoute: typeof ItemsIdRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/items/$id': { - id: '/items/$id' - path: '/items/$id' - fullPath: '/items/$id' - preLoaderRoute: typeof ItemsIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - ItemsIdRoute: ItemsIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/react/src/router.tsx b/benchmarks/memory/client/scenarios/unique-location-churn/react/src/router.tsx deleted file mode 100644 index 50ad269060..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/react/src/router.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { createMemoryHistory, createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - history: createMemoryHistory({ - initialEntries: ['/items/initial?q=q-initial'], - }), - routeTree, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/react/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/unique-location-churn/react/src/routes/__root.tsx deleted file mode 100644 index 889395056b..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/react/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createRootRoute } from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return -} diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/react/src/routes/items.$id.tsx b/benchmarks/memory/client/scenarios/unique-location-churn/react/src/routes/items.$id.tsx deleted file mode 100644 index c9e823f6c2..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/react/src/routes/items.$id.tsx +++ /dev/null @@ -1,28 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -type ItemSearch = { - q: string -} - -export const Route = createFileRoute('/items/$id')({ - validateSearch: (search: Record): ItemSearch => ({ - q: typeof search.q === 'string' ? search.q : '', - }), - loaderDeps: ({ search }) => ({ q: search.q }), - loader: ({ params, deps }) => ({ - id: params.id, - q: deps.q, - checksum: params.id.length + deps.q.length, - }), - component: ItemComponent, -}) - -function ItemComponent() { - const data = Route.useLoaderData() - - return ( -
{`${data.id}:${data.q}:${data.checksum}`}
- ) -} diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/react/tsconfig.json b/benchmarks/memory/client/scenarios/unique-location-churn/react/tsconfig.json deleted file mode 100644 index ea566061d9..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/react/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "allowImportingTsExtensions": true, - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "src/**/*.ts", - "src/**/*.tsx", - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../../../vitest.setup.ts" - ] -} 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 deleted file mode 100644 index 7ee67bfe30..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/react/vite.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -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)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/app.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - ...memoryConfig('client'), - name: '@benchmarks/memory-client unique-location-churn (react)', - watch: false, - environment: 'jsdom', - }, -}) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/shared.ts b/benchmarks/memory/client/scenarios/unique-location-churn/shared.ts deleted file mode 100644 index 3b36c7811e..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/shared.ts +++ /dev/null @@ -1,149 +0,0 @@ -import { - createDeterministicRandom, - randomSegment, -} from '#memory-client/bench-utils' -import { - createBenchContainer, - nextAnimationFrame, - noop, - removeBenchContainer, - warnClientMemoryDevMode, -} from '#memory-client/lifecycle' -import type { Framework, MountTestApp } from '#memory-client/lifecycle' - -type ItemLocation = { - id: string - q: string -} - -type NavigationRouter = { - load: () => Promise - navigate: (options: { - to: '/items/$id' - params: { id: string } - search: { q: string } - replace: true - }) => Promise - subscribe: (event: 'onRendered', listener: () => void) => () => void -} - -const uniqueLocationChurnIterations = 300 -// Module-level so ids stay unique across runner invocations on one mount; the -// counter prefix removes any residual LCG birthday-collision risk. -const benchmarkRandom = createDeterministicRandom(0xdecafbad) -let locationCounter = 0 - -const uninitialized = () => - Promise.reject( - new Error('unique-location-churn benchmark is not initialized'), - ) - -export function createWorkload( - framework: Framework, - mountTestApp: MountTestApp, -) { - warnClientMemoryDevMode(framework) - - let container: HTMLDivElement | undefined = undefined - let unmount = noop - let unsub = noop - let resolveRendered: () => void = noop - let navigateTo: (location: ItemLocation) => Promise = uninitialized - - function assertRenderedId(expected: string) { - const actual = - container?.querySelector('[data-bench-id]')?.dataset.benchId - - if (actual !== expected) { - throw new Error(`Expected rendered item id ${expected}, got ${actual}`) - } - } - - async function waitForRenderedId(expected: string) { - for (let attempt = 0; attempt < 10; attempt++) { - try { - assertRenderedId(expected) - return - } catch { - await nextAnimationFrame() - } - } - - assertRenderedId(expected) - } - - function waitForNextRender() { - return new Promise((resolve) => { - resolveRendered = resolve - }) - } - - async function before() { - if (container) { - after() - } - - container = createBenchContainer() - - const mounted = mountTestApp(container) - const router = mounted.router as NavigationRouter - unmount = mounted.unmount - - unsub = router.subscribe('onRendered', () => { - resolveRendered() - }) - - navigateTo = async (location) => { - const rendered = waitForNextRender() - await Promise.all([ - router.navigate({ - to: '/items/$id', - params: { id: location.id }, - search: { q: location.q }, - replace: true, - }), - rendered, - ]) - } - - await router.load() - await waitForRenderedId('initial') - } - - function after() { - unmount() - removeBenchContainer(container) - unsub() - - container = undefined - unmount = noop - unsub = noop - resolveRendered = noop - navigateTo = uninitialized - } - - return { - name: `mem client unique-location-churn (${framework})`, - before, - navigate: (location: ItemLocation) => navigateTo(location), - async run() { - for (let index = 0; index < uniqueLocationChurnIterations; index++) { - const id = `${(locationCounter++).toString(36)}-${randomSegment(benchmarkRandom)}` - const q = `q-${randomSegment(benchmarkRandom)}` - - await navigateTo({ id, q }) - } - }, - async sanity() { - await before() - - try { - await navigateTo({ id: 'sanity-one', q: 'q-sanity-one' }) - assertRenderedId('sanity-one') - } finally { - after() - } - }, - after, - } -} 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 deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/solid/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' -import { workload } from './setup' - -await workload.sanity() - -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) -}) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/solid/memory.flame.ts b/benchmarks/memory/client/scenarios/unique-location-churn/solid/memory.flame.ts deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/solid/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runClientFlameBenchmark } from '#memory-client/flame-runner' -import { workload } from './setup.ts' - -await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/solid/project.json b/benchmarks/memory/client/scenarios/unique-location-churn/solid/project.json deleted file mode 100644 index 5be22de7a4..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/solid/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-client-unique-location-churn-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.config.ts" - } - }, - "build:client:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:client:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "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/memory/client/scenarios/unique-location-churn/solid/setup.ts b/benchmarks/memory/client/scenarios/unique-location-churn/solid/setup.ts deleted file mode 100644 index 493425c6a2..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/solid/setup.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { ClientMemoryWorkload } from '#memory-client/benchmark' -import type * as App from './src/app' -import { createWorkload } from '../shared.ts' - -const appModulePath = './dist/app.js' -const { mountTestApp } = (await import( - /* @vite-ignore */ appModulePath -)) as typeof App - -export const workload: ClientMemoryWorkload = createWorkload( - 'solid', - mountTestApp, -) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/app.tsx b/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/app.tsx deleted file mode 100644 index 16000c90a1..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/app.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { RouterProvider } from '@tanstack/solid-router' -import { render } from 'solid-js/web' -import { getRouter } from './router' - -export function mountTestApp(container: Element) { - const router = getRouter() - const dispose = render(() => , container) - let didUnmount = false - - // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, - // release the devtools global, and detach history listeners. - return { - router, - unmount() { - if (didUnmount) { - return - } - - didUnmount = true - dispose() - - if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { - self.__TSR_ROUTER__ = undefined - } - - router.history.destroy() - }, - } -} diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/routeTree.gen.ts deleted file mode 100644 index 4a451735ff..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,59 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as ItemsIdRouteImport } from './routes/items.$id' - -const ItemsIdRoute = ItemsIdRouteImport.update({ - id: '/items/$id', - path: '/items/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/items/$id': typeof ItemsIdRoute -} -export interface FileRoutesByTo { - '/items/$id': typeof ItemsIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/items/$id': typeof ItemsIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/items/$id' - fileRoutesByTo: FileRoutesByTo - to: '/items/$id' - id: '__root__' | '/items/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - ItemsIdRoute: typeof ItemsIdRoute -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/items/$id': { - id: '/items/$id' - path: '/items/$id' - fullPath: '/items/$id' - preLoaderRoute: typeof ItemsIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - ItemsIdRoute: ItemsIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/router.tsx b/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/router.tsx deleted file mode 100644 index 2969b06914..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/router.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { createMemoryHistory, createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - history: createMemoryHistory({ - initialEntries: ['/items/initial?q=q-initial'], - }), - routeTree, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/routes/__root.tsx deleted file mode 100644 index cb8d5a688d..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createRootRoute } from '@tanstack/solid-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return -} diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/routes/items.$id.tsx b/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/routes/items.$id.tsx deleted file mode 100644 index 9724922b8d..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/routes/items.$id.tsx +++ /dev/null @@ -1,28 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -type ItemSearch = { - q: string -} - -export const Route = createFileRoute('/items/$id')({ - validateSearch: (search: Record): ItemSearch => ({ - q: typeof search.q === 'string' ? search.q : '', - }), - loaderDeps: ({ search }) => ({ q: search.q }), - loader: ({ params, deps }) => ({ - id: params.id, - q: deps.q, - checksum: params.id.length + deps.q.length, - }), - component: ItemComponent, -}) - -function ItemComponent() { - const data = Route.useLoaderData() - - return ( -
{`${data().id}:${data().q}:${data().checksum}`}
- ) -} diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/solid/tsconfig.json b/benchmarks/memory/client/scenarios/unique-location-churn/solid/tsconfig.json deleted file mode 100644 index b12dcb7ade..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/solid/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "allowImportingTsExtensions": true, - "jsxImportSource": "solid-js", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "src/**/*.ts", - "src/**/*.tsx", - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../../../vitest.setup.ts" - ] -} 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 deleted file mode 100644 index 4db90da2d2..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/solid/vite.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -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)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - solid({ hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/app.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - ...memoryConfig('client'), - name: '@benchmarks/memory-client unique-location-churn (solid)', - watch: false, - environment: 'jsdom', - }, -}) 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 deleted file mode 100644 index 43ab822de3..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/vue/memory.bench.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' -import { workload } from './setup' - -await workload.sanity() - -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) -}) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/vue/memory.flame.ts b/benchmarks/memory/client/scenarios/unique-location-churn/vue/memory.flame.ts deleted file mode 100644 index 952fd9a62c..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/vue/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runClientFlameBenchmark } from '#memory-client/flame-runner' -import { workload } from './setup.ts' - -await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/vue/project.json b/benchmarks/memory/client/scenarios/unique-location-churn/vue/project.json deleted file mode 100644 index 6c05cf80b0..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/vue/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-client-unique-location-churn-vue", - "projectType": "application", - "targets": { - "build:client": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "build:client:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-router"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:client:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "test:types:client": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/vue-router"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/vue/setup.ts b/benchmarks/memory/client/scenarios/unique-location-churn/vue/setup.ts deleted file mode 100644 index a38df04788..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/vue/setup.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { ClientMemoryWorkload } from '#memory-client/benchmark' -import type * as App from './src/app' -import { createWorkload } from '../shared.ts' - -const appModulePath = './dist/app.js' -const { mountTestApp } = (await import( - /* @vite-ignore */ appModulePath -)) as typeof App - -export const workload: ClientMemoryWorkload = createWorkload( - 'vue', - mountTestApp, -) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/app.tsx b/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/app.tsx deleted file mode 100644 index fad2251cc0..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/app.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import { RouterProvider } from '@tanstack/vue-router' -import { createApp } from 'vue' -import { getRouter } from './router' -import type {} from '@tanstack/router-core' - -export function mountTestApp(container: Element) { - const router = getRouter() - const vueApp = createApp({ - setup() { - return () => - }, - }) - let didUnmount = false - - vueApp.mount(container) - - // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, - // release the devtools global, and detach history listeners. - return { - router, - unmount() { - if (didUnmount) { - return - } - - didUnmount = true - vueApp.unmount() - - if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { - self.__TSR_ROUTER__ = undefined - } - - router.history.destroy() - }, - } -} diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/routeTree.gen.ts deleted file mode 100644 index d3e9db0345..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,59 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as ItemsIdRouteImport } from './routes/items.$id' - -const ItemsIdRoute = ItemsIdRouteImport.update({ - id: '/items/$id', - path: '/items/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/items/$id': typeof ItemsIdRoute -} -export interface FileRoutesByTo { - '/items/$id': typeof ItemsIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/items/$id': typeof ItemsIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/items/$id' - fileRoutesByTo: FileRoutesByTo - to: '/items/$id' - id: '__root__' | '/items/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - ItemsIdRoute: typeof ItemsIdRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/items/$id': { - id: '/items/$id' - path: '/items/$id' - fullPath: '/items/$id' - preLoaderRoute: typeof ItemsIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - ItemsIdRoute: ItemsIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/router.tsx b/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/router.tsx deleted file mode 100644 index 72f9ab565b..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/router.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { createMemoryHistory, createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - history: createMemoryHistory({ - initialEntries: ['/items/initial?q=q-initial'], - }), - routeTree, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/routes/__root.tsx deleted file mode 100644 index 91296e6f84..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/routes/__root.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createRootRoute } from '@tanstack/vue-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return -} 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 deleted file mode 100644 index e796ee14d1..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/routes/items.$id.tsx +++ /dev/null @@ -1,37 +0,0 @@ -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 : '', - }), - loaderDeps: ({ search }: { search: ItemSearch }) => ({ q: search.q }), - loader: ({ - params, - deps, - }: { - params: { id: string } - deps: { q: string } - }) => ({ - id: params.id, - q: deps.q, - checksum: params.id.length + deps.q.length, - }), - component: ItemComponent, -}) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/vue/tsconfig.json b/benchmarks/memory/client/scenarios/unique-location-churn/vue/tsconfig.json deleted file mode 100644 index 9a5872a4c0..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/vue/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "allowImportingTsExtensions": true, - "jsxImportSource": "vue", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "src/**/*.ts", - "src/**/*.tsx", - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../../../vitest.setup.ts" - ] -} 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 deleted file mode 100644 index d074d571b9..0000000000 --- a/benchmarks/memory/client/scenarios/unique-location-churn/vue/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/app.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - ...memoryConfig('client'), - name: '@benchmarks/memory-client unique-location-churn (vue)', - watch: false, - environment: 'jsdom', - }, -}) diff --git a/benchmarks/memory/client/tsconfig.json b/benchmarks/memory/client/tsconfig.json deleted file mode 100644 index eefc5c581e..0000000000 --- a/benchmarks/memory/client/tsconfig.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "extends": "../../../tsconfig.json", - "compilerOptions": { - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "bench-utils.ts", - "lifecycle.ts", - "vitest.setup.ts", - "scenarios/*/shared.ts" - ] -} diff --git a/benchmarks/memory/client/vitest.react.config.ts b/benchmarks/memory/client/vitest.react.config.ts deleted file mode 100644 index 44643b4d60..0000000000 --- a/benchmarks/memory/client/vitest.react.config.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { defineConfig } from 'vitest/config' - -export default defineConfig({ - test: { - watch: false, - fileParallelism: false, - projects: ['./scenarios/*/react/vite.config.ts'], - }, -}) diff --git a/benchmarks/memory/client/vitest.setup.ts b/benchmarks/memory/client/vitest.setup.ts deleted file mode 100644 index ce3127275a..0000000000 --- a/benchmarks/memory/client/vitest.setup.ts +++ /dev/null @@ -1,9 +0,0 @@ -// @ts-expect-error -global.IS_REACT_ACT_ENVIRONMENT = true - -const scrollTo = () => {} - -window.scrollTo = scrollTo -globalThis.scrollTo = scrollTo - -export {} diff --git a/benchmarks/memory/client/vitest.solid.config.ts b/benchmarks/memory/client/vitest.solid.config.ts deleted file mode 100644 index 5c8185cdd9..0000000000 --- a/benchmarks/memory/client/vitest.solid.config.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { defineConfig } from 'vitest/config' - -export default defineConfig({ - test: { - watch: false, - fileParallelism: false, - projects: ['./scenarios/*/solid/vite.config.ts'], - }, -}) diff --git a/benchmarks/memory/client/vitest.vue.config.ts b/benchmarks/memory/client/vitest.vue.config.ts deleted file mode 100644 index 01768185ee..0000000000 --- a/benchmarks/memory/client/vitest.vue.config.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { defineConfig } from 'vitest/config' - -export default defineConfig({ - test: { - watch: false, - fileParallelism: false, - projects: ['./scenarios/*/vue/vite.config.ts'], - }, -}) diff --git a/benchmarks/memory/flame-control.ts b/benchmarks/memory/flame-control.ts deleted file mode 100644 index 0d6f42df33..0000000000 --- a/benchmarks/memory/flame-control.ts +++ /dev/null @@ -1,123 +0,0 @@ -import fs from 'node:fs' -import { createRequire } from 'node:module' -import path from 'node:path' - -const flameEnabled = process.env.TSR_MEMORY_FLAME === '1' -const heapIntervalBytes = 512 * 1024 -const heapStackDepth = 64 - -interface HeapProfile { - encode: () => Uint8Array -} - -interface HeapProfiler { - start: (intervalBytes: number, stackDepth: number) => void - stop: () => void - v8Profile: () => unknown - convertProfile: ( - v8Profile: unknown, - ignoreSamplePath?: string, - sourceMapper?: unknown, - ) => HeapProfile -} - -interface SourceMapperConstructor { - create: (searchDirs: Array) => Promise -} - -interface PprofModule { - heap: HeapProfiler - SourceMapper: SourceMapperConstructor -} - -function loadPprof() { - const requireFrom = process.env.TSR_MEMORY_REQUIRE_FROM - ? path.resolve(process.env.TSR_MEMORY_REQUIRE_FROM) - : import.meta.url - const require = createRequire(requireFrom) - - return require('@datadog/pprof') as PprofModule -} - -function getSourcemapDirs() { - return (process.env.TSR_MEMORY_SOURCEMAP_DIRS ?? '') - .split(path.delimiter) - .filter(Boolean) -} - -async function createSourceMapper(pprof: PprofModule) { - const sourcemapDirs = getSourcemapDirs() - - if (sourcemapDirs.length === 0) { - return undefined - } - - return pprof.SourceMapper.create(sourcemapDirs) -} - -function formatTimestamp() { - return new Date().toISOString().replace(/[:.]/g, '-') -} - -function formatProfileFileName(profileName?: string) { - const profileNameSlug = profileName - ?.trim() - .toLowerCase() - .replace(/[^a-z0-9]+/g, '-') - .replace(/^-+|-+$/g, '') - const profileNamePart = profileNameSlug ? `${profileNameSlug}-` : '' - - return `heap-profile-${profileNamePart}${formatTimestamp()}.pb` -} - -export async function profileFlameWorkload( - workload: () => Promise | void, - profileName?: string, -) { - if (!flameEnabled) { - await workload() - return - } - - const profileDir = process.env.TSR_MEMORY_PROFILE_DIR - - if (!profileDir) { - throw new Error('TSR_MEMORY_PROFILE_DIR must be set for flame profiling') - } - - fs.mkdirSync(profileDir, { recursive: true }) - - const pprof = loadPprof() - const sourceMapper = await createSourceMapper(pprof) - - pprof.heap.start(heapIntervalBytes, heapStackDepth) - - let workloadError: unknown = undefined - let v8Profile: unknown = undefined - - try { - await workload() - } catch (error) { - workloadError = error - } finally { - try { - v8Profile = pprof.heap.v8Profile() - } finally { - pprof.heap.stop() - } - } - - const heapProfile = pprof.heap.convertProfile( - v8Profile, - undefined, - sourceMapper, - ) - const profilePath = path.join(profileDir, formatProfileFileName(profileName)) - - fs.writeFileSync(profilePath, heapProfile.encode()) - console.log(`Heap profile written to: ${profilePath}`) - - if (workloadError) { - throw workloadError - } -} diff --git a/benchmarks/memory/run-flame.mjs b/benchmarks/memory/run-flame.mjs deleted file mode 100644 index cc568f3f77..0000000000 --- a/benchmarks/memory/run-flame.mjs +++ /dev/null @@ -1,117 +0,0 @@ -#!/usr/bin/env node -import { spawn } from 'node:child_process' -import fs from 'node:fs' -import { createRequire } from 'node:module' -import path from 'node:path' -import process from 'node:process' - -const [, , entrypointArg, sourcemapDirArg] = process.argv - -if (!entrypointArg || !sourcemapDirArg) { - console.error( - 'Usage: node benchmarks/memory/run-flame.mjs ', - ) - process.exit(1) -} - -const entrypointPath = path.resolve(entrypointArg) -const sourcemapDirPath = path.resolve(sourcemapDirArg) - -if (!fs.existsSync(entrypointPath)) { - console.error(`Flame entrypoint not found: ${entrypointPath}`) - process.exit(1) -} - -if (!fs.existsSync(sourcemapDirPath)) { - console.error(`Flame sourcemap directory not found: ${sourcemapDirPath}`) - process.exit(1) -} - -const profileDir = path.join( - path.dirname(entrypointPath), - '.profiles', - new Date().toISOString().replace(/[:.]/g, '-'), -) - -fs.mkdirSync(profileDir, { recursive: true }) - -const entrypointRequire = createRequire(entrypointPath) -const { generateFlamegraph, generateMarkdown } = entrypointRequire( - '@platformatic/flame', -) - -process.env.NODE_ENV = 'production' - -console.log(`Flame profile directory: ${profileDir}`) - -const childProcess = spawn(process.execPath, [entrypointPath], { - cwd: profileDir, - env: { - ...process.env, - NODE_ENV: 'production', - TSR_MEMORY_FLAME: '1', - TSR_MEMORY_PROFILE_DIR: profileDir, - TSR_MEMORY_REQUIRE_FROM: entrypointPath, - TSR_MEMORY_SOURCEMAP_DIRS: sourcemapDirPath, - }, - stdio: 'inherit', -}) - -console.log(`Flame profiling process: ${childProcess.pid}`) - -const childCode = await new Promise((resolve) => { - childProcess.on('error', (error) => { - console.error(`Failed to start Flame profiled process: ${error.message}`) - resolve(1) - }) - - childProcess.on('close', (code, signal) => { - if (signal) { - console.error(`Flame profiled process exited via signal ${signal}`) - resolve(1) - return - } - - resolve(code ?? 0) - }) -}) - -const heapProfilePaths = fs - .readdirSync(profileDir) - .filter((fileName) => /^heap-profile-.*\.pb$/.test(fileName)) - .sort() - .map((fileName) => path.join(profileDir, fileName)) - -for (const heapProfilePath of heapProfilePaths) { - const htmlPath = heapProfilePath.replace(/\.pb$/, '.html') - const mdPath = heapProfilePath.replace(/\.pb$/, '.md') - - console.log(`Generating heap flamegraph: ${htmlPath}`) - try { - await generateFlamegraph(heapProfilePath, htmlPath) - } catch (error) { - console.warn(`Failed to generate heap flamegraph: ${error.message}`) - } - - console.log(`Generating heap markdown: ${mdPath}`) - try { - await generateMarkdown(heapProfilePath, mdPath, { format: 'detailed' }) - } catch (error) { - console.warn(`Failed to generate heap markdown: ${error.message}`) - } -} - -const heapReportPaths = fs - .readdirSync(profileDir) - .filter((fileName) => /^heap-profile-.*\.(?:html|md)$/.test(fileName)) - .sort() - .map((fileName) => path.join(profileDir, fileName)) - -if (heapReportPaths.length > 0) { - console.log('Generated heap profile reports:') - for (const heapReportPath of heapReportPaths) { - console.log(` ${heapReportPath}`) - } -} - -process.exit(childCode) diff --git a/benchmarks/memory/runtime.ts b/benchmarks/memory/runtime.ts deleted file mode 100644 index 010149b4df..0000000000 --- a/benchmarks/memory/runtime.ts +++ /dev/null @@ -1,36 +0,0 @@ -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 deleted file mode 100644 index 9caaf63384..0000000000 --- a/benchmarks/memory/server/bench-utils.ts +++ /dev/null @@ -1,99 +0,0 @@ -export { memoryBenchHooks } from '../turn' - -export interface StartRequestHandler { - fetch: (request: Request) => Promise | Response -} - -type RunSequentialRequestLoopRandomOptions = - | { - seed: number - random?: never - } - | { - random: () => number - seed?: never - } - -export type RunSequentialRequestLoopOptions = - RunSequentialRequestLoopRandomOptions & { - iterations?: number - buildRequest: (random: () => number, index: number) => Request - validateResponse?: (response: Response, request: Request) => void - } - -export const memoryBenchOptions = { - iterations: 1, - warmupIterations: 1, - time: 0, - warmupTime: 0, - throws: true, -} - -export function createDeterministicRandom(seed: number) { - let state = seed >>> 0 - - return () => { - state = (state * 1664525 + 1013904223) >>> 0 - return state / 0x100000000 - } -} - -export function randomSegment(random: () => number) { - return Math.floor(random() * 1_000_000_000).toString(36) -} - -export async function drainResponse(response: Response) { - const reader = response.body?.getReader() - - if (!reader) { - return - } - - try { - for (;;) { - const result = await reader.read() - - if (result.done) { - break - } - } - } finally { - reader.releaseLock() - } -} - -export async function runSequentialRequestLoop( - handler: StartRequestHandler, - options: RunSequentialRequestLoopOptions, -) { - const { iterations = 10, buildRequest, validateResponse } = options - const random = - options.seed !== undefined - ? createDeterministicRandom(options.seed) - : options.random - const validate = - validateResponse ?? - ((response: Response, request: Request) => { - if (response.status !== 200) { - throw new Error( - `Request failed with non-200 status ${response.status} (${request.url})`, - ) - } - }) - - for (let index = 0; index < iterations; index++) { - const request = buildRequest(random, index) - const response = await handler.fetch(request) - - validate(response, request) - - await drainResponse(response) - } -} - -// 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)) - } -} diff --git a/benchmarks/memory/server/benchmark.ts b/benchmarks/memory/server/benchmark.ts deleted file mode 100644 index 9b8dc2c76f..0000000000 --- a/benchmarks/memory/server/benchmark.ts +++ /dev/null @@ -1,13 +0,0 @@ -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 -} - -export interface ServerMemoryWorkloadGroup { - sanity: () => Promise | void - workloads: Array -} diff --git a/benchmarks/memory/server/flame-runner.ts b/benchmarks/memory/server/flame-runner.ts deleted file mode 100644 index 1930085aad..0000000000 --- a/benchmarks/memory/server/flame-runner.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { profileFlameWorkload } from '../flame-control.ts' -import type { ServerMemoryWorkloadGroup } from './benchmark.ts' - -export async function runServerFlameBenchmark( - workloadGroup: ServerMemoryWorkloadGroup, -) { - await workloadGroup.sanity() - - for (const workload of workloadGroup.workloads) { - await profileFlameWorkload(workload.run, workload.name) - } -} diff --git a/benchmarks/memory/server/package.json b/benchmarks/memory/server/package.json deleted file mode 100644 index d09343c7b6..0000000000 --- a/benchmarks/memory/server/package.json +++ /dev/null @@ -1,283 +0,0 @@ -{ - "name": "@benchmarks/memory-server", - "private": true, - "type": "module", - "scripts": { - "clean:profiles": "rm -rf scenarios/*/*/.profiles" - }, - "imports": { - "#memory-server/benchmark": "./benchmark.ts", - "#memory-server/bench-utils": "./bench-utils.ts", - "#memory-server/flame-runner": "./flame-runner.ts" - }, - "dependencies": { - "@tanstack/react-router": "workspace:*", - "@tanstack/react-start": "workspace:*", - "@tanstack/solid-router": "workspace:*", - "@tanstack/solid-start": "workspace:*", - "@tanstack/vue-router": "workspace:*", - "@tanstack/vue-start": "workspace:*", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "solid-js": "^1.9.10", - "vue": "^3.5.16" - }, - "devDependencies": { - "@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": "catalog:" - }, - "nx": { - "targets": { - "build:react": { - "executor": "nx:noop", - "cache": false, - "dependsOn": [ - { - "projects": [ - "@benchmarks/memory-server-request-churn-react", - "@benchmarks/memory-server-server-fn-churn-react", - "@benchmarks/memory-server-error-paths-react", - "@benchmarks/memory-server-aborted-requests-react", - "@benchmarks/memory-server-peak-large-page-react", - "@benchmarks/memory-server-streaming-peak-react", - "@benchmarks/memory-server-serialization-payload-react" - ], - "target": "build:ssr" - } - ] - }, - "build:solid": { - "executor": "nx:noop", - "cache": false, - "dependsOn": [ - { - "projects": [ - "@benchmarks/memory-server-request-churn-solid", - "@benchmarks/memory-server-server-fn-churn-solid", - "@benchmarks/memory-server-error-paths-solid", - "@benchmarks/memory-server-aborted-requests-solid", - "@benchmarks/memory-server-peak-large-page-solid", - "@benchmarks/memory-server-streaming-peak-solid", - "@benchmarks/memory-server-serialization-payload-solid" - ], - "target": "build:ssr" - } - ] - }, - "build:vue": { - "executor": "nx:noop", - "cache": false, - "dependsOn": [ - { - "projects": [ - "@benchmarks/memory-server-request-churn-vue", - "@benchmarks/memory-server-server-fn-churn-vue", - "@benchmarks/memory-server-error-paths-vue", - "@benchmarks/memory-server-aborted-requests-vue", - "@benchmarks/memory-server-peak-large-page-vue", - "@benchmarks/memory-server-streaming-peak-vue", - "@benchmarks/memory-server-serialization-payload-vue" - ], - "target": "build:ssr" - } - ] - }, - "build:react:flame": { - "executor": "nx:noop", - "cache": false, - "dependsOn": [ - { - "projects": [ - "@benchmarks/memory-server-request-churn-react", - "@benchmarks/memory-server-server-fn-churn-react", - "@benchmarks/memory-server-error-paths-react", - "@benchmarks/memory-server-aborted-requests-react", - "@benchmarks/memory-server-peak-large-page-react", - "@benchmarks/memory-server-streaming-peak-react", - "@benchmarks/memory-server-serialization-payload-react" - ], - "target": "build:ssr:flame" - } - ] - }, - "build:solid:flame": { - "executor": "nx:noop", - "cache": false, - "dependsOn": [ - { - "projects": [ - "@benchmarks/memory-server-request-churn-solid", - "@benchmarks/memory-server-server-fn-churn-solid", - "@benchmarks/memory-server-error-paths-solid", - "@benchmarks/memory-server-aborted-requests-solid", - "@benchmarks/memory-server-peak-large-page-solid", - "@benchmarks/memory-server-streaming-peak-solid", - "@benchmarks/memory-server-serialization-payload-solid" - ], - "target": "build:ssr:flame" - } - ] - }, - "build:vue:flame": { - "executor": "nx:noop", - "cache": false, - "dependsOn": [ - { - "projects": [ - "@benchmarks/memory-server-request-churn-vue", - "@benchmarks/memory-server-server-fn-churn-vue", - "@benchmarks/memory-server-error-paths-vue", - "@benchmarks/memory-server-aborted-requests-vue", - "@benchmarks/memory-server-peak-large-page-vue", - "@benchmarks/memory-server-streaming-peak-vue", - "@benchmarks/memory-server-serialization-payload-vue" - ], - "target": "build:ssr:flame" - } - ] - }, - "test:flame:react": { - "executor": "nx:noop", - "cache": false, - "dependsOn": [ - { - "projects": [ - "@benchmarks/memory-server-request-churn-react", - "@benchmarks/memory-server-server-fn-churn-react", - "@benchmarks/memory-server-error-paths-react", - "@benchmarks/memory-server-aborted-requests-react", - "@benchmarks/memory-server-peak-large-page-react", - "@benchmarks/memory-server-streaming-peak-react", - "@benchmarks/memory-server-serialization-payload-react" - ], - "target": "test:flame" - } - ] - }, - "test:flame:solid": { - "executor": "nx:noop", - "cache": false, - "dependsOn": [ - { - "projects": [ - "@benchmarks/memory-server-request-churn-solid", - "@benchmarks/memory-server-server-fn-churn-solid", - "@benchmarks/memory-server-error-paths-solid", - "@benchmarks/memory-server-aborted-requests-solid", - "@benchmarks/memory-server-peak-large-page-solid", - "@benchmarks/memory-server-streaming-peak-solid", - "@benchmarks/memory-server-serialization-payload-solid" - ], - "target": "test:flame" - } - ] - }, - "test:flame:vue": { - "executor": "nx:noop", - "cache": false, - "dependsOn": [ - { - "projects": [ - "@benchmarks/memory-server-request-churn-vue", - "@benchmarks/memory-server-server-fn-churn-vue", - "@benchmarks/memory-server-error-paths-vue", - "@benchmarks/memory-server-aborted-requests-vue", - "@benchmarks/memory-server-peak-large-page-vue", - "@benchmarks/memory-server-streaming-peak-vue", - "@benchmarks/memory-server-serialization-payload-vue" - ], - "target": "test:flame" - } - ] - }, - "test:perf:react": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": [ - "build:react" - ], - "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.react.config.ts", - "cwd": "benchmarks/memory/server" - } - }, - "test:perf:solid": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": [ - "build:solid" - ], - "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.solid.config.ts", - "cwd": "benchmarks/memory/server" - } - }, - "test:perf:vue": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": [ - "build:vue" - ], - "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.vue.config.ts", - "cwd": "benchmarks/memory/server" - } - }, - "test:types": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": [ - "@benchmarks/memory-server-request-churn-react", - "@benchmarks/memory-server-server-fn-churn-react", - "@benchmarks/memory-server-error-paths-react", - "@benchmarks/memory-server-aborted-requests-react", - "@benchmarks/memory-server-peak-large-page-react", - "@benchmarks/memory-server-streaming-peak-react", - "@benchmarks/memory-server-serialization-payload-react", - "@benchmarks/memory-server-request-churn-solid", - "@benchmarks/memory-server-server-fn-churn-solid", - "@benchmarks/memory-server-error-paths-solid", - "@benchmarks/memory-server-aborted-requests-solid", - "@benchmarks/memory-server-peak-large-page-solid", - "@benchmarks/memory-server-streaming-peak-solid", - "@benchmarks/memory-server-serialization-payload-solid", - "@benchmarks/memory-server-request-churn-vue", - "@benchmarks/memory-server-server-fn-churn-vue", - "@benchmarks/memory-server-error-paths-vue", - "@benchmarks/memory-server-aborted-requests-vue", - "@benchmarks/memory-server-peak-large-page-vue", - "@benchmarks/memory-server-streaming-peak-vue", - "@benchmarks/memory-server-serialization-payload-vue" - ], - "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 deleted file mode 100644 index 7a1cd6d254..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/deferred-records.ts +++ /dev/null @@ -1,57 +0,0 @@ -const recordCount = 20 - -export type RecordGroup = 'alpha' | 'beta' - -export interface DeferredRecord { - id: string - label: string -} - -export function makeAbortedRequestRecords( - id: string, - group: RecordGroup, -): Array { - return Array.from({ length: recordCount }, (_, index) => ({ - id: `${group}-${id}-${index}`, - 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 deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/react/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' -import { workloadGroup } from './setup' - -await workloadGroup.sanity() - -test('memory', async ({ bench }) => { - for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) - } -}) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/react/memory.flame.ts b/benchmarks/memory/server/scenarios/aborted-requests/react/memory.flame.ts deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/react/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runServerFlameBenchmark } from '#memory-server/flame-runner' -import { workloadGroup } from './setup.ts' - -await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/react/project.json b/benchmarks/memory/server/scenarios/aborted-requests/react/project.json deleted file mode 100644 index bea90c8766..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/react/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-server-aborted-requests-react", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "build:ssr:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:ssr:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/react/setup.ts b/benchmarks/memory/server/scenarios/aborted-requests/react/setup.ts deleted file mode 100644 index 0c98f54ddd..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/react/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' -import { createWorkloadGroup } from '../shared.ts' -import type { StartRequestHandler } from '../shared.ts' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} - -export const workloadGroup: ServerMemoryWorkloadGroup = - await createWorkloadGroup('react', handler) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/react/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/aborted-requests/react/src/routeTree.gen.ts deleted file mode 100644 index fbbc25ecfb..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/react/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as StreamIdRouteImport } from './routes/stream.$id' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const StreamIdRoute = StreamIdRouteImport.update({ - id: '/stream/$id', - path: '/stream/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/stream/$id': typeof StreamIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/stream/$id': typeof StreamIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/stream/$id': typeof StreamIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/stream/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/stream/$id' - id: '__root__' | '/' | '/stream/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - StreamIdRoute: typeof StreamIdRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/stream/$id': { - id: '/stream/$id' - path: '/stream/$id' - fullPath: '/stream/$id' - preLoaderRoute: typeof StreamIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - StreamIdRoute: StreamIdRoute, -} -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/benchmarks/memory/server/scenarios/aborted-requests/react/src/router.tsx b/benchmarks/memory/server/scenarios/aborted-requests/react/src/router.tsx deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/react/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/aborted-requests/react/src/routes/__root.tsx deleted file mode 100644 index c5f9de6922..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/react/src/routes/__root.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' - -export const Route = createRootRoute({ - head: () => ({ - meta: [{ charSet: 'utf-8' }], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/react/src/routes/index.tsx b/benchmarks/memory/server/scenarios/aborted-requests/react/src/routes/index.tsx deleted file mode 100644 index 08d534a779..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/react/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
aborted-requests-index
-} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/react/src/routes/stream.$id.tsx b/benchmarks/memory/server/scenarios/aborted-requests/react/src/routes/stream.$id.tsx deleted file mode 100644 index ecd9ef524d..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/react/src/routes/stream.$id.tsx +++ /dev/null @@ -1,66 +0,0 @@ -import { Await, createFileRoute } from '@tanstack/react-router' -import { Suspense } from 'react' -import { makeAbortedRequestRecords } from '../../../deferred-records' - -function resolveAfterMicrotasks(microtasks: number, value: () => T) { - let promise = Promise.resolve() - - for (let index = 0; index < microtasks; index++) { - promise = promise.then(() => undefined) - } - - return promise.then(value) -} - -export const Route = createFileRoute('/stream/$id')({ - loader: ({ params }) => ({ - eager: `eager-${params.id}`, - alpha: resolveAfterMicrotasks(32, () => - makeAbortedRequestRecords(params.id, 'alpha'), - ), - beta: resolveAfterMicrotasks(64, () => - makeAbortedRequestRecords(params.id, 'beta'), - ), - }), - component: StreamComponent, -}) - -function StreamComponent() { - const data = Route.useLoaderData() - - return ( -
-

{data.eager}

- loading-alpha

- } - > - - {(records) => ( -
    - {records.map((record) => ( -
  • {record.label}
  • - ))} -
- )} -
-
- loading-beta

- } - > - - {(records) => ( -
    - {records.map((record) => ( -
  • {record.label}
  • - ))} -
- )} -
-
-
- ) -} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/react/tsconfig.json b/benchmarks/memory/server/scenarios/aborted-requests/react/tsconfig.json deleted file mode 100644 index 11ddcce4ea..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/react/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "allowImportingTsExtensions": true, - "jsx": "react-jsx", - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/react/vite.config.ts b/benchmarks/memory/server/scenarios/aborted-requests/react/vite.config.ts deleted file mode 100644 index eff0d0e043..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/react/vite.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - ...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 deleted file mode 100644 index 29eca99e00..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/shared.ts +++ /dev/null @@ -1,235 +0,0 @@ -import { settle } from '#memory-server/bench-utils' -import type { StartRequestHandler } from '#memory-server/bench-utils' - -export type { StartRequestHandler } - -type Framework = 'react' | 'solid' | 'vue' - -type AbortedRequestReadMode = 'first-chunk' | 'shell-before-deferred' -const abortedRequestIterations = 40 -let abortedRequestCounter = 0 -const eagerMarker = 'data-bench="aborted-requests-eager"' -const alphaFallbackMarker = 'data-bench="aborted-requests-alpha-fallback"' -const betaFallbackMarker = 'data-bench="aborted-requests-beta-fallback"' -const alphaFirstRecord = (id: string) => `deferred-alpha-${id}-0` -const alphaLastRecord = (id: string) => `deferred-alpha-${id}-19` -const betaFirstRecord = (id: string) => `deferred-beta-${id}-0` -const betaLastRecord = (id: string) => `deferred-beta-${id}-19` - -const textDecoder = new TextDecoder() -const abortedRequestModes: Record = { - react: 'first-chunk', - solid: 'first-chunk', - vue: 'shell-before-deferred', -} - -const documentRequestInit = { - method: 'GET', - headers: { - accept: 'text/html', - }, -} satisfies RequestInit - -function buildStreamRequest(id: string, signal?: AbortSignal) { - const init: RequestInit = { ...documentRequestInit } - - if (signal) { - init.signal = signal - } - - return new Request(`http://localhost/stream/${id}`, init) -} - -function validateDocumentResponse(response: Response, request: Request) { - if (response.status !== 200) { - throw new Error( - `Expected status 200 for ${request.url}, got ${response.status}`, - ) - } -} - -async function readFirstChunk(response: Response, request: Request) { - if (!response.body) { - throw new Error(`Expected response body for ${request.url}`) - } - - const reader = response.body.getReader() - const result = await reader.read() - const value = result.value - - if (result.done || !value || value.byteLength === 0) { - await reader.cancel() - throw new Error(`Expected a non-empty first chunk for ${request.url}`) - } - - return { - reader, - value, - } -} - -async function readShellBeforeDeferred( - response: Response, - request: Request, - id: string, -) { - if (!response.body) { - throw new Error(`Expected response body for ${request.url}`) - } - - const reader = response.body.getReader() - let text = '' - - for (;;) { - const result = await reader.read() - const value = result.value - - if (result.done || !value || value.byteLength === 0) { - await reader.cancel() - throw new Error(`Expected shell content for ${request.url}`) - } - - text += textDecoder.decode(value, { stream: true }) - - for (const marker of [ - alphaFirstRecord(id), - alphaLastRecord(id), - betaFirstRecord(id), - betaLastRecord(id), - ]) { - if (text.includes(marker)) { - await reader.cancel() - throw new Error( - `Shell chunks already included deferred content ${marker}`, - ) - } - } - - if ( - text.includes(eagerMarker) && - text.includes(alphaFallbackMarker) && - text.includes(betaFallbackMarker) - ) { - return { - reader, - text, - } - } - } -} - -async function readSanityStream( - response: Response, - request: Request, - mode: AbortedRequestReadMode, - id: string, -) { - if (mode === 'shell-before-deferred') { - return readShellBeforeDeferred(response, request, id) - } - - const { reader, value } = await readFirstChunk(response, request) - - return { - reader, - text: textDecoder.decode(value), - } -} - -function readLoopStream( - mode: AbortedRequestReadMode, - response: Response, - request: Request, - id: string, -) { - if (mode === 'shell-before-deferred') { - return readShellBeforeDeferred(response, request, id) - } - - return readFirstChunk(response, request) -} - -async function cancelReader(reader: ReadableStreamDefaultReader) { - try { - await reader.cancel() - } catch (error) { - if (!(error instanceof DOMException && error.name === 'AbortError')) { - throw error - } - } -} - -async function assertAbortedRequestsSanity( - handler: StartRequestHandler, - mode: AbortedRequestReadMode, -) { - const fullId = 'sanity-full' - const fullRequest = buildStreamRequest(fullId) - const fullResponse = await handler.fetch(fullRequest) - validateDocumentResponse(fullResponse, fullRequest) - - const fullBody = await fullResponse.text() - - if (!fullBody.includes(eagerMarker)) { - throw new Error('Expected full sanity response to include the eager marker') - } - - const midStreamId = 'sanity-mid-stream' - const controller = new AbortController() - const midStreamRequest = buildStreamRequest(midStreamId, controller.signal) - const midStreamResponse = await handler.fetch(midStreamRequest) - validateDocumentResponse(midStreamResponse, midStreamRequest) - - const { reader, text } = await readSanityStream( - midStreamResponse, - midStreamRequest, - mode, - midStreamId, - ) - - if (!text.includes(eagerMarker)) { - throw new Error('Expected sanity stream to include the eager marker') - } - - // reader.cancel() is the response-stream cancellation path if the handler - // does not observe Request.signal for this in-process request. - controller.abort() - await cancelReader(reader) - await settle() -} - -async function runAbortedRequestLoop( - handler: StartRequestHandler, - mode: AbortedRequestReadMode, -) { - for (let index = 0; index < abortedRequestIterations; index++) { - const controller = new AbortController() - const id = `abort-${(abortedRequestCounter++).toString(36)}` - const request = buildStreamRequest(id, controller.signal) - const response = await handler.fetch(request) - validateDocumentResponse(response, request) - - const { reader } = await readLoopStream(mode, response, request, id) - controller.abort() - await cancelReader(reader) - await settle() - } -} - -export function createWorkloadGroup( - framework: Framework, - handler: StartRequestHandler, -) { - const mode = abortedRequestModes[framework] - const run = async () => runAbortedRequestLoop(handler, mode) - - return { - sanity: () => assertAbortedRequestsSanity(handler, mode), - workloads: [ - { - name: `mem server aborted-requests (${framework})`, - run, - }, - ], - } -} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/solid/memory.bench.ts b/benchmarks/memory/server/scenarios/aborted-requests/solid/memory.bench.ts deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' -import { workloadGroup } from './setup' - -await workloadGroup.sanity() - -test('memory', async ({ bench }) => { - for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) - } -}) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/solid/memory.flame.ts b/benchmarks/memory/server/scenarios/aborted-requests/solid/memory.flame.ts deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runServerFlameBenchmark } from '#memory-server/flame-runner' -import { workloadGroup } from './setup.ts' - -await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/solid/project.json b/benchmarks/memory/server/scenarios/aborted-requests/solid/project.json deleted file mode 100644 index 345fcc0720..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-server-aborted-requests-solid", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "build:ssr:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:ssr:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/solid/setup.ts b/benchmarks/memory/server/scenarios/aborted-requests/solid/setup.ts deleted file mode 100644 index 4fe85c3f00..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' -import { createWorkloadGroup } from '../shared.ts' -import type { StartRequestHandler } from '../shared.ts' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} - -export const workloadGroup: ServerMemoryWorkloadGroup = - await createWorkloadGroup('solid', handler) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routeTree.gen.ts deleted file mode 100644 index 04ebed80f0..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as StreamIdRouteImport } from './routes/stream.$id' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const StreamIdRoute = StreamIdRouteImport.update({ - id: '/stream/$id', - path: '/stream/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/stream/$id': typeof StreamIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/stream/$id': typeof StreamIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/stream/$id': typeof StreamIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/stream/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/stream/$id' - id: '__root__' | '/' | '/stream/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - StreamIdRoute: typeof StreamIdRoute -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/stream/$id': { - id: '/stream/$id' - path: '/stream/$id' - fullPath: '/stream/$id' - preLoaderRoute: typeof StreamIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - StreamIdRoute: StreamIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/solid-start' -declare module '@tanstack/solid-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/solid/src/router.tsx b/benchmarks/memory/server/scenarios/aborted-requests/solid/src/router.tsx deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routes/__root.tsx deleted file mode 100644 index aaf7dfdd89..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/solid-router' -import { HydrationScript } from 'solid-js/web' - -export const Route = createRootRoute({ - head: () => ({ - meta: [{ charset: 'utf-8' }], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - - ) -} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routes/index.tsx b/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routes/index.tsx deleted file mode 100644 index 3aac56e824..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
aborted-requests-index
-} 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 deleted file mode 100644 index bf6af17f31..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routes/stream.$id.tsx +++ /dev/null @@ -1,69 +0,0 @@ -import { createServerOnlyFn } from '@tanstack/solid-start' -import { getRequest } from '@tanstack/solid-start/server' -import { createFileRoute } from '@tanstack/solid-router' -import { Show, Suspense, createResource } from 'solid-js' -import { makeDeferredRecords } from '../../../deferred-records' -import type { DeferredRecord } from '../../../deferred-records' - -const getRequestSignal = createServerOnlyFn(() => getRequest().signal) - -export const Route = createFileRoute('/stream/$id')({ - loader: ({ params }) => ({ - eager: `eager-${params.id}`, - alpha: makeDeferredRecords(params.id, 'alpha', getRequestSignal()), - beta: makeDeferredRecords(params.id, 'beta', getRequestSignal()), - }), - component: StreamComponent, -}) - -function StreamComponent() { - const data = Route.useLoaderData() - - return ( -
-

{data().eager}

- loading-alpha

- } - > - -
- loading-beta

- } - > - -
-
- ) -} - -function DeferredRecords(props: { - promise: Promise> - dataBench: string -}) { - const [records] = createResource( - () => props.promise, - (promise) => promise, - ) - - return ( - - {(resolvedRecords) => ( -
    - {resolvedRecords().map((record) => ( -
  • {record.label}
  • - ))} -
- )} -
- ) -} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/solid/tsconfig.json b/benchmarks/memory/server/scenarios/aborted-requests/solid/tsconfig.json deleted file mode 100644 index 4b61264e11..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "allowImportingTsExtensions": true, - "jsx": "preserve", - "jsxImportSource": "solid-js", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/solid/vite.config.ts b/benchmarks/memory/server/scenarios/aborted-requests/solid/vite.config.ts deleted file mode 100644 index d7fd3459ee..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/vite.config.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - solid({ ssr: true, hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - ...memoryConfig('server'), - name: '@benchmarks/memory-server aborted-requests (solid)', - watch: false, - environment: 'node', - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/vue/memory.bench.ts b/benchmarks/memory/server/scenarios/aborted-requests/vue/memory.bench.ts deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' -import { workloadGroup } from './setup' - -await workloadGroup.sanity() - -test('memory', async ({ bench }) => { - for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) - } -}) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/vue/memory.flame.ts b/benchmarks/memory/server/scenarios/aborted-requests/vue/memory.flame.ts deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runServerFlameBenchmark } from '#memory-server/flame-runner' -import { workloadGroup } from './setup.ts' - -await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/vue/project.json b/benchmarks/memory/server/scenarios/aborted-requests/vue/project.json deleted file mode 100644 index 8ca7d84660..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-server-aborted-requests-vue", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "build:ssr:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:ssr:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/vue/setup.ts b/benchmarks/memory/server/scenarios/aborted-requests/vue/setup.ts deleted file mode 100644 index 6683dafe6b..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' -import { createWorkloadGroup } from '../shared.ts' -import type { StartRequestHandler } from '../shared.ts' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} - -export const workloadGroup: ServerMemoryWorkloadGroup = - await createWorkloadGroup('vue', handler) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routeTree.gen.ts deleted file mode 100644 index 192f1d6dc7..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as StreamIdRouteImport } from './routes/stream.$id' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const StreamIdRoute = StreamIdRouteImport.update({ - id: '/stream/$id', - path: '/stream/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/stream/$id': typeof StreamIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/stream/$id': typeof StreamIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/stream/$id': typeof StreamIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/stream/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/stream/$id' - id: '__root__' | '/' | '/stream/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - StreamIdRoute: typeof StreamIdRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/stream/$id': { - id: '/stream/$id' - path: '/stream/$id' - fullPath: '/stream/$id' - preLoaderRoute: typeof StreamIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - StreamIdRoute: StreamIdRoute, -} -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/benchmarks/memory/server/scenarios/aborted-requests/vue/src/router.tsx b/benchmarks/memory/server/scenarios/aborted-requests/vue/src/router.tsx deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routes/__root.tsx deleted file mode 100644 index de29ee1612..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { - Body, - HeadContent, - Html, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/vue-router' - -export const Route = createRootRoute({ - head: () => ({ - meta: [{ charSet: 'utf-8' }], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routes/index.tsx b/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routes/index.tsx deleted file mode 100644 index af662b29f7..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
aborted-requests-index
-} 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 deleted file mode 100644 index e41af03c16..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routes/stream.$id.tsx +++ /dev/null @@ -1,65 +0,0 @@ -import { createServerOnlyFn } from '@tanstack/vue-start' -import { getRequest } from '@tanstack/vue-start/server' -import { Await, createFileRoute } from '@tanstack/vue-router' -import { Suspense, defineComponent } from 'vue' -import { makeDeferredRecords } from '../../../deferred-records' -import type { DeferredRecord } from '../../../deferred-records' - -const getRequestSignal = createServerOnlyFn(() => getRequest().signal) - -const StreamComponent = defineComponent({ - setup() { - 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, - }} -
-
- ) - }, -}) - -export const Route = createFileRoute('/stream/$id')({ - loader: ({ params }) => ({ - eager: `eager-${params.id}`, - alpha: makeDeferredRecords(params.id, 'alpha', getRequestSignal()), - beta: makeDeferredRecords(params.id, 'beta', getRequestSignal()), - }), - component: StreamComponent, -}) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/vue/tsconfig.json b/benchmarks/memory/server/scenarios/aborted-requests/vue/tsconfig.json deleted file mode 100644 index 9ad6481342..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "allowImportingTsExtensions": true, - "jsx": "preserve", - "jsxImportSource": "vue", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/vue/vite.config.ts b/benchmarks/memory/server/scenarios/aborted-requests/vue/vite.config.ts deleted file mode 100644 index e4e1eb66d4..0000000000 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/vite.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - ...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 deleted file mode 100644 index a6f07b97be..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' -import { workloadGroup } from './setup' - -await workloadGroup.sanity() - -const workload = workloadGroup.workloads[0]! - -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) -}) 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 deleted file mode 100644 index 89071137c3..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/memory.error.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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.flame.ts b/benchmarks/memory/server/scenarios/error-paths/react/memory.flame.ts deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runServerFlameBenchmark } from '#memory-server/flame-runner' -import { workloadGroup } from './setup.ts' - -await runServerFlameBenchmark(workloadGroup) 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 deleted file mode 100644 index fa6a6693ed..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/memory.not-found.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index b2c3d24200..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/memory.unmatched.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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/project.json b/benchmarks/memory/server/scenarios/error-paths/react/project.json deleted file mode 100644 index 6a399fe41e..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-server-error-paths-react", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "build:ssr:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:ssr:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/memory/server/scenarios/error-paths/react/setup.ts b/benchmarks/memory/server/scenarios/error-paths/react/setup.ts deleted file mode 100644 index 0c98f54ddd..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' -import { createWorkloadGroup } from '../shared.ts' -import type { StartRequestHandler } from '../shared.ts' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} - -export const workloadGroup: ServerMemoryWorkloadGroup = - await createWorkloadGroup('react', handler) diff --git a/benchmarks/memory/server/scenarios/error-paths/react/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/error-paths/react/src/routeTree.gen.ts deleted file mode 100644 index 4e8e4ce0e4..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/src/routeTree.gen.ts +++ /dev/null @@ -1,146 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as BoomIdRouteImport } from './routes/boom.$id' -import { Route as FromIdRouteImport } from './routes/from.$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 BoomIdRoute = BoomIdRouteImport.update({ - id: '/boom/$id', - path: '/boom/$id', - getParentRoute: () => rootRouteImport, -} as any) -const FromIdRoute = FromIdRouteImport.update({ - id: '/from/$id', - path: '/from/$id', - getParentRoute: () => rootRouteImport, -} as any) -const 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) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/boom/$id': typeof BoomIdRoute - '/from/$id': typeof FromIdRoute - '/missing/$id': typeof MissingIdRoute - '/target/$id': typeof TargetIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/boom/$id': typeof BoomIdRoute - '/from/$id': typeof FromIdRoute - '/missing/$id': typeof MissingIdRoute - '/target/$id': typeof TargetIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/boom/$id': typeof BoomIdRoute - '/from/$id': typeof FromIdRoute - '/missing/$id': typeof MissingIdRoute - '/target/$id': typeof TargetIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/boom/$id' | '/from/$id' | '/missing/$id' | '/target/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/boom/$id' | '/from/$id' | '/missing/$id' | '/target/$id' - id: - | '__root__' - | '/' - | '/boom/$id' - | '/from/$id' - | '/missing/$id' - | '/target/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - BoomIdRoute: typeof BoomIdRoute - FromIdRoute: typeof FromIdRoute - MissingIdRoute: typeof MissingIdRoute - TargetIdRoute: typeof TargetIdRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/boom/$id': { - id: '/boom/$id' - path: '/boom/$id' - fullPath: '/boom/$id' - preLoaderRoute: typeof BoomIdRouteImport - parentRoute: typeof rootRouteImport - } - '/from/$id': { - id: '/from/$id' - path: '/from/$id' - fullPath: '/from/$id' - preLoaderRoute: typeof FromIdRouteImport - parentRoute: typeof rootRouteImport - } - '/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 - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - BoomIdRoute: BoomIdRoute, - FromIdRoute: FromIdRoute, - MissingIdRoute: MissingIdRoute, - TargetIdRoute: TargetIdRoute, -} -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/benchmarks/memory/server/scenarios/error-paths/react/src/router.tsx b/benchmarks/memory/server/scenarios/error-paths/react/src/router.tsx deleted file mode 100644 index e31bd0abf7..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/src/router.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - defaultNotFoundComponent: DefaultNotFound, - }) -} - -// Without this, every unmatched-URL request logs a router warning in -// non-production ad-hoc runs. -function DefaultNotFound() { - return

error-paths-unmatched

-} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/server/scenarios/error-paths/react/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/error-paths/react/src/routes/__root.tsx deleted file mode 100644 index c5f9de6922..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/src/routes/__root.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' - -export const Route = createRootRoute({ - head: () => ({ - meta: [{ charSet: 'utf-8' }], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/memory/server/scenarios/error-paths/react/src/routes/boom.$id.tsx b/benchmarks/memory/server/scenarios/error-paths/react/src/routes/boom.$id.tsx deleted file mode 100644 index fafa81a9bb..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/src/routes/boom.$id.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/boom/$id')({ - loader: ({ params }) => { - throw new Error(`boom-${params.id}`) - }, - errorComponent: BoomErrorComponent, - component: BoomComponent, -}) - -function BoomErrorComponent() { - return
error-paths-error-boundary
-} - -function BoomComponent() { - return null -} diff --git a/benchmarks/memory/server/scenarios/error-paths/react/src/routes/from.$id.tsx b/benchmarks/memory/server/scenarios/error-paths/react/src/routes/from.$id.tsx deleted file mode 100644 index 4c45e76c92..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/src/routes/from.$id.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute, redirect } from '@tanstack/react-router' - -export const Route = createFileRoute('/from/$id')({ - loader: ({ params }) => { - const { id } = params - - throw redirect({ to: '/target/$id', params: { id }, statusCode: 302 }) - }, - component: FromComponent, -}) - -function FromComponent() { - return null -} diff --git a/benchmarks/memory/server/scenarios/error-paths/react/src/routes/index.tsx b/benchmarks/memory/server/scenarios/error-paths/react/src/routes/index.tsx deleted file mode 100644 index c5492486b4..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
error-paths-index
-} diff --git a/benchmarks/memory/server/scenarios/error-paths/react/src/routes/missing.$id.tsx b/benchmarks/memory/server/scenarios/error-paths/react/src/routes/missing.$id.tsx deleted file mode 100644 index 84640e9712..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/src/routes/missing.$id.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import { createFileRoute, notFound } from '@tanstack/react-router' - -export const Route = createFileRoute('/missing/$id')({ - loader: () => { - throw notFound() - }, - notFoundComponent: MissingNotFoundComponent, - component: MissingComponent, -}) - -function MissingNotFoundComponent() { - return ( -
error-paths-not-found-boundary
- ) -} - -function MissingComponent() { - return null -} diff --git a/benchmarks/memory/server/scenarios/error-paths/react/src/routes/target.$id.tsx b/benchmarks/memory/server/scenarios/error-paths/react/src/routes/target.$id.tsx deleted file mode 100644 index 1c13394cb2..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/src/routes/target.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/target/$id')({ - component: TargetComponent, -}) - -function TargetComponent() { - const params = Route.useParams() - - return
{`target-${params.id}`}
-} diff --git a/benchmarks/memory/server/scenarios/error-paths/react/tsconfig.json b/benchmarks/memory/server/scenarios/error-paths/react/tsconfig.json deleted file mode 100644 index 2dba47fc99..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "allowImportingTsExtensions": true, - "jsx": "react-jsx", - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "memory*.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/memory/server/scenarios/error-paths/react/vite.config.ts b/benchmarks/memory/server/scenarios/error-paths/react/vite.config.ts deleted file mode 100644 index c00de7727a..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/react/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - 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 deleted file mode 100644 index 11ed293d22..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/shared.ts +++ /dev/null @@ -1,192 +0,0 @@ -import { - createDeterministicRandom, - randomSegment, - runSequentialRequestLoop, -} from '#memory-server/bench-utils' -import type { StartRequestHandler } from '#memory-server/bench-utils' - -export type { StartRequestHandler } - -type Framework = 'react' | 'solid' | 'vue' - -const errorPathsIterations = 18 -const redirectSeed = 0xdecafbad -const notFoundSeed = 0xdecafb0d -const errorSeed = 0xdecafbed -const unmatchedSeed = 0xdecaf00d -const redirectStatus = 302 -const notFoundStatus = 404 -const errorStatus = 500 -// Module-level so each error-path bench keeps advancing across runner invocations. -const redirectRandom = createDeterministicRandom(redirectSeed) -const notFoundRandom = createDeterministicRandom(notFoundSeed) -const errorRandom = createDeterministicRandom(errorSeed) -const unmatchedRandom = createDeterministicRandom(unmatchedSeed) -let redirectCounter = 0 -let notFoundCounter = 0 -let errorCounter = 0 -let unmatchedCounter = 0 - -const requestInit = { - method: 'GET', - headers: { - accept: 'text/html', - }, -} satisfies RequestInit - -function buildRedirectRequest(random: () => number) { - const id = `${(redirectCounter++).toString(36)}-${randomSegment(random)}` - - return new Request(`http://localhost/from/${id}`, requestInit) -} - -function buildNotFoundRequest(random: () => number) { - const id = `${(notFoundCounter++).toString(36)}-${randomSegment(random)}` - - return new Request(`http://localhost/missing/${id}`, requestInit) -} - -function buildErrorRequest(random: () => number) { - const id = `${(errorCounter++).toString(36)}-${randomSegment(random)}` - - return new Request(`http://localhost/boom/${id}`, requestInit) -} - -function buildUnmatchedRequest(random: () => number) { - const id = `${(unmatchedCounter++).toString(36)}-${randomSegment(random)}` - - return new Request(`http://localhost/nope/${id}`, requestInit) -} - -function getRequestId(request: Request) { - const id = new URL(request.url).pathname.split('/').pop() - - if (!id) { - throw new Error(`Expected request id in ${request.url}`) - } - - return id -} - -function validateRedirectResponse(response: Response, request: Request) { - if (response.status !== redirectStatus) { - throw new Error( - `Expected status ${redirectStatus} for ${request.url}, got ${response.status}`, - ) - } - - const id = getRequestId(request) - const location = response.headers.get('location') - - if (location !== `/target/${id}`) { - throw new Error(`Expected redirect location /target/${id}, got ${location}`) - } -} - -function validateNotFoundResponse(response: Response, request: Request) { - if (response.status !== notFoundStatus) { - throw new Error( - `Expected status ${notFoundStatus} for ${request.url}, got ${response.status}`, - ) - } -} - -function validateErrorResponse(response: Response, request: Request) { - if (response.status !== errorStatus) { - throw new Error( - `Expected status ${errorStatus} for ${request.url}, got ${response.status}`, - ) - } -} - -async function assertStatusSanity( - handler: StartRequestHandler, - request: Request, - validateResponse: (response: Response, request: Request) => void, -) { - const response = await handler.fetch(request) - validateResponse(response, request) - await response.text() -} - -async function assertErrorPathsSanity(handler: StartRequestHandler) { - await assertStatusSanity( - handler, - new Request('http://localhost/from/sanity-redirect', requestInit), - validateRedirectResponse, - ) - await assertStatusSanity( - handler, - new Request('http://localhost/missing/sanity-missing', requestInit), - validateNotFoundResponse, - ) - await assertStatusSanity( - handler, - new Request('http://localhost/boom/sanity-error', requestInit), - validateErrorResponse, - ) - await assertStatusSanity( - handler, - new Request('http://localhost/nope/sanity-unmatched', requestInit), - validateNotFoundResponse, - ) -} - -export function createWorkloadGroup( - framework: Framework, - handler: StartRequestHandler, -) { - const runRedirect = async () => - runSequentialRequestLoop(handler, { - random: redirectRandom, - iterations: errorPathsIterations, - buildRequest: buildRedirectRequest, - validateResponse: validateRedirectResponse, - }) - - const runNotFound = async () => - runSequentialRequestLoop(handler, { - random: notFoundRandom, - iterations: errorPathsIterations, - buildRequest: buildNotFoundRequest, - validateResponse: validateNotFoundResponse, - }) - - const runError = async () => - runSequentialRequestLoop(handler, { - random: errorRandom, - iterations: errorPathsIterations, - buildRequest: buildErrorRequest, - validateResponse: validateErrorResponse, - }) - - const runUnmatched = async () => - runSequentialRequestLoop(handler, { - random: unmatchedRandom, - iterations: errorPathsIterations, - buildRequest: buildUnmatchedRequest, - validateResponse: validateNotFoundResponse, - }) - - return { - sanity: () => assertErrorPathsSanity(handler), - workloads: [ - { - name: `mem server error-paths redirect (${framework})`, - run: runRedirect, - }, - { - name: `mem server error-paths not-found (${framework})`, - run: runNotFound, - }, - { - name: `mem server error-paths error (${framework})`, - run: runError, - }, - { - name: `mem server error-paths unmatched (${framework})`, - run: runUnmatched, - }, - ], - } -} diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/memory.bench.ts b/benchmarks/memory/server/scenarios/error-paths/solid/memory.bench.ts deleted file mode 100644 index a6f07b97be..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' -import { workloadGroup } from './setup' - -await workloadGroup.sanity() - -const workload = workloadGroup.workloads[0]! - -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) -}) 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 deleted file mode 100644 index 89071137c3..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/memory.error.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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.flame.ts b/benchmarks/memory/server/scenarios/error-paths/solid/memory.flame.ts deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runServerFlameBenchmark } from '#memory-server/flame-runner' -import { workloadGroup } from './setup.ts' - -await runServerFlameBenchmark(workloadGroup) 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 deleted file mode 100644 index fa6a6693ed..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/memory.not-found.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index b2c3d24200..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/memory.unmatched.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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/project.json b/benchmarks/memory/server/scenarios/error-paths/solid/project.json deleted file mode 100644 index 77fcfaf578..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-server-error-paths-solid", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "build:ssr:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:ssr:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/setup.ts b/benchmarks/memory/server/scenarios/error-paths/solid/setup.ts deleted file mode 100644 index 4fe85c3f00..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' -import { createWorkloadGroup } from '../shared.ts' -import type { StartRequestHandler } from '../shared.ts' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} - -export const workloadGroup: ServerMemoryWorkloadGroup = - await createWorkloadGroup('solid', handler) diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/error-paths/solid/src/routeTree.gen.ts deleted file mode 100644 index 32a4d56d3a..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,146 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as TargetIdRouteImport } from './routes/target.$id' -import { Route as MissingIdRouteImport } from './routes/missing.$id' -import { Route as FromIdRouteImport } from './routes/from.$id' -import { Route as BoomIdRouteImport } from './routes/boom.$id' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const 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 FromIdRoute = FromIdRouteImport.update({ - id: '/from/$id', - path: '/from/$id', - getParentRoute: () => rootRouteImport, -} as any) -const BoomIdRoute = BoomIdRouteImport.update({ - id: '/boom/$id', - path: '/boom/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/boom/$id': typeof BoomIdRoute - '/from/$id': typeof FromIdRoute - '/missing/$id': typeof MissingIdRoute - '/target/$id': typeof TargetIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/boom/$id': typeof BoomIdRoute - '/from/$id': typeof FromIdRoute - '/missing/$id': typeof MissingIdRoute - '/target/$id': typeof TargetIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/boom/$id': typeof BoomIdRoute - '/from/$id': typeof FromIdRoute - '/missing/$id': typeof MissingIdRoute - '/target/$id': typeof TargetIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/boom/$id' | '/from/$id' | '/missing/$id' | '/target/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/boom/$id' | '/from/$id' | '/missing/$id' | '/target/$id' - id: - | '__root__' - | '/' - | '/boom/$id' - | '/from/$id' - | '/missing/$id' - | '/target/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - BoomIdRoute: typeof BoomIdRoute - FromIdRoute: typeof FromIdRoute - MissingIdRoute: typeof MissingIdRoute - TargetIdRoute: typeof TargetIdRoute -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - 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 - } - '/from/$id': { - id: '/from/$id' - path: '/from/$id' - fullPath: '/from/$id' - preLoaderRoute: typeof FromIdRouteImport - parentRoute: typeof rootRouteImport - } - '/boom/$id': { - id: '/boom/$id' - path: '/boom/$id' - fullPath: '/boom/$id' - preLoaderRoute: typeof BoomIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - BoomIdRoute: BoomIdRoute, - FromIdRoute: FromIdRoute, - MissingIdRoute: MissingIdRoute, - TargetIdRoute: TargetIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/solid-start' -declare module '@tanstack/solid-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/src/router.tsx b/benchmarks/memory/server/scenarios/error-paths/solid/src/router.tsx deleted file mode 100644 index ae51f8b5e9..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/src/router.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import { createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - defaultNotFoundComponent: DefaultNotFound, - }) -} - -// Without this, every unmatched-URL request logs a router warning in -// non-production ad-hoc runs. -function DefaultNotFound() { - return

error-paths-unmatched

-} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/__root.tsx deleted file mode 100644 index aaf7dfdd89..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/solid-router' -import { HydrationScript } from 'solid-js/web' - -export const Route = createRootRoute({ - head: () => ({ - meta: [{ charset: 'utf-8' }], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - - ) -} diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/boom.$id.tsx b/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/boom.$id.tsx deleted file mode 100644 index bebc638caa..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/boom.$id.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/boom/$id')({ - loader: ({ params }) => { - throw new Error(`boom-${params.id}`) - }, - errorComponent: BoomErrorComponent, - component: BoomComponent, -}) - -function BoomErrorComponent() { - return
error-paths-error-boundary
-} - -function BoomComponent() { - return null -} diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/from.$id.tsx b/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/from.$id.tsx deleted file mode 100644 index e96b7864f2..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/from.$id.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute, redirect } from '@tanstack/solid-router' - -export const Route = createFileRoute('/from/$id')({ - loader: ({ params }) => { - const { id } = params - - throw redirect({ to: '/target/$id', params: { id }, statusCode: 302 }) - }, - component: FromComponent, -}) - -function FromComponent() { - return null -} diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/index.tsx b/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/index.tsx deleted file mode 100644 index 43282af801..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
error-paths-index
-} diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/missing.$id.tsx b/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/missing.$id.tsx deleted file mode 100644 index 1b9ec5e29d..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/missing.$id.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import { createFileRoute, notFound } from '@tanstack/solid-router' - -export const Route = createFileRoute('/missing/$id')({ - loader: () => { - throw notFound() - }, - notFoundComponent: MissingNotFoundComponent, - component: MissingComponent, -}) - -function MissingNotFoundComponent() { - return ( -
error-paths-not-found-boundary
- ) -} - -function MissingComponent() { - return null -} diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/target.$id.tsx b/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/target.$id.tsx deleted file mode 100644 index 4196fc1183..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/target.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/target/$id')({ - component: TargetComponent, -}) - -function TargetComponent() { - const params = Route.useParams() - - return
{`target-${params().id}`}
-} diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/tsconfig.json b/benchmarks/memory/server/scenarios/error-paths/solid/tsconfig.json deleted file mode 100644 index 1e8103127a..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "allowImportingTsExtensions": true, - "jsx": "preserve", - "jsxImportSource": "solid-js", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "memory*.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/vite.config.ts b/benchmarks/memory/server/scenarios/error-paths/solid/vite.config.ts deleted file mode 100644 index d7a0bb51b0..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/solid/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - solid({ ssr: true, hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - isolate: true, - ...memoryConfig('server'), - name: '@benchmarks/memory-server error-paths (solid)', - watch: false, - environment: 'node', - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/memory.bench.ts b/benchmarks/memory/server/scenarios/error-paths/vue/memory.bench.ts deleted file mode 100644 index a6f07b97be..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' -import { workloadGroup } from './setup' - -await workloadGroup.sanity() - -const workload = workloadGroup.workloads[0]! - -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) -}) 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 deleted file mode 100644 index 89071137c3..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/memory.error.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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.flame.ts b/benchmarks/memory/server/scenarios/error-paths/vue/memory.flame.ts deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runServerFlameBenchmark } from '#memory-server/flame-runner' -import { workloadGroup } from './setup.ts' - -await runServerFlameBenchmark(workloadGroup) 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 deleted file mode 100644 index fa6a6693ed..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/memory.not-found.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index b2c3d24200..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/memory.unmatched.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -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/project.json b/benchmarks/memory/server/scenarios/error-paths/vue/project.json deleted file mode 100644 index 8472470bde..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-server-error-paths-vue", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "build:ssr:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:ssr:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/setup.ts b/benchmarks/memory/server/scenarios/error-paths/vue/setup.ts deleted file mode 100644 index 6683dafe6b..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' -import { createWorkloadGroup } from '../shared.ts' -import type { StartRequestHandler } from '../shared.ts' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} - -export const workloadGroup: ServerMemoryWorkloadGroup = - await createWorkloadGroup('vue', handler) diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/error-paths/vue/src/routeTree.gen.ts deleted file mode 100644 index ea5bafa386..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,146 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as TargetIdRouteImport } from './routes/target.$id' -import { Route as MissingIdRouteImport } from './routes/missing.$id' -import { Route as FromIdRouteImport } from './routes/from.$id' -import { Route as BoomIdRouteImport } from './routes/boom.$id' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const 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 FromIdRoute = FromIdRouteImport.update({ - id: '/from/$id', - path: '/from/$id', - getParentRoute: () => rootRouteImport, -} as any) -const BoomIdRoute = BoomIdRouteImport.update({ - id: '/boom/$id', - path: '/boom/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/boom/$id': typeof BoomIdRoute - '/from/$id': typeof FromIdRoute - '/missing/$id': typeof MissingIdRoute - '/target/$id': typeof TargetIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/boom/$id': typeof BoomIdRoute - '/from/$id': typeof FromIdRoute - '/missing/$id': typeof MissingIdRoute - '/target/$id': typeof TargetIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/boom/$id': typeof BoomIdRoute - '/from/$id': typeof FromIdRoute - '/missing/$id': typeof MissingIdRoute - '/target/$id': typeof TargetIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/boom/$id' | '/from/$id' | '/missing/$id' | '/target/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/boom/$id' | '/from/$id' | '/missing/$id' | '/target/$id' - id: - | '__root__' - | '/' - | '/boom/$id' - | '/from/$id' - | '/missing/$id' - | '/target/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - BoomIdRoute: typeof BoomIdRoute - FromIdRoute: typeof FromIdRoute - MissingIdRoute: typeof MissingIdRoute - TargetIdRoute: typeof TargetIdRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - 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 - } - '/from/$id': { - id: '/from/$id' - path: '/from/$id' - fullPath: '/from/$id' - preLoaderRoute: typeof FromIdRouteImport - parentRoute: typeof rootRouteImport - } - '/boom/$id': { - id: '/boom/$id' - path: '/boom/$id' - fullPath: '/boom/$id' - preLoaderRoute: typeof BoomIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - BoomIdRoute: BoomIdRoute, - FromIdRoute: FromIdRoute, - MissingIdRoute: MissingIdRoute, - TargetIdRoute: TargetIdRoute, -} -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/benchmarks/memory/server/scenarios/error-paths/vue/src/router.tsx b/benchmarks/memory/server/scenarios/error-paths/vue/src/router.tsx deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/__root.tsx deleted file mode 100644 index de29ee1612..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { - Body, - HeadContent, - Html, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/vue-router' - -export const Route = createRootRoute({ - head: () => ({ - meta: [{ charSet: 'utf-8' }], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/boom.$id.tsx b/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/boom.$id.tsx deleted file mode 100644 index d933b93df2..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/boom.$id.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' - -export const Route = createFileRoute('/boom/$id')({ - loader: ({ params }) => { - throw new Error(`boom-${params.id}`) - }, - errorComponent: BoomErrorComponent, - component: BoomComponent, -}) - -function BoomErrorComponent() { - return
error-paths-error-boundary
-} - -function BoomComponent() { - return <> -} diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/from.$id.tsx b/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/from.$id.tsx deleted file mode 100644 index 6ffba96bce..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/from.$id.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute, redirect } from '@tanstack/vue-router' - -export const Route = createFileRoute('/from/$id')({ - loader: ({ params }) => { - const { id } = params - - throw redirect({ to: '/target/$id', params: { id }, statusCode: 302 }) - }, - component: FromComponent, -}) - -function FromComponent() { - return <> -} diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/index.tsx b/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/index.tsx deleted file mode 100644 index 53fb604c60..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
error-paths-index
-} diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/missing.$id.tsx b/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/missing.$id.tsx deleted file mode 100644 index 0e4972f5c6..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/missing.$id.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import { createFileRoute, notFound } from '@tanstack/vue-router' - -export const Route = createFileRoute('/missing/$id')({ - loader: () => { - throw notFound() - }, - notFoundComponent: MissingNotFoundComponent, - component: MissingComponent, -}) - -function MissingNotFoundComponent() { - return ( -
error-paths-not-found-boundary
- ) -} - -function MissingComponent() { - return <> -} 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 deleted file mode 100644 index 0bbf4a3dc6..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/target.$id.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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, -}) diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/tsconfig.json b/benchmarks/memory/server/scenarios/error-paths/vue/tsconfig.json deleted file mode 100644 index af8b83005c..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "allowImportingTsExtensions": true, - "jsx": "preserve", - "jsxImportSource": "vue", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "memory*.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/vite.config.ts b/benchmarks/memory/server/scenarios/error-paths/vue/vite.config.ts deleted file mode 100644 index 3dc0762aa0..0000000000 --- a/benchmarks/memory/server/scenarios/error-paths/vue/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - 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/large-page-data.ts b/benchmarks/memory/server/scenarios/peak-large-page/large-page-data.ts deleted file mode 100644 index 8f77c58731..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/large-page-data.ts +++ /dev/null @@ -1,111 +0,0 @@ -export interface LargePageRecord { - id: string - name: string - description: string -} - -export interface LargePageLevelData { - level: number - marker: string - records: Array -} - -const recordCount = 200 -const descriptionLength = 104 - -export function makeLargePageLevelData(level: number, seed: number) { - const random = createDeterministicRandom(seed) - - return { - level, - marker: makeLargePageMarker(level), - records: Array.from({ length: recordCount }, (_, index) => { - const idToken = randomSegment(random) - const descriptionTokenA = randomSegment(random) - const descriptionTokenB = randomSegment(random) - - return { - id: `l${level}-${index}-${idToken}`, - name: makeLargePageRecordName(level, index), - description: makeDescription( - level, - index, - descriptionTokenA, - descriptionTokenB, - ), - } - }), - } satisfies LargePageLevelData -} - -export function makeLargePageHead(loaderData: LargePageLevelData | undefined) { - if (!loaderData) { - return { - meta: [{ title: 'Peak Large Page' }], - } - } - - const first = loaderData.records[0]! - const last = loaderData.records[loaderData.records.length - 1]! - - return { - meta: [ - { title: `Peak Large Page L${loaderData.level} ${first.name}` }, - { - name: `peak-large-page-l${loaderData.level}-count`, - content: String(loaderData.records.length), - }, - { - name: `peak-large-page-l${loaderData.level}-first-id`, - content: first.id, - }, - { - name: `peak-large-page-l${loaderData.level}-first-name`, - content: first.name, - }, - { - name: `peak-large-page-l${loaderData.level}-last-id`, - content: last.id, - }, - { - name: `peak-large-page-l${loaderData.level}-description`, - content: first.description, - }, - ], - } -} - -function makeLargePageRecordName(level: number, index: number) { - return `peak-large-page-l${level}-record-${index}` -} - -function makeLargePageMarker(level: number) { - return `peak-large-page-level-${level}` -} - -function makeDescription( - level: number, - index: number, - tokenA: string, - tokenB: string, -) { - return `Level ${level} record ${index} uses seeded fragments ${tokenA} and ${tokenB} to keep a fresh deterministic loader payload.`.padEnd( - descriptionLength, - 'x', - ) -} - -// Local copy of the LCG from benchmarks/memory/server/bench-utils.ts - app -// source cannot import from outside the app root. Keep in sync. -function createDeterministicRandom(seed: number) { - let state = seed >>> 0 - - return () => { - state = (state * 1664525 + 1013904223) >>> 0 - return state / 0x100000000 - } -} - -function randomSegment(random: () => number) { - return Math.floor(random() * 1_000_000_000).toString(36) -} 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 deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' -import { workloadGroup } from './setup' - -await workloadGroup.sanity() - -test('memory', async ({ bench }) => { - for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) - } -}) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/memory.flame.ts b/benchmarks/memory/server/scenarios/peak-large-page/react/memory.flame.ts deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runServerFlameBenchmark } from '#memory-server/flame-runner' -import { workloadGroup } from './setup.ts' - -await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/project.json b/benchmarks/memory/server/scenarios/peak-large-page/react/project.json deleted file mode 100644 index 699a243a03..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-server-peak-large-page-react", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "build:ssr:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:ssr:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/setup.ts b/benchmarks/memory/server/scenarios/peak-large-page/react/setup.ts deleted file mode 100644 index 0c98f54ddd..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' -import { createWorkloadGroup } from '../shared.ts' -import type { StartRequestHandler } from '../shared.ts' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} - -export const workloadGroup: ServerMemoryWorkloadGroup = - await createWorkloadGroup('react', handler) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routeTree.gen.ts deleted file mode 100644 index 6004590f9b..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routeTree.gen.ts +++ /dev/null @@ -1,305 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as L1RouteImport } from './routes/l1' -import { Route as L1L2RouteImport } from './routes/l1.l2' -import { Route as L1L2L3RouteImport } from './routes/l1.l2.l3' -import { Route as L1L2L3L4RouteImport } from './routes/l1.l2.l3.l4' -import { Route as L1L2L3L4L5RouteImport } from './routes/l1.l2.l3.l4.l5' -import { Route as L1L2L3L4L5L6RouteImport } from './routes/l1.l2.l3.l4.l5.l6' -import { Route as L1L2L3L4L5L6L7RouteImport } from './routes/l1.l2.l3.l4.l5.l6.l7' -import { Route as L1L2L3L4L5L6L7L8RouteImport } from './routes/l1.l2.l3.l4.l5.l6.l7.l8' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const L1Route = L1RouteImport.update({ - id: '/l1', - path: '/l1', - getParentRoute: () => rootRouteImport, -} as any) -const L1L2Route = L1L2RouteImport.update({ - id: '/l2', - path: '/l2', - getParentRoute: () => L1Route, -} as any) -const L1L2L3Route = L1L2L3RouteImport.update({ - id: '/l3', - path: '/l3', - getParentRoute: () => L1L2Route, -} as any) -const L1L2L3L4Route = L1L2L3L4RouteImport.update({ - id: '/l4', - path: '/l4', - getParentRoute: () => L1L2L3Route, -} as any) -const L1L2L3L4L5Route = L1L2L3L4L5RouteImport.update({ - id: '/l5', - path: '/l5', - getParentRoute: () => L1L2L3L4Route, -} as any) -const L1L2L3L4L5L6Route = L1L2L3L4L5L6RouteImport.update({ - id: '/l6', - path: '/l6', - getParentRoute: () => L1L2L3L4L5Route, -} as any) -const L1L2L3L4L5L6L7Route = L1L2L3L4L5L6L7RouteImport.update({ - id: '/l7', - path: '/l7', - getParentRoute: () => L1L2L3L4L5L6Route, -} as any) -const L1L2L3L4L5L6L7L8Route = L1L2L3L4L5L6L7L8RouteImport.update({ - id: '/l8', - path: '/l8', - getParentRoute: () => L1L2L3L4L5L6L7Route, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/l1': typeof L1RouteWithChildren - '/l1/l2': typeof L1L2RouteWithChildren - '/l1/l2/l3': typeof L1L2L3RouteWithChildren - '/l1/l2/l3/l4': typeof L1L2L3L4RouteWithChildren - '/l1/l2/l3/l4/l5': typeof L1L2L3L4L5RouteWithChildren - '/l1/l2/l3/l4/l5/l6': typeof L1L2L3L4L5L6RouteWithChildren - '/l1/l2/l3/l4/l5/l6/l7': typeof L1L2L3L4L5L6L7RouteWithChildren - '/l1/l2/l3/l4/l5/l6/l7/l8': typeof L1L2L3L4L5L6L7L8Route -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/l1': typeof L1RouteWithChildren - '/l1/l2': typeof L1L2RouteWithChildren - '/l1/l2/l3': typeof L1L2L3RouteWithChildren - '/l1/l2/l3/l4': typeof L1L2L3L4RouteWithChildren - '/l1/l2/l3/l4/l5': typeof L1L2L3L4L5RouteWithChildren - '/l1/l2/l3/l4/l5/l6': typeof L1L2L3L4L5L6RouteWithChildren - '/l1/l2/l3/l4/l5/l6/l7': typeof L1L2L3L4L5L6L7RouteWithChildren - '/l1/l2/l3/l4/l5/l6/l7/l8': typeof L1L2L3L4L5L6L7L8Route -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/l1': typeof L1RouteWithChildren - '/l1/l2': typeof L1L2RouteWithChildren - '/l1/l2/l3': typeof L1L2L3RouteWithChildren - '/l1/l2/l3/l4': typeof L1L2L3L4RouteWithChildren - '/l1/l2/l3/l4/l5': typeof L1L2L3L4L5RouteWithChildren - '/l1/l2/l3/l4/l5/l6': typeof L1L2L3L4L5L6RouteWithChildren - '/l1/l2/l3/l4/l5/l6/l7': typeof L1L2L3L4L5L6L7RouteWithChildren - '/l1/l2/l3/l4/l5/l6/l7/l8': typeof L1L2L3L4L5L6L7L8Route -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/l1' - | '/l1/l2' - | '/l1/l2/l3' - | '/l1/l2/l3/l4' - | '/l1/l2/l3/l4/l5' - | '/l1/l2/l3/l4/l5/l6' - | '/l1/l2/l3/l4/l5/l6/l7' - | '/l1/l2/l3/l4/l5/l6/l7/l8' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/l1' - | '/l1/l2' - | '/l1/l2/l3' - | '/l1/l2/l3/l4' - | '/l1/l2/l3/l4/l5' - | '/l1/l2/l3/l4/l5/l6' - | '/l1/l2/l3/l4/l5/l6/l7' - | '/l1/l2/l3/l4/l5/l6/l7/l8' - id: - | '__root__' - | '/' - | '/l1' - | '/l1/l2' - | '/l1/l2/l3' - | '/l1/l2/l3/l4' - | '/l1/l2/l3/l4/l5' - | '/l1/l2/l3/l4/l5/l6' - | '/l1/l2/l3/l4/l5/l6/l7' - | '/l1/l2/l3/l4/l5/l6/l7/l8' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - L1Route: typeof L1RouteWithChildren -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/l1': { - id: '/l1' - path: '/l1' - fullPath: '/l1' - preLoaderRoute: typeof L1RouteImport - parentRoute: typeof rootRouteImport - } - '/l1/l2': { - id: '/l1/l2' - path: '/l2' - fullPath: '/l1/l2' - preLoaderRoute: typeof L1L2RouteImport - parentRoute: typeof L1Route - } - '/l1/l2/l3': { - id: '/l1/l2/l3' - path: '/l3' - fullPath: '/l1/l2/l3' - preLoaderRoute: typeof L1L2L3RouteImport - parentRoute: typeof L1L2Route - } - '/l1/l2/l3/l4': { - id: '/l1/l2/l3/l4' - path: '/l4' - fullPath: '/l1/l2/l3/l4' - preLoaderRoute: typeof L1L2L3L4RouteImport - parentRoute: typeof L1L2L3Route - } - '/l1/l2/l3/l4/l5': { - id: '/l1/l2/l3/l4/l5' - path: '/l5' - fullPath: '/l1/l2/l3/l4/l5' - preLoaderRoute: typeof L1L2L3L4L5RouteImport - parentRoute: typeof L1L2L3L4Route - } - '/l1/l2/l3/l4/l5/l6': { - id: '/l1/l2/l3/l4/l5/l6' - path: '/l6' - fullPath: '/l1/l2/l3/l4/l5/l6' - preLoaderRoute: typeof L1L2L3L4L5L6RouteImport - parentRoute: typeof L1L2L3L4L5Route - } - '/l1/l2/l3/l4/l5/l6/l7': { - id: '/l1/l2/l3/l4/l5/l6/l7' - path: '/l7' - fullPath: '/l1/l2/l3/l4/l5/l6/l7' - preLoaderRoute: typeof L1L2L3L4L5L6L7RouteImport - parentRoute: typeof L1L2L3L4L5L6Route - } - '/l1/l2/l3/l4/l5/l6/l7/l8': { - id: '/l1/l2/l3/l4/l5/l6/l7/l8' - path: '/l8' - fullPath: '/l1/l2/l3/l4/l5/l6/l7/l8' - preLoaderRoute: typeof L1L2L3L4L5L6L7L8RouteImport - parentRoute: typeof L1L2L3L4L5L6L7Route - } - } -} - -interface L1L2L3L4L5L6L7RouteChildren { - L1L2L3L4L5L6L7L8Route: typeof L1L2L3L4L5L6L7L8Route -} - -const L1L2L3L4L5L6L7RouteChildren: L1L2L3L4L5L6L7RouteChildren = { - L1L2L3L4L5L6L7L8Route: L1L2L3L4L5L6L7L8Route, -} - -const L1L2L3L4L5L6L7RouteWithChildren = L1L2L3L4L5L6L7Route._addFileChildren( - L1L2L3L4L5L6L7RouteChildren, -) - -interface L1L2L3L4L5L6RouteChildren { - L1L2L3L4L5L6L7Route: typeof L1L2L3L4L5L6L7RouteWithChildren -} - -const L1L2L3L4L5L6RouteChildren: L1L2L3L4L5L6RouteChildren = { - L1L2L3L4L5L6L7Route: L1L2L3L4L5L6L7RouteWithChildren, -} - -const L1L2L3L4L5L6RouteWithChildren = L1L2L3L4L5L6Route._addFileChildren( - L1L2L3L4L5L6RouteChildren, -) - -interface L1L2L3L4L5RouteChildren { - L1L2L3L4L5L6Route: typeof L1L2L3L4L5L6RouteWithChildren -} - -const L1L2L3L4L5RouteChildren: L1L2L3L4L5RouteChildren = { - L1L2L3L4L5L6Route: L1L2L3L4L5L6RouteWithChildren, -} - -const L1L2L3L4L5RouteWithChildren = L1L2L3L4L5Route._addFileChildren( - L1L2L3L4L5RouteChildren, -) - -interface L1L2L3L4RouteChildren { - L1L2L3L4L5Route: typeof L1L2L3L4L5RouteWithChildren -} - -const L1L2L3L4RouteChildren: L1L2L3L4RouteChildren = { - L1L2L3L4L5Route: L1L2L3L4L5RouteWithChildren, -} - -const L1L2L3L4RouteWithChildren = L1L2L3L4Route._addFileChildren( - L1L2L3L4RouteChildren, -) - -interface L1L2L3RouteChildren { - L1L2L3L4Route: typeof L1L2L3L4RouteWithChildren -} - -const L1L2L3RouteChildren: L1L2L3RouteChildren = { - L1L2L3L4Route: L1L2L3L4RouteWithChildren, -} - -const L1L2L3RouteWithChildren = - L1L2L3Route._addFileChildren(L1L2L3RouteChildren) - -interface L1L2RouteChildren { - L1L2L3Route: typeof L1L2L3RouteWithChildren -} - -const L1L2RouteChildren: L1L2RouteChildren = { - L1L2L3Route: L1L2L3RouteWithChildren, -} - -const L1L2RouteWithChildren = L1L2Route._addFileChildren(L1L2RouteChildren) - -interface L1RouteChildren { - L1L2Route: typeof L1L2RouteWithChildren -} - -const L1RouteChildren: L1RouteChildren = { - L1L2Route: L1L2RouteWithChildren, -} - -const L1RouteWithChildren = L1Route._addFileChildren(L1RouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - L1Route: L1RouteWithChildren, -} -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/benchmarks/memory/server/scenarios/peak-large-page/react/src/router.tsx b/benchmarks/memory/server/scenarios/peak-large-page/react/src/router.tsx deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/__root.tsx deleted file mode 100644 index c5f9de6922..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/__root.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' - -export const Route = createRootRoute({ - head: () => ({ - meta: [{ charSet: 'utf-8' }], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/index.tsx b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/index.tsx deleted file mode 100644 index 25099720e4..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
peak-large-page-index
-} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.l5.l6.l7.l8.tsx b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.l5.l6.l7.l8.tsx deleted file mode 100644 index 0651ba886d..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.l5.l6.l7.l8.tsx +++ /dev/null @@ -1,28 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { - makeLargePageHead, - makeLargePageLevelData, -} from '../../../large-page-data' - -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.records[0]! - - return ( -
-

{data.marker}

-

records: {data.records.length}

-
-

{first.name}

-

{first.id}

-

{first.description}

-
-
- ) -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.l5.l6.l7.tsx b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.l5.l6.l7.tsx deleted file mode 100644 index 1f89e6f454..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.l5.l6.l7.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import { - makeLargePageHead, - makeLargePageLevelData, -} from '../../../large-page-data' - -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.records[0]! - - return ( -
-

{data.marker}

-

records: {data.records.length}

-
-

{first.name}

-

{first.id}

-

{first.description}

-
- -
- ) -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.l5.l6.tsx b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.l5.l6.tsx deleted file mode 100644 index 1a8c98ceb2..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.l5.l6.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import { - makeLargePageHead, - makeLargePageLevelData, -} from '../../../large-page-data' - -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.records[0]! - - return ( -
-

{data.marker}

-

records: {data.records.length}

-
-

{first.name}

-

{first.id}

-

{first.description}

-
- -
- ) -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.l5.tsx b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.l5.tsx deleted file mode 100644 index 3e9afad0b9..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.l5.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import { - makeLargePageHead, - makeLargePageLevelData, -} from '../../../large-page-data' - -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.records[0]! - - return ( -
-

{data.marker}

-

records: {data.records.length}

-
-

{first.name}

-

{first.id}

-

{first.description}

-
- -
- ) -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.tsx b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.tsx deleted file mode 100644 index 73c29bc402..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import { - makeLargePageHead, - makeLargePageLevelData, -} from '../../../large-page-data' - -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.records[0]! - - return ( -
-

{data.marker}

-

records: {data.records.length}

-
-

{first.name}

-

{first.id}

-

{first.description}

-
- -
- ) -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.tsx b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.tsx deleted file mode 100644 index e5b57463ad..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import { - makeLargePageHead, - makeLargePageLevelData, -} from '../../../large-page-data' - -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.records[0]! - - return ( -
-

{data.marker}

-

records: {data.records.length}

-
-

{first.name}

-

{first.id}

-

{first.description}

-
- -
- ) -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.tsx b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.tsx deleted file mode 100644 index 18999233cc..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import { - makeLargePageHead, - makeLargePageLevelData, -} from '../../../large-page-data' - -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.records[0]! - - return ( -
-

{data.marker}

-

records: {data.records.length}

-
-

{first.name}

-

{first.id}

-

{first.description}

-
- -
- ) -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.tsx b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.tsx deleted file mode 100644 index 8fa7a5e0dc..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import { - makeLargePageHead, - makeLargePageLevelData, -} from '../../../large-page-data' - -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.records[0]! - - return ( -
-

{data.marker}

-

records: {data.records.length}

-
-

{first.name}

-

{first.id}

-

{first.description}

-
- -
- ) -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/tsconfig.json b/benchmarks/memory/server/scenarios/peak-large-page/react/tsconfig.json deleted file mode 100644 index 11ddcce4ea..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "allowImportingTsExtensions": true, - "jsx": "react-jsx", - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} 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 deleted file mode 100644 index dcfcf1f92b..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/vite.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - ...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 deleted file mode 100644 index 085e576244..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/shared.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { runSequentialRequestLoop } from '#memory-server/bench-utils' -import type { StartRequestHandler } from '#memory-server/bench-utils' - -export type { StartRequestHandler } - -type Framework = 'react' | 'solid' | 'vue' - -const benchmarkSeed = 0x5eed_0005 -const peakLargePageIterations = 1 -const peakLargePageUrl = 'http://localhost/l1/l2/l3/l4/l5/l6/l7/l8' -const levelEightMarker = 'data-bench="peak-large-page-level-8"' - -const requestInit = { - method: 'GET', - headers: { - accept: 'text/html', - }, -} satisfies RequestInit - -function buildPeakLargePageRequest() { - return new Request(peakLargePageUrl, requestInit) -} - -function validatePeakLargePageResponse(response: Response, request: Request) { - if (response.status !== 200) { - throw new Error( - `Expected status 200 for ${request.url}, got ${response.status}`, - ) - } -} - -function validatePeakLargePageBody(body: string) { - if (!body.includes(levelEightMarker)) { - throw new Error('Expected peak-large-page level-8 marker in response body') - } -} - -async function assertPeakLargePageSanity(handler: StartRequestHandler) { - const request = new Request(peakLargePageUrl, requestInit) - const response = await handler.fetch(request) - const body = await response.text() - - validatePeakLargePageResponse(response, request) - validatePeakLargePageBody(body) -} - -export function createWorkloadGroup( - framework: Framework, - handler: StartRequestHandler, -) { - const run = async () => - runSequentialRequestLoop(handler, { - seed: benchmarkSeed, - iterations: peakLargePageIterations, - buildRequest: buildPeakLargePageRequest, - validateResponse: validatePeakLargePageResponse, - }) - - return { - sanity: () => assertPeakLargePageSanity(handler), - workloads: [ - { - name: `mem server peak-large-page (${framework})`, - run, - }, - ], - } -} 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 deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' -import { workloadGroup } from './setup' - -await workloadGroup.sanity() - -test('memory', async ({ bench }) => { - for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) - } -}) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/memory.flame.ts b/benchmarks/memory/server/scenarios/peak-large-page/solid/memory.flame.ts deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runServerFlameBenchmark } from '#memory-server/flame-runner' -import { workloadGroup } from './setup.ts' - -await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/project.json b/benchmarks/memory/server/scenarios/peak-large-page/solid/project.json deleted file mode 100644 index 85e8f83224..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-server-peak-large-page-solid", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "build:ssr:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:ssr:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/setup.ts b/benchmarks/memory/server/scenarios/peak-large-page/solid/setup.ts deleted file mode 100644 index 4fe85c3f00..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' -import { createWorkloadGroup } from '../shared.ts' -import type { StartRequestHandler } from '../shared.ts' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} - -export const workloadGroup: ServerMemoryWorkloadGroup = - await createWorkloadGroup('solid', handler) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routeTree.gen.ts deleted file mode 100644 index c3ccdaaa0e..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,305 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as L1RouteImport } from './routes/l1' -import { Route as IndexRouteImport } from './routes/index' -import { Route as L1L2RouteImport } from './routes/l1.l2' -import { Route as L1L2L3RouteImport } from './routes/l1.l2.l3' -import { Route as L1L2L3L4RouteImport } from './routes/l1.l2.l3.l4' -import { Route as L1L2L3L4L5RouteImport } from './routes/l1.l2.l3.l4.l5' -import { Route as L1L2L3L4L5L6RouteImport } from './routes/l1.l2.l3.l4.l5.l6' -import { Route as L1L2L3L4L5L6L7RouteImport } from './routes/l1.l2.l3.l4.l5.l6.l7' -import { Route as L1L2L3L4L5L6L7L8RouteImport } from './routes/l1.l2.l3.l4.l5.l6.l7.l8' - -const L1Route = L1RouteImport.update({ - id: '/l1', - path: '/l1', - getParentRoute: () => rootRouteImport, -} as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const L1L2Route = L1L2RouteImport.update({ - id: '/l2', - path: '/l2', - getParentRoute: () => L1Route, -} as any) -const L1L2L3Route = L1L2L3RouteImport.update({ - id: '/l3', - path: '/l3', - getParentRoute: () => L1L2Route, -} as any) -const L1L2L3L4Route = L1L2L3L4RouteImport.update({ - id: '/l4', - path: '/l4', - getParentRoute: () => L1L2L3Route, -} as any) -const L1L2L3L4L5Route = L1L2L3L4L5RouteImport.update({ - id: '/l5', - path: '/l5', - getParentRoute: () => L1L2L3L4Route, -} as any) -const L1L2L3L4L5L6Route = L1L2L3L4L5L6RouteImport.update({ - id: '/l6', - path: '/l6', - getParentRoute: () => L1L2L3L4L5Route, -} as any) -const L1L2L3L4L5L6L7Route = L1L2L3L4L5L6L7RouteImport.update({ - id: '/l7', - path: '/l7', - getParentRoute: () => L1L2L3L4L5L6Route, -} as any) -const L1L2L3L4L5L6L7L8Route = L1L2L3L4L5L6L7L8RouteImport.update({ - id: '/l8', - path: '/l8', - getParentRoute: () => L1L2L3L4L5L6L7Route, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/l1': typeof L1RouteWithChildren - '/l1/l2': typeof L1L2RouteWithChildren - '/l1/l2/l3': typeof L1L2L3RouteWithChildren - '/l1/l2/l3/l4': typeof L1L2L3L4RouteWithChildren - '/l1/l2/l3/l4/l5': typeof L1L2L3L4L5RouteWithChildren - '/l1/l2/l3/l4/l5/l6': typeof L1L2L3L4L5L6RouteWithChildren - '/l1/l2/l3/l4/l5/l6/l7': typeof L1L2L3L4L5L6L7RouteWithChildren - '/l1/l2/l3/l4/l5/l6/l7/l8': typeof L1L2L3L4L5L6L7L8Route -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/l1': typeof L1RouteWithChildren - '/l1/l2': typeof L1L2RouteWithChildren - '/l1/l2/l3': typeof L1L2L3RouteWithChildren - '/l1/l2/l3/l4': typeof L1L2L3L4RouteWithChildren - '/l1/l2/l3/l4/l5': typeof L1L2L3L4L5RouteWithChildren - '/l1/l2/l3/l4/l5/l6': typeof L1L2L3L4L5L6RouteWithChildren - '/l1/l2/l3/l4/l5/l6/l7': typeof L1L2L3L4L5L6L7RouteWithChildren - '/l1/l2/l3/l4/l5/l6/l7/l8': typeof L1L2L3L4L5L6L7L8Route -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/l1': typeof L1RouteWithChildren - '/l1/l2': typeof L1L2RouteWithChildren - '/l1/l2/l3': typeof L1L2L3RouteWithChildren - '/l1/l2/l3/l4': typeof L1L2L3L4RouteWithChildren - '/l1/l2/l3/l4/l5': typeof L1L2L3L4L5RouteWithChildren - '/l1/l2/l3/l4/l5/l6': typeof L1L2L3L4L5L6RouteWithChildren - '/l1/l2/l3/l4/l5/l6/l7': typeof L1L2L3L4L5L6L7RouteWithChildren - '/l1/l2/l3/l4/l5/l6/l7/l8': typeof L1L2L3L4L5L6L7L8Route -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/l1' - | '/l1/l2' - | '/l1/l2/l3' - | '/l1/l2/l3/l4' - | '/l1/l2/l3/l4/l5' - | '/l1/l2/l3/l4/l5/l6' - | '/l1/l2/l3/l4/l5/l6/l7' - | '/l1/l2/l3/l4/l5/l6/l7/l8' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/l1' - | '/l1/l2' - | '/l1/l2/l3' - | '/l1/l2/l3/l4' - | '/l1/l2/l3/l4/l5' - | '/l1/l2/l3/l4/l5/l6' - | '/l1/l2/l3/l4/l5/l6/l7' - | '/l1/l2/l3/l4/l5/l6/l7/l8' - id: - | '__root__' - | '/' - | '/l1' - | '/l1/l2' - | '/l1/l2/l3' - | '/l1/l2/l3/l4' - | '/l1/l2/l3/l4/l5' - | '/l1/l2/l3/l4/l5/l6' - | '/l1/l2/l3/l4/l5/l6/l7' - | '/l1/l2/l3/l4/l5/l6/l7/l8' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - L1Route: typeof L1RouteWithChildren -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/l1': { - id: '/l1' - path: '/l1' - fullPath: '/l1' - preLoaderRoute: typeof L1RouteImport - parentRoute: typeof rootRouteImport - } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/l1/l2': { - id: '/l1/l2' - path: '/l2' - fullPath: '/l1/l2' - preLoaderRoute: typeof L1L2RouteImport - parentRoute: typeof L1Route - } - '/l1/l2/l3': { - id: '/l1/l2/l3' - path: '/l3' - fullPath: '/l1/l2/l3' - preLoaderRoute: typeof L1L2L3RouteImport - parentRoute: typeof L1L2Route - } - '/l1/l2/l3/l4': { - id: '/l1/l2/l3/l4' - path: '/l4' - fullPath: '/l1/l2/l3/l4' - preLoaderRoute: typeof L1L2L3L4RouteImport - parentRoute: typeof L1L2L3Route - } - '/l1/l2/l3/l4/l5': { - id: '/l1/l2/l3/l4/l5' - path: '/l5' - fullPath: '/l1/l2/l3/l4/l5' - preLoaderRoute: typeof L1L2L3L4L5RouteImport - parentRoute: typeof L1L2L3L4Route - } - '/l1/l2/l3/l4/l5/l6': { - id: '/l1/l2/l3/l4/l5/l6' - path: '/l6' - fullPath: '/l1/l2/l3/l4/l5/l6' - preLoaderRoute: typeof L1L2L3L4L5L6RouteImport - parentRoute: typeof L1L2L3L4L5Route - } - '/l1/l2/l3/l4/l5/l6/l7': { - id: '/l1/l2/l3/l4/l5/l6/l7' - path: '/l7' - fullPath: '/l1/l2/l3/l4/l5/l6/l7' - preLoaderRoute: typeof L1L2L3L4L5L6L7RouteImport - parentRoute: typeof L1L2L3L4L5L6Route - } - '/l1/l2/l3/l4/l5/l6/l7/l8': { - id: '/l1/l2/l3/l4/l5/l6/l7/l8' - path: '/l8' - fullPath: '/l1/l2/l3/l4/l5/l6/l7/l8' - preLoaderRoute: typeof L1L2L3L4L5L6L7L8RouteImport - parentRoute: typeof L1L2L3L4L5L6L7Route - } - } -} - -interface L1L2L3L4L5L6L7RouteChildren { - L1L2L3L4L5L6L7L8Route: typeof L1L2L3L4L5L6L7L8Route -} - -const L1L2L3L4L5L6L7RouteChildren: L1L2L3L4L5L6L7RouteChildren = { - L1L2L3L4L5L6L7L8Route: L1L2L3L4L5L6L7L8Route, -} - -const L1L2L3L4L5L6L7RouteWithChildren = L1L2L3L4L5L6L7Route._addFileChildren( - L1L2L3L4L5L6L7RouteChildren, -) - -interface L1L2L3L4L5L6RouteChildren { - L1L2L3L4L5L6L7Route: typeof L1L2L3L4L5L6L7RouteWithChildren -} - -const L1L2L3L4L5L6RouteChildren: L1L2L3L4L5L6RouteChildren = { - L1L2L3L4L5L6L7Route: L1L2L3L4L5L6L7RouteWithChildren, -} - -const L1L2L3L4L5L6RouteWithChildren = L1L2L3L4L5L6Route._addFileChildren( - L1L2L3L4L5L6RouteChildren, -) - -interface L1L2L3L4L5RouteChildren { - L1L2L3L4L5L6Route: typeof L1L2L3L4L5L6RouteWithChildren -} - -const L1L2L3L4L5RouteChildren: L1L2L3L4L5RouteChildren = { - L1L2L3L4L5L6Route: L1L2L3L4L5L6RouteWithChildren, -} - -const L1L2L3L4L5RouteWithChildren = L1L2L3L4L5Route._addFileChildren( - L1L2L3L4L5RouteChildren, -) - -interface L1L2L3L4RouteChildren { - L1L2L3L4L5Route: typeof L1L2L3L4L5RouteWithChildren -} - -const L1L2L3L4RouteChildren: L1L2L3L4RouteChildren = { - L1L2L3L4L5Route: L1L2L3L4L5RouteWithChildren, -} - -const L1L2L3L4RouteWithChildren = L1L2L3L4Route._addFileChildren( - L1L2L3L4RouteChildren, -) - -interface L1L2L3RouteChildren { - L1L2L3L4Route: typeof L1L2L3L4RouteWithChildren -} - -const L1L2L3RouteChildren: L1L2L3RouteChildren = { - L1L2L3L4Route: L1L2L3L4RouteWithChildren, -} - -const L1L2L3RouteWithChildren = - L1L2L3Route._addFileChildren(L1L2L3RouteChildren) - -interface L1L2RouteChildren { - L1L2L3Route: typeof L1L2L3RouteWithChildren -} - -const L1L2RouteChildren: L1L2RouteChildren = { - L1L2L3Route: L1L2L3RouteWithChildren, -} - -const L1L2RouteWithChildren = L1L2Route._addFileChildren(L1L2RouteChildren) - -interface L1RouteChildren { - L1L2Route: typeof L1L2RouteWithChildren -} - -const L1RouteChildren: L1RouteChildren = { - L1L2Route: L1L2RouteWithChildren, -} - -const L1RouteWithChildren = L1Route._addFileChildren(L1RouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - L1Route: L1RouteWithChildren, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/solid-start' -declare module '@tanstack/solid-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/router.tsx b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/router.tsx deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/__root.tsx deleted file mode 100644 index aaf7dfdd89..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/solid-router' -import { HydrationScript } from 'solid-js/web' - -export const Route = createRootRoute({ - head: () => ({ - meta: [{ charset: 'utf-8' }], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - - ) -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/index.tsx b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/index.tsx deleted file mode 100644 index 111ffaa36a..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
peak-large-page-index
-} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.l5.l6.l7.l8.tsx b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.l5.l6.l7.l8.tsx deleted file mode 100644 index b0f94893fb..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.l5.l6.l7.l8.tsx +++ /dev/null @@ -1,28 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { - makeLargePageHead, - makeLargePageLevelData, -} from '../../../large-page-data' - -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().records[0]! - - return ( -
-

{data().marker}

-

records: {data().records.length}

-
-

{first().name}

-

{first().id}

-

{first().description}

-
-
- ) -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.l5.l6.l7.tsx b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.l5.l6.l7.tsx deleted file mode 100644 index f8a3819c85..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.l5.l6.l7.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' -import { - makeLargePageHead, - makeLargePageLevelData, -} from '../../../large-page-data' - -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().records[0]! - - return ( -
-

{data().marker}

-

records: {data().records.length}

-
-

{first().name}

-

{first().id}

-

{first().description}

-
- -
- ) -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.l5.l6.tsx b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.l5.l6.tsx deleted file mode 100644 index 7a438ddbd2..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.l5.l6.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' -import { - makeLargePageHead, - makeLargePageLevelData, -} from '../../../large-page-data' - -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().records[0]! - - return ( -
-

{data().marker}

-

records: {data().records.length}

-
-

{first().name}

-

{first().id}

-

{first().description}

-
- -
- ) -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.l5.tsx b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.l5.tsx deleted file mode 100644 index 2e05985ac5..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.l5.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' -import { - makeLargePageHead, - makeLargePageLevelData, -} from '../../../large-page-data' - -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().records[0]! - - return ( -
-

{data().marker}

-

records: {data().records.length}

-
-

{first().name}

-

{first().id}

-

{first().description}

-
- -
- ) -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.tsx b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.tsx deleted file mode 100644 index 4f38f0cb76..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' -import { - makeLargePageHead, - makeLargePageLevelData, -} from '../../../large-page-data' - -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().records[0]! - - return ( -
-

{data().marker}

-

records: {data().records.length}

-
-

{first().name}

-

{first().id}

-

{first().description}

-
- -
- ) -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.tsx b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.tsx deleted file mode 100644 index 3f1f113fe3..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' -import { - makeLargePageHead, - makeLargePageLevelData, -} from '../../../large-page-data' - -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().records[0]! - - return ( -
-

{data().marker}

-

records: {data().records.length}

-
-

{first().name}

-

{first().id}

-

{first().description}

-
- -
- ) -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.tsx b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.tsx deleted file mode 100644 index bd338fd53f..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' -import { - makeLargePageHead, - makeLargePageLevelData, -} from '../../../large-page-data' - -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().records[0]! - - return ( -
-

{data().marker}

-

records: {data().records.length}

-
-

{first().name}

-

{first().id}

-

{first().description}

-
- -
- ) -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.tsx b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.tsx deleted file mode 100644 index 9dcfd7448a..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' -import { - makeLargePageHead, - makeLargePageLevelData, -} from '../../../large-page-data' - -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().records[0]! - - return ( -
-

{data().marker}

-

records: {data().records.length}

-
-

{first().name}

-

{first().id}

-

{first().description}

-
- -
- ) -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/tsconfig.json b/benchmarks/memory/server/scenarios/peak-large-page/solid/tsconfig.json deleted file mode 100644 index 4b61264e11..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "allowImportingTsExtensions": true, - "jsx": "preserve", - "jsxImportSource": "solid-js", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} 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 deleted file mode 100644 index 15b8c3a571..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/vite.config.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - solid({ ssr: true, hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - ...memoryConfig('server'), - name: '@benchmarks/memory-server peak-large-page (solid)', - watch: false, - environment: 'node', - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) 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 deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' -import { workloadGroup } from './setup' - -await workloadGroup.sanity() - -test('memory', async ({ bench }) => { - for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) - } -}) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/memory.flame.ts b/benchmarks/memory/server/scenarios/peak-large-page/vue/memory.flame.ts deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runServerFlameBenchmark } from '#memory-server/flame-runner' -import { workloadGroup } from './setup.ts' - -await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/project.json b/benchmarks/memory/server/scenarios/peak-large-page/vue/project.json deleted file mode 100644 index f424a2134f..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-server-peak-large-page-vue", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "build:ssr:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:ssr:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/setup.ts b/benchmarks/memory/server/scenarios/peak-large-page/vue/setup.ts deleted file mode 100644 index 6683dafe6b..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' -import { createWorkloadGroup } from '../shared.ts' -import type { StartRequestHandler } from '../shared.ts' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} - -export const workloadGroup: ServerMemoryWorkloadGroup = - await createWorkloadGroup('vue', handler) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routeTree.gen.ts deleted file mode 100644 index 26cc9f6058..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,305 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as L1RouteImport } from './routes/l1' -import { Route as IndexRouteImport } from './routes/index' -import { Route as L1L2RouteImport } from './routes/l1.l2' -import { Route as L1L2L3RouteImport } from './routes/l1.l2.l3' -import { Route as L1L2L3L4RouteImport } from './routes/l1.l2.l3.l4' -import { Route as L1L2L3L4L5RouteImport } from './routes/l1.l2.l3.l4.l5' -import { Route as L1L2L3L4L5L6RouteImport } from './routes/l1.l2.l3.l4.l5.l6' -import { Route as L1L2L3L4L5L6L7RouteImport } from './routes/l1.l2.l3.l4.l5.l6.l7' -import { Route as L1L2L3L4L5L6L7L8RouteImport } from './routes/l1.l2.l3.l4.l5.l6.l7.l8' - -const L1Route = L1RouteImport.update({ - id: '/l1', - path: '/l1', - getParentRoute: () => rootRouteImport, -} as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const L1L2Route = L1L2RouteImport.update({ - id: '/l2', - path: '/l2', - getParentRoute: () => L1Route, -} as any) -const L1L2L3Route = L1L2L3RouteImport.update({ - id: '/l3', - path: '/l3', - getParentRoute: () => L1L2Route, -} as any) -const L1L2L3L4Route = L1L2L3L4RouteImport.update({ - id: '/l4', - path: '/l4', - getParentRoute: () => L1L2L3Route, -} as any) -const L1L2L3L4L5Route = L1L2L3L4L5RouteImport.update({ - id: '/l5', - path: '/l5', - getParentRoute: () => L1L2L3L4Route, -} as any) -const L1L2L3L4L5L6Route = L1L2L3L4L5L6RouteImport.update({ - id: '/l6', - path: '/l6', - getParentRoute: () => L1L2L3L4L5Route, -} as any) -const L1L2L3L4L5L6L7Route = L1L2L3L4L5L6L7RouteImport.update({ - id: '/l7', - path: '/l7', - getParentRoute: () => L1L2L3L4L5L6Route, -} as any) -const L1L2L3L4L5L6L7L8Route = L1L2L3L4L5L6L7L8RouteImport.update({ - id: '/l8', - path: '/l8', - getParentRoute: () => L1L2L3L4L5L6L7Route, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/l1': typeof L1RouteWithChildren - '/l1/l2': typeof L1L2RouteWithChildren - '/l1/l2/l3': typeof L1L2L3RouteWithChildren - '/l1/l2/l3/l4': typeof L1L2L3L4RouteWithChildren - '/l1/l2/l3/l4/l5': typeof L1L2L3L4L5RouteWithChildren - '/l1/l2/l3/l4/l5/l6': typeof L1L2L3L4L5L6RouteWithChildren - '/l1/l2/l3/l4/l5/l6/l7': typeof L1L2L3L4L5L6L7RouteWithChildren - '/l1/l2/l3/l4/l5/l6/l7/l8': typeof L1L2L3L4L5L6L7L8Route -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/l1': typeof L1RouteWithChildren - '/l1/l2': typeof L1L2RouteWithChildren - '/l1/l2/l3': typeof L1L2L3RouteWithChildren - '/l1/l2/l3/l4': typeof L1L2L3L4RouteWithChildren - '/l1/l2/l3/l4/l5': typeof L1L2L3L4L5RouteWithChildren - '/l1/l2/l3/l4/l5/l6': typeof L1L2L3L4L5L6RouteWithChildren - '/l1/l2/l3/l4/l5/l6/l7': typeof L1L2L3L4L5L6L7RouteWithChildren - '/l1/l2/l3/l4/l5/l6/l7/l8': typeof L1L2L3L4L5L6L7L8Route -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/l1': typeof L1RouteWithChildren - '/l1/l2': typeof L1L2RouteWithChildren - '/l1/l2/l3': typeof L1L2L3RouteWithChildren - '/l1/l2/l3/l4': typeof L1L2L3L4RouteWithChildren - '/l1/l2/l3/l4/l5': typeof L1L2L3L4L5RouteWithChildren - '/l1/l2/l3/l4/l5/l6': typeof L1L2L3L4L5L6RouteWithChildren - '/l1/l2/l3/l4/l5/l6/l7': typeof L1L2L3L4L5L6L7RouteWithChildren - '/l1/l2/l3/l4/l5/l6/l7/l8': typeof L1L2L3L4L5L6L7L8Route -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/l1' - | '/l1/l2' - | '/l1/l2/l3' - | '/l1/l2/l3/l4' - | '/l1/l2/l3/l4/l5' - | '/l1/l2/l3/l4/l5/l6' - | '/l1/l2/l3/l4/l5/l6/l7' - | '/l1/l2/l3/l4/l5/l6/l7/l8' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/l1' - | '/l1/l2' - | '/l1/l2/l3' - | '/l1/l2/l3/l4' - | '/l1/l2/l3/l4/l5' - | '/l1/l2/l3/l4/l5/l6' - | '/l1/l2/l3/l4/l5/l6/l7' - | '/l1/l2/l3/l4/l5/l6/l7/l8' - id: - | '__root__' - | '/' - | '/l1' - | '/l1/l2' - | '/l1/l2/l3' - | '/l1/l2/l3/l4' - | '/l1/l2/l3/l4/l5' - | '/l1/l2/l3/l4/l5/l6' - | '/l1/l2/l3/l4/l5/l6/l7' - | '/l1/l2/l3/l4/l5/l6/l7/l8' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - L1Route: typeof L1RouteWithChildren -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/l1': { - id: '/l1' - path: '/l1' - fullPath: '/l1' - preLoaderRoute: typeof L1RouteImport - parentRoute: typeof rootRouteImport - } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/l1/l2': { - id: '/l1/l2' - path: '/l2' - fullPath: '/l1/l2' - preLoaderRoute: typeof L1L2RouteImport - parentRoute: typeof L1Route - } - '/l1/l2/l3': { - id: '/l1/l2/l3' - path: '/l3' - fullPath: '/l1/l2/l3' - preLoaderRoute: typeof L1L2L3RouteImport - parentRoute: typeof L1L2Route - } - '/l1/l2/l3/l4': { - id: '/l1/l2/l3/l4' - path: '/l4' - fullPath: '/l1/l2/l3/l4' - preLoaderRoute: typeof L1L2L3L4RouteImport - parentRoute: typeof L1L2L3Route - } - '/l1/l2/l3/l4/l5': { - id: '/l1/l2/l3/l4/l5' - path: '/l5' - fullPath: '/l1/l2/l3/l4/l5' - preLoaderRoute: typeof L1L2L3L4L5RouteImport - parentRoute: typeof L1L2L3L4Route - } - '/l1/l2/l3/l4/l5/l6': { - id: '/l1/l2/l3/l4/l5/l6' - path: '/l6' - fullPath: '/l1/l2/l3/l4/l5/l6' - preLoaderRoute: typeof L1L2L3L4L5L6RouteImport - parentRoute: typeof L1L2L3L4L5Route - } - '/l1/l2/l3/l4/l5/l6/l7': { - id: '/l1/l2/l3/l4/l5/l6/l7' - path: '/l7' - fullPath: '/l1/l2/l3/l4/l5/l6/l7' - preLoaderRoute: typeof L1L2L3L4L5L6L7RouteImport - parentRoute: typeof L1L2L3L4L5L6Route - } - '/l1/l2/l3/l4/l5/l6/l7/l8': { - id: '/l1/l2/l3/l4/l5/l6/l7/l8' - path: '/l8' - fullPath: '/l1/l2/l3/l4/l5/l6/l7/l8' - preLoaderRoute: typeof L1L2L3L4L5L6L7L8RouteImport - parentRoute: typeof L1L2L3L4L5L6L7Route - } - } -} - -interface L1L2L3L4L5L6L7RouteChildren { - L1L2L3L4L5L6L7L8Route: typeof L1L2L3L4L5L6L7L8Route -} - -const L1L2L3L4L5L6L7RouteChildren: L1L2L3L4L5L6L7RouteChildren = { - L1L2L3L4L5L6L7L8Route: L1L2L3L4L5L6L7L8Route, -} - -const L1L2L3L4L5L6L7RouteWithChildren = L1L2L3L4L5L6L7Route._addFileChildren( - L1L2L3L4L5L6L7RouteChildren, -) - -interface L1L2L3L4L5L6RouteChildren { - L1L2L3L4L5L6L7Route: typeof L1L2L3L4L5L6L7RouteWithChildren -} - -const L1L2L3L4L5L6RouteChildren: L1L2L3L4L5L6RouteChildren = { - L1L2L3L4L5L6L7Route: L1L2L3L4L5L6L7RouteWithChildren, -} - -const L1L2L3L4L5L6RouteWithChildren = L1L2L3L4L5L6Route._addFileChildren( - L1L2L3L4L5L6RouteChildren, -) - -interface L1L2L3L4L5RouteChildren { - L1L2L3L4L5L6Route: typeof L1L2L3L4L5L6RouteWithChildren -} - -const L1L2L3L4L5RouteChildren: L1L2L3L4L5RouteChildren = { - L1L2L3L4L5L6Route: L1L2L3L4L5L6RouteWithChildren, -} - -const L1L2L3L4L5RouteWithChildren = L1L2L3L4L5Route._addFileChildren( - L1L2L3L4L5RouteChildren, -) - -interface L1L2L3L4RouteChildren { - L1L2L3L4L5Route: typeof L1L2L3L4L5RouteWithChildren -} - -const L1L2L3L4RouteChildren: L1L2L3L4RouteChildren = { - L1L2L3L4L5Route: L1L2L3L4L5RouteWithChildren, -} - -const L1L2L3L4RouteWithChildren = L1L2L3L4Route._addFileChildren( - L1L2L3L4RouteChildren, -) - -interface L1L2L3RouteChildren { - L1L2L3L4Route: typeof L1L2L3L4RouteWithChildren -} - -const L1L2L3RouteChildren: L1L2L3RouteChildren = { - L1L2L3L4Route: L1L2L3L4RouteWithChildren, -} - -const L1L2L3RouteWithChildren = - L1L2L3Route._addFileChildren(L1L2L3RouteChildren) - -interface L1L2RouteChildren { - L1L2L3Route: typeof L1L2L3RouteWithChildren -} - -const L1L2RouteChildren: L1L2RouteChildren = { - L1L2L3Route: L1L2L3RouteWithChildren, -} - -const L1L2RouteWithChildren = L1L2Route._addFileChildren(L1L2RouteChildren) - -interface L1RouteChildren { - L1L2Route: typeof L1L2RouteWithChildren -} - -const L1RouteChildren: L1RouteChildren = { - L1L2Route: L1L2RouteWithChildren, -} - -const L1RouteWithChildren = L1Route._addFileChildren(L1RouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - L1Route: L1RouteWithChildren, -} -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/benchmarks/memory/server/scenarios/peak-large-page/vue/src/router.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/router.tsx deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/__root.tsx deleted file mode 100644 index de29ee1612..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { - Body, - HeadContent, - Html, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/vue-router' - -export const Route = createRootRoute({ - head: () => ({ - meta: [{ charSet: 'utf-8' }], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/index.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/index.tsx deleted file mode 100644 index e9a57d46fd..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
peak-large-page-index
-} 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 deleted file mode 100644 index 7f7a42d645..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.l7.l8.tsx +++ /dev/null @@ -1,34 +0,0 @@ -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, -}) 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 deleted file mode 100644 index a99c56e529..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.l7.tsx +++ /dev/null @@ -1,35 +0,0 @@ -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, -}) 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 deleted file mode 100644 index 3de3f03427..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.tsx +++ /dev/null @@ -1,35 +0,0 @@ -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, -}) 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 deleted file mode 100644 index 5d936f83b5..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.tsx +++ /dev/null @@ -1,35 +0,0 @@ -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, -}) 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 deleted file mode 100644 index 8e10331f2d..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.tsx +++ /dev/null @@ -1,35 +0,0 @@ -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, -}) 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 deleted file mode 100644 index d69529c50c..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.tsx +++ /dev/null @@ -1,35 +0,0 @@ -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, -}) 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 deleted file mode 100644 index d04bc7f827..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.tsx +++ /dev/null @@ -1,35 +0,0 @@ -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, -}) 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 deleted file mode 100644 index a95ae7f9b0..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.tsx +++ /dev/null @@ -1,35 +0,0 @@ -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, -}) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/tsconfig.json b/benchmarks/memory/server/scenarios/peak-large-page/vue/tsconfig.json deleted file mode 100644 index 9ad6481342..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "allowImportingTsExtensions": true, - "jsx": "preserve", - "jsxImportSource": "vue", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} 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 deleted file mode 100644 index 3fab2aff9e..0000000000 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/vite.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - ...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 deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/react/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' -import { workloadGroup } from './setup' - -await workloadGroup.sanity() - -test('memory', async ({ bench }) => { - for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) - } -}) diff --git a/benchmarks/memory/server/scenarios/request-churn/react/memory.flame.ts b/benchmarks/memory/server/scenarios/request-churn/react/memory.flame.ts deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/react/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runServerFlameBenchmark } from '#memory-server/flame-runner' -import { workloadGroup } from './setup.ts' - -await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/request-churn/react/project.json b/benchmarks/memory/server/scenarios/request-churn/react/project.json deleted file mode 100644 index d997054b95..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/react/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-server-request-churn-react", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "build:ssr:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:ssr:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/memory/server/scenarios/request-churn/react/setup.ts b/benchmarks/memory/server/scenarios/request-churn/react/setup.ts deleted file mode 100644 index 0c98f54ddd..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/react/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' -import { createWorkloadGroup } from '../shared.ts' -import type { StartRequestHandler } from '../shared.ts' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} - -export const workloadGroup: ServerMemoryWorkloadGroup = - await createWorkloadGroup('react', handler) diff --git a/benchmarks/memory/server/scenarios/request-churn/react/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/request-churn/react/src/routeTree.gen.ts deleted file mode 100644 index d22f1bee18..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/react/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as ItemsIdRouteImport } from './routes/items.$id' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ItemsIdRoute = ItemsIdRouteImport.update({ - id: '/items/$id', - path: '/items/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/items/$id': typeof ItemsIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/items/$id': typeof ItemsIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/items/$id': typeof ItemsIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/items/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/items/$id' - id: '__root__' | '/' | '/items/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ItemsIdRoute: typeof ItemsIdRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/items/$id': { - id: '/items/$id' - path: '/items/$id' - fullPath: '/items/$id' - preLoaderRoute: typeof ItemsIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ItemsIdRoute: ItemsIdRoute, -} -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/benchmarks/memory/server/scenarios/request-churn/react/src/router.tsx b/benchmarks/memory/server/scenarios/request-churn/react/src/router.tsx deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/server/scenarios/request-churn/react/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/request-churn/react/src/routes/__root.tsx deleted file mode 100644 index c5f9de6922..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/react/src/routes/__root.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' - -export const Route = createRootRoute({ - head: () => ({ - meta: [{ charSet: 'utf-8' }], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/memory/server/scenarios/request-churn/react/src/routes/index.tsx b/benchmarks/memory/server/scenarios/request-churn/react/src/routes/index.tsx deleted file mode 100644 index e6335b0d83..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/react/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
request-churn-index
-} diff --git a/benchmarks/memory/server/scenarios/request-churn/react/src/routes/items.$id.tsx b/benchmarks/memory/server/scenarios/request-churn/react/src/routes/items.$id.tsx deleted file mode 100644 index 5fd86ee5fb..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/react/src/routes/items.$id.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -const itemIndexes = Array.from({ length: 5 }, (_, index) => index) - -type ItemSearch = { - q: string -} - -export const Route = createFileRoute('/items/$id')({ - validateSearch: (search: Record): ItemSearch => ({ - q: typeof search.q === 'string' ? search.q : '', - }), - loaderDeps: ({ search }) => ({ q: search.q }), - loader: ({ params, deps }) => ({ - id: params.id, - title: `Item ${params.id}`, - q: deps.q, - items: itemIndexes.map((index) => ({ - id: `${params.id}-${index}`, - label: `${deps.q}-${index}`, - })), - }), - component: ItemComponent, -}) - -function ItemComponent() { - const data = Route.useLoaderData() - - return ( -
-

{data.title}

-

{data.q}

-
    - {data.items.map((item) => ( -
  • {item.label}
  • - ))} -
-
- ) -} diff --git a/benchmarks/memory/server/scenarios/request-churn/react/tsconfig.json b/benchmarks/memory/server/scenarios/request-churn/react/tsconfig.json deleted file mode 100644 index 11ddcce4ea..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/react/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "allowImportingTsExtensions": true, - "jsx": "react-jsx", - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/memory/server/scenarios/request-churn/react/vite.config.ts b/benchmarks/memory/server/scenarios/request-churn/react/vite.config.ts deleted file mode 100644 index 35adf6a249..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/react/vite.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - ...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 deleted file mode 100644 index b200c96ed6..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/shared.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { - createDeterministicRandom, - randomSegment, - runSequentialRequestLoop, -} from '#memory-server/bench-utils' -import type { StartRequestHandler } from '#memory-server/bench-utils' - -export type { StartRequestHandler } - -type Framework = 'react' | 'solid' | 'vue' - -const benchmarkSeed = 0xdecafbad -const requestChurnIterations = 40 -const itemPageMarker = 'data-bench="request-churn-item"' -// Module-level so CodSpeed warmups and measurement never replay URLs. -const benchmarkRandom = createDeterministicRandom(benchmarkSeed) -let requestCounter = 0 - -const requestInit = { - method: 'GET', - headers: { - accept: 'text/html', - }, -} satisfies RequestInit - -function validateItemResponse(response: Response, request: Request) { - if (response.status !== 200) { - throw new Error( - `Expected status 200 for ${request.url}, got ${response.status}`, - ) - } -} - -function validateItemBody(body: string) { - if (!body.includes(itemPageMarker)) { - throw new Error('Expected request-churn item marker in response body') - } -} - -async function assertRequestChurnSanity(handler: StartRequestHandler) { - const response = await handler.fetch( - new Request('http://localhost/items/sanity-item?q=q-sanity', requestInit), - ) - const body = await response.text() - - if (response.status !== 200) { - throw new Error(`Expected sanity status 200, got ${response.status}`) - } - - validateItemBody(body) -} - -export function createWorkloadGroup( - framework: Framework, - handler: StartRequestHandler, -) { - function buildItemRequest(random: () => number) { - const counter = (requestCounter++).toString(36) - const id = `${counter}-${randomSegment(random)}` - const q = `q-${randomSegment(random)}` - - return new Request(`http://localhost/items/${id}?q=${q}`, requestInit) - } - - const run = async () => - runSequentialRequestLoop(handler, { - random: benchmarkRandom, - iterations: requestChurnIterations, - buildRequest: buildItemRequest, - validateResponse: validateItemResponse, - }) - - return { - sanity: () => assertRequestChurnSanity(handler), - workloads: [ - { - name: `mem server request-churn (${framework})`, - run, - }, - ], - } -} diff --git a/benchmarks/memory/server/scenarios/request-churn/solid/memory.bench.ts b/benchmarks/memory/server/scenarios/request-churn/solid/memory.bench.ts deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/solid/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' -import { workloadGroup } from './setup' - -await workloadGroup.sanity() - -test('memory', async ({ bench }) => { - for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) - } -}) diff --git a/benchmarks/memory/server/scenarios/request-churn/solid/memory.flame.ts b/benchmarks/memory/server/scenarios/request-churn/solid/memory.flame.ts deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/solid/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runServerFlameBenchmark } from '#memory-server/flame-runner' -import { workloadGroup } from './setup.ts' - -await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/request-churn/solid/project.json b/benchmarks/memory/server/scenarios/request-churn/solid/project.json deleted file mode 100644 index 3f3434ee24..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/solid/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-server-request-churn-solid", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "build:ssr:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:ssr:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/memory/server/scenarios/request-churn/solid/setup.ts b/benchmarks/memory/server/scenarios/request-churn/solid/setup.ts deleted file mode 100644 index 4fe85c3f00..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/solid/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' -import { createWorkloadGroup } from '../shared.ts' -import type { StartRequestHandler } from '../shared.ts' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} - -export const workloadGroup: ServerMemoryWorkloadGroup = - await createWorkloadGroup('solid', handler) diff --git a/benchmarks/memory/server/scenarios/request-churn/solid/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/request-churn/solid/src/routeTree.gen.ts deleted file mode 100644 index 8f49ec5d1f..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as ItemsIdRouteImport } from './routes/items.$id' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ItemsIdRoute = ItemsIdRouteImport.update({ - id: '/items/$id', - path: '/items/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/items/$id': typeof ItemsIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/items/$id': typeof ItemsIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/items/$id': typeof ItemsIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/items/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/items/$id' - id: '__root__' | '/' | '/items/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ItemsIdRoute: typeof ItemsIdRoute -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/items/$id': { - id: '/items/$id' - path: '/items/$id' - fullPath: '/items/$id' - preLoaderRoute: typeof ItemsIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ItemsIdRoute: ItemsIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/solid-start' -declare module '@tanstack/solid-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/benchmarks/memory/server/scenarios/request-churn/solid/src/router.tsx b/benchmarks/memory/server/scenarios/request-churn/solid/src/router.tsx deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/server/scenarios/request-churn/solid/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/request-churn/solid/src/routes/__root.tsx deleted file mode 100644 index aaf7dfdd89..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/solid/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/solid-router' -import { HydrationScript } from 'solid-js/web' - -export const Route = createRootRoute({ - head: () => ({ - meta: [{ charset: 'utf-8' }], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - - ) -} diff --git a/benchmarks/memory/server/scenarios/request-churn/solid/src/routes/index.tsx b/benchmarks/memory/server/scenarios/request-churn/solid/src/routes/index.tsx deleted file mode 100644 index d32d31f301..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/solid/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
request-churn-index
-} diff --git a/benchmarks/memory/server/scenarios/request-churn/solid/src/routes/items.$id.tsx b/benchmarks/memory/server/scenarios/request-churn/solid/src/routes/items.$id.tsx deleted file mode 100644 index e687e22741..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/solid/src/routes/items.$id.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -const itemIndexes = Array.from({ length: 5 }, (_, index) => index) - -type ItemSearch = { - q: string -} - -export const Route = createFileRoute('/items/$id')({ - validateSearch: (search: Record): ItemSearch => ({ - q: typeof search.q === 'string' ? search.q : '', - }), - loaderDeps: ({ search }) => ({ q: search.q }), - loader: ({ params, deps }) => ({ - id: params.id, - title: `Item ${params.id}`, - q: deps.q, - items: itemIndexes.map((index) => ({ - id: `${params.id}-${index}`, - label: `${deps.q}-${index}`, - })), - }), - component: ItemComponent, -}) - -function ItemComponent() { - const data = Route.useLoaderData() - - return ( -
-

{data().title}

-

{data().q}

-
    - {data().items.map((item) => ( -
  • {item.label}
  • - ))} -
-
- ) -} diff --git a/benchmarks/memory/server/scenarios/request-churn/solid/tsconfig.json b/benchmarks/memory/server/scenarios/request-churn/solid/tsconfig.json deleted file mode 100644 index 4b61264e11..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/solid/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "allowImportingTsExtensions": true, - "jsx": "preserve", - "jsxImportSource": "solid-js", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/memory/server/scenarios/request-churn/solid/vite.config.ts b/benchmarks/memory/server/scenarios/request-churn/solid/vite.config.ts deleted file mode 100644 index 6601309a74..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/solid/vite.config.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - solid({ ssr: true, hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - ...memoryConfig('server'), - name: '@benchmarks/memory-server request-churn (solid)', - watch: false, - environment: 'node', - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/memory/server/scenarios/request-churn/vue/memory.bench.ts b/benchmarks/memory/server/scenarios/request-churn/vue/memory.bench.ts deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/vue/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' -import { workloadGroup } from './setup' - -await workloadGroup.sanity() - -test('memory', async ({ bench }) => { - for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) - } -}) diff --git a/benchmarks/memory/server/scenarios/request-churn/vue/memory.flame.ts b/benchmarks/memory/server/scenarios/request-churn/vue/memory.flame.ts deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/vue/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runServerFlameBenchmark } from '#memory-server/flame-runner' -import { workloadGroup } from './setup.ts' - -await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/request-churn/vue/project.json b/benchmarks/memory/server/scenarios/request-churn/vue/project.json deleted file mode 100644 index 11eb1d868b..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/vue/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-server-request-churn-vue", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "build:ssr:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:ssr:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/memory/server/scenarios/request-churn/vue/setup.ts b/benchmarks/memory/server/scenarios/request-churn/vue/setup.ts deleted file mode 100644 index 6683dafe6b..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/vue/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' -import { createWorkloadGroup } from '../shared.ts' -import type { StartRequestHandler } from '../shared.ts' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} - -export const workloadGroup: ServerMemoryWorkloadGroup = - await createWorkloadGroup('vue', handler) diff --git a/benchmarks/memory/server/scenarios/request-churn/vue/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/request-churn/vue/src/routeTree.gen.ts deleted file mode 100644 index 86ccc14a0c..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as ItemsIdRouteImport } from './routes/items.$id' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ItemsIdRoute = ItemsIdRouteImport.update({ - id: '/items/$id', - path: '/items/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/items/$id': typeof ItemsIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/items/$id': typeof ItemsIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/items/$id': typeof ItemsIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/items/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/items/$id' - id: '__root__' | '/' | '/items/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ItemsIdRoute: typeof ItemsIdRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/items/$id': { - id: '/items/$id' - path: '/items/$id' - fullPath: '/items/$id' - preLoaderRoute: typeof ItemsIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ItemsIdRoute: ItemsIdRoute, -} -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/benchmarks/memory/server/scenarios/request-churn/vue/src/router.tsx b/benchmarks/memory/server/scenarios/request-churn/vue/src/router.tsx deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/server/scenarios/request-churn/vue/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/request-churn/vue/src/routes/__root.tsx deleted file mode 100644 index de29ee1612..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/vue/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { - Body, - HeadContent, - Html, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/vue-router' - -export const Route = createRootRoute({ - head: () => ({ - meta: [{ charSet: 'utf-8' }], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/memory/server/scenarios/request-churn/vue/src/routes/index.tsx b/benchmarks/memory/server/scenarios/request-churn/vue/src/routes/index.tsx deleted file mode 100644 index 30751100a4..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/vue/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
request-churn-index
-} 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 deleted file mode 100644 index 570561f2a8..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/vue/src/routes/items.$id.tsx +++ /dev/null @@ -1,43 +0,0 @@ -import { defineComponent } from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const itemIndexes = Array.from({ length: 5 }, (_, index) => index) - -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 : '', - }), - loaderDeps: ({ search }) => ({ q: search.q }), - loader: ({ params, deps }) => ({ - id: params.id, - title: `Item ${params.id}`, - q: deps.q, - items: itemIndexes.map((index) => ({ - id: `${params.id}-${index}`, - label: `${deps.q}-${index}`, - })), - }), - component: ItemComponent, -}) diff --git a/benchmarks/memory/server/scenarios/request-churn/vue/tsconfig.json b/benchmarks/memory/server/scenarios/request-churn/vue/tsconfig.json deleted file mode 100644 index 9ad6481342..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/vue/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "allowImportingTsExtensions": true, - "jsx": "preserve", - "jsxImportSource": "vue", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/memory/server/scenarios/request-churn/vue/vite.config.ts b/benchmarks/memory/server/scenarios/request-churn/vue/vite.config.ts deleted file mode 100644 index 7f15c5c7af..0000000000 --- a/benchmarks/memory/server/scenarios/request-churn/vue/vite.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - ...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 deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/react/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' -import { workloadGroup } from './setup' - -await workloadGroup.sanity() - -test('memory', async ({ bench }) => { - for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) - } -}) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/react/memory.flame.ts b/benchmarks/memory/server/scenarios/serialization-payload/react/memory.flame.ts deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/react/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runServerFlameBenchmark } from '#memory-server/flame-runner' -import { workloadGroup } from './setup.ts' - -await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/react/project.json b/benchmarks/memory/server/scenarios/serialization-payload/react/project.json deleted file mode 100644 index 467b40d734..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/react/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-server-serialization-payload-react", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "build:ssr:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:ssr:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/react/setup.ts b/benchmarks/memory/server/scenarios/serialization-payload/react/setup.ts deleted file mode 100644 index 0c98f54ddd..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/react/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' -import { createWorkloadGroup } from '../shared.ts' -import type { StartRequestHandler } from '../shared.ts' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} - -export const workloadGroup: ServerMemoryWorkloadGroup = - await createWorkloadGroup('react', handler) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/react/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/serialization-payload/react/src/routeTree.gen.ts deleted file mode 100644 index 7e370fd84c..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/react/src/routeTree.gen.ts +++ /dev/null @@ -1,68 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as DataIdRouteImport } from './routes/data.$id' - -const DataIdRoute = DataIdRouteImport.update({ - id: '/data/$id', - path: '/data/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/data/$id': typeof DataIdRoute -} -export interface FileRoutesByTo { - '/data/$id': typeof DataIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/data/$id': typeof DataIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/data/$id' - fileRoutesByTo: FileRoutesByTo - to: '/data/$id' - id: '__root__' | '/data/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - DataIdRoute: typeof DataIdRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/data/$id': { - id: '/data/$id' - path: '/data/$id' - fullPath: '/data/$id' - preLoaderRoute: typeof DataIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - DataIdRoute: DataIdRoute, -} -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/benchmarks/memory/server/scenarios/serialization-payload/react/src/router.tsx b/benchmarks/memory/server/scenarios/serialization-payload/react/src/router.tsx deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/react/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/serialization-payload/react/src/routes/__root.tsx deleted file mode 100644 index c5f9de6922..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/react/src/routes/__root.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' - -export const Route = createRootRoute({ - head: () => ({ - meta: [{ charSet: 'utf-8' }], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/react/src/routes/data.$id.tsx b/benchmarks/memory/server/scenarios/serialization-payload/react/src/routes/data.$id.tsx deleted file mode 100644 index cfba0dbd62..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/react/src/routes/data.$id.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { makeSerializationPayload } from '../../../serialization-payload' - -export const Route = createFileRoute('/data/$id')({ - loader: ({ params }) => makeSerializationPayload(params.id), - component: DataComponent, -}) - -function DataComponent() { - const data = Route.useLoaderData() - - return ( -
Map size: {data.lookup.size}
- ) -} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/react/tsconfig.json b/benchmarks/memory/server/scenarios/serialization-payload/react/tsconfig.json deleted file mode 100644 index 11ddcce4ea..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/react/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "allowImportingTsExtensions": true, - "jsx": "react-jsx", - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/react/vite.config.ts b/benchmarks/memory/server/scenarios/serialization-payload/react/vite.config.ts deleted file mode 100644 index 1ed3bcc335..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/react/vite.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - ...memoryConfig('server'), - name: '@benchmarks/memory-server serialization-payload (react)', - watch: false, - environment: 'node', - }, -}) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/serialization-payload.ts b/benchmarks/memory/server/scenarios/serialization-payload/serialization-payload.ts deleted file mode 100644 index b6f401640e..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/serialization-payload.ts +++ /dev/null @@ -1,115 +0,0 @@ -const mapEntryCount = 500 -const setEntryCount = 500 -const temporalEntryCount = 500 -const nestedTreeDepth = 5 -const nestedTreeBreadth = 6 -const payloadTextLength = 150 - -export interface MapPayloadValue { - index: number - label: string - createdAt: Date - count: bigint - text: string -} - -export interface NestedPayloadNode { - id: string - depth: number - text: string - values: Array - children: Array -} - -export interface SerializationPayload { - id: string - lookup: Map - tags: Set - dates: Array - bigints: Array - tree: NestedPayloadNode -} - -export function makeSerializationPayload(id: string): SerializationPayload { - const hash = hashId(id) - const baseTimestamp = Date.UTC(2024, 0, 1) + hash - - return { - id, - lookup: new Map( - Array.from( - { length: mapEntryCount }, - (_, index): [string, MapPayloadValue] => [ - makeMapKey(id, index), - { - index, - label: `${id}-map-${index}`, - createdAt: new Date(baseTimestamp + index * 1_000), - count: BigInt(hash) * 10_000n + BigInt(index), - text: makePayloadText(id, `map-${index}`), - }, - ], - ), - ), - tags: new Set( - Array.from({ length: setEntryCount }, (_, index) => - makePayloadText(id, `set-${index}`), - ), - ), - dates: Array.from( - { length: temporalEntryCount }, - (_, index) => new Date(baseTimestamp + index * 60_000), - ), - bigints: Array.from( - { length: temporalEntryCount }, - (_, index) => BigInt(hash) * 1_000_000n + BigInt(index), - ), - tree: makeNestedTree(id, 0, 'root', hash), - } -} - -function makeMapKey(id: string, index: number) { - return `map-${id}-${index.toString().padStart(3, '0')}` -} - -function makeNestedTree( - id: string, - depth: number, - path: string, - hash: number, -): NestedPayloadNode { - return { - id: `${id}-node-${path}`, - depth, - text: makePayloadText(id, `tree-${depth}-${path}`), - values: [hash, depth, path.length], - children: - depth === nestedTreeDepth - ? [] - : Array.from({ length: nestedTreeBreadth }, (_, index) => - makeNestedTree(id, depth + 1, `${path}-${index}`, hash), - ), - } -} - -function makePayloadText(id: string, segment: string) { - const filler = 'abcdefghijklmnopqrstuvwxyz0123456789' - let value = `${id}|${segment}|` - - while (value.length < payloadTextLength) { - value += filler - } - - return value.slice(0, payloadTextLength) -} - -function hashId(id: string) { - let hash = 2_166_136_261 - - for (let index = 0; index < id.length; index++) { - hash ^= id.charCodeAt(index) - hash = Math.imul(hash, 16_777_619) - } - - return hash >>> 0 -} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/shared.ts b/benchmarks/memory/server/scenarios/serialization-payload/shared.ts deleted file mode 100644 index 14ec8f7e0a..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/shared.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { - randomSegment, - runSequentialRequestLoop, -} from '#memory-server/bench-utils' -import type { StartRequestHandler } from '#memory-server/bench-utils' - -export type { StartRequestHandler } - -type Framework = 'react' | 'solid' | 'vue' - -const benchmarkSeed = 0x51eaa11 -const serializationPayloadIterations = 1 -const payloadPageMarker = 'data-bench="serialization-payload"' - -const requestInit = { - method: 'GET', - headers: { - accept: 'text/html', - }, -} satisfies RequestInit - -function buildPayloadRequest(random: () => number, index: number) { - const id = `payload-${index}-${randomSegment(random)}` - - return new Request(`http://localhost/data/${id}`, requestInit) -} - -function validatePayloadResponse(response: Response, request: Request) { - if (response.status !== 200) { - throw new Error( - `Expected status 200 for ${request.url}, got ${response.status}`, - ) - } -} - -function validatePayloadBody(body: string) { - if (!body.includes(payloadPageMarker)) { - throw new Error('Expected serialization-payload marker in response body') - } -} - -async function assertSerializationPayloadSanity(handler: StartRequestHandler) { - const request = new Request( - 'http://localhost/data/sanity-payload', - requestInit, - ) - const response = await handler.fetch(request) - const body = await response.text() - - validatePayloadResponse(response, request) - validatePayloadBody(body) -} - -export function createWorkloadGroup( - framework: Framework, - handler: StartRequestHandler, -) { - const run = async () => - runSequentialRequestLoop(handler, { - seed: benchmarkSeed, - iterations: serializationPayloadIterations, - buildRequest: buildPayloadRequest, - validateResponse: validatePayloadResponse, - }) - - return { - sanity: () => assertSerializationPayloadSanity(handler), - workloads: [ - { - name: `mem server serialization-payload (${framework})`, - run, - }, - ], - } -} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/solid/memory.bench.ts b/benchmarks/memory/server/scenarios/serialization-payload/solid/memory.bench.ts deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/solid/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' -import { workloadGroup } from './setup' - -await workloadGroup.sanity() - -test('memory', async ({ bench }) => { - for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) - } -}) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/solid/memory.flame.ts b/benchmarks/memory/server/scenarios/serialization-payload/solid/memory.flame.ts deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/solid/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runServerFlameBenchmark } from '#memory-server/flame-runner' -import { workloadGroup } from './setup.ts' - -await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/solid/project.json b/benchmarks/memory/server/scenarios/serialization-payload/solid/project.json deleted file mode 100644 index 6f381ef389..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/solid/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-server-serialization-payload-solid", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "build:ssr:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:ssr:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/solid/setup.ts b/benchmarks/memory/server/scenarios/serialization-payload/solid/setup.ts deleted file mode 100644 index 4fe85c3f00..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/solid/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' -import { createWorkloadGroup } from '../shared.ts' -import type { StartRequestHandler } from '../shared.ts' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} - -export const workloadGroup: ServerMemoryWorkloadGroup = - await createWorkloadGroup('solid', handler) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/solid/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/serialization-payload/solid/src/routeTree.gen.ts deleted file mode 100644 index 082cbb290c..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,68 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as DataIdRouteImport } from './routes/data.$id' - -const DataIdRoute = DataIdRouteImport.update({ - id: '/data/$id', - path: '/data/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/data/$id': typeof DataIdRoute -} -export interface FileRoutesByTo { - '/data/$id': typeof DataIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/data/$id': typeof DataIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/data/$id' - fileRoutesByTo: FileRoutesByTo - to: '/data/$id' - id: '__root__' | '/data/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - DataIdRoute: typeof DataIdRoute -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/data/$id': { - id: '/data/$id' - path: '/data/$id' - fullPath: '/data/$id' - preLoaderRoute: typeof DataIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - DataIdRoute: DataIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/solid-start' -declare module '@tanstack/solid-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/solid/src/router.tsx b/benchmarks/memory/server/scenarios/serialization-payload/solid/src/router.tsx deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/solid/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/serialization-payload/solid/src/routes/__root.tsx deleted file mode 100644 index aaf7dfdd89..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/solid/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/solid-router' -import { HydrationScript } from 'solid-js/web' - -export const Route = createRootRoute({ - head: () => ({ - meta: [{ charset: 'utf-8' }], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - - ) -} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/solid/src/routes/data.$id.tsx b/benchmarks/memory/server/scenarios/serialization-payload/solid/src/routes/data.$id.tsx deleted file mode 100644 index 8cdbdb9046..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/solid/src/routes/data.$id.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { makeSerializationPayload } from '../../../serialization-payload' - -export const Route = createFileRoute('/data/$id')({ - loader: ({ params }) => makeSerializationPayload(params.id), - component: DataComponent, -}) - -function DataComponent() { - const data = Route.useLoaderData() - - return ( -
- Map size: {data().lookup.size} -
- ) -} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/solid/tsconfig.json b/benchmarks/memory/server/scenarios/serialization-payload/solid/tsconfig.json deleted file mode 100644 index 4b61264e11..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/solid/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "allowImportingTsExtensions": true, - "jsx": "preserve", - "jsxImportSource": "solid-js", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/solid/vite.config.ts b/benchmarks/memory/server/scenarios/serialization-payload/solid/vite.config.ts deleted file mode 100644 index a2d04b986c..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/solid/vite.config.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - solid({ ssr: true, hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - ...memoryConfig('server'), - name: '@benchmarks/memory-server serialization-payload (solid)', - watch: false, - environment: 'node', - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/vue/memory.bench.ts b/benchmarks/memory/server/scenarios/serialization-payload/vue/memory.bench.ts deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/vue/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' -import { workloadGroup } from './setup' - -await workloadGroup.sanity() - -test('memory', async ({ bench }) => { - for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) - } -}) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/vue/memory.flame.ts b/benchmarks/memory/server/scenarios/serialization-payload/vue/memory.flame.ts deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/vue/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runServerFlameBenchmark } from '#memory-server/flame-runner' -import { workloadGroup } from './setup.ts' - -await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/vue/project.json b/benchmarks/memory/server/scenarios/serialization-payload/vue/project.json deleted file mode 100644 index 425b50a0d5..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/vue/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-server-serialization-payload-vue", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "build:ssr:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:ssr:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/vue/setup.ts b/benchmarks/memory/server/scenarios/serialization-payload/vue/setup.ts deleted file mode 100644 index 6683dafe6b..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/vue/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' -import { createWorkloadGroup } from '../shared.ts' -import type { StartRequestHandler } from '../shared.ts' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} - -export const workloadGroup: ServerMemoryWorkloadGroup = - await createWorkloadGroup('vue', handler) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/vue/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/serialization-payload/vue/src/routeTree.gen.ts deleted file mode 100644 index 8adce01d75..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,68 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as DataIdRouteImport } from './routes/data.$id' - -const DataIdRoute = DataIdRouteImport.update({ - id: '/data/$id', - path: '/data/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/data/$id': typeof DataIdRoute -} -export interface FileRoutesByTo { - '/data/$id': typeof DataIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/data/$id': typeof DataIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/data/$id' - fileRoutesByTo: FileRoutesByTo - to: '/data/$id' - id: '__root__' | '/data/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - DataIdRoute: typeof DataIdRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/data/$id': { - id: '/data/$id' - path: '/data/$id' - fullPath: '/data/$id' - preLoaderRoute: typeof DataIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - DataIdRoute: DataIdRoute, -} -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/benchmarks/memory/server/scenarios/serialization-payload/vue/src/router.tsx b/benchmarks/memory/server/scenarios/serialization-payload/vue/src/router.tsx deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/vue/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/serialization-payload/vue/src/routes/__root.tsx deleted file mode 100644 index de29ee1612..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/vue/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { - Body, - HeadContent, - Html, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/vue-router' - -export const Route = createRootRoute({ - head: () => ({ - meta: [{ charSet: 'utf-8' }], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} 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 deleted file mode 100644 index 37b1a590e4..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/vue/src/routes/data.$id.tsx +++ /dev/null @@ -1,20 +0,0 @@ -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, -}) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/vue/tsconfig.json b/benchmarks/memory/server/scenarios/serialization-payload/vue/tsconfig.json deleted file mode 100644 index 9ad6481342..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/vue/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "allowImportingTsExtensions": true, - "jsx": "preserve", - "jsxImportSource": "vue", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/vue/vite.config.ts b/benchmarks/memory/server/scenarios/serialization-payload/vue/vite.config.ts deleted file mode 100644 index b63a561228..0000000000 --- a/benchmarks/memory/server/scenarios/serialization-payload/vue/vite.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - ...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 deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/react/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' -import { workloadGroup } from './setup' - -await workloadGroup.sanity() - -test('memory', async ({ bench }) => { - for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) - } -}) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/react/memory.flame.ts b/benchmarks/memory/server/scenarios/server-fn-churn/react/memory.flame.ts deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/react/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runServerFlameBenchmark } from '#memory-server/flame-runner' -import { workloadGroup } from './setup.ts' - -await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/react/project.json b/benchmarks/memory/server/scenarios/server-fn-churn/react/project.json deleted file mode 100644 index 841bbedca0..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/react/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-server-server-fn-churn-react", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "build:ssr:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:ssr:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/react/setup.ts b/benchmarks/memory/server/scenarios/server-fn-churn/react/setup.ts deleted file mode 100644 index 0c98f54ddd..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/react/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' -import { createWorkloadGroup } from '../shared.ts' -import type { StartRequestHandler } from '../shared.ts' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} - -export const workloadGroup: ServerMemoryWorkloadGroup = - await createWorkloadGroup('react', handler) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/react/src/fns.ts b/benchmarks/memory/server/scenarios/server-fn-churn/react/src/fns.ts deleted file mode 100644 index 22770278cd..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/react/src/fns.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { createMiddleware, createServerFn } from '@tanstack/react-start' -import { - makeServerFnChurnPayload, - validateServerFnInput, -} from '../../server-fn-payload' - -const contextMiddleware = createMiddleware({ type: 'function' }).server( - ({ next }) => - next({ - context: { - ctx: 'ctx-server-fn-churn', - }, - }), -) - -export const churnGet = createServerFn({ method: 'GET' }) - .middleware([contextMiddleware]) - .validator(validateServerFnInput) - .handler(({ data, context }) => makeServerFnChurnPayload(data, context)) - -export const churnPost = createServerFn({ method: 'POST' }) - .middleware([contextMiddleware]) - .validator(validateServerFnInput) - .handler(({ data, context }) => makeServerFnChurnPayload(data, context)) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/react/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/server-fn-churn/react/src/routeTree.gen.ts deleted file mode 100644 index 10e933da3d..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/react/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as ApiFnUrlsRouteImport } from './routes/api.fn-urls' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ - id: '/api/fn-urls', - path: '/api/fn-urls', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/api/fn-urls' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/api/fn-urls' - id: '__root__' | '/' | '/api/fn-urls' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ApiFnUrlsRoute: typeof ApiFnUrlsRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/api/fn-urls': { - id: '/api/fn-urls' - path: '/api/fn-urls' - fullPath: '/api/fn-urls' - preLoaderRoute: typeof ApiFnUrlsRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ApiFnUrlsRoute: ApiFnUrlsRoute, -} -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/benchmarks/memory/server/scenarios/server-fn-churn/react/src/router.tsx b/benchmarks/memory/server/scenarios/server-fn-churn/react/src/router.tsx deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/react/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/server-fn-churn/react/src/routes/__root.tsx deleted file mode 100644 index c5f9de6922..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/react/src/routes/__root.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' - -export const Route = createRootRoute({ - head: () => ({ - meta: [{ charSet: 'utf-8' }], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/react/src/routes/api.fn-urls.ts b/benchmarks/memory/server/scenarios/server-fn-churn/react/src/routes/api.fn-urls.ts deleted file mode 100644 index da74a20f62..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/react/src/routes/api.fn-urls.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { churnGet, churnPost } from '../fns' - -export const Route = createFileRoute('/api/fn-urls')({ - server: { - handlers: { - GET: () => - Response.json({ - get: churnGet.url, - post: churnPost.url, - }), - }, - }, -}) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/react/src/routes/index.tsx b/benchmarks/memory/server/scenarios/server-fn-churn/react/src/routes/index.tsx deleted file mode 100644 index de0acfc2b3..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/react/src/routes/index.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { churnGet, churnPost } from '../fns' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return ( -
- memory-server-fn-churn-index -
- ) -} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/react/tsconfig.json b/benchmarks/memory/server/scenarios/server-fn-churn/react/tsconfig.json deleted file mode 100644 index 11ddcce4ea..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/react/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "allowImportingTsExtensions": true, - "jsx": "react-jsx", - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} 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 deleted file mode 100644 index f72cc53d6f..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/react/vite.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - ...memoryConfig('server'), - name: '@benchmarks/memory-server server-fn-churn (react)', - watch: false, - environment: 'node', - }, -}) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/server-fn-payload.ts b/benchmarks/memory/server/scenarios/server-fn-churn/server-fn-payload.ts deleted file mode 100644 index 0f23390a6c..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/server-fn-payload.ts +++ /dev/null @@ -1,33 +0,0 @@ -export type ServerFnInput = { - id: string -} - -export type ServerFnChurnContext = { - ctx: string -} - -const recordIndexes = Array.from({ length: 5 }, (_, index) => index) - -export function validateServerFnInput(input: unknown): ServerFnInput { - const payload = input as Partial | null - - if (typeof payload?.id !== 'string') { - throw new Error('invalid server-fn churn input') - } - - return { id: payload.id } -} - -export function makeServerFnChurnPayload( - data: ServerFnInput, - context: ServerFnChurnContext, -) { - return { - id: data.id, - ctx: context.ctx, - payload: recordIndexes.map((index) => ({ - id: `${data.id}-${index}`, - label: `record-${index}`, - })), - } -} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/shared.ts b/benchmarks/memory/server/scenarios/server-fn-churn/shared.ts deleted file mode 100644 index 167b24d3b6..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/shared.ts +++ /dev/null @@ -1,232 +0,0 @@ -import { - createDeterministicRandom, - randomSegment, - runSequentialRequestLoop, -} from '#memory-server/bench-utils' -import type { StartRequestHandler } from '#memory-server/bench-utils' - -export type { StartRequestHandler } - -type Framework = 'react' | 'solid' | 'vue' - -type FnUrls = { - get: string - post: string -} - -type PayloadFixture = { - id: string - body: string - query: string -} - -type SerovalNode = - | { - t: 1 - s: string - } - | { - t: 10 - i: number - p: { - k: Array - v: Array - } - o: number - } - -const benchmarkSeed = 0xdecafbad -const payloadSeed = 0x51f0cafe -const fixtureCount = 16 -const serverFnChurnIterations = 30 -const origin = 'http://localhost' -const tssContentTypeFramed = 'application/x-tss-framed' -const acceptHeader = `${tssContentTypeFramed}, application/x-ndjson, application/json` -const xTssSerialized = 'x-tss-serialized' -const contextMarker = 'ctx-server-fn-churn' - -const commonHeaders = { - 'x-tsr-serverFn': 'true', - 'sec-fetch-site': 'same-origin', - accept: acceptHeader, -} satisfies HeadersInit - -const postHeaders = { - ...commonHeaders, - 'content-type': 'application/json', -} satisfies HeadersInit - -// Hand-rolled copy of Start's seroval RPC wire format so POST bodies can be -// precomputed at module level. Coupled to the internal protocol on purpose; -// the module-load sanity check below throws loudly if the protocol drifts. -function stringNode(value: string): SerovalNode { - return { t: 1, s: value } -} - -function objectNode( - id: number, - entries: Array, -): SerovalNode { - return { - t: 10, - i: id, - p: { - k: entries.map(([key]) => key), - v: entries.map(([, value]) => value), - }, - o: 0, - } -} - -function serializePayload(id: string) { - return JSON.stringify({ - t: objectNode(0, [['data', objectNode(1, [['id', stringNode(id)]])]]), - f: 63, - m: [], - }) -} - -function createFixtures(kind: 'get' | 'post') { - const random = createDeterministicRandom(payloadSeed ^ kind.length) - - return Array.from({ length: fixtureCount }, (_, index): PayloadFixture => { - const id = [kind, index, randomSegment(random), randomSegment(random)].join( - '-', - ) - const body = serializePayload(id) - - return { - id, - body, - query: `?${new URLSearchParams({ payload: body })}`, - } - }) -} - -const getFixtures = createFixtures('get') -const postFixtures = createFixtures('post') - -async function discoverUrls(handler: StartRequestHandler) { - const response = await handler.fetch(new Request(`${origin}/api/fn-urls`)) - const text = await response.text() - - if (response.status !== 200) { - throw new Error( - `URL discovery failed with status ${response.status}: ${text}`, - ) - } - - let urls: Partial - - try { - urls = JSON.parse(text) as Partial - } catch (error) { - throw new Error(`URL discovery returned invalid JSON: ${text}`, { - cause: error, - }) - } - - if (typeof urls.get !== 'string' || typeof urls.post !== 'string') { - throw new Error(`URL discovery returned invalid payload: ${text}`) - } - - return urls as FnUrls -} - -function buildGetRequest(url: string, fixture: PayloadFixture) { - return new Request(`${origin}${url}${fixture.query}`, { - method: 'GET', - headers: commonHeaders, - }) -} - -function buildPostRequest(url: string, fixture: PayloadFixture) { - return new Request(`${origin}${url}`, { - method: 'POST', - headers: postHeaders, - body: fixture.body, - }) -} - -function validateServerFnResponse(response: Response, request: Request) { - if (response.status !== 200) { - throw new Error( - `Expected status 200 for ${request.url}, got ${response.status}`, - ) - } - - if (!response.headers.get(xTssSerialized)) { - throw new Error(`Expected ${xTssSerialized} header for ${request.url}`) - } -} - -function validateEchoedBody( - body: string, - request: Request, - expectedId: string, -) { - if (!body.includes(expectedId)) { - throw new Error(`Expected echoed id ${expectedId} in ${request.url}`) - } - - if (!body.includes(contextMarker)) { - throw new Error( - `Expected context marker ${contextMarker} in ${request.url}`, - ) - } -} - -async function assertServerFnChurnSanity( - handler: StartRequestHandler, - urls: FnUrls, -) { - const getFixture = getFixtures[0]! - const getRequest = buildGetRequest(urls.get, getFixture) - const getResponse = await handler.fetch(getRequest) - const getBody = await getResponse.text() - - validateServerFnResponse(getResponse, getRequest) - validateEchoedBody(getBody, getRequest, getFixture.id) - - const postFixture = postFixtures[0]! - const postRequest = buildPostRequest(urls.post, postFixture) - const postResponse = await handler.fetch(postRequest) - const postBody = await postResponse.text() - - validateServerFnResponse(postResponse, postRequest) - validateEchoedBody(postBody, postRequest, postFixture.id) -} - -export async function createWorkloadGroup( - framework: Framework, - handler: StartRequestHandler, -) { - const urls = await discoverUrls(handler) - const run = async () => - runSequentialRequestLoop(handler, { - seed: benchmarkSeed, - iterations: serverFnChurnIterations, - buildRequest: (_random, index) => { - const fixtureIndex = Math.floor(index / 2) % fixtureCount - - if (index % 2 === 0) { - const fixture = getFixtures[fixtureIndex]! - return buildGetRequest(urls.get, fixture) - } else { - const fixture = postFixtures[fixtureIndex]! - return buildPostRequest(urls.post, fixture) - } - }, - validateResponse: validateServerFnResponse, - }) - - return { - sanity: () => assertServerFnChurnSanity(handler, urls), - workloads: [ - { - name: `mem server server-fn-churn (${framework})`, - run, - }, - ], - } -} 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 deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/solid/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' -import { workloadGroup } from './setup' - -await workloadGroup.sanity() - -test('memory', async ({ bench }) => { - for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) - } -}) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/solid/memory.flame.ts b/benchmarks/memory/server/scenarios/server-fn-churn/solid/memory.flame.ts deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/solid/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runServerFlameBenchmark } from '#memory-server/flame-runner' -import { workloadGroup } from './setup.ts' - -await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/solid/project.json b/benchmarks/memory/server/scenarios/server-fn-churn/solid/project.json deleted file mode 100644 index 53aca0cea6..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/solid/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-server-server-fn-churn-solid", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "build:ssr:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:ssr:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/solid/setup.ts b/benchmarks/memory/server/scenarios/server-fn-churn/solid/setup.ts deleted file mode 100644 index 4fe85c3f00..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/solid/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' -import { createWorkloadGroup } from '../shared.ts' -import type { StartRequestHandler } from '../shared.ts' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} - -export const workloadGroup: ServerMemoryWorkloadGroup = - await createWorkloadGroup('solid', handler) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/fns.ts b/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/fns.ts deleted file mode 100644 index 31669dff50..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/fns.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { createMiddleware, createServerFn } from '@tanstack/solid-start' -import { - makeServerFnChurnPayload, - validateServerFnInput, -} from '../../server-fn-payload' - -const contextMiddleware = createMiddleware({ type: 'function' }).server( - ({ next }) => - next({ - context: { - ctx: 'ctx-server-fn-churn', - }, - }), -) - -export const churnGet = createServerFn({ method: 'GET' }) - .middleware([contextMiddleware]) - .validator(validateServerFnInput) - .handler(({ data, context }) => makeServerFnChurnPayload(data, context)) - -export const churnPost = createServerFn({ method: 'POST' }) - .middleware([contextMiddleware]) - .validator(validateServerFnInput) - .handler(({ data, context }) => makeServerFnChurnPayload(data, context)) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/routeTree.gen.ts deleted file mode 100644 index 298ac3168d..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as ApiFnUrlsRouteImport } from './routes/api.fn-urls' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ - id: '/api/fn-urls', - path: '/api/fn-urls', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/api/fn-urls' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/api/fn-urls' - id: '__root__' | '/' | '/api/fn-urls' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ApiFnUrlsRoute: typeof ApiFnUrlsRoute -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/api/fn-urls': { - id: '/api/fn-urls' - path: '/api/fn-urls' - fullPath: '/api/fn-urls' - preLoaderRoute: typeof ApiFnUrlsRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ApiFnUrlsRoute: ApiFnUrlsRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/solid-start' -declare module '@tanstack/solid-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/router.tsx b/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/router.tsx deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/routes/__root.tsx deleted file mode 100644 index aaf7dfdd89..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/solid-router' -import { HydrationScript } from 'solid-js/web' - -export const Route = createRootRoute({ - head: () => ({ - meta: [{ charset: 'utf-8' }], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - - ) -} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/routes/api.fn-urls.ts b/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/routes/api.fn-urls.ts deleted file mode 100644 index 2063684034..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/routes/api.fn-urls.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { churnGet, churnPost } from '../fns' - -export const Route = createFileRoute('/api/fn-urls')({ - server: { - handlers: { - GET: () => - Response.json({ - get: churnGet.url, - post: churnPost.url, - }), - }, - }, -}) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/routes/index.tsx b/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/routes/index.tsx deleted file mode 100644 index 99fea371f8..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/routes/index.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { churnGet, churnPost } from '../fns' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return ( -
- memory-server-fn-churn-index -
- ) -} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/solid/tsconfig.json b/benchmarks/memory/server/scenarios/server-fn-churn/solid/tsconfig.json deleted file mode 100644 index 4b61264e11..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/solid/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "allowImportingTsExtensions": true, - "jsx": "preserve", - "jsxImportSource": "solid-js", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} 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 deleted file mode 100644 index 4fba196bd2..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/solid/vite.config.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - solid({ ssr: true, hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - ...memoryConfig('server'), - name: '@benchmarks/memory-server server-fn-churn (solid)', - watch: false, - environment: 'node', - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) 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 deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/vue/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' -import { workloadGroup } from './setup' - -await workloadGroup.sanity() - -test('memory', async ({ bench }) => { - for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) - } -}) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/vue/memory.flame.ts b/benchmarks/memory/server/scenarios/server-fn-churn/vue/memory.flame.ts deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/vue/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runServerFlameBenchmark } from '#memory-server/flame-runner' -import { workloadGroup } from './setup.ts' - -await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/vue/project.json b/benchmarks/memory/server/scenarios/server-fn-churn/vue/project.json deleted file mode 100644 index c5809a259b..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/vue/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-server-server-fn-churn-vue", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "build:ssr:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:ssr:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/vue/setup.ts b/benchmarks/memory/server/scenarios/server-fn-churn/vue/setup.ts deleted file mode 100644 index 6683dafe6b..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/vue/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' -import { createWorkloadGroup } from '../shared.ts' -import type { StartRequestHandler } from '../shared.ts' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} - -export const workloadGroup: ServerMemoryWorkloadGroup = - await createWorkloadGroup('vue', handler) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/fns.ts b/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/fns.ts deleted file mode 100644 index 0fa679f76f..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/fns.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { createMiddleware, createServerFn } from '@tanstack/vue-start' -import { - makeServerFnChurnPayload, - validateServerFnInput, -} from '../../server-fn-payload' - -const contextMiddleware = createMiddleware({ type: 'function' }).server( - ({ next }) => - next({ - context: { - ctx: 'ctx-server-fn-churn', - }, - }), -) - -export const churnGet = createServerFn({ method: 'GET' }) - .middleware([contextMiddleware]) - .validator(validateServerFnInput) - .handler(({ data, context }) => makeServerFnChurnPayload(data, context)) - -export const churnPost = createServerFn({ method: 'POST' }) - .middleware([contextMiddleware]) - .validator(validateServerFnInput) - .handler(({ data, context }) => makeServerFnChurnPayload(data, context)) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/routeTree.gen.ts deleted file mode 100644 index b226f0a25a..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as ApiFnUrlsRouteImport } from './routes/api.fn-urls' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ - id: '/api/fn-urls', - path: '/api/fn-urls', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/api/fn-urls' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/api/fn-urls' - id: '__root__' | '/' | '/api/fn-urls' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ApiFnUrlsRoute: typeof ApiFnUrlsRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/api/fn-urls': { - id: '/api/fn-urls' - path: '/api/fn-urls' - fullPath: '/api/fn-urls' - preLoaderRoute: typeof ApiFnUrlsRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ApiFnUrlsRoute: ApiFnUrlsRoute, -} -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/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/router.tsx b/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/router.tsx deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/routes/__root.tsx deleted file mode 100644 index de29ee1612..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { - Body, - HeadContent, - Html, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/vue-router' - -export const Route = createRootRoute({ - head: () => ({ - meta: [{ charSet: 'utf-8' }], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/routes/api.fn-urls.ts b/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/routes/api.fn-urls.ts deleted file mode 100644 index ff99e89e4c..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/routes/api.fn-urls.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' -import { churnGet, churnPost } from '../fns' - -export const Route = createFileRoute('/api/fn-urls')({ - server: { - handlers: { - GET: () => - Response.json({ - get: churnGet.url, - post: churnPost.url, - }), - }, - }, -}) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/routes/index.tsx b/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/routes/index.tsx deleted file mode 100644 index 0a39b9301c..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/routes/index.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' -import { churnGet, churnPost } from '../fns' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return ( -
- memory-server-fn-churn-index -
- ) -} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/vue/tsconfig.json b/benchmarks/memory/server/scenarios/server-fn-churn/vue/tsconfig.json deleted file mode 100644 index 9ad6481342..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/vue/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "allowImportingTsExtensions": true, - "jsx": "preserve", - "jsxImportSource": "vue", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} 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 deleted file mode 100644 index 5ab5ec37e3..0000000000 --- a/benchmarks/memory/server/scenarios/server-fn-churn/vue/vite.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - ...memoryConfig('server'), - name: '@benchmarks/memory-server server-fn-churn (vue)', - watch: false, - environment: 'node', - }, -}) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/deferred-section-data.ts b/benchmarks/memory/server/scenarios/streaming-peak/deferred-section-data.ts deleted file mode 100644 index b30352ef39..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/deferred-section-data.ts +++ /dev/null @@ -1,37 +0,0 @@ -const deferredRecordCount = 250 -const recordValueLength = 128 - -interface DeferredRecord { - id: string - value: string -} - -export interface DeferredSectionPayload { - index: number - records: Array -} - -export function makeDeferredSectionPayload( - id: string, - sectionIndex: number, -): DeferredSectionPayload { - return { - index: sectionIndex, - records: Array.from({ length: deferredRecordCount }, (_, recordIndex) => ({ - id: `${id}-${sectionIndex}-${recordIndex}`, - value: makeRecordValue(id, sectionIndex, recordIndex), - })), - } -} - -function makeRecordValue( - id: string, - sectionIndex: number, - recordIndex: number, -) { - const token = `${id}:${sectionIndex}:${recordIndex}:streaming-peak-record;` - - return token - .repeat(Math.ceil(recordValueLength / token.length)) - .slice(0, recordValueLength) -} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/react/memory.bench.ts b/benchmarks/memory/server/scenarios/streaming-peak/react/memory.bench.ts deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' -import { workloadGroup } from './setup' - -await workloadGroup.sanity() - -test('memory', async ({ bench }) => { - for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) - } -}) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/react/memory.flame.ts b/benchmarks/memory/server/scenarios/streaming-peak/react/memory.flame.ts deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runServerFlameBenchmark } from '#memory-server/flame-runner' -import { workloadGroup } from './setup.ts' - -await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/react/project.json b/benchmarks/memory/server/scenarios/streaming-peak/react/project.json deleted file mode 100644 index 6fc1dcdda0..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-server-streaming-peak-react", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "build:ssr:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:ssr:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/react/setup.ts b/benchmarks/memory/server/scenarios/streaming-peak/react/setup.ts deleted file mode 100644 index 0c98f54ddd..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' -import { createWorkloadGroup } from '../shared.ts' -import type { StartRequestHandler } from '../shared.ts' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} - -export const workloadGroup: ServerMemoryWorkloadGroup = - await createWorkloadGroup('react', handler) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/react/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/streaming-peak/react/src/routeTree.gen.ts deleted file mode 100644 index fbbc25ecfb..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as StreamIdRouteImport } from './routes/stream.$id' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const StreamIdRoute = StreamIdRouteImport.update({ - id: '/stream/$id', - path: '/stream/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/stream/$id': typeof StreamIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/stream/$id': typeof StreamIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/stream/$id': typeof StreamIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/stream/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/stream/$id' - id: '__root__' | '/' | '/stream/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - StreamIdRoute: typeof StreamIdRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/stream/$id': { - id: '/stream/$id' - path: '/stream/$id' - fullPath: '/stream/$id' - preLoaderRoute: typeof StreamIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - StreamIdRoute: StreamIdRoute, -} -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/benchmarks/memory/server/scenarios/streaming-peak/react/src/router.tsx b/benchmarks/memory/server/scenarios/streaming-peak/react/src/router.tsx deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/react/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/streaming-peak/react/src/routes/__root.tsx deleted file mode 100644 index c5f9de6922..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/src/routes/__root.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' - -export const Route = createRootRoute({ - head: () => ({ - meta: [{ charSet: 'utf-8' }], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/react/src/routes/index.tsx b/benchmarks/memory/server/scenarios/streaming-peak/react/src/routes/index.tsx deleted file mode 100644 index 669fdef2e1..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
streaming-peak-index
-} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/react/src/routes/stream.$id.tsx b/benchmarks/memory/server/scenarios/streaming-peak/react/src/routes/stream.$id.tsx deleted file mode 100644 index 886cb64d45..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/src/routes/stream.$id.tsx +++ /dev/null @@ -1,98 +0,0 @@ -import { Await, createFileRoute } from '@tanstack/react-router' -import { Suspense } from 'react' -import { - makeDeferredSectionPayload, - type DeferredSectionPayload, -} from '../../../deferred-section-data' - -const fallbackFlushTicks = 4 - -export const Route = createFileRoute('/stream/$id')({ - loader: ({ params }) => ({ - eager: `streaming-peak-eager-${params.id}`, - deferred0: makeDeferredSection(params.id, 0), - deferred1: makeDeferredSection(params.id, 1), - deferred2: makeDeferredSection(params.id, 2), - deferred3: makeDeferredSection(params.id, 3), - }), - component: StreamComponent, -}) - -// Deferred sections must settle strictly AFTER React's shell flush, which -// React schedules via setImmediate internally. Microtask chains drain during -// router load (sections resolve before the Suspense boundaries are even -// reached) and setImmediate chains registered at loader time win the race -// against React's flush — either way no fallback ever streams and the bench -// stops exercising multi-flush streaming. Timers-phase callbacks reliably -// lose that race, but a millisecond delay makes the loss margin wall-clock -// dependent, so this chains 0ms hops instead: each hop yields one full -// event-loop turn (immediates and microtasks included), making the flush -// ordering a function of turn count, not runner speed. Distinct hop counts -// keep section ordering deterministic. -function afterFallbackFlush(sectionIndex: number) { - return new Promise((resolve) => { - let remaining = fallbackFlushTicks + sectionIndex - - const step = () => { - remaining -= 1 - - if (remaining <= 0) { - resolve() - return - } - - setTimeout(step, 0) - } - - setTimeout(step, 0) - }) -} - -function makeDeferredSection(id: string, sectionIndex: number) { - return afterFallbackFlush(sectionIndex).then(() => - makeDeferredSectionPayload(id, sectionIndex), - ) -} - -function StreamComponent() { - const data = Route.useLoaderData() - const deferredSections = [ - { index: 0, promise: data.deferred0 }, - { index: 1, promise: data.deferred1 }, - { index: 2, promise: data.deferred2 }, - { index: 3, promise: data.deferred3 }, - ] as const - - return ( -
-

{data.eager}

- {deferredSections.map(({ index, promise }) => ( - - streaming-peak-fallback-{index} -

- } - > - - {(section) => } - -
- ))} -
- ) -} - -function DeferredSection({ section }: { section: DeferredSectionPayload }) { - const marker = `streaming-peak-deferred-${section.index}` - - return ( -
-

{marker}

- {section.records.map((record) => ( -

{record.value}

- ))} -
- ) -} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/react/tsconfig.json b/benchmarks/memory/server/scenarios/streaming-peak/react/tsconfig.json deleted file mode 100644 index 11ddcce4ea..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "allowImportingTsExtensions": true, - "jsx": "react-jsx", - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/react/vite.config.ts b/benchmarks/memory/server/scenarios/streaming-peak/react/vite.config.ts deleted file mode 100644 index 5d555441b6..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/vite.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - ...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 deleted file mode 100644 index c027047408..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/shared.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { - randomSegment, - runSequentialRequestLoop, -} from '#memory-server/bench-utils' -import type { StartRequestHandler } from '#memory-server/bench-utils' - -export type { StartRequestHandler } - -type Framework = 'react' | 'solid' | 'vue' - -const benchmarkSeed = 0xdecafbad -const streamingPeakIterations = 1 -const fallbackMarker = 'streaming-peak-fallback-0' - -const requestInit = { - method: 'GET', - headers: { - accept: 'text/html', - }, -} satisfies RequestInit - -function buildStreamingRequest(random: () => number, index: number) { - return new Request( - `http://localhost/stream/${index}-${randomSegment(random)}`, - requestInit, - ) -} - -function validateStreamingResponse(response: Response, request: Request) { - if (response.status !== 200) { - throw new Error( - `Expected status 200 for ${request.url}, got ${response.status}`, - ) - } -} - -function getResponseReader(response: Response) { - const reader = response.body?.getReader() - - if (!reader) { - throw new Error('Expected streaming response body') - } - - return reader -} - -async function readStreamingBody(response: Response) { - const reader = getResponseReader(response) - const decoder = new TextDecoder() - let body = '' - let chunkCount = 0 - - for (;;) { - const result = await reader.read() - - if (result.done) { - break - } - - chunkCount++ - body += decoder.decode(result.value, { stream: true }) - } - - body += decoder.decode() - - return { body, chunkCount } -} - -async function assertStreamingPeakSanity(handler: StartRequestHandler) { - const chunkedRequest = new Request( - 'http://localhost/stream/sanity-chunked', - requestInit, - ) - const chunkedResponse = await handler.fetch(chunkedRequest) - - validateStreamingResponse(chunkedResponse, chunkedRequest) - - const chunked = await readStreamingBody(chunkedResponse) - - if (chunked.chunkCount <= 1) { - throw new Error( - `Expected chunked sanity response to produce multiple chunks, got ${chunked.chunkCount}`, - ) - } - - if (!chunked.body.includes(fallbackMarker)) { - throw new Error('Expected streaming-peak fallback marker in response body') - } -} - -export function createWorkloadGroup( - framework: Framework, - handler: StartRequestHandler, -) { - const run = async () => - runSequentialRequestLoop(handler, { - seed: benchmarkSeed, - iterations: streamingPeakIterations, - buildRequest: buildStreamingRequest, - validateResponse: validateStreamingResponse, - }) - - return { - sanity: async () => { - // Import the route chunks before checking streaming. Cold disk I/O can - // otherwise outlast the deferred payload and collapse the first response. - await run() - await assertStreamingPeakSanity(handler) - }, - workloads: [ - { - name: `mem server streaming-peak chunked (${framework})`, - run, - }, - ], - } -} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/solid/memory.bench.ts b/benchmarks/memory/server/scenarios/streaming-peak/solid/memory.bench.ts deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' -import { workloadGroup } from './setup' - -await workloadGroup.sanity() - -test('memory', async ({ bench }) => { - for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) - } -}) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/solid/memory.flame.ts b/benchmarks/memory/server/scenarios/streaming-peak/solid/memory.flame.ts deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runServerFlameBenchmark } from '#memory-server/flame-runner' -import { workloadGroup } from './setup.ts' - -await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/solid/project.json b/benchmarks/memory/server/scenarios/streaming-peak/solid/project.json deleted file mode 100644 index 80f44d1063..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-server-streaming-peak-solid", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "build:ssr:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:ssr:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/solid/setup.ts b/benchmarks/memory/server/scenarios/streaming-peak/solid/setup.ts deleted file mode 100644 index 4fe85c3f00..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' -import { createWorkloadGroup } from '../shared.ts' -import type { StartRequestHandler } from '../shared.ts' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} - -export const workloadGroup: ServerMemoryWorkloadGroup = - await createWorkloadGroup('solid', handler) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routeTree.gen.ts deleted file mode 100644 index 04ebed80f0..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as StreamIdRouteImport } from './routes/stream.$id' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const StreamIdRoute = StreamIdRouteImport.update({ - id: '/stream/$id', - path: '/stream/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/stream/$id': typeof StreamIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/stream/$id': typeof StreamIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/stream/$id': typeof StreamIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/stream/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/stream/$id' - id: '__root__' | '/' | '/stream/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - StreamIdRoute: typeof StreamIdRoute -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/stream/$id': { - id: '/stream/$id' - path: '/stream/$id' - fullPath: '/stream/$id' - preLoaderRoute: typeof StreamIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - StreamIdRoute: StreamIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/solid-start' -declare module '@tanstack/solid-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/solid/src/router.tsx b/benchmarks/memory/server/scenarios/streaming-peak/solid/src/router.tsx deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routes/__root.tsx deleted file mode 100644 index aaf7dfdd89..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/solid-router' -import { HydrationScript } from 'solid-js/web' - -export const Route = createRootRoute({ - head: () => ({ - meta: [{ charset: 'utf-8' }], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - - ) -} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routes/index.tsx b/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routes/index.tsx deleted file mode 100644 index 5815e36b3d..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
streaming-peak-index
-} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routes/stream.$id.tsx b/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routes/stream.$id.tsx deleted file mode 100644 index 977f43061e..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routes/stream.$id.tsx +++ /dev/null @@ -1,91 +0,0 @@ -import { Await, createFileRoute } from '@tanstack/solid-router' -import { Suspense } from 'solid-js' -import { - makeDeferredSectionPayload, - type DeferredSectionPayload, -} from '../../../deferred-section-data' - -const fallbackFlushTicks = 12 - -export const Route = createFileRoute('/stream/$id')({ - loader: ({ params }) => ({ - eager: `streaming-peak-eager-${params.id}`, - deferred0: makeDeferredSection(params.id, 0), - deferred1: makeDeferredSection(params.id, 1), - deferred2: makeDeferredSection(params.id, 2), - deferred3: makeDeferredSection(params.id, 3), - }), - component: StreamComponent, -}) - -// Deferred sections must settle after the framework shell flush so the bench -// continues exercising multi-flush streaming with visible fallback chunks. -// Chained 0ms timers-phase hops give the renderer a deterministic number of -// full event-loop turns to flush, instead of a wall-clock delay whose margin -// varies with runner load; distinct hop counts keep section ordering stable. -function afterFallbackFlush(sectionIndex: number) { - return new Promise((resolve) => { - let remaining = fallbackFlushTicks + sectionIndex - - const step = () => { - remaining -= 1 - - if (remaining <= 0) { - resolve() - return - } - - setTimeout(step, 0) - } - - setTimeout(step, 0) - }) -} - -function makeDeferredSection(id: string, sectionIndex: number) { - return afterFallbackFlush(sectionIndex).then(() => - makeDeferredSectionPayload(id, sectionIndex), - ) -} - -function StreamComponent() { - const data = Route.useLoaderData() - const deferredSections = () => - [ - { index: 0, promise: data().deferred0 }, - { index: 1, promise: data().deferred1 }, - { index: 2, promise: data().deferred2 }, - { index: 3, promise: data().deferred3 }, - ] as const - - return ( -
-

{data().eager}

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

- streaming-peak-fallback-{index} -

- - - {(section) => } - - - - ))} -
- ) -} - -function DeferredSection(props: { section: DeferredSectionPayload }) { - const marker = () => `streaming-peak-deferred-${props.section.index}` - - return ( -
-

{marker()}

- {props.section.records.map((record) => ( -

{record.value}

- ))} -
- ) -} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/solid/tsconfig.json b/benchmarks/memory/server/scenarios/streaming-peak/solid/tsconfig.json deleted file mode 100644 index 4b61264e11..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "allowImportingTsExtensions": true, - "jsx": "preserve", - "jsxImportSource": "solid-js", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/solid/vite.config.ts b/benchmarks/memory/server/scenarios/streaming-peak/solid/vite.config.ts deleted file mode 100644 index 5fbdb48c23..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/vite.config.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - solid({ ssr: true, hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - ...memoryConfig('server'), - name: '@benchmarks/memory-server streaming-peak (solid)', - watch: false, - environment: 'node', - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/vue/memory.bench.ts b/benchmarks/memory/server/scenarios/streaming-peak/vue/memory.bench.ts deleted file mode 100644 index 8b5f16ad63..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/memory.bench.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' -import { workloadGroup } from './setup' - -await workloadGroup.sanity() - -test('memory', async ({ bench }) => { - for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) - } -}) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/vue/memory.flame.ts b/benchmarks/memory/server/scenarios/streaming-peak/vue/memory.flame.ts deleted file mode 100644 index 0182c472a8..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/memory.flame.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { runServerFlameBenchmark } from '#memory-server/flame-runner' -import { workloadGroup } from './setup.ts' - -await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/vue/project.json b/benchmarks/memory/server/scenarios/streaming-peak/vue/project.json deleted file mode 100644 index 55771aebe3..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/project.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "@benchmarks/memory-server-streaming-peak-vue", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "build:ssr:flame": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" - } - }, - "test:flame": { - "executor": "nx:run-commands", - "parallelism": false, - "cache": false, - "dependsOn": ["build:ssr:flame"], - "options": { - "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", - "cwd": "." - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/vue/setup.ts b/benchmarks/memory/server/scenarios/streaming-peak/vue/setup.ts deleted file mode 100644 index 6683dafe6b..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/setup.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' -import { createWorkloadGroup } from '../shared.ts' -import type { StartRequestHandler } from '../shared.ts' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} - -export const workloadGroup: ServerMemoryWorkloadGroup = - await createWorkloadGroup('vue', handler) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routeTree.gen.ts deleted file mode 100644 index 192f1d6dc7..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as StreamIdRouteImport } from './routes/stream.$id' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const StreamIdRoute = StreamIdRouteImport.update({ - id: '/stream/$id', - path: '/stream/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/stream/$id': typeof StreamIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/stream/$id': typeof StreamIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/stream/$id': typeof StreamIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/stream/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/stream/$id' - id: '__root__' | '/' | '/stream/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - StreamIdRoute: typeof StreamIdRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/stream/$id': { - id: '/stream/$id' - path: '/stream/$id' - fullPath: '/stream/$id' - preLoaderRoute: typeof StreamIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - StreamIdRoute: StreamIdRoute, -} -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/benchmarks/memory/server/scenarios/streaming-peak/vue/src/router.tsx b/benchmarks/memory/server/scenarios/streaming-peak/vue/src/router.tsx deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routes/__root.tsx deleted file mode 100644 index de29ee1612..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { - Body, - HeadContent, - Html, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/vue-router' - -export const Route = createRootRoute({ - head: () => ({ - meta: [{ charSet: 'utf-8' }], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routes/index.tsx b/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routes/index.tsx deleted file mode 100644 index bc55b49adc..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
streaming-peak-index
-} 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 deleted file mode 100644 index 750d1cb47d..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routes/stream.$id.tsx +++ /dev/null @@ -1,103 +0,0 @@ -import { Await, createFileRoute } from '@tanstack/vue-router' -import { Suspense, defineComponent } from 'vue' -import { - makeDeferredSectionPayload, - type DeferredSectionPayload, -} from '../../../deferred-section-data' - -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}`, - deferred0: makeDeferredSection(params.id, 0), - deferred1: makeDeferredSection(params.id, 1), - deferred2: makeDeferredSection(params.id, 2), - deferred3: makeDeferredSection(params.id, 3), - }), - component: StreamComponent, -}) - -// Deferred sections must settle strictly AFTER Vue's shell has a chance to -// flush, so fallbacks are emitted before deferred section content. -// Chained 0ms timers-phase hops give the renderer a deterministic number of -// full event-loop turns to flush, instead of a wall-clock delay whose margin -// varies with runner load; distinct hop counts keep section ordering stable. -function afterFallbackFlush(sectionIndex: number) { - return new Promise((resolve) => { - let remaining = fallbackFlushTicks + sectionIndex - - const step = () => { - remaining -= 1 - - if (remaining <= 0) { - resolve() - return - } - - setTimeout(step, 0) - } - - setTimeout(step, 0) - }) -} - -function makeDeferredSection(id: string, sectionIndex: number) { - return afterFallbackFlush(sectionIndex).then(() => - makeDeferredSectionPayload(id, sectionIndex), - ) -} - -function DeferredSection({ section }: { section: DeferredSectionPayload }) { - const marker = `streaming-peak-deferred-${section.index}` - - return ( -
-

{marker}

- {section.records.map((record) => ( -

{record.value}

- ))} -
- ) -} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/vue/tsconfig.json b/benchmarks/memory/server/scenarios/streaming-peak/vue/tsconfig.json deleted file mode 100644 index 9ad6481342..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "extends": "../../../../../../tsconfig.json", - "compilerOptions": { - "allowImportingTsExtensions": true, - "jsx": "preserve", - "jsxImportSource": "vue", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "memory.bench.ts", - "memory.flame.ts", - "setup.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/vue/vite.config.ts b/benchmarks/memory/server/scenarios/streaming-peak/vue/vite.config.ts deleted file mode 100644 index cd848584a5..0000000000 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/vite.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - ...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 deleted file mode 100644 index 86d36f047a..0000000000 --- a/benchmarks/memory/server/tsconfig.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "extends": "../../../tsconfig.json", - "compilerOptions": { - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "bench-utils.ts", - "scenarios/*/shared.ts", - "../runtime.ts", - "vitest.setup.ts" - ] -} diff --git a/benchmarks/memory/server/vitest.react.config.ts b/benchmarks/memory/server/vitest.react.config.ts deleted file mode 100644 index 44643b4d60..0000000000 --- a/benchmarks/memory/server/vitest.react.config.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { defineConfig } from 'vitest/config' - -export default defineConfig({ - test: { - watch: false, - fileParallelism: false, - projects: ['./scenarios/*/react/vite.config.ts'], - }, -}) diff --git a/benchmarks/memory/server/vitest.solid.config.ts b/benchmarks/memory/server/vitest.solid.config.ts deleted file mode 100644 index 5c8185cdd9..0000000000 --- a/benchmarks/memory/server/vitest.solid.config.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { defineConfig } from 'vitest/config' - -export default defineConfig({ - test: { - watch: false, - fileParallelism: false, - projects: ['./scenarios/*/solid/vite.config.ts'], - }, -}) diff --git a/benchmarks/memory/server/vitest.vue.config.ts b/benchmarks/memory/server/vitest.vue.config.ts deleted file mode 100644 index 01768185ee..0000000000 --- a/benchmarks/memory/server/vitest.vue.config.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { defineConfig } from 'vitest/config' - -export default defineConfig({ - test: { - watch: false, - fileParallelism: false, - projects: ['./scenarios/*/vue/vite.config.ts'], - }, -}) diff --git a/benchmarks/memory/tsconfig.json b/benchmarks/memory/tsconfig.json deleted file mode 100644 index 5a325f3b6c..0000000000 --- a/benchmarks/memory/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "../../tsconfig.json", - "compilerOptions": { - "types": ["node"] - }, - "include": ["runtime.ts"] -} diff --git a/benchmarks/memory/turn.ts b/benchmarks/memory/turn.ts deleted file mode 100644 index 08729685fe..0000000000 --- a/benchmarks/memory/turn.ts +++ /dev/null @@ -1,34 +0,0 @@ -export function isMemoryInstrumented() { - return ( - process.env.CODSPEED_ENV !== undefined && - process.env.CODSPEED_RUNNER_MODE === 'memory' - ) -} - -// CodSpeed calls beforeEach before its forced GC and measurement marker. End -// the previous warmup's job so WeakRef targets can be released by that GC. -export function endMemoryTurn() { - return new Promise((resolve) => setImmediate(resolve)) -} - -/** - * Per-invocation bench hooks. CodSpeed runs them around every warmup - * invocation and the measured one, outside the measurement marker: the turn - * ends first, then the workload prepares fresh state before the forced GC. - */ -export function memoryBenchHooks( - workload: { - before?: () => Promise | void - after?: () => Promise | void - } = {}, -) { - return { - async beforeEach() { - if (isMemoryInstrumented()) { - await endMemoryTurn() - } - await workload.before?.() - }, - afterEach: workload.after, - } -} diff --git a/benchmarks/ssr/README.md b/benchmarks/ssr/README.md deleted file mode 100644 index 3d90af1598..0000000000 --- a/benchmarks/ssr/README.md +++ /dev/null @@ -1,115 +0,0 @@ -# SSR Benchmarks - -Cross-framework SSR request-loop benchmarks for: - -- `@tanstack/react-start` -- `@tanstack/solid-start` -- `@tanstack/vue-start` - -Each benchmark builds a Start app with file-based routes and runs Vitest benches against the built server handler. - -## Layout - -- `react/` - React Start baseline benchmark + Vitest config -- `solid/` - Solid Start baseline benchmark + Vitest config -- `vue/` - Vue Start baseline benchmark + Vitest config -- `vitest.react.config.ts`, `vitest.solid.config.ts`, `vitest.vue.config.ts` - per-framework aggregate configs that run the baseline first, then scenario projects -- `scenarios///` - isolated scenario apps - -Scenario app layout: - -```text -scenarios/// - vite.config.ts - speed.bench.ts - tsconfig.json - src/ - router.tsx - routes/ - routeTree.gen.ts -``` - -Each scenario uses one app per framework instead of sharing routes in the baseline app. This keeps route-tree size, middleware, Start options, and generated route trees isolated so one scenario cannot shift another scenario's numbers. The existing baseline apps and bench names stay stable for CodSpeed continuity. - -## Scenario Responsibilities - -Each scenario isolates one Start server-side responsibility so benchmark changes can be attributed to a specific feature area. - -| Scenario | Start server-side responsibility | -| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `react/`, `solid/`, `vue/` baseline apps | Document SSR for nested file routes, route matching, search parsing, and full-page HTML response generation. | -| `assets` | Per-request asset pipeline work: CSS inlining, CDN asset URL transforms with uncached manifest resolution, and response `Link` header collection for early hints. | -| `before-load` | Nested `beforeLoad` execution: sequential per-match context building, context merging across matches, and context consumption by loaders during document SSR. | -| `control-flow` | Loader-thrown `redirect`, `notFound`, plain errors, unmatched routes, and route `headers()` emission, including HTTP status selection, redirect `location` headers, route error boundaries, and not-found HTML rendering. | -| `global-middleware` | Global `createStart` middleware registration: request middleware wrapping document SSR, server-function, and server-route requests, plus global function middleware on server functions. | -| `head` | Nested route `head` evaluation, title/meta/link serialization, and head-entry deduplication during SSR. | -| `loaders` | Nested route loader execution, loader deps from search params, router context reads, and dehydrated loader payload generation. | -| `rewrites` | Composed location rewrites from router `basepath` plus locale input/output rewrites; unprefixed URLs redirect to `/app/*` when the basepath output rewrite canonicalizes them. | -| `serialization` | Dehydration and RPC serialization of rich non-plain-JSON types: seroval native types in loader payloads, custom serialization adapters, and shallow-error serialization. | -| `selective-ssr` | Route-level `ssr` modes: rendered server HTML with `ssr: true`, dehydrated data without HTML with `ssr: 'data-only'`, and client-only omission with `ssr: false`. | -| `server-fn-transport` | Non-JSON server-function transport: multipart/FormData request decoding, raw `Response` returns, and `RawStream` streamed responses through the binary frame protocol. | -| `server-fns` | `createServerFn` GET/POST request handling, thrown redirect/notFound results, sendContext serialization, SSR-time direct calls, middleware context, input validation, and URL discovery. | -| `server-routes` | File route `server.handlers` dispatch for parameterized JSON API routes without document HTML rendering. | -| `server-routes-middleware` | Server route request middleware chains, middleware-provided context merging, and handler access to accumulated context. | -| `streaming` | Deferred loader data, `Await`/Suspense fallback output, larger streamed HTML body scanning, streamed HTML ordering, and later dehydration payload emission. | - -## Run - -Run all benchmarks through Nx so dependency builds are part of the graph: - -```bash -pnpm nx run @benchmarks/ssr:test:perf --outputStyle=stream --skipRemoteCache -``` - -Run framework-specific benchmarks: - -```bash -pnpm nx run @benchmarks/ssr:test:perf:react --outputStyle=stream --skipRemoteCache -pnpm nx run @benchmarks/ssr:test:perf:solid --outputStyle=stream --skipRemoteCache -pnpm nx run @benchmarks/ssr:test:perf:vue --outputStyle=stream --skipRemoteCache -``` - -Build framework-specific benchmark apps: - -```bash -pnpm nx run @benchmarks/ssr:build:react --outputStyle=stream --skipRemoteCache -pnpm nx run @benchmarks/ssr:build:solid --outputStyle=stream --skipRemoteCache -pnpm nx run @benchmarks/ssr:build:vue --outputStyle=stream --skipRemoteCache -``` - -Typecheck benchmark sources: - -```bash -pnpm nx run @benchmarks/ssr:test:types --outputStyle=stream --skipRemoteCache -``` - -Run one scenario app manually through Nx: - -```bash -pnpm nx run @benchmarks/ssr--:build:ssr --outputStyle=stream --skipRemoteCache -pnpm nx run @benchmarks/ssr--:test:types:ssr --outputStyle=stream --skipRemoteCache -``` - -Use `react`, `solid`, or `vue` for ``. The baseline projects use `@benchmarks/ssr-` without a scenario segment. - -## Request Conventions - -- Document GET loops use `accept: text/html`, matching the baseline request shape. -- 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/bench-utils.test.ts b/benchmarks/ssr/bench-utils.test.ts deleted file mode 100644 index c6a520447b..0000000000 --- a/benchmarks/ssr/bench-utils.test.ts +++ /dev/null @@ -1,145 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { buildRequestSequences, runRequestLoop } from './bench-utils' -import type { StartRequestHandler } from './bench-utils' - -function deferred() { - let resolve = () => {} - const promise = new Promise((resolvePromise) => { - resolve = resolvePromise - }) - return { promise, resolve } -} - -describe('runRequestLoop', () => { - it('caps fixed concurrency and waits for every streaming body', async () => { - const concurrency = 4 - const totalRequests = 20 - const firstWaveStarted = deferred() - let builtRequests = 0 - let executedRequests = 0 - let validatedResponses = 0 - let finishedBodies = 0 - let inFlightRequests = 0 - let maximumInFlightRequests = 0 - - const handler: StartRequestHandler = { - fetch() { - expect(builtRequests).toBe(totalRequests) - executedRequests += 1 - inFlightRequests += 1 - maximumInFlightRequests = Math.max( - maximumInFlightRequests, - inFlightRequests, - ) - - if (inFlightRequests === concurrency) { - firstWaveStarted.resolve() - } - - const body = new ReadableStream({ - async start(controller) { - await firstWaveStarted.promise - controller.enqueue(new Uint8Array([1])) - controller.close() - finishedBodies += 1 - inFlightRequests -= 1 - }, - }) - - return new Response(body) - }, - } - - await runRequestLoop(handler, { - seed: 123, - concurrency, - totalRequests, - buildRequest: (_random, index) => { - builtRequests += 1 - return new Request(`http://localhost/request/${index}`) - }, - validateResponse: () => { - validatedResponses += 1 - }, - }) - - expect(builtRequests).toBe(totalRequests) - expect(executedRequests).toBe(totalRequests) - expect(validatedResponses).toBe(totalRequests) - expect(maximumInFlightRequests).toBe(concurrency) - expect(inFlightRequests).toBe(0) - expect(finishedBodies).toBe(totalRequests) - }) - - it('builds identical predetermined worker sequences from identical seeds', () => { - const buildSequences = (seed: number) => - buildRequestSequences({ - seed, - concurrency: 4, - totalRequests: 12, - buildRequest: (random, index) => - new Request( - `http://localhost/request/${index}?value=${random().toString(36)}`, - ), - }).map((requests) => requests.map((request) => request.url)) - - const first = buildSequences(456) - const second = buildSequences(456) - - expect(second).toEqual(first) - expect(first.map((requests) => requests.map(requestIndex))).toEqual([ - [0, 4, 8], - [1, 5, 9], - [2, 6, 10], - [3, 7, 11], - ]) - }) - - it('drains every started body before reporting a worker failure', async () => { - const concurrency = 4 - const firstWaveStarted = deferred() - let executedRequests = 0 - let finishedBodies = 0 - let inFlightRequests = 0 - - const handler: StartRequestHandler = { - fetch(request) { - executedRequests += 1 - inFlightRequests += 1 - if (inFlightRequests === concurrency) { - firstWaveStarted.resolve() - } - - const body = new ReadableStream({ - async start(controller) { - await firstWaveStarted.promise - controller.close() - finishedBodies += 1 - inFlightRequests -= 1 - }, - }) - - return new Response(body, { - status: request.url.endsWith('/0') ? 500 : 200, - }) - }, - } - - await expect( - runRequestLoop(handler, { - seed: 789, - concurrency, - totalRequests: 12, - buildRequest: (_random, index) => - new Request(`http://localhost/request/${index}`), - }), - ).rejects.toThrow('non-200 status 500') - - expect(finishedBodies).toBe(executedRequests) - expect(inFlightRequests).toBe(0) - }) -}) - -function requestIndex(url: string) { - return Number(new URL(url).pathname.split('/').at(-1)) -} diff --git a/benchmarks/ssr/bench-utils.ts b/benchmarks/ssr/bench-utils.ts deleted file mode 100644 index 7a54fce897..0000000000 --- a/benchmarks/ssr/bench-utils.ts +++ /dev/null @@ -1,205 +0,0 @@ -export interface StartRequestHandler { - fetch: (request: Request) => Promise | Response -} - -export interface RunSsrRequestLoopOptions { - seed: number - iterations?: number -} - -export interface RunRequestLoopOptions { - seed: number - concurrency: number - totalRequests: number - buildRequest: (random: () => number, index: number) => Request - validateResponse?: (response: Response, request: Request) => void -} - -const requestInit = { - method: 'GET', - headers: { - accept: 'text/html', - }, -} satisfies RequestInit - -function createDeterministicRandom(seed: number) { - let state = seed >>> 0 - - return () => { - state = (state * 1664525 + 1013904223) >>> 0 - return state / 0x100000000 - } -} - -function randomSegment(random: () => number) { - return Math.floor(random() * 1_000_000_000).toString(36) -} - -export { createDeterministicRandom, randomSegment } - -export async function drainResponse(response: Response) { - const reader = response.body?.getReader() - - if (!reader) { - return - } - - try { - while (true) { - const result = await reader.read() - - if (result.done) { - break - } - } - } finally { - reader.releaseLock() - } -} - -function randomSearchValue(random: () => number) { - return `q-${randomSegment(random)}` -} - -function randomRequestUrl(random: () => number) { - const a = randomSegment(random) - const b = randomSegment(random) - const c = randomSegment(random) - const d = randomSegment(random) - const q = randomSearchValue(random) - - return `http://localhost/${a}/${b}/${c}/${d}?q=${q}` -} - -export async function runSsrRequestLoop( - handler: StartRequestHandler, - { seed, iterations = 10 }: RunSsrRequestLoopOptions, -) { - const random = createDeterministicRandom(seed) - const pendingBodyReads: Array> = [] - - for (let index = 0; index < iterations; index++) { - const requestUrl = randomRequestUrl(random) - const response = await handler.fetch(new Request(requestUrl, requestInit)) - - if (response.status !== 200) { - await Promise.allSettled(pendingBodyReads) - - throw new Error( - `Request failed with non-200 status ${response.status} (${requestUrl})`, - ) - } - - pendingBodyReads.push(drainResponse(response)) - } - - await Promise.all(pendingBodyReads) -} - -export async function runRequestLoop( - handler: StartRequestHandler, - { - seed, - concurrency, - totalRequests, - buildRequest, - validateResponse, - }: RunRequestLoopOptions, -) { - const requestSequences = buildRequestSequences({ - seed, - concurrency, - totalRequests, - buildRequest, - }) - const validate = - validateResponse ?? - ((response: Response, request: Request) => { - if (response.status !== 200) { - throw new Error( - `Request failed with non-200 status ${response.status} (${request.url})`, - ) - } - }) - - let startWorkers = () => {} - const startBarrier = new Promise((resolve) => { - startWorkers = resolve - }) - - const workers = requestSequences.map(async (requests) => { - await startBarrier - - for (const request of requests) { - const response = await handler.fetch(request) - let validationFailure: { error: unknown } | undefined - - try { - validate(response, request) - } catch (error) { - validationFailure = { error } - } - - await drainResponse(response) - - if (validationFailure) { - throw validationFailure.error - } - } - }) - - startWorkers() - const results = await Promise.allSettled(workers) - const failedWorker = results.find( - (result): result is PromiseRejectedResult => result.status === 'rejected', - ) - - if (failedWorker) { - throw failedWorker.reason - } -} - -export type BuildRequestSequencesOptions = Pick< - RunRequestLoopOptions, - 'seed' | 'concurrency' | 'totalRequests' | 'buildRequest' -> - -/** - * Build the entire seeded workload before any request starts, then partition - * it round-robin so completion timing can never change a worker's next input. - */ -export function buildRequestSequences({ - seed, - concurrency, - totalRequests, - buildRequest, -}: BuildRequestSequencesOptions): Array> { - assertPositiveInteger('concurrency', concurrency) - assertPositiveInteger('totalRequests', totalRequests) - - if (concurrency > totalRequests) { - throw new RangeError( - `concurrency (${concurrency}) cannot exceed totalRequests (${totalRequests})`, - ) - } - - const random = createDeterministicRandom(seed) - const requestSequences = Array.from( - { length: concurrency }, - () => new Array(), - ) - - for (let index = 0; index < totalRequests; index++) { - requestSequences[index % concurrency]!.push(buildRequest(random, index)) - } - - return requestSequences -} - -function assertPositiveInteger(name: string, value: number) { - if (!Number.isSafeInteger(value) || value < 1) { - throw new RangeError( - `${name} must be a positive integer; received ${value}`, - ) - } -} diff --git a/benchmarks/ssr/package.json b/benchmarks/ssr/package.json deleted file mode 100644 index 20c1837468..0000000000 --- a/benchmarks/ssr/package.json +++ /dev/null @@ -1,231 +0,0 @@ -{ - "name": "@benchmarks/ssr", - "private": true, - "type": "module", - "dependencies": { - "@tanstack/react-router": "workspace:^", - "@tanstack/react-start": "workspace:^", - "@tanstack/solid-router": "workspace:^", - "@tanstack/solid-start": "workspace:^", - "@tanstack/vue-router": "workspace:^", - "@tanstack/vue-start": "workspace:^", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "solid-js": "^1.9.10", - "vue": "^3.5.16" - }, - "devDependencies": { - "@codspeed/vitest-plugin": "^6.0.1", - "@vitejs/plugin-react": "^6.0.1", - "@vitejs/plugin-vue-jsx": "^5.1.5", - "@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": "catalog:" - }, - "nx": { - "targets": { - "build:react": { - "executor": "nx:noop", - "cache": false, - "dependsOn": [ - { - "projects": [ - "@benchmarks/ssr-react", - "@benchmarks/ssr-assets-react", - "@benchmarks/ssr-before-load-react", - "@benchmarks/ssr-control-flow-react", - "@benchmarks/ssr-global-middleware-react", - "@benchmarks/ssr-head-react", - "@benchmarks/ssr-loaders-react", - "@benchmarks/ssr-rewrites-react", - "@benchmarks/ssr-serialization-react", - "@benchmarks/ssr-selective-ssr-react", - "@benchmarks/ssr-server-fn-transport-react", - "@benchmarks/ssr-server-fns-react", - "@benchmarks/ssr-server-routes-react", - "@benchmarks/ssr-server-routes-middleware-react", - "@benchmarks/ssr-streaming-react" - ], - "target": "build:ssr" - } - ] - }, - "build:solid": { - "executor": "nx:noop", - "cache": false, - "dependsOn": [ - { - "projects": [ - "@benchmarks/ssr-solid", - "@benchmarks/ssr-assets-solid", - "@benchmarks/ssr-before-load-solid", - "@benchmarks/ssr-control-flow-solid", - "@benchmarks/ssr-global-middleware-solid", - "@benchmarks/ssr-head-solid", - "@benchmarks/ssr-loaders-solid", - "@benchmarks/ssr-rewrites-solid", - "@benchmarks/ssr-serialization-solid", - "@benchmarks/ssr-selective-ssr-solid", - "@benchmarks/ssr-server-fn-transport-solid", - "@benchmarks/ssr-server-fns-solid", - "@benchmarks/ssr-server-routes-solid", - "@benchmarks/ssr-server-routes-middleware-solid", - "@benchmarks/ssr-streaming-solid" - ], - "target": "build:ssr" - } - ] - }, - "build:vue": { - "executor": "nx:noop", - "cache": false, - "dependsOn": [ - { - "projects": [ - "@benchmarks/ssr-vue", - "@benchmarks/ssr-assets-vue", - "@benchmarks/ssr-before-load-vue", - "@benchmarks/ssr-control-flow-vue", - "@benchmarks/ssr-global-middleware-vue", - "@benchmarks/ssr-head-vue", - "@benchmarks/ssr-loaders-vue", - "@benchmarks/ssr-rewrites-vue", - "@benchmarks/ssr-serialization-vue", - "@benchmarks/ssr-selective-ssr-vue", - "@benchmarks/ssr-server-fn-transport-vue", - "@benchmarks/ssr-server-fns-vue", - "@benchmarks/ssr-server-routes-vue", - "@benchmarks/ssr-server-routes-middleware-vue", - "@benchmarks/ssr-streaming-vue" - ], - "target": "build:ssr" - } - ] - }, - "test:perf": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - "build:react", - "build:solid", - "build:vue" - ], - "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark", - "cwd": "benchmarks/ssr" - } - }, - "test:unit": { - "executor": "nx:run-commands", - "options": { - "command": "vitest run --config ./vitest.unit.config.ts", - "cwd": "benchmarks/ssr" - } - }, - "test:perf:react": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - "build:react" - ], - "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.react.config.ts", - "cwd": "benchmarks/ssr" - } - }, - "test:perf:solid": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - "build:solid" - ], - "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.solid.config.ts", - "cwd": "benchmarks/ssr" - } - }, - "test:perf:vue": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - "build:vue" - ], - "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.vue.config.ts", - "cwd": "benchmarks/ssr" - } - }, - "test:types": { - "executor": "nx:run-commands", - "options": { - "command": "tsc -p ./tsconfig.json --noEmit", - "cwd": "benchmarks/ssr" - }, - "dependsOn": [ - { - "projects": [ - "@benchmarks/ssr-react", - "@benchmarks/ssr-assets-react", - "@benchmarks/ssr-before-load-react", - "@benchmarks/ssr-control-flow-react", - "@benchmarks/ssr-global-middleware-react", - "@benchmarks/ssr-head-react", - "@benchmarks/ssr-loaders-react", - "@benchmarks/ssr-rewrites-react", - "@benchmarks/ssr-serialization-react", - "@benchmarks/ssr-selective-ssr-react", - "@benchmarks/ssr-server-fn-transport-react", - "@benchmarks/ssr-server-fns-react", - "@benchmarks/ssr-server-routes-react", - "@benchmarks/ssr-server-routes-middleware-react", - "@benchmarks/ssr-streaming-react", - "@benchmarks/ssr-solid", - "@benchmarks/ssr-assets-solid", - "@benchmarks/ssr-before-load-solid", - "@benchmarks/ssr-control-flow-solid", - "@benchmarks/ssr-global-middleware-solid", - "@benchmarks/ssr-head-solid", - "@benchmarks/ssr-loaders-solid", - "@benchmarks/ssr-rewrites-solid", - "@benchmarks/ssr-serialization-solid", - "@benchmarks/ssr-selective-ssr-solid", - "@benchmarks/ssr-server-fn-transport-solid", - "@benchmarks/ssr-server-fns-solid", - "@benchmarks/ssr-server-routes-solid", - "@benchmarks/ssr-server-routes-middleware-solid", - "@benchmarks/ssr-streaming-solid", - "@benchmarks/ssr-vue", - "@benchmarks/ssr-assets-vue", - "@benchmarks/ssr-before-load-vue", - "@benchmarks/ssr-control-flow-vue", - "@benchmarks/ssr-global-middleware-vue", - "@benchmarks/ssr-head-vue", - "@benchmarks/ssr-loaders-vue", - "@benchmarks/ssr-rewrites-vue", - "@benchmarks/ssr-serialization-vue", - "@benchmarks/ssr-selective-ssr-vue", - "@benchmarks/ssr-server-fn-transport-vue", - "@benchmarks/ssr-server-fns-vue", - "@benchmarks/ssr-server-routes-vue", - "@benchmarks/ssr-server-routes-middleware-vue", - "@benchmarks/ssr-streaming-vue" - ], - "target": "test:types:ssr" - } - ], - "inputs": [ - "default", - "^production", - "{workspaceRoot}/eslint.config.js", - "{workspaceRoot}/benchmarks/cpu-simulation.ts", - "dependentTaskOutputs" - ] - } - } - } -} diff --git a/benchmarks/ssr/react/project.json b/benchmarks/ssr/react/project.json deleted file mode 100644 index d7f674cc83..0000000000 --- a/benchmarks/ssr/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-react", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/react/speed.bench.ts b/benchmarks/ssr/react/speed.bench.ts deleted file mode 100644 index 6825a7ddfb..0000000000 --- a/benchmarks/ssr/react/speed.bench.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { test } from 'vitest' -import { runSsrRequestLoop } from '../bench-utils' -import type { StartRequestHandler } from '../bench-utils' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href -const benchmarkSeed = 0xdecafbad - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} - -test('ssr', async ({ bench }) => { - await bench('ssr request loop (react)', async () => - runSsrRequestLoop(handler, { seed: benchmarkSeed }), - ).run({ - warmupIterations: 100, - time: 10_000, - throws: true, - }) -}) diff --git a/benchmarks/ssr/react/src/routeTree.gen.ts b/benchmarks/ssr/react/src/routeTree.gen.ts deleted file mode 100644 index 9f110bba31..0000000000 --- a/benchmarks/ssr/react/src/routeTree.gen.ts +++ /dev/null @@ -1,146 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as ARouteImport } from './routes/$a' -import { Route as ABRouteImport } from './routes/$a.$b' -import { Route as ABCRouteImport } from './routes/$a.$b.$c' -import { Route as ABCDRouteImport } from './routes/$a.$b.$c.$d' - -const ARoute = ARouteImport.update({ - id: '/$a', - path: '/$a', - getParentRoute: () => rootRouteImport, -} as any) -const ABRoute = ABRouteImport.update({ - id: '/$b', - path: '/$b', - getParentRoute: () => ARoute, -} as any) -const ABCRoute = ABCRouteImport.update({ - id: '/$c', - path: '/$c', - getParentRoute: () => ABRoute, -} as any) -const ABCDRoute = ABCDRouteImport.update({ - id: '/$d', - path: '/$d', - getParentRoute: () => ABCRoute, -} as any) - -export interface FileRoutesByFullPath { - '/$a': typeof ARouteWithChildren - '/$a/$b': typeof ABRouteWithChildren - '/$a/$b/$c': typeof ABCRouteWithChildren - '/$a/$b/$c/$d': typeof ABCDRoute -} -export interface FileRoutesByTo { - '/$a': typeof ARouteWithChildren - '/$a/$b': typeof ABRouteWithChildren - '/$a/$b/$c': typeof ABCRouteWithChildren - '/$a/$b/$c/$d': typeof ABCDRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/$a': typeof ARouteWithChildren - '/$a/$b': typeof ABRouteWithChildren - '/$a/$b/$c': typeof ABCRouteWithChildren - '/$a/$b/$c/$d': typeof ABCDRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/$a' | '/$a/$b' | '/$a/$b/$c' | '/$a/$b/$c/$d' - fileRoutesByTo: FileRoutesByTo - to: '/$a' | '/$a/$b' | '/$a/$b/$c' | '/$a/$b/$c/$d' - id: '__root__' | '/$a' | '/$a/$b' | '/$a/$b/$c' | '/$a/$b/$c/$d' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - ARoute: typeof ARouteWithChildren -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/$a': { - id: '/$a' - path: '/$a' - fullPath: '/$a' - preLoaderRoute: typeof ARouteImport - parentRoute: typeof rootRouteImport - } - '/$a/$b': { - id: '/$a/$b' - path: '/$b' - fullPath: '/$a/$b' - preLoaderRoute: typeof ABRouteImport - parentRoute: typeof ARoute - } - '/$a/$b/$c': { - id: '/$a/$b/$c' - path: '/$c' - fullPath: '/$a/$b/$c' - preLoaderRoute: typeof ABCRouteImport - parentRoute: typeof ABRoute - } - '/$a/$b/$c/$d': { - id: '/$a/$b/$c/$d' - path: '/$d' - fullPath: '/$a/$b/$c/$d' - preLoaderRoute: typeof ABCDRouteImport - parentRoute: typeof ABCRoute - } - } -} - -interface ABCRouteChildren { - ABCDRoute: typeof ABCDRoute -} - -const ABCRouteChildren: ABCRouteChildren = { - ABCDRoute: ABCDRoute, -} - -const ABCRouteWithChildren = ABCRoute._addFileChildren(ABCRouteChildren) - -interface ABRouteChildren { - ABCRoute: typeof ABCRouteWithChildren -} - -const ABRouteChildren: ABRouteChildren = { - ABCRoute: ABCRouteWithChildren, -} - -const ABRouteWithChildren = ABRoute._addFileChildren(ABRouteChildren) - -interface ARouteChildren { - ABRoute: typeof ABRouteWithChildren -} - -const ARouteChildren: ARouteChildren = { - ABRoute: ABRouteWithChildren, -} - -const ARouteWithChildren = ARoute._addFileChildren(ARouteChildren) - -const rootRouteChildren: RootRouteChildren = { - ARoute: ARouteWithChildren, -} -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/benchmarks/ssr/react/src/router.tsx b/benchmarks/ssr/react/src/router.tsx deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/ssr/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/react/src/routes/$a.$b.$c.$d.tsx b/benchmarks/ssr/react/src/routes/$a.$b.$c.$d.tsx deleted file mode 100644 index 056f1c308e..0000000000 --- a/benchmarks/ssr/react/src/routes/$a.$b.$c.$d.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { RouteWorkload } from '../workload' - -export const Route = createFileRoute('/$a/$b/$c/$d')({ - component: LevelDComponent, -}) - -function LevelDComponent() { - return -} diff --git a/benchmarks/ssr/react/src/routes/$a.$b.$c.tsx b/benchmarks/ssr/react/src/routes/$a.$b.$c.tsx deleted file mode 100644 index b73ede60f4..0000000000 --- a/benchmarks/ssr/react/src/routes/$a.$b.$c.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import { RouteWorkload } from '../workload' - -export const Route = createFileRoute('/$a/$b/$c')({ - component: LevelCComponent, -}) - -function LevelCComponent() { - return ( - <> - - - - ) -} diff --git a/benchmarks/ssr/react/src/routes/$a.$b.tsx b/benchmarks/ssr/react/src/routes/$a.$b.tsx deleted file mode 100644 index 649b0f0a46..0000000000 --- a/benchmarks/ssr/react/src/routes/$a.$b.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import { RouteWorkload } from '../workload' - -export const Route = createFileRoute('/$a/$b')({ - component: LevelBComponent, -}) - -function LevelBComponent() { - return ( - <> - - - - ) -} diff --git a/benchmarks/ssr/react/src/routes/$a.tsx b/benchmarks/ssr/react/src/routes/$a.tsx deleted file mode 100644 index cc2fa1483b..0000000000 --- a/benchmarks/ssr/react/src/routes/$a.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import { RouteWorkload } from '../workload' - -export const Route = createFileRoute('/$a')({ - component: LevelAComponent, -}) - -function LevelAComponent() { - return ( - <> - - - - ) -} diff --git a/benchmarks/ssr/react/src/routes/__root.tsx b/benchmarks/ssr/react/src/routes/__root.tsx deleted file mode 100644 index 1973ca20bb..0000000000 --- a/benchmarks/ssr/react/src/routes/__root.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: RootComponent, - validateSearch: (s) => s as { q?: string }, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/react/src/workload.tsx b/benchmarks/ssr/react/src/workload.tsx deleted file mode 100644 index 2cc5c9f1ae..0000000000 --- a/benchmarks/ssr/react/src/workload.tsx +++ /dev/null @@ -1,81 +0,0 @@ -import { Link, useParams, useSearch } from '@tanstack/react-router' - -const probes = Array.from({ length: 10 }, (_, index) => index) - -function runSelectorWork(input: string, salt: number) { - let value = salt - - for (let index = 0; index < input.length; index++) { - value = (value * 33 + input.charCodeAt(index) + index) >>> 0 - } - - for (let index = 0; index < 16; index++) { - value = (value ^ (value << 13)) >>> 0 - value = (value ^ (value >> 17)) >>> 0 - value = (value ^ (value << 5)) >>> 0 - } - - return value -} - -function ParamsProbe({ salt }: { salt: number }) { - const params = useParams({ - strict: false, - select: (nextParams) => - runSelectorWork( - `${nextParams.a ?? ''}/${nextParams.b ?? ''}/${nextParams.c ?? ''}/${nextParams.d ?? ''}`, - salt, - ), - }) - - void params - - return null -} - -function SearchProbe({ salt }: { salt: number }) { - const search = useSearch({ - strict: false, - select: (nextSearch) => runSelectorWork(String(nextSearch.q ?? ''), salt), - }) - - void search - - return null -} - -function LinkProbe({ salt }: { salt: number }) { - const value = String((salt % 97) + 1) - - return ( - - Link - - ) -} - -export function RouteWorkload() { - return ( - <> - {probes.map((probe) => ( - - ))} - {probes.map((probe) => ( - - ))} - {probes.map((probe) => ( - - ))} - - ) -} diff --git a/benchmarks/ssr/react/tsconfig.json b/benchmarks/ssr/react/tsconfig.json deleted file mode 100644 index 4de88f2eb4..0000000000 --- a/benchmarks/ssr/react/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "vite.config.ts", - "../bench-utils.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/react/vite.config.ts b/benchmarks/ssr/react/vite.config.ts deleted file mode 100644 index e607db366b..0000000000 --- a/benchmarks/ssr/react/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - execArgv: cpuSimulationExecArgv(), - isolate: true, - name: '@benchmarks/ssr (react)', - watch: false, - environment: 'node', - }, -}) diff --git a/benchmarks/ssr/scenarios/assets/react/project.json b/benchmarks/ssr/scenarios/assets/react/project.json deleted file mode 100644 index a2d5a6c8ba..0000000000 --- a/benchmarks/ssr/scenarios/assets/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-assets-react", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} 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 deleted file mode 100644 index 0496613afb..0000000000 --- a/benchmarks/ssr/scenarios/assets/react/speed.assets-linked-css-control.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 7dc57d89f1..0000000000 --- a/benchmarks/ssr/scenarios/assets/react/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertAssetsScenario, - assetsBenchOptions, - runAssetsInlineLoop, -} 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 inline-css cdn (react)', async () => - runAssetsInlineLoop(handler), - ).run(assetsBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/assets/react/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/assets/react/src/routeTree.gen.ts deleted file mode 100644 index 201df5fd3b..0000000000 --- a/benchmarks/ssr/scenarios/assets/react/src/routeTree.gen.ts +++ /dev/null @@ -1,94 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as AXRouteImport } from './routes/a.$x' -import { Route as AXYRouteImport } from './routes/a.$x.$y' - -const AXRoute = AXRouteImport.update({ - id: '/a/$x', - path: '/a/$x', - getParentRoute: () => rootRouteImport, -} as any) -const AXYRoute = AXYRouteImport.update({ - id: '/$y', - path: '/$y', - getParentRoute: () => AXRoute, -} as any) - -export interface FileRoutesByFullPath { - '/a/$x': typeof AXRouteWithChildren - '/a/$x/$y': typeof AXYRoute -} -export interface FileRoutesByTo { - '/a/$x': typeof AXRouteWithChildren - '/a/$x/$y': typeof AXYRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/a/$x': typeof AXRouteWithChildren - '/a/$x/$y': typeof AXYRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/a/$x' | '/a/$x/$y' - fileRoutesByTo: FileRoutesByTo - to: '/a/$x' | '/a/$x/$y' - id: '__root__' | '/a/$x' | '/a/$x/$y' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - AXRoute: typeof AXRouteWithChildren -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/a/$x': { - id: '/a/$x' - path: '/a/$x' - fullPath: '/a/$x' - preLoaderRoute: typeof AXRouteImport - parentRoute: typeof rootRouteImport - } - '/a/$x/$y': { - id: '/a/$x/$y' - path: '/$y' - fullPath: '/a/$x/$y' - preLoaderRoute: typeof AXYRouteImport - parentRoute: typeof AXRoute - } - } -} - -interface AXRouteChildren { - AXYRoute: typeof AXYRoute -} - -const AXRouteChildren: AXRouteChildren = { - AXYRoute: AXYRoute, -} - -const AXRouteWithChildren = AXRoute._addFileChildren(AXRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - AXRoute: AXRouteWithChildren, -} -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/benchmarks/ssr/scenarios/assets/react/src/router.tsx b/benchmarks/ssr/scenarios/assets/react/src/router.tsx deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/ssr/scenarios/assets/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/assets/react/src/routes/__root.tsx b/benchmarks/ssr/scenarios/assets/react/src/routes/__root.tsx deleted file mode 100644 index 8c46c7060a..0000000000 --- a/benchmarks/ssr/scenarios/assets/react/src/routes/__root.tsx +++ /dev/null @@ -1,31 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' - -export const Route = createRootRoute({ - head: () => ({ - meta: [ - { charSet: 'utf-8' }, - { name: 'viewport', content: 'width=device-width, initial-scale=1' }, - { name: 'application-name', content: 'SSR assets benchmark' }, - ], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/assets/react/src/routes/a.$x.$y.tsx b/benchmarks/ssr/scenarios/assets/react/src/routes/a.$x.$y.tsx deleted file mode 100644 index be709e53e6..0000000000 --- a/benchmarks/ssr/scenarios/assets/react/src/routes/a.$x.$y.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import '../styles/assets-leaf.css' - -export const Route = createFileRoute('/a/$x/$y')({ - head: ({ params }) => ({ - meta: [{ title: `SSR Assets ${params.x} ${params.y}` }], - links: Array.from({ length: 3 }, (_, index) => ({ - rel: 'preload', - as: 'image', - href: `/asset-preload/${params.y}-${index}.png`, - })), - }), - component: LeafComponent, -}) - -function LeafComponent() { - const { x, y } = Route.useParams() - - return ( -
-

- assets-leaf-{x}-{y} -

-
- ) -} diff --git a/benchmarks/ssr/scenarios/assets/react/src/routes/a.$x.tsx b/benchmarks/ssr/scenarios/assets/react/src/routes/a.$x.tsx deleted file mode 100644 index ecc7de680a..0000000000 --- a/benchmarks/ssr/scenarios/assets/react/src/routes/a.$x.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import '../styles/assets-a.css' - -export const Route = createFileRoute('/a/$x')({ - head: ({ params }) => ({ - meta: [{ title: `SSR Assets ${params.x}` }], - links: Array.from({ length: 2 }, (_, index) => ({ - rel: 'preload', - as: 'image', - href: `/asset-preload/${params.x}-${index}.png`, - })), - }), - component: LevelAComponent, -}) - -function LevelAComponent() { - const { x } = Route.useParams() - - return ( -
-

assets-level-a-{x}

- -
- ) -} diff --git a/benchmarks/ssr/scenarios/assets/react/src/server.ts b/benchmarks/ssr/scenarios/assets/react/src/server.ts deleted file mode 100644 index 64fb21708c..0000000000 --- a/benchmarks/ssr/scenarios/assets/react/src/server.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { - createStartHandler, - defaultStreamHandler, -} from '@tanstack/react-start/server' -import { createServerEntry } from '@tanstack/react-start/server-entry' -import type { - TransformAssets, - TransformAssetsFn, -} from '@tanstack/react-start/server' - -type CreateTransformContext = - | { warmup: true } - | { request: Request; warmup: false } - -const cdnOrigin = 'https://cdn.example.com' - -const createCdnTransform = (prefix: string): TransformAssetsFn => { - return ({ url }) => `${prefix}${url}` -} - -const transformAssets: TransformAssets = { - createTransform: (ctx: CreateTransformContext) => { - const prefix = ctx.warmup - ? cdnOrigin - : (ctx.request.headers.get('x-assets-cdn') ?? cdnOrigin) - - return createCdnTransform(prefix) - }, - cache: false, -} - -const handler = createStartHandler({ - handler: defaultStreamHandler, - inlineCss: true, - transformAssets, -}) - -export default createServerEntry({ - fetch(request) { - return handler(request, { - inlineCss: request.headers.get('x-inline-css') !== 'false', - responseLinkHeader: true, - }) - }, -}) diff --git a/benchmarks/ssr/scenarios/assets/react/src/styles/assets-a.css b/benchmarks/ssr/scenarios/assets/react/src/styles/assets-a.css deleted file mode 100644 index d3511ddd85..0000000000 --- a/benchmarks/ssr/scenarios/assets/react/src/styles/assets-a.css +++ /dev/null @@ -1,8 +0,0 @@ -.assets-level-a { - color: #1f2937; - background-image: url('/asset-bg-a.svg'); -} - -.assets-level-a::before { - content: 'assets-level-a-css'; -} diff --git a/benchmarks/ssr/scenarios/assets/react/src/styles/assets-leaf.css b/benchmarks/ssr/scenarios/assets/react/src/styles/assets-leaf.css deleted file mode 100644 index 55e051b9a5..0000000000 --- a/benchmarks/ssr/scenarios/assets/react/src/styles/assets-leaf.css +++ /dev/null @@ -1,8 +0,0 @@ -.assets-leaf { - border-color: #2563eb; - background-image: url('/asset-bg-leaf.svg'); -} - -.assets-leaf::before { - content: 'assets-leaf-css'; -} diff --git a/benchmarks/ssr/scenarios/assets/react/tsconfig.json b/benchmarks/ssr/scenarios/assets/react/tsconfig.json deleted file mode 100644 index cf14e1d440..0000000000 --- a/benchmarks/ssr/scenarios/assets/react/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "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 deleted file mode 100644 index 5990bba6d3..0000000000 --- a/benchmarks/ssr/scenarios/assets/react/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - server: { - build: { - inlineCss: { enabled: true, transformAssets: true }, - }, - }, - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - execArgv: cpuSimulationExecArgv(), - isolate: true, - name: '@benchmarks/ssr assets (react)', - watch: false, - environment: 'node', - }, -}) diff --git a/benchmarks/ssr/scenarios/assets/shared.ts b/benchmarks/ssr/scenarios/assets/shared.ts deleted file mode 100644 index ec811794e3..0000000000 --- a/benchmarks/ssr/scenarios/assets/shared.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { expect } from 'vitest' -import { randomSegment, runRequestLoop } from '../../bench-utils' -import type { StartRequestHandler } from '../../bench-utils' - -export type { StartRequestHandler } - -const benchmarkSeed = 0xdecafbad -const origin = 'http://localhost' -const cdnOrigin = 'https://cdn.example.com' -const inlineCssLoopTotalRequests = 32 -const linkedCssLoopTotalRequests = 32 - -const inlineRequestInit = { - method: 'GET', - headers: { - accept: 'text/html', - }, -} satisfies RequestInit - -const linkedRequestInit = { - method: 'GET', - headers: { - accept: 'text/html', - 'x-inline-css': 'false', - }, -} satisfies RequestInit - -export const assetsBenchOptions = { - warmupIterations: 100, - time: 10_000, - throws: true, -} - -function buildAssetsRequest(random: () => number, requestInit: RequestInit) { - return new Request( - `${origin}/a/${randomSegment(random)}/${randomSegment(random)}`, - requestInit, - ) -} - -export function runAssetsInlineLoop(handler: StartRequestHandler) { - return runRequestLoop(handler, { - seed: benchmarkSeed, - concurrency: 16, - totalRequests: inlineCssLoopTotalRequests, - buildRequest: (random) => buildAssetsRequest(random, inlineRequestInit), - }) -} - -export function runAssetsLinkedControlLoop(handler: StartRequestHandler) { - return runRequestLoop(handler, { - seed: benchmarkSeed, - concurrency: 16, - totalRequests: linkedCssLoopTotalRequests, - buildRequest: (random) => buildAssetsRequest(random, linkedRequestInit), - }) -} - -export async function assertAssetsScenario(handler: StartRequestHandler) { - const inlineResponse = await handler.fetch( - new Request(`${origin}/a/sanity-x/sanity-y`, inlineRequestInit), - ) - const inlineBody = await inlineResponse.text() - const inlineLinkHeader = inlineResponse.headers.get('link') ?? '' - - expect(inlineResponse.status).toBe(200) - expect(inlineBody).toContain('SSR Assets sanity-x sanity-y') - expect(inlineBody).toContain(' { - 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 deleted file mode 100644 index 47f483df11..0000000000 --- a/benchmarks/ssr/scenarios/assets/solid/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertAssetsScenario, - assetsBenchOptions, - runAssetsInlineLoop, -} 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 inline-css cdn (solid)', async () => - runAssetsInlineLoop(handler), - ).run(assetsBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/assets/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/assets/solid/src/routeTree.gen.ts deleted file mode 100644 index f6f7ffe57e..0000000000 --- a/benchmarks/ssr/scenarios/assets/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,94 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as AXRouteImport } from './routes/a.$x' -import { Route as AXYRouteImport } from './routes/a.$x.$y' - -const AXRoute = AXRouteImport.update({ - id: '/a/$x', - path: '/a/$x', - getParentRoute: () => rootRouteImport, -} as any) -const AXYRoute = AXYRouteImport.update({ - id: '/$y', - path: '/$y', - getParentRoute: () => AXRoute, -} as any) - -export interface FileRoutesByFullPath { - '/a/$x': typeof AXRouteWithChildren - '/a/$x/$y': typeof AXYRoute -} -export interface FileRoutesByTo { - '/a/$x': typeof AXRouteWithChildren - '/a/$x/$y': typeof AXYRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/a/$x': typeof AXRouteWithChildren - '/a/$x/$y': typeof AXYRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/a/$x' | '/a/$x/$y' - fileRoutesByTo: FileRoutesByTo - to: '/a/$x' | '/a/$x/$y' - id: '__root__' | '/a/$x' | '/a/$x/$y' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - AXRoute: typeof AXRouteWithChildren -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/a/$x': { - id: '/a/$x' - path: '/a/$x' - fullPath: '/a/$x' - preLoaderRoute: typeof AXRouteImport - parentRoute: typeof rootRouteImport - } - '/a/$x/$y': { - id: '/a/$x/$y' - path: '/$y' - fullPath: '/a/$x/$y' - preLoaderRoute: typeof AXYRouteImport - parentRoute: typeof AXRoute - } - } -} - -interface AXRouteChildren { - AXYRoute: typeof AXYRoute -} - -const AXRouteChildren: AXRouteChildren = { - AXYRoute: AXYRoute, -} - -const AXRouteWithChildren = AXRoute._addFileChildren(AXRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - AXRoute: AXRouteWithChildren, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/solid-start' -declare module '@tanstack/solid-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/benchmarks/ssr/scenarios/assets/solid/src/router.tsx b/benchmarks/ssr/scenarios/assets/solid/src/router.tsx deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/ssr/scenarios/assets/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/assets/solid/src/routes/__root.tsx b/benchmarks/ssr/scenarios/assets/solid/src/routes/__root.tsx deleted file mode 100644 index ca760406ce..0000000000 --- a/benchmarks/ssr/scenarios/assets/solid/src/routes/__root.tsx +++ /dev/null @@ -1,31 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/solid-router' - -export const Route = createRootRoute({ - head: () => ({ - meta: [ - { charSet: 'utf-8' }, - { name: 'viewport', content: 'width=device-width, initial-scale=1' }, - { name: 'application-name', content: 'SSR assets benchmark' }, - ], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/assets/solid/src/routes/a.$x.$y.tsx b/benchmarks/ssr/scenarios/assets/solid/src/routes/a.$x.$y.tsx deleted file mode 100644 index 2a3d35cb68..0000000000 --- a/benchmarks/ssr/scenarios/assets/solid/src/routes/a.$x.$y.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import '../styles/assets-leaf.css' - -export const Route = createFileRoute('/a/$x/$y')({ - head: ({ params }) => ({ - meta: [{ title: `SSR Assets ${params.x} ${params.y}` }], - links: Array.from({ length: 3 }, (_, index) => ({ - rel: 'preload', - as: 'image', - href: `/asset-preload/${params.y}-${index}.png`, - })), - }), - component: LeafComponent, -}) - -function LeafComponent() { - const params = Route.useParams() - - return ( -
-

- assets-leaf-{params().x}-{params().y} -

-
- ) -} diff --git a/benchmarks/ssr/scenarios/assets/solid/src/routes/a.$x.tsx b/benchmarks/ssr/scenarios/assets/solid/src/routes/a.$x.tsx deleted file mode 100644 index 2209addcbe..0000000000 --- a/benchmarks/ssr/scenarios/assets/solid/src/routes/a.$x.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' -import '../styles/assets-a.css' - -export const Route = createFileRoute('/a/$x')({ - head: ({ params }) => ({ - meta: [{ title: `SSR Assets ${params.x}` }], - links: Array.from({ length: 2 }, (_, index) => ({ - rel: 'preload', - as: 'image', - href: `/asset-preload/${params.x}-${index}.png`, - })), - }), - component: LevelAComponent, -}) - -function LevelAComponent() { - const params = Route.useParams() - - return ( -
-

assets-level-a-{params().x}

- -
- ) -} diff --git a/benchmarks/ssr/scenarios/assets/solid/src/server.ts b/benchmarks/ssr/scenarios/assets/solid/src/server.ts deleted file mode 100644 index 541e776a79..0000000000 --- a/benchmarks/ssr/scenarios/assets/solid/src/server.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { - createStartHandler, - defaultStreamHandler, -} from '@tanstack/solid-start/server' -import { createServerEntry } from '@tanstack/solid-start/server-entry' -import type { - TransformAssets, - TransformAssetsFn, -} from '@tanstack/solid-start/server' - -type CreateTransformContext = - | { warmup: true } - | { request: Request; warmup: false } - -const cdnOrigin = 'https://cdn.example.com' - -const createCdnTransform = (prefix: string): TransformAssetsFn => { - return ({ url }) => `${prefix}${url}` -} - -const transformAssets: TransformAssets = { - createTransform: (ctx: CreateTransformContext) => { - const prefix = ctx.warmup - ? cdnOrigin - : (ctx.request.headers.get('x-assets-cdn') ?? cdnOrigin) - - return createCdnTransform(prefix) - }, - cache: false, -} - -const handler = createStartHandler({ - handler: defaultStreamHandler, - inlineCss: true, - transformAssets, -}) - -export default createServerEntry({ - fetch(request) { - return handler(request, { - inlineCss: request.headers.get('x-inline-css') !== 'false', - responseLinkHeader: true, - }) - }, -}) diff --git a/benchmarks/ssr/scenarios/assets/solid/src/styles/assets-a.css b/benchmarks/ssr/scenarios/assets/solid/src/styles/assets-a.css deleted file mode 100644 index d3511ddd85..0000000000 --- a/benchmarks/ssr/scenarios/assets/solid/src/styles/assets-a.css +++ /dev/null @@ -1,8 +0,0 @@ -.assets-level-a { - color: #1f2937; - background-image: url('/asset-bg-a.svg'); -} - -.assets-level-a::before { - content: 'assets-level-a-css'; -} diff --git a/benchmarks/ssr/scenarios/assets/solid/src/styles/assets-leaf.css b/benchmarks/ssr/scenarios/assets/solid/src/styles/assets-leaf.css deleted file mode 100644 index 55e051b9a5..0000000000 --- a/benchmarks/ssr/scenarios/assets/solid/src/styles/assets-leaf.css +++ /dev/null @@ -1,8 +0,0 @@ -.assets-leaf { - border-color: #2563eb; - background-image: url('/asset-bg-leaf.svg'); -} - -.assets-leaf::before { - content: 'assets-leaf-css'; -} diff --git a/benchmarks/ssr/scenarios/assets/solid/tsconfig.json b/benchmarks/ssr/scenarios/assets/solid/tsconfig.json deleted file mode 100644 index 42c3a2160f..0000000000 --- a/benchmarks/ssr/scenarios/assets/solid/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "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 deleted file mode 100644 index 3ee54e5ae2..0000000000 --- a/benchmarks/ssr/scenarios/assets/solid/vite.config.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - server: { - build: { - inlineCss: { enabled: true, transformAssets: true }, - }, - }, - }), - solid({ ssr: true, hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - execArgv: cpuSimulationExecArgv(), - isolate: true, - name: '@benchmarks/ssr assets (solid)', - watch: false, - environment: 'node', - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/assets/vue/project.json b/benchmarks/ssr/scenarios/assets/vue/project.json deleted file mode 100644 index 9667ff902c..0000000000 --- a/benchmarks/ssr/scenarios/assets/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-assets-vue", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} 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 deleted file mode 100644 index e56d41df6b..0000000000 --- a/benchmarks/ssr/scenarios/assets/vue/speed.assets-linked-css-control.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 3f77a0dcc1..0000000000 --- a/benchmarks/ssr/scenarios/assets/vue/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertAssetsScenario, - assetsBenchOptions, - runAssetsInlineLoop, -} 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 inline-css cdn (vue)', async () => - runAssetsInlineLoop(handler), - ).run(assetsBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/assets/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/assets/vue/src/routeTree.gen.ts deleted file mode 100644 index 2a6eb91f50..0000000000 --- a/benchmarks/ssr/scenarios/assets/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,94 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as AXRouteImport } from './routes/a.$x' -import { Route as AXYRouteImport } from './routes/a.$x.$y' - -const AXRoute = AXRouteImport.update({ - id: '/a/$x', - path: '/a/$x', - getParentRoute: () => rootRouteImport, -} as any) -const AXYRoute = AXYRouteImport.update({ - id: '/$y', - path: '/$y', - getParentRoute: () => AXRoute, -} as any) - -export interface FileRoutesByFullPath { - '/a/$x': typeof AXRouteWithChildren - '/a/$x/$y': typeof AXYRoute -} -export interface FileRoutesByTo { - '/a/$x': typeof AXRouteWithChildren - '/a/$x/$y': typeof AXYRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/a/$x': typeof AXRouteWithChildren - '/a/$x/$y': typeof AXYRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/a/$x' | '/a/$x/$y' - fileRoutesByTo: FileRoutesByTo - to: '/a/$x' | '/a/$x/$y' - id: '__root__' | '/a/$x' | '/a/$x/$y' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - AXRoute: typeof AXRouteWithChildren -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/a/$x': { - id: '/a/$x' - path: '/a/$x' - fullPath: '/a/$x' - preLoaderRoute: typeof AXRouteImport - parentRoute: typeof rootRouteImport - } - '/a/$x/$y': { - id: '/a/$x/$y' - path: '/$y' - fullPath: '/a/$x/$y' - preLoaderRoute: typeof AXYRouteImport - parentRoute: typeof AXRoute - } - } -} - -interface AXRouteChildren { - AXYRoute: typeof AXYRoute -} - -const AXRouteChildren: AXRouteChildren = { - AXYRoute: AXYRoute, -} - -const AXRouteWithChildren = AXRoute._addFileChildren(AXRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - AXRoute: AXRouteWithChildren, -} -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/benchmarks/ssr/scenarios/assets/vue/src/router.tsx b/benchmarks/ssr/scenarios/assets/vue/src/router.tsx deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/ssr/scenarios/assets/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/assets/vue/src/routes/__root.tsx b/benchmarks/ssr/scenarios/assets/vue/src/routes/__root.tsx deleted file mode 100644 index 760545d248..0000000000 --- a/benchmarks/ssr/scenarios/assets/vue/src/routes/__root.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import { - Body, - HeadContent, - Html, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/vue-router' - -export const Route = createRootRoute({ - head: () => ({ - meta: [ - { charSet: 'utf-8' }, - { name: 'viewport', content: 'width=device-width, initial-scale=1' }, - { name: 'application-name', content: 'SSR assets benchmark' }, - ], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} 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 deleted file mode 100644 index a29fe59f22..0000000000 --- a/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.$y.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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}` }], - links: Array.from({ length: 3 }, (_, index) => ({ - rel: 'preload', - as: 'image', - href: `/asset-preload/${params.y}-${index}.png`, - })), - }), - component: LeafComponent, -}) diff --git a/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.tsx b/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.tsx deleted file mode 100644 index e1fe0418e4..0000000000 --- a/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.tsx +++ /dev/null @@ -1,28 +0,0 @@ -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}` }], - links: Array.from({ length: 2 }, (_, index) => ({ - rel: 'preload', - as: 'image', - href: `/asset-preload/${params.x}-${index}.png`, - })), - }), - component: LevelAComponent, -}) diff --git a/benchmarks/ssr/scenarios/assets/vue/src/server.ts b/benchmarks/ssr/scenarios/assets/vue/src/server.ts deleted file mode 100644 index fd1e83d6b8..0000000000 --- a/benchmarks/ssr/scenarios/assets/vue/src/server.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { - createStartHandler, - defaultStreamHandler, -} from '@tanstack/vue-start/server' -import { createServerEntry } from '@tanstack/vue-start/server-entry' -import type { - TransformAssets, - TransformAssetsFn, -} from '@tanstack/vue-start/server' - -type CreateTransformContext = - | { warmup: true } - | { request: Request; warmup: false } - -const cdnOrigin = 'https://cdn.example.com' - -const createCdnTransform = (prefix: string): TransformAssetsFn => { - return ({ url }) => `${prefix}${url}` -} - -const transformAssets: TransformAssets = { - createTransform: (ctx: CreateTransformContext) => { - const prefix = ctx.warmup - ? cdnOrigin - : (ctx.request.headers.get('x-assets-cdn') ?? cdnOrigin) - - return createCdnTransform(prefix) - }, - cache: false, -} - -const handler = createStartHandler({ - handler: defaultStreamHandler, - inlineCss: true, - transformAssets, -}) - -export default createServerEntry({ - fetch(request) { - return handler(request, { - inlineCss: request.headers.get('x-inline-css') !== 'false', - responseLinkHeader: true, - }) - }, -}) diff --git a/benchmarks/ssr/scenarios/assets/vue/src/styles/assets-a.css b/benchmarks/ssr/scenarios/assets/vue/src/styles/assets-a.css deleted file mode 100644 index d3511ddd85..0000000000 --- a/benchmarks/ssr/scenarios/assets/vue/src/styles/assets-a.css +++ /dev/null @@ -1,8 +0,0 @@ -.assets-level-a { - color: #1f2937; - background-image: url('/asset-bg-a.svg'); -} - -.assets-level-a::before { - content: 'assets-level-a-css'; -} diff --git a/benchmarks/ssr/scenarios/assets/vue/src/styles/assets-leaf.css b/benchmarks/ssr/scenarios/assets/vue/src/styles/assets-leaf.css deleted file mode 100644 index 55e051b9a5..0000000000 --- a/benchmarks/ssr/scenarios/assets/vue/src/styles/assets-leaf.css +++ /dev/null @@ -1,8 +0,0 @@ -.assets-leaf { - border-color: #2563eb; - background-image: url('/asset-bg-leaf.svg'); -} - -.assets-leaf::before { - content: 'assets-leaf-css'; -} diff --git a/benchmarks/ssr/scenarios/assets/vue/tsconfig.json b/benchmarks/ssr/scenarios/assets/vue/tsconfig.json deleted file mode 100644 index 08c94853f4..0000000000 --- a/benchmarks/ssr/scenarios/assets/vue/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "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 deleted file mode 100644 index e664b9b02b..0000000000 --- a/benchmarks/ssr/scenarios/assets/vue/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - server: { - build: { - inlineCss: { enabled: true, transformAssets: true }, - }, - }, - }), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - 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/project.json b/benchmarks/ssr/scenarios/before-load/react/project.json deleted file mode 100644 index df2004f1f5..0000000000 --- a/benchmarks/ssr/scenarios/before-load/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-before-load-react", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/before-load/react/speed.bench.ts b/benchmarks/ssr/scenarios/before-load/react/speed.bench.ts deleted file mode 100644 index 8a4355a168..0000000000 --- a/benchmarks/ssr/scenarios/before-load/react/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertBeforeLoadScenario, - beforeLoadBenchOptions, - runBeforeLoadLoop, - 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 assertBeforeLoadScenario(handler) - -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/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/before-load/react/src/routeTree.gen.ts deleted file mode 100644 index 068b5a5433..0000000000 --- a/benchmarks/ssr/scenarios/before-load/react/src/routeTree.gen.ts +++ /dev/null @@ -1,120 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as ARouteImport } from './routes/$a' -import { Route as ABRouteImport } from './routes/$a.$b' -import { Route as ABCRouteImport } from './routes/$a.$b.$c' - -const ARoute = ARouteImport.update({ - id: '/$a', - path: '/$a', - getParentRoute: () => rootRouteImport, -} as any) -const ABRoute = ABRouteImport.update({ - id: '/$b', - path: '/$b', - getParentRoute: () => ARoute, -} as any) -const ABCRoute = ABCRouteImport.update({ - id: '/$c', - path: '/$c', - getParentRoute: () => ABRoute, -} as any) - -export interface FileRoutesByFullPath { - '/$a': typeof ARouteWithChildren - '/$a/$b': typeof ABRouteWithChildren - '/$a/$b/$c': typeof ABCRoute -} -export interface FileRoutesByTo { - '/$a': typeof ARouteWithChildren - '/$a/$b': typeof ABRouteWithChildren - '/$a/$b/$c': typeof ABCRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/$a': typeof ARouteWithChildren - '/$a/$b': typeof ABRouteWithChildren - '/$a/$b/$c': typeof ABCRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/$a' | '/$a/$b' | '/$a/$b/$c' - fileRoutesByTo: FileRoutesByTo - to: '/$a' | '/$a/$b' | '/$a/$b/$c' - id: '__root__' | '/$a' | '/$a/$b' | '/$a/$b/$c' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - ARoute: typeof ARouteWithChildren -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/$a': { - id: '/$a' - path: '/$a' - fullPath: '/$a' - preLoaderRoute: typeof ARouteImport - parentRoute: typeof rootRouteImport - } - '/$a/$b': { - id: '/$a/$b' - path: '/$b' - fullPath: '/$a/$b' - preLoaderRoute: typeof ABRouteImport - parentRoute: typeof ARoute - } - '/$a/$b/$c': { - id: '/$a/$b/$c' - path: '/$c' - fullPath: '/$a/$b/$c' - preLoaderRoute: typeof ABCRouteImport - parentRoute: typeof ABRoute - } - } -} - -interface ABRouteChildren { - ABCRoute: typeof ABCRoute -} - -const ABRouteChildren: ABRouteChildren = { - ABCRoute: ABCRoute, -} - -const ABRouteWithChildren = ABRoute._addFileChildren(ABRouteChildren) - -interface ARouteChildren { - ABRoute: typeof ABRouteWithChildren -} - -const ARouteChildren: ARouteChildren = { - ABRoute: ABRouteWithChildren, -} - -const ARouteWithChildren = ARoute._addFileChildren(ARouteChildren) - -const rootRouteChildren: RootRouteChildren = { - ARoute: ARouteWithChildren, -} -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/benchmarks/ssr/scenarios/before-load/react/src/router.tsx b/benchmarks/ssr/scenarios/before-load/react/src/router.tsx deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/ssr/scenarios/before-load/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/before-load/react/src/routes/$a.$b.$c.tsx b/benchmarks/ssr/scenarios/before-load/react/src/routes/$a.$b.$c.tsx deleted file mode 100644 index 71719a4f88..0000000000 --- a/benchmarks/ssr/scenarios/before-load/react/src/routes/$a.$b.$c.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { makeBeforeLoadMarker, type BeforeLoadContext } from '../../../shared' - -export const Route = createFileRoute('/$a/$b/$c')({ - beforeLoad: ({ params, context }) => { - const parent = context as BeforeLoadContext - - return { - chainToken: `${parent.chainToken}.${params.c}`, - ctxC: params.c, - } - }, - loader: ({ context }) => ({ - marker: makeBeforeLoadMarker(context as BeforeLoadContext), - }), - component: LevelCComponent, -}) - -function LevelCComponent() { - const data = Route.useLoaderData() - - return
{data.marker}
-} diff --git a/benchmarks/ssr/scenarios/before-load/react/src/routes/$a.$b.tsx b/benchmarks/ssr/scenarios/before-load/react/src/routes/$a.$b.tsx deleted file mode 100644 index 1a148e05fa..0000000000 --- a/benchmarks/ssr/scenarios/before-load/react/src/routes/$a.$b.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import type { BeforeLoadContext } from '../../../shared' - -export const Route = createFileRoute('/$a/$b')({ - beforeLoad: ({ params, context }) => { - const parent = context as BeforeLoadContext - - return { - chainToken: `${parent.chainToken}.${params.b}`, - ctxB: params.b, - } - }, - component: LevelBComponent, -}) - -function LevelBComponent() { - return -} diff --git a/benchmarks/ssr/scenarios/before-load/react/src/routes/$a.tsx b/benchmarks/ssr/scenarios/before-load/react/src/routes/$a.tsx deleted file mode 100644 index b5dcca33c3..0000000000 --- a/benchmarks/ssr/scenarios/before-load/react/src/routes/$a.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/$a')({ - beforeLoad: ({ params }) => ({ - chainToken: params.a, - ctxA: params.a, - }), - component: LevelAComponent, -}) - -function LevelAComponent() { - return -} diff --git a/benchmarks/ssr/scenarios/before-load/react/src/routes/__root.tsx b/benchmarks/ssr/scenarios/before-load/react/src/routes/__root.tsx deleted file mode 100644 index ff1da4c304..0000000000 --- a/benchmarks/ssr/scenarios/before-load/react/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/before-load/react/tsconfig.json b/benchmarks/ssr/scenarios/before-load/react/tsconfig.json deleted file mode 100644 index 232763bbe1..0000000000 --- a/benchmarks/ssr/scenarios/before-load/react/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../shared.ts", - "../shared-bench.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/before-load/react/vite.config.ts b/benchmarks/ssr/scenarios/before-load/react/vite.config.ts deleted file mode 100644 index 3fd72c5f1d..0000000000 --- a/benchmarks/ssr/scenarios/before-load/react/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - 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/shared-bench.ts b/benchmarks/ssr/scenarios/before-load/shared-bench.ts deleted file mode 100644 index cf3a02f114..0000000000 --- a/benchmarks/ssr/scenarios/before-load/shared-bench.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { makeBeforeLoadMarker } from './shared' -import { randomSegment, runRequestLoop } from '../../bench-utils' -import type { StartRequestHandler } from '../../bench-utils' - -export type { StartRequestHandler } - -const benchmarkSeed = 0xdecafbad -const beforeLoadLoopTotalRequests = 32 - -const requestInit = { - method: 'GET', - headers: { - accept: 'text/html', - }, -} satisfies RequestInit - -function buildBeforeLoadRequest(random: () => number, index: number) { - const suffix = index.toString(36) - const a = `${randomSegment(random)}-${suffix}` - const b = `${randomSegment(random)}-${suffix}` - const c = `${randomSegment(random)}-${suffix}` - - return new Request(`http://localhost/${a}/${b}/${c}`, requestInit) -} - -export async function assertBeforeLoadScenario(handler: StartRequestHandler) { - const response = await handler.fetch( - new Request('http://localhost/a-sanity/b-sanity/c-sanity', requestInit), - ) - const body = await response.text() - const expectedMarker = makeBeforeLoadMarker({ - ctxA: 'a-sanity', - ctxB: 'b-sanity', - ctxC: 'c-sanity', - chainToken: 'a-sanity.b-sanity.c-sanity', - }) - - if (response.status !== 200) { - throw new Error( - `Expected beforeLoad setup status 200, received ${response.status}`, - ) - } - - if (!body.includes(expectedMarker)) { - throw new Error( - `Expected beforeLoad setup response to include ${expectedMarker}`, - ) - } -} - -export const beforeLoadBenchOptions = { - warmupIterations: 100, - time: 10_000, - throws: true, -} - -export function runBeforeLoadLoop(handler: StartRequestHandler) { - return runRequestLoop(handler, { - seed: benchmarkSeed, - concurrency: 16, - totalRequests: beforeLoadLoopTotalRequests, - buildRequest: buildBeforeLoadRequest, - }) -} diff --git a/benchmarks/ssr/scenarios/before-load/shared.ts b/benchmarks/ssr/scenarios/before-load/shared.ts deleted file mode 100644 index 3c895aca03..0000000000 --- a/benchmarks/ssr/scenarios/before-load/shared.ts +++ /dev/null @@ -1,10 +0,0 @@ -export interface BeforeLoadContext { - chainToken?: string - ctxA?: string - ctxB?: string - ctxC?: string -} - -export function makeBeforeLoadMarker(context: BeforeLoadContext) { - return `ctx:${context.ctxA}:${context.ctxB}:${context.ctxC}:${context.chainToken}` -} diff --git a/benchmarks/ssr/scenarios/before-load/solid/project.json b/benchmarks/ssr/scenarios/before-load/solid/project.json deleted file mode 100644 index 804cd9c1b0..0000000000 --- a/benchmarks/ssr/scenarios/before-load/solid/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-before-load-solid", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/before-load/solid/speed.bench.ts b/benchmarks/ssr/scenarios/before-load/solid/speed.bench.ts deleted file mode 100644 index 27e0d3a64c..0000000000 --- a/benchmarks/ssr/scenarios/before-load/solid/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertBeforeLoadScenario, - beforeLoadBenchOptions, - runBeforeLoadLoop, - 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 assertBeforeLoadScenario(handler) - -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/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/before-load/solid/src/routeTree.gen.ts deleted file mode 100644 index 7b299cfcd1..0000000000 --- a/benchmarks/ssr/scenarios/before-load/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,120 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as ARouteImport } from './routes/$a' -import { Route as ABRouteImport } from './routes/$a.$b' -import { Route as ABCRouteImport } from './routes/$a.$b.$c' - -const ARoute = ARouteImport.update({ - id: '/$a', - path: '/$a', - getParentRoute: () => rootRouteImport, -} as any) -const ABRoute = ABRouteImport.update({ - id: '/$b', - path: '/$b', - getParentRoute: () => ARoute, -} as any) -const ABCRoute = ABCRouteImport.update({ - id: '/$c', - path: '/$c', - getParentRoute: () => ABRoute, -} as any) - -export interface FileRoutesByFullPath { - '/$a': typeof ARouteWithChildren - '/$a/$b': typeof ABRouteWithChildren - '/$a/$b/$c': typeof ABCRoute -} -export interface FileRoutesByTo { - '/$a': typeof ARouteWithChildren - '/$a/$b': typeof ABRouteWithChildren - '/$a/$b/$c': typeof ABCRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/$a': typeof ARouteWithChildren - '/$a/$b': typeof ABRouteWithChildren - '/$a/$b/$c': typeof ABCRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/$a' | '/$a/$b' | '/$a/$b/$c' - fileRoutesByTo: FileRoutesByTo - to: '/$a' | '/$a/$b' | '/$a/$b/$c' - id: '__root__' | '/$a' | '/$a/$b' | '/$a/$b/$c' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - ARoute: typeof ARouteWithChildren -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/$a': { - id: '/$a' - path: '/$a' - fullPath: '/$a' - preLoaderRoute: typeof ARouteImport - parentRoute: typeof rootRouteImport - } - '/$a/$b': { - id: '/$a/$b' - path: '/$b' - fullPath: '/$a/$b' - preLoaderRoute: typeof ABRouteImport - parentRoute: typeof ARoute - } - '/$a/$b/$c': { - id: '/$a/$b/$c' - path: '/$c' - fullPath: '/$a/$b/$c' - preLoaderRoute: typeof ABCRouteImport - parentRoute: typeof ABRoute - } - } -} - -interface ABRouteChildren { - ABCRoute: typeof ABCRoute -} - -const ABRouteChildren: ABRouteChildren = { - ABCRoute: ABCRoute, -} - -const ABRouteWithChildren = ABRoute._addFileChildren(ABRouteChildren) - -interface ARouteChildren { - ABRoute: typeof ABRouteWithChildren -} - -const ARouteChildren: ARouteChildren = { - ABRoute: ABRouteWithChildren, -} - -const ARouteWithChildren = ARoute._addFileChildren(ARouteChildren) - -const rootRouteChildren: RootRouteChildren = { - ARoute: ARouteWithChildren, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/solid-start' -declare module '@tanstack/solid-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/benchmarks/ssr/scenarios/before-load/solid/src/router.tsx b/benchmarks/ssr/scenarios/before-load/solid/src/router.tsx deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/ssr/scenarios/before-load/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/before-load/solid/src/routes/$a.$b.$c.tsx b/benchmarks/ssr/scenarios/before-load/solid/src/routes/$a.$b.$c.tsx deleted file mode 100644 index 7966bcc4c2..0000000000 --- a/benchmarks/ssr/scenarios/before-load/solid/src/routes/$a.$b.$c.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { makeBeforeLoadMarker, type BeforeLoadContext } from '../../../shared' - -export const Route = createFileRoute('/$a/$b/$c')({ - beforeLoad: ({ params, context }) => { - const parent = context as BeforeLoadContext - - return { - chainToken: `${parent.chainToken}.${params.c}`, - ctxC: params.c, - } - }, - loader: ({ context }) => ({ - marker: makeBeforeLoadMarker(context as BeforeLoadContext), - }), - component: LevelCComponent, -}) - -function LevelCComponent() { - const data = Route.useLoaderData() - - return
{data().marker}
-} diff --git a/benchmarks/ssr/scenarios/before-load/solid/src/routes/$a.$b.tsx b/benchmarks/ssr/scenarios/before-load/solid/src/routes/$a.$b.tsx deleted file mode 100644 index 90656dc7a1..0000000000 --- a/benchmarks/ssr/scenarios/before-load/solid/src/routes/$a.$b.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' -import type { BeforeLoadContext } from '../../../shared' - -export const Route = createFileRoute('/$a/$b')({ - beforeLoad: ({ params, context }) => { - const parent = context as BeforeLoadContext - - return { - chainToken: `${parent.chainToken}.${params.b}`, - ctxB: params.b, - } - }, - component: LevelBComponent, -}) - -function LevelBComponent() { - return -} diff --git a/benchmarks/ssr/scenarios/before-load/solid/src/routes/$a.tsx b/benchmarks/ssr/scenarios/before-load/solid/src/routes/$a.tsx deleted file mode 100644 index 6336f56640..0000000000 --- a/benchmarks/ssr/scenarios/before-load/solid/src/routes/$a.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/$a')({ - beforeLoad: ({ params }) => ({ - chainToken: params.a, - ctxA: params.a, - }), - component: LevelAComponent, -}) - -function LevelAComponent() { - return -} diff --git a/benchmarks/ssr/scenarios/before-load/solid/src/routes/__root.tsx b/benchmarks/ssr/scenarios/before-load/solid/src/routes/__root.tsx deleted file mode 100644 index e59de72236..0000000000 --- a/benchmarks/ssr/scenarios/before-load/solid/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/solid-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/before-load/solid/tsconfig.json b/benchmarks/ssr/scenarios/before-load/solid/tsconfig.json deleted file mode 100644 index 0995292743..0000000000 --- a/benchmarks/ssr/scenarios/before-load/solid/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../shared.ts", - "../shared-bench.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/before-load/solid/vite.config.ts b/benchmarks/ssr/scenarios/before-load/solid/vite.config.ts deleted file mode 100644 index a20e32742e..0000000000 --- a/benchmarks/ssr/scenarios/before-load/solid/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - solid({ ssr: true, hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - execArgv: cpuSimulationExecArgv(), - isolate: true, - name: '@benchmarks/ssr before-load (solid)', - watch: false, - environment: 'node', - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/before-load/vue/project.json b/benchmarks/ssr/scenarios/before-load/vue/project.json deleted file mode 100644 index 92d724821e..0000000000 --- a/benchmarks/ssr/scenarios/before-load/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-before-load-vue", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/before-load/vue/speed.bench.ts b/benchmarks/ssr/scenarios/before-load/vue/speed.bench.ts deleted file mode 100644 index 8684c159eb..0000000000 --- a/benchmarks/ssr/scenarios/before-load/vue/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertBeforeLoadScenario, - beforeLoadBenchOptions, - runBeforeLoadLoop, - 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 assertBeforeLoadScenario(handler) - -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/routeTree.gen.ts b/benchmarks/ssr/scenarios/before-load/vue/src/routeTree.gen.ts deleted file mode 100644 index 24ee6c3b9d..0000000000 --- a/benchmarks/ssr/scenarios/before-load/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,120 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as ARouteImport } from './routes/$a' -import { Route as ABRouteImport } from './routes/$a.$b' -import { Route as ABCRouteImport } from './routes/$a.$b.$c' - -const ARoute = ARouteImport.update({ - id: '/$a', - path: '/$a', - getParentRoute: () => rootRouteImport, -} as any) -const ABRoute = ABRouteImport.update({ - id: '/$b', - path: '/$b', - getParentRoute: () => ARoute, -} as any) -const ABCRoute = ABCRouteImport.update({ - id: '/$c', - path: '/$c', - getParentRoute: () => ABRoute, -} as any) - -export interface FileRoutesByFullPath { - '/$a': typeof ARouteWithChildren - '/$a/$b': typeof ABRouteWithChildren - '/$a/$b/$c': typeof ABCRoute -} -export interface FileRoutesByTo { - '/$a': typeof ARouteWithChildren - '/$a/$b': typeof ABRouteWithChildren - '/$a/$b/$c': typeof ABCRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/$a': typeof ARouteWithChildren - '/$a/$b': typeof ABRouteWithChildren - '/$a/$b/$c': typeof ABCRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/$a' | '/$a/$b' | '/$a/$b/$c' - fileRoutesByTo: FileRoutesByTo - to: '/$a' | '/$a/$b' | '/$a/$b/$c' - id: '__root__' | '/$a' | '/$a/$b' | '/$a/$b/$c' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - ARoute: typeof ARouteWithChildren -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/$a': { - id: '/$a' - path: '/$a' - fullPath: '/$a' - preLoaderRoute: typeof ARouteImport - parentRoute: typeof rootRouteImport - } - '/$a/$b': { - id: '/$a/$b' - path: '/$b' - fullPath: '/$a/$b' - preLoaderRoute: typeof ABRouteImport - parentRoute: typeof ARoute - } - '/$a/$b/$c': { - id: '/$a/$b/$c' - path: '/$c' - fullPath: '/$a/$b/$c' - preLoaderRoute: typeof ABCRouteImport - parentRoute: typeof ABRoute - } - } -} - -interface ABRouteChildren { - ABCRoute: typeof ABCRoute -} - -const ABRouteChildren: ABRouteChildren = { - ABCRoute: ABCRoute, -} - -const ABRouteWithChildren = ABRoute._addFileChildren(ABRouteChildren) - -interface ARouteChildren { - ABRoute: typeof ABRouteWithChildren -} - -const ARouteChildren: ARouteChildren = { - ABRoute: ABRouteWithChildren, -} - -const ARouteWithChildren = ARoute._addFileChildren(ARouteChildren) - -const rootRouteChildren: RootRouteChildren = { - ARoute: ARouteWithChildren, -} -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/benchmarks/ssr/scenarios/before-load/vue/src/router.tsx b/benchmarks/ssr/scenarios/before-load/vue/src/router.tsx deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/ssr/scenarios/before-load/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} 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 deleted file mode 100644 index 178d4071eb..0000000000 --- a/benchmarks/ssr/scenarios/before-load/vue/src/routes/$a.$b.$c.tsx +++ /dev/null @@ -1,26 +0,0 @@ -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 - - return { - chainToken: `${parent.chainToken}.${params.c}`, - ctxC: params.c, - } - }, - loader: ({ context }) => ({ - marker: makeBeforeLoadMarker(context as BeforeLoadContext), - }), - component: LevelCComponent, -}) diff --git a/benchmarks/ssr/scenarios/before-load/vue/src/routes/$a.$b.tsx b/benchmarks/ssr/scenarios/before-load/vue/src/routes/$a.$b.tsx deleted file mode 100644 index 43ea0dcf87..0000000000 --- a/benchmarks/ssr/scenarios/before-load/vue/src/routes/$a.$b.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/vue-router' -import type { BeforeLoadContext } from '../../../shared' - -export const Route = createFileRoute('/$a/$b')({ - beforeLoad: ({ params, context }) => { - const parent = context as BeforeLoadContext - - return { - chainToken: `${parent.chainToken}.${params.b}`, - ctxB: params.b, - } - }, - component: LevelBComponent, -}) - -function LevelBComponent() { - return -} diff --git a/benchmarks/ssr/scenarios/before-load/vue/src/routes/$a.tsx b/benchmarks/ssr/scenarios/before-load/vue/src/routes/$a.tsx deleted file mode 100644 index 7f036dceac..0000000000 --- a/benchmarks/ssr/scenarios/before-load/vue/src/routes/$a.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/vue-router' - -export const Route = createFileRoute('/$a')({ - beforeLoad: ({ params }) => ({ - chainToken: params.a, - ctxA: params.a, - }), - component: LevelAComponent, -}) - -function LevelAComponent() { - return -} diff --git a/benchmarks/ssr/scenarios/before-load/vue/src/routes/__root.tsx b/benchmarks/ssr/scenarios/before-load/vue/src/routes/__root.tsx deleted file mode 100644 index 49422aac38..0000000000 --- a/benchmarks/ssr/scenarios/before-load/vue/src/routes/__root.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { - Body, - HeadContent, - Html, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/vue-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/before-load/vue/tsconfig.json b/benchmarks/ssr/scenarios/before-load/vue/tsconfig.json deleted file mode 100644 index 33e5cc442d..0000000000 --- a/benchmarks/ssr/scenarios/before-load/vue/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../shared.ts", - "../shared-bench.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/before-load/vue/vite.config.ts b/benchmarks/ssr/scenarios/before-load/vue/vite.config.ts deleted file mode 100644 index 093776869f..0000000000 --- a/benchmarks/ssr/scenarios/before-load/vue/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - 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/project.json b/benchmarks/ssr/scenarios/control-flow/react/project.json deleted file mode 100644 index 80086788eb..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-control-flow-react", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/control-flow/react/speed.bench.ts b/benchmarks/ssr/scenarios/control-flow/react/speed.bench.ts deleted file mode 100644 index 899f400799..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertControlFlowSanity, - controlFlowBenchOptions, - runRedirectLoop, -} 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 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 deleted file mode 100644 index 0a93c5eac3..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-error-500.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 53e09fd34e..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-route-headers.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 1cd7c1044c..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-unmatched-404.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 1e8abfd318..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/speed.not-found.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/control-flow/react/src/routeTree.gen.ts deleted file mode 100644 index 4d4424c222..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/src/routeTree.gen.ts +++ /dev/null @@ -1,177 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 BoomIdRoute = BoomIdRouteImport.update({ - id: '/boom/$id', - path: '/boom/$id', - getParentRoute: () => rootRouteImport, -} as any) -const FromIdRoute = FromIdRouteImport.update({ - id: '/from/$id', - path: '/from/$id', - getParentRoute: () => rootRouteImport, -} as any) -const HeadersIdRoute = HeadersIdRouteImport.update({ - id: '/headers/$id', - path: '/headers/$id', - 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) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/boom/$id': typeof BoomIdRoute - '/from/$id': typeof FromIdRoute - '/headers/$id': typeof HeadersIdRoute - '/missing/$id': typeof MissingIdRoute - '/target/$id': typeof TargetIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/boom/$id': typeof BoomIdRoute - '/from/$id': typeof FromIdRoute - '/headers/$id': typeof HeadersIdRoute - '/missing/$id': typeof MissingIdRoute - '/target/$id': typeof TargetIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/boom/$id': typeof BoomIdRoute - '/from/$id': typeof FromIdRoute - '/headers/$id': typeof HeadersIdRoute - '/missing/$id': typeof MissingIdRoute - '/target/$id': typeof TargetIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/boom/$id' - | '/from/$id' - | '/headers/$id' - | '/missing/$id' - | '/target/$id' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/boom/$id' - | '/from/$id' - | '/headers/$id' - | '/missing/$id' - | '/target/$id' - id: - | '__root__' - | '/' - | '/boom/$id' - | '/from/$id' - | '/headers/$id' - | '/missing/$id' - | '/target/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - BoomIdRoute: typeof BoomIdRoute - FromIdRoute: typeof FromIdRoute - HeadersIdRoute: typeof HeadersIdRoute - MissingIdRoute: typeof MissingIdRoute - TargetIdRoute: typeof TargetIdRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/boom/$id': { - id: '/boom/$id' - path: '/boom/$id' - fullPath: '/boom/$id' - preLoaderRoute: typeof BoomIdRouteImport - parentRoute: typeof rootRouteImport - } - '/from/$id': { - id: '/from/$id' - path: '/from/$id' - fullPath: '/from/$id' - preLoaderRoute: typeof FromIdRouteImport - parentRoute: typeof rootRouteImport - } - '/headers/$id': { - id: '/headers/$id' - path: '/headers/$id' - fullPath: '/headers/$id' - preLoaderRoute: typeof HeadersIdRouteImport - 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 - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - BoomIdRoute: BoomIdRoute, - FromIdRoute: FromIdRoute, - HeadersIdRoute: HeadersIdRoute, - MissingIdRoute: MissingIdRoute, - TargetIdRoute: TargetIdRoute, -} -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/benchmarks/ssr/scenarios/control-flow/react/src/router.tsx b/benchmarks/ssr/scenarios/control-flow/react/src/router.tsx deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/control-flow/react/src/routes/__root.tsx b/benchmarks/ssr/scenarios/control-flow/react/src/routes/__root.tsx deleted file mode 100644 index e08ff06361..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/src/routes/__root.tsx +++ /dev/null @@ -1,30 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: RootComponent, - notFoundComponent: RootNotFoundComponent, - validateSearch: (s) => s as { q?: string }, -}) - -function RootNotFoundComponent() { - return
root-not-found-marker
-} - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/control-flow/react/src/routes/boom.$id.tsx b/benchmarks/ssr/scenarios/control-flow/react/src/routes/boom.$id.tsx deleted file mode 100644 index eb47d34070..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/src/routes/boom.$id.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/boom/$id')({ - loader: ({ params }) => { - throw new Error(`boom-${params.id}`) - }, - errorComponent: BoomErrorComponent, - component: BoomComponent, -}) - -function BoomErrorComponent() { - return
control-flow-error-boundary
-} - -function BoomComponent() { - return null -} diff --git a/benchmarks/ssr/scenarios/control-flow/react/src/routes/from.$id.tsx b/benchmarks/ssr/scenarios/control-flow/react/src/routes/from.$id.tsx deleted file mode 100644 index e9289fce30..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/src/routes/from.$id.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute, redirect } from '@tanstack/react-router' - -export const Route = createFileRoute('/from/$id')({ - loader: ({ params }) => { - const { id } = params - - throw redirect({ to: '/target/$id', params: { id } }) - }, - component: FromComponent, -}) - -function FromComponent() { - return null -} diff --git a/benchmarks/ssr/scenarios/control-flow/react/src/routes/headers.$id.tsx b/benchmarks/ssr/scenarios/control-flow/react/src/routes/headers.$id.tsx deleted file mode 100644 index 412d056d85..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/src/routes/headers.$id.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/headers/$id')({ - headers: ({ params }) => ({ - 'x-bench-route-header': `route-header-${params.id}`, - 'x-bench-route-static': 'control-flow-route-headers', - }), - component: HeadersComponent, -}) - -function HeadersComponent() { - const params = Route.useParams() - - return
{`headers-${params.id}`}
-} diff --git a/benchmarks/ssr/scenarios/control-flow/react/src/routes/index.tsx b/benchmarks/ssr/scenarios/control-flow/react/src/routes/index.tsx deleted file mode 100644 index e9886f60c4..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
control-flow-index
-} diff --git a/benchmarks/ssr/scenarios/control-flow/react/src/routes/missing.$id.tsx b/benchmarks/ssr/scenarios/control-flow/react/src/routes/missing.$id.tsx deleted file mode 100644 index b7d760e562..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/src/routes/missing.$id.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import { createFileRoute, notFound } from '@tanstack/react-router' - -export const Route = createFileRoute('/missing/$id')({ - loader: () => { - throw notFound() - }, - component: MissingComponent, -}) - -function MissingComponent() { - return null -} diff --git a/benchmarks/ssr/scenarios/control-flow/react/src/routes/target.$id.tsx b/benchmarks/ssr/scenarios/control-flow/react/src/routes/target.$id.tsx deleted file mode 100644 index 1c13394cb2..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/src/routes/target.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/target/$id')({ - component: TargetComponent, -}) - -function TargetComponent() { - const params = Route.useParams() - - return
{`target-${params.id}`}
-} diff --git a/benchmarks/ssr/scenarios/control-flow/react/tsconfig.json b/benchmarks/ssr/scenarios/control-flow/react/tsconfig.json deleted file mode 100644 index cf14e1d440..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "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 deleted file mode 100644 index 273d7d9d80..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/react/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - 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/shared.ts b/benchmarks/ssr/scenarios/control-flow/shared.ts deleted file mode 100644 index 307665d59d..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/shared.ts +++ /dev/null @@ -1,230 +0,0 @@ -import { expect } from 'vitest' -import { randomSegment, runRequestLoop } from '../../bench-utils' -import type { StartRequestHandler } from '../../bench-utils' - -export type { StartRequestHandler } - -const benchmarkSeed = 0xdecafbad -const redirectLoopTotalRequests = 112 -const notFoundLoopTotalRequests = 48 -const errorLoopTotalRequests = 48 -const unmatchedLoopTotalRequests = 64 -const routeHeadersLoopTotalRequests = 64 - -// Pinned to the current built handler responses for these control-flow routes. -const OK_STATUS = 200 -const REDIRECT_STATUS = 307 -const NOT_FOUND_STATUS = 404 -const ERROR_STATUS = 500 -const ROUTE_HEADERS_STATIC_VALUE = 'control-flow-route-headers' - -const requestInit = { - method: 'GET', - headers: { - accept: 'text/html', - }, -} satisfies RequestInit - -export const controlFlowBenchOptions = { - warmupIterations: 100, - time: 10_000, - throws: true, -} - -function buildRedirectRequest(random: () => number) { - return new Request( - `http://localhost/from/${randomSegment(random)}`, - requestInit, - ) -} - -function buildNotFoundRequest(random: () => number) { - return new Request( - `http://localhost/missing/${randomSegment(random)}`, - requestInit, - ) -} - -function buildErrorRequest(random: () => number) { - return new Request( - `http://localhost/boom/${randomSegment(random)}`, - requestInit, - ) -} - -function buildUnmatchedRequest(random: () => number) { - return new Request( - `http://localhost/definitely-not-a-route/${randomSegment(random)}`, - requestInit, - ) -} - -function buildRouteHeadersRequest(random: () => number) { - return new Request( - `http://localhost/headers/${randomSegment(random)}`, - requestInit, - ) -} - -function getRequestId(request: Request) { - const id = new URL(request.url).pathname.split('/').pop() - - if (!id) { - throw new Error(`expected request id in ${request.url}`) - } - - return id -} - -function validateRedirectResponse(response: Response) { - if (response.status !== REDIRECT_STATUS) { - throw new Error(`expected ${REDIRECT_STATUS}, got ${response.status}`) - } -} - -function validateNotFoundResponse(response: Response) { - if (response.status !== NOT_FOUND_STATUS) { - throw new Error(`expected ${NOT_FOUND_STATUS}, got ${response.status}`) - } -} - -function validateErrorResponse(response: Response) { - if (response.status !== ERROR_STATUS) { - throw new Error(`expected ${ERROR_STATUS}, got ${response.status}`) - } -} - -function validateUnmatchedResponse(response: Response) { - if (response.status !== NOT_FOUND_STATUS) { - throw new Error(`expected ${NOT_FOUND_STATUS}, got ${response.status}`) - } -} - -function validateRouteHeadersResponse(response: Response, request: Request) { - if (response.status !== OK_STATUS) { - throw new Error(`expected ${OK_STATUS}, got ${response.status}`) - } - - const id = getRequestId(request) - const routeHeader = response.headers.get('x-bench-route-header') - - if (routeHeader !== `route-header-${id}`) { - throw new Error(`expected route header for ${id}, got ${routeHeader}`) - } - - const staticHeader = response.headers.get('x-bench-route-static') - - if (staticHeader !== ROUTE_HEADERS_STATIC_VALUE) { - throw new Error( - `expected route static header ${ROUTE_HEADERS_STATIC_VALUE}, got ${staticHeader}`, - ) - } -} - -export function runRedirectLoop(handler: StartRequestHandler) { - return runRequestLoop(handler, { - seed: benchmarkSeed, - concurrency: 16, - totalRequests: redirectLoopTotalRequests, - buildRequest: buildRedirectRequest, - validateResponse: validateRedirectResponse, - }) -} - -export function runNotFoundLoop(handler: StartRequestHandler) { - return runRequestLoop(handler, { - seed: benchmarkSeed, - concurrency: 16, - totalRequests: notFoundLoopTotalRequests, - buildRequest: buildNotFoundRequest, - validateResponse: validateNotFoundResponse, - }) -} - -export function runErrorLoop(handler: StartRequestHandler) { - return runRequestLoop(handler, { - seed: benchmarkSeed, - concurrency: 16, - totalRequests: errorLoopTotalRequests, - buildRequest: buildErrorRequest, - validateResponse: validateErrorResponse, - }) -} - -export function runUnmatchedLoop(handler: StartRequestHandler) { - return runRequestLoop(handler, { - seed: benchmarkSeed, - concurrency: 16, - totalRequests: unmatchedLoopTotalRequests, - buildRequest: buildUnmatchedRequest, - validateResponse: validateUnmatchedResponse, - }) -} - -export function runRouteHeadersLoop(handler: StartRequestHandler) { - return runRequestLoop(handler, { - seed: benchmarkSeed, - concurrency: 16, - totalRequests: routeHeadersLoopTotalRequests, - buildRequest: buildRouteHeadersRequest, - validateResponse: validateRouteHeadersResponse, - }) -} - -export async function assertControlFlowSanity(handler: StartRequestHandler) { - const redirectId = 'sanity-redirect' - const redirectResponse = await handler.fetch( - new Request(`http://localhost/from/${redirectId}`, requestInit), - ) - - expect(redirectResponse.status).toBe(REDIRECT_STATUS) - expect(redirectResponse.headers.get('location')).toBe(`/target/${redirectId}`) - - const notFoundResponse = await handler.fetch( - new Request('http://localhost/missing/sanity-missing', requestInit), - ) - const notFoundBody = await notFoundResponse.text() - - expect(notFoundResponse.status).toBe(NOT_FOUND_STATUS) - expect(notFoundBody).toContain('root-not-found-marker') - - const errorId = 'sanity-error' - const errorResponse = await handler.fetch( - new Request(`http://localhost/boom/${errorId}`, requestInit), - ) - const errorBody = await errorResponse.text() - - expect(errorResponse.status).toBe(ERROR_STATUS) - expect(errorBody).toContain('data-bench="error-boundary"') - const firstScriptIndex = errorBody.indexOf(' { - 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 deleted file mode 100644 index 57a2f0fbe9..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-error-500.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 6581e92b39..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-route-headers.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 40f1679320..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-unmatched-404.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index efcb7cc229..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/speed.not-found.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 3cec17d9c8..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,177 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 BoomIdRoute = BoomIdRouteImport.update({ - id: '/boom/$id', - path: '/boom/$id', - getParentRoute: () => rootRouteImport, -} as any) -const FromIdRoute = FromIdRouteImport.update({ - id: '/from/$id', - path: '/from/$id', - getParentRoute: () => rootRouteImport, -} as any) -const HeadersIdRoute = HeadersIdRouteImport.update({ - id: '/headers/$id', - path: '/headers/$id', - 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) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/boom/$id': typeof BoomIdRoute - '/from/$id': typeof FromIdRoute - '/headers/$id': typeof HeadersIdRoute - '/missing/$id': typeof MissingIdRoute - '/target/$id': typeof TargetIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/boom/$id': typeof BoomIdRoute - '/from/$id': typeof FromIdRoute - '/headers/$id': typeof HeadersIdRoute - '/missing/$id': typeof MissingIdRoute - '/target/$id': typeof TargetIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/boom/$id': typeof BoomIdRoute - '/from/$id': typeof FromIdRoute - '/headers/$id': typeof HeadersIdRoute - '/missing/$id': typeof MissingIdRoute - '/target/$id': typeof TargetIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/boom/$id' - | '/from/$id' - | '/headers/$id' - | '/missing/$id' - | '/target/$id' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/boom/$id' - | '/from/$id' - | '/headers/$id' - | '/missing/$id' - | '/target/$id' - id: - | '__root__' - | '/' - | '/boom/$id' - | '/from/$id' - | '/headers/$id' - | '/missing/$id' - | '/target/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - BoomIdRoute: typeof BoomIdRoute - FromIdRoute: typeof FromIdRoute - HeadersIdRoute: typeof HeadersIdRoute - MissingIdRoute: typeof MissingIdRoute - TargetIdRoute: typeof TargetIdRoute -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/boom/$id': { - id: '/boom/$id' - path: '/boom/$id' - fullPath: '/boom/$id' - preLoaderRoute: typeof BoomIdRouteImport - parentRoute: typeof rootRouteImport - } - '/from/$id': { - id: '/from/$id' - path: '/from/$id' - fullPath: '/from/$id' - preLoaderRoute: typeof FromIdRouteImport - parentRoute: typeof rootRouteImport - } - '/headers/$id': { - id: '/headers/$id' - path: '/headers/$id' - fullPath: '/headers/$id' - preLoaderRoute: typeof HeadersIdRouteImport - 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 - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - BoomIdRoute: BoomIdRoute, - FromIdRoute: FromIdRoute, - HeadersIdRoute: HeadersIdRoute, - MissingIdRoute: MissingIdRoute, - TargetIdRoute: TargetIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/solid-start' -declare module '@tanstack/solid-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/benchmarks/ssr/scenarios/control-flow/solid/src/router.tsx b/benchmarks/ssr/scenarios/control-flow/solid/src/router.tsx deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/control-flow/solid/src/routes/__root.tsx b/benchmarks/ssr/scenarios/control-flow/solid/src/routes/__root.tsx deleted file mode 100644 index dc8b783e76..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/src/routes/__root.tsx +++ /dev/null @@ -1,30 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/solid-router' - -export const Route = createRootRoute({ - component: RootComponent, - notFoundComponent: RootNotFoundComponent, - validateSearch: (s) => s as { q?: string }, -}) - -function RootNotFoundComponent() { - return
root-not-found-marker
-} - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/control-flow/solid/src/routes/boom.$id.tsx b/benchmarks/ssr/scenarios/control-flow/solid/src/routes/boom.$id.tsx deleted file mode 100644 index 0bcc4dc02b..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/src/routes/boom.$id.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/boom/$id')({ - loader: ({ params }) => { - throw new Error(`boom-${params.id}`) - }, - errorComponent: BoomErrorComponent, - component: BoomComponent, -}) - -function BoomErrorComponent() { - return
control-flow-error-boundary
-} - -function BoomComponent() { - return null -} diff --git a/benchmarks/ssr/scenarios/control-flow/solid/src/routes/from.$id.tsx b/benchmarks/ssr/scenarios/control-flow/solid/src/routes/from.$id.tsx deleted file mode 100644 index a319375db3..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/src/routes/from.$id.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute, redirect } from '@tanstack/solid-router' - -export const Route = createFileRoute('/from/$id')({ - loader: ({ params }) => { - const { id } = params - - throw redirect({ to: '/target/$id', params: { id } }) - }, - component: FromComponent, -}) - -function FromComponent() { - return null -} diff --git a/benchmarks/ssr/scenarios/control-flow/solid/src/routes/headers.$id.tsx b/benchmarks/ssr/scenarios/control-flow/solid/src/routes/headers.$id.tsx deleted file mode 100644 index 9d87b4a354..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/src/routes/headers.$id.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/headers/$id')({ - headers: ({ params }) => ({ - 'x-bench-route-header': `route-header-${params.id}`, - 'x-bench-route-static': 'control-flow-route-headers', - }), - component: HeadersComponent, -}) - -function HeadersComponent() { - const params = Route.useParams() - - return
{`headers-${params().id}`}
-} diff --git a/benchmarks/ssr/scenarios/control-flow/solid/src/routes/index.tsx b/benchmarks/ssr/scenarios/control-flow/solid/src/routes/index.tsx deleted file mode 100644 index 96b26a2d6c..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
control-flow-index
-} diff --git a/benchmarks/ssr/scenarios/control-flow/solid/src/routes/missing.$id.tsx b/benchmarks/ssr/scenarios/control-flow/solid/src/routes/missing.$id.tsx deleted file mode 100644 index e5c42b56dc..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/src/routes/missing.$id.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import { createFileRoute, notFound } from '@tanstack/solid-router' - -export const Route = createFileRoute('/missing/$id')({ - loader: () => { - throw notFound() - }, - component: MissingComponent, -}) - -function MissingComponent() { - return null -} diff --git a/benchmarks/ssr/scenarios/control-flow/solid/src/routes/target.$id.tsx b/benchmarks/ssr/scenarios/control-flow/solid/src/routes/target.$id.tsx deleted file mode 100644 index 4196fc1183..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/src/routes/target.$id.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/target/$id')({ - component: TargetComponent, -}) - -function TargetComponent() { - const params = Route.useParams() - - return
{`target-${params().id}`}
-} diff --git a/benchmarks/ssr/scenarios/control-flow/solid/tsconfig.json b/benchmarks/ssr/scenarios/control-flow/solid/tsconfig.json deleted file mode 100644 index 42c3a2160f..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "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 deleted file mode 100644 index c75c957466..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/solid/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - solid({ ssr: true, hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - execArgv: cpuSimulationExecArgv(), - isolate: true, - name: '@benchmarks/ssr control-flow (solid)', - watch: false, - environment: 'node', - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/control-flow/vue/project.json b/benchmarks/ssr/scenarios/control-flow/vue/project.json deleted file mode 100644 index e0e014e588..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-control-flow-vue", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/control-flow/vue/speed.bench.ts b/benchmarks/ssr/scenarios/control-flow/vue/speed.bench.ts deleted file mode 100644 index 0b95f426f2..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertControlFlowSanity, - controlFlowBenchOptions, - runRedirectLoop, -} 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 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 deleted file mode 100644 index 262ca951af..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-error-500.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index bf8c90a8a1..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-route-headers.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index d7f8ebeb9e..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-unmatched-404.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 4b84fb594c..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/speed.not-found.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 6dcf0d095e..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,177 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 BoomIdRoute = BoomIdRouteImport.update({ - id: '/boom/$id', - path: '/boom/$id', - getParentRoute: () => rootRouteImport, -} as any) -const FromIdRoute = FromIdRouteImport.update({ - id: '/from/$id', - path: '/from/$id', - getParentRoute: () => rootRouteImport, -} as any) -const HeadersIdRoute = HeadersIdRouteImport.update({ - id: '/headers/$id', - path: '/headers/$id', - 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) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/boom/$id': typeof BoomIdRoute - '/from/$id': typeof FromIdRoute - '/headers/$id': typeof HeadersIdRoute - '/missing/$id': typeof MissingIdRoute - '/target/$id': typeof TargetIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/boom/$id': typeof BoomIdRoute - '/from/$id': typeof FromIdRoute - '/headers/$id': typeof HeadersIdRoute - '/missing/$id': typeof MissingIdRoute - '/target/$id': typeof TargetIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/boom/$id': typeof BoomIdRoute - '/from/$id': typeof FromIdRoute - '/headers/$id': typeof HeadersIdRoute - '/missing/$id': typeof MissingIdRoute - '/target/$id': typeof TargetIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/boom/$id' - | '/from/$id' - | '/headers/$id' - | '/missing/$id' - | '/target/$id' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/boom/$id' - | '/from/$id' - | '/headers/$id' - | '/missing/$id' - | '/target/$id' - id: - | '__root__' - | '/' - | '/boom/$id' - | '/from/$id' - | '/headers/$id' - | '/missing/$id' - | '/target/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - BoomIdRoute: typeof BoomIdRoute - FromIdRoute: typeof FromIdRoute - HeadersIdRoute: typeof HeadersIdRoute - MissingIdRoute: typeof MissingIdRoute - TargetIdRoute: typeof TargetIdRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/boom/$id': { - id: '/boom/$id' - path: '/boom/$id' - fullPath: '/boom/$id' - preLoaderRoute: typeof BoomIdRouteImport - parentRoute: typeof rootRouteImport - } - '/from/$id': { - id: '/from/$id' - path: '/from/$id' - fullPath: '/from/$id' - preLoaderRoute: typeof FromIdRouteImport - parentRoute: typeof rootRouteImport - } - '/headers/$id': { - id: '/headers/$id' - path: '/headers/$id' - fullPath: '/headers/$id' - preLoaderRoute: typeof HeadersIdRouteImport - 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 - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - BoomIdRoute: BoomIdRoute, - FromIdRoute: FromIdRoute, - HeadersIdRoute: HeadersIdRoute, - MissingIdRoute: MissingIdRoute, - TargetIdRoute: TargetIdRoute, -} -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/benchmarks/ssr/scenarios/control-flow/vue/src/router.tsx b/benchmarks/ssr/scenarios/control-flow/vue/src/router.tsx deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/__root.tsx b/benchmarks/ssr/scenarios/control-flow/vue/src/routes/__root.tsx deleted file mode 100644 index 815466918a..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/__root.tsx +++ /dev/null @@ -1,32 +0,0 @@ -import { - Body, - HeadContent, - Html, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/vue-router' - -export const Route = createRootRoute({ - component: RootComponent, - notFoundComponent: RootNotFoundComponent, - validateSearch: (s) => s as { q?: string }, -}) - -function RootNotFoundComponent() { - return
root-not-found-marker
-} - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/boom.$id.tsx b/benchmarks/ssr/scenarios/control-flow/vue/src/routes/boom.$id.tsx deleted file mode 100644 index dfae636ae7..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/boom.$id.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' - -export const Route = createFileRoute('/boom/$id')({ - loader: ({ params }) => { - throw new Error(`boom-${params.id}`) - }, - errorComponent: BoomErrorComponent, - component: BoomComponent, -}) - -function BoomErrorComponent() { - return
control-flow-error-boundary
-} - -function BoomComponent() { - return <> -} diff --git a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/from.$id.tsx b/benchmarks/ssr/scenarios/control-flow/vue/src/routes/from.$id.tsx deleted file mode 100644 index dfb90a51f8..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/from.$id.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute, redirect } from '@tanstack/vue-router' - -export const Route = createFileRoute('/from/$id')({ - loader: ({ params }) => { - const { id } = params - - throw redirect({ to: '/target/$id', params: { id } }) - }, - component: FromComponent, -}) - -function FromComponent() { - return <> -} 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 deleted file mode 100644 index 20c1bbe5ac..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/headers.$id.tsx +++ /dev/null @@ -1,18 +0,0 @@ -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}`, - 'x-bench-route-static': 'control-flow-route-headers', - }), - component: HeadersComponent, -}) diff --git a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/index.tsx b/benchmarks/ssr/scenarios/control-flow/vue/src/routes/index.tsx deleted file mode 100644 index 51a503a1d1..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
control-flow-index
-} diff --git a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/missing.$id.tsx b/benchmarks/ssr/scenarios/control-flow/vue/src/routes/missing.$id.tsx deleted file mode 100644 index b15333f5a3..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/missing.$id.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import { createFileRoute, notFound } from '@tanstack/vue-router' - -export const Route = createFileRoute('/missing/$id')({ - loader: () => { - throw notFound() - }, - component: MissingComponent, -}) - -function MissingComponent() { - return <> -} 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 deleted file mode 100644 index 0bbf4a3dc6..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/target.$id.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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, -}) diff --git a/benchmarks/ssr/scenarios/control-flow/vue/tsconfig.json b/benchmarks/ssr/scenarios/control-flow/vue/tsconfig.json deleted file mode 100644 index 08c94853f4..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "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 deleted file mode 100644 index 1b77968d96..0000000000 --- a/benchmarks/ssr/scenarios/control-flow/vue/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - 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 deleted file mode 100644 index d2784aed38..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/bench.ts +++ /dev/null @@ -1,309 +0,0 @@ -import { toJSONAsync } from 'seroval' -import { - createDeterministicRandom, - randomSegment, - runRequestLoop, -} from '../../bench-utils' -import { - expectedFunctionTotal, - expectedRequestTotal, - getExpectedRequestContext, - makeDocumentMarker, - makeServerFnMarker, - makeServerRouteMarker, - setRequestMiddlewareCount, -} from './shared' -import type { RequestMiddlewareCount } from './shared' -import type { StartRequestHandler } from '../../bench-utils' - -export type { StartRequestHandler } - -type Payload = { - q: string - n: number - nested: { list: Array } -} - -type FnUrls = { - post: string -} - -export interface GlobalMiddlewareBenchContext { - urls: FnUrls - bodies: Array - expectedFnMarker: string -} - -const benchmarkSeed = 0xdecafbad -const origin = 'http://localhost' -const tssContentTypeFramed = 'application/x-tss-framed' -const xTssSerialized = 'x-tss-serialized' -const acceptHeader = `${tssContentTypeFramed}, application/x-ndjson, application/json` -const documentRequestInit = { - method: 'GET', - headers: { - accept: 'text/html', - }, -} satisfies RequestInit -const apiRequestInit = { - method: 'GET', - headers: { - accept: 'application/json', - }, -} satisfies RequestInit -const postHeaders = { - 'x-tsr-serverFn': 'true', - 'sec-fetch-site': 'same-origin', - accept: acceptHeader, - 'content-type': 'application/json', -} satisfies HeadersInit -const documentLoopTotalRequests = 64 -const serverFnLoopTotalRequests = 128 -const serverRouteLoopTotalRequests = 256 - -export const globalMiddlewareBenchOptions = { - warmupIterations: 100, - time: 10_000, - throws: true, -} as const - -function createPayloads() { - const random = createDeterministicRandom(benchmarkSeed) - - return Array.from({ length: 10 }, (_, index): Payload => { - const queryParts = Array.from({ length: 6 }, () => randomSegment(random)) - - return { - q: `q-${index}-${queryParts.join('-')}`, - n: 100 + index, - nested: { - list: Array.from( - { length: 5 }, - () => `l-${index}-${randomSegment(random)}-${randomSegment(random)}`, - ), - }, - } - }) -} - -async function createBodies(payloads: Array) { - return await Promise.all( - payloads.map(async (payload) => - JSON.stringify(await toJSONAsync({ data: payload })), - ), - ) -} - -async function discoverUrls(handler: StartRequestHandler) { - const response = await handler.fetch(new Request(`${origin}/api/fn-urls`)) - - if (response.status === 404) { - throw new Error('URL discovery route returned 404 for /api/fn-urls') - } - - if (response.status !== 200) { - throw new Error( - `URL discovery failed with status ${response.status}: ${await response.text()}`, - ) - } - - const urls = (await response.json()) as Partial - - if (typeof urls.post !== 'string') { - throw new Error( - `URL discovery returned invalid payload: ${JSON.stringify(urls)}`, - ) - } - - return { post: urls.post } -} - -function buildDocumentRequest(random: () => number, index: number) { - return new Request( - `${origin}/page/${randomSegment(random)}-${index.toString(36)}`, - documentRequestInit, - ) -} - -function buildServerRouteRequest(random: () => number, index: number) { - return new Request( - `${origin}/api/ping/${randomSegment(random)}-${index.toString(36)}`, - apiRequestInit, - ) -} - -function buildPostRequest(urls: FnUrls, bodies: Array, index: number) { - return new Request(`${origin}${urls.post}`, { - method: 'POST', - headers: postHeaders, - body: bodies[index % bodies.length], - }) -} - -export async function setupGlobalMiddlewareBench( - handler: StartRequestHandler, -): Promise { - setRequestMiddlewareCount(3) - const urls = await discoverUrls(handler) - const payloads = createPayloads() - const bodies = await createBodies(payloads) - const expectedFnMarker = makeServerFnMarker(payloads[0]!.q, { - requestTrace: 'req.r1.r2.r3', - requestTotal: expectedRequestTotal, - functionTrace: 'fn.f1.f2', - functionTotal: expectedFunctionTotal, - }) - - return { urls, bodies, expectedFnMarker } -} - -async function assertDocumentResponse(handler: StartRequestHandler) { - setRequestMiddlewareCount(3) - const id = 'page-sanity' - const response = await handler.fetch( - new Request(`${origin}/page/${id}`, documentRequestInit), - ) - const body = await response.text() - const expectedMarker = makeDocumentMarker(id, { - requestTrace: 'req.r1.r2.r3', - requestTotal: expectedRequestTotal, - }) - - if (response.status !== 200) { - throw new Error(`Expected document status 200, received ${response.status}`) - } - - if (!body.includes(expectedMarker)) { - throw new Error( - `Expected document response to include global middleware marker ${expectedMarker}`, - ) - } -} - -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), - ) - - if (response.status !== 200) { - throw new Error( - `Expected server route status 200, received ${response.status}`, - ) - } - - const contentType = response.headers.get('content-type') - - if (!contentType?.includes('application/json')) { - throw new Error( - `Expected JSON server route response, received ${contentType}`, - ) - } - - const body = (await response.json()) as { - marker?: string - requestTotal?: number - } - const expectedContext = getExpectedRequestContext(count) - const expectedMarker = makeServerRouteMarker(id, expectedContext) - - if (body.marker !== expectedMarker) { - throw new Error( - `Expected server route marker ${expectedMarker}, received ${body.marker}`, - ) - } - - if (body.requestTotal !== expectedContext.requestTotal) { - throw new Error( - `Expected server route requestTotal ${expectedContext.requestTotal}, received ${body.requestTotal}`, - ) - } -} - -async function assertServerFnResponse( - handler: StartRequestHandler, - context: GlobalMiddlewareBenchContext, -) { - setRequestMiddlewareCount(3) - const response = await handler.fetch( - buildPostRequest(context.urls, context.bodies, 0), - ) - const text = await response.text() - - if (response.status === 403) { - throw new Error('Server function sanity check failed with 403') - } - - if (response.status === 404) { - throw new Error('Server function sanity check failed with 404') - } - - if (response.status !== 200) { - throw new Error( - `Server function sanity check failed with status ${response.status}: ${text}`, - ) - } - - if (!response.headers.get(xTssSerialized)) { - throw new Error(`Server function response missing ${xTssSerialized} header`) - } - - if (!text.includes(context.expectedFnMarker)) { - throw new Error( - `Expected server function response to include ${context.expectedFnMarker}: ${text}`, - ) - } -} - -export async function assertGlobalMiddlewareScenario( - handler: StartRequestHandler, - context: GlobalMiddlewareBenchContext, -) { - await assertDocumentResponse(handler) - await assertServerFnResponse(handler, context) - 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, - totalRequests: documentLoopTotalRequests, - buildRequest: buildDocumentRequest, - }) -} - -export function runGlobalMiddlewareServerFnLoop( - handler: StartRequestHandler, - context: GlobalMiddlewareBenchContext, -) { - setRequestMiddlewareCount(3) - return runRequestLoop(handler, { - seed: benchmarkSeed, - concurrency: 16, - totalRequests: serverFnLoopTotalRequests, - buildRequest: (_random, index) => - buildPostRequest(context.urls, context.bodies, index), - }) -} - -export function runGlobalMiddlewareServerRouteLoop( - handler: StartRequestHandler, - count: RequestMiddlewareCount = 3, -) { - setRequestMiddlewareCount(count) - return runRequestLoop(handler, { - seed: benchmarkSeed, - concurrency: 16, - totalRequests: serverRouteLoopTotalRequests, - buildRequest: buildServerRouteRequest, - }) -} diff --git a/benchmarks/ssr/scenarios/global-middleware/react/project.json b/benchmarks/ssr/scenarios/global-middleware/react/project.json deleted file mode 100644 index bded6925fd..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-global-middleware-react", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/global-middleware/react/speed.bench.ts b/benchmarks/ssr/scenarios/global-middleware/react/speed.bench.ts deleted file mode 100644 index cb3f9f427c..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/speed.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareDocumentLoop, - 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 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 deleted file mode 100644 index 48c444de77..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-fn.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index 22f53883ee..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-0-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 0 middleware (react)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 0), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-1-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-1-middleware.bench.ts deleted file mode 100644 index f01b48d66e..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-1-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 1 middleware (react)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 1), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-2-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-2-middleware.bench.ts deleted file mode 100644 index b01957f806..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-2-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 2 middlewares (react)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 2), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route.bench.ts b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route.bench.ts deleted file mode 100644 index 08d97fcaf6..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 3 middlewares (react)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 3), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/src/fns.ts b/benchmarks/ssr/scenarios/global-middleware/react/src/fns.ts deleted file mode 100644 index 68cfd992c6..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/src/fns.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { createServerFn } from '@tanstack/react-start' -import { makeServerFnMarker, type GlobalMiddlewareContext } from '../../shared' - -type Payload = { q: string; n: number; nested: { list: Array } } - -const validate = (input: unknown): Payload => { - const payload = input as Payload - - if ( - typeof payload?.q !== 'string' || - typeof payload?.n !== 'number' || - !Array.isArray(payload?.nested?.list) - ) { - throw new Error('invalid payload') - } - - return payload -} - -export const echoPost = createServerFn({ method: 'POST' }) - .validator(validate) - .handler(({ data, context }) => { - const middlewareContext = (context ?? {}) as GlobalMiddlewareContext - - return { - echoed: data, - marker: makeServerFnMarker(data.q, middlewareContext), - sum: - data.n + - (middlewareContext.requestTotal ?? 0) + - (middlewareContext.functionTotal ?? 0), - list: data.nested.list.map((item) => `global-${item}`), - } - }) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/global-middleware/react/src/routeTree.gen.ts deleted file mode 100644 index 8dfaa80562..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/src/routeTree.gen.ts +++ /dev/null @@ -1,123 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ - id: '/api/fn-urls', - path: '/api/fn-urls', - getParentRoute: () => rootRouteImport, -} as any) -const PageIdRoute = PageIdRouteImport.update({ - id: '/page/$id', - path: '/page/$id', - getParentRoute: () => rootRouteImport, -} as any) -const ApiPingIdRoute = ApiPingIdRouteImport.update({ - id: '/api/ping/$id', - path: '/api/ping/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute - '/page/$id': typeof PageIdRoute - '/api/ping/$id': typeof ApiPingIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute - '/page/$id': typeof PageIdRoute - '/api/ping/$id': typeof ApiPingIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute - '/page/$id': typeof PageIdRoute - '/api/ping/$id': typeof ApiPingIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/api/fn-urls' | '/page/$id' | '/api/ping/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/api/fn-urls' | '/page/$id' | '/api/ping/$id' - id: '__root__' | '/' | '/api/fn-urls' | '/page/$id' | '/api/ping/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ApiFnUrlsRoute: typeof ApiFnUrlsRoute - PageIdRoute: typeof PageIdRoute - ApiPingIdRoute: typeof ApiPingIdRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/api/fn-urls': { - id: '/api/fn-urls' - path: '/api/fn-urls' - fullPath: '/api/fn-urls' - preLoaderRoute: typeof ApiFnUrlsRouteImport - parentRoute: typeof rootRouteImport - } - '/page/$id': { - id: '/page/$id' - path: '/page/$id' - fullPath: '/page/$id' - preLoaderRoute: typeof PageIdRouteImport - parentRoute: typeof rootRouteImport - } - '/api/ping/$id': { - id: '/api/ping/$id' - path: '/api/ping/$id' - fullPath: '/api/ping/$id' - preLoaderRoute: typeof ApiPingIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ApiFnUrlsRoute: ApiFnUrlsRoute, - PageIdRoute: PageIdRoute, - ApiPingIdRoute: ApiPingIdRoute, -} -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/benchmarks/ssr/scenarios/global-middleware/react/src/router.tsx b/benchmarks/ssr/scenarios/global-middleware/react/src/router.tsx deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/global-middleware/react/src/routes/__root.tsx b/benchmarks/ssr/scenarios/global-middleware/react/src/routes/__root.tsx deleted file mode 100644 index ff1da4c304..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/global-middleware/react/src/routes/api.fn-urls.ts b/benchmarks/ssr/scenarios/global-middleware/react/src/routes/api.fn-urls.ts deleted file mode 100644 index bcb2111930..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/src/routes/api.fn-urls.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { echoPost } from '../fns' - -export const Route = createFileRoute('/api/fn-urls')({ - server: { - handlers: { - GET: () => Response.json({ post: echoPost.url }), - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/src/routes/api.ping.$id.ts b/benchmarks/ssr/scenarios/global-middleware/react/src/routes/api.ping.$id.ts deleted file mode 100644 index 434833f018..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/src/routes/api.ping.$id.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { - makeServerRouteMarker, - type GlobalMiddlewareContext, -} from '../../../shared' - -export const Route = createFileRoute('/api/ping/$id')({ - server: { - handlers: { - GET: ({ params, context }) => { - const middlewareContext = (context ?? {}) as GlobalMiddlewareContext - - return Response.json({ - id: params.id, - marker: makeServerRouteMarker(params.id, middlewareContext), - requestTrace: middlewareContext.requestTrace, - requestTotal: middlewareContext.requestTotal, - }) - }, - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/src/routes/index.tsx b/benchmarks/ssr/scenarios/global-middleware/react/src/routes/index.tsx deleted file mode 100644 index a0d3aec869..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/src/routes/index.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { echoPost } from '../fns' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
global-middleware
-} diff --git a/benchmarks/ssr/scenarios/global-middleware/react/src/routes/page.$id.tsx b/benchmarks/ssr/scenarios/global-middleware/react/src/routes/page.$id.tsx deleted file mode 100644 index 6b7a42c12e..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/src/routes/page.$id.tsx +++ /dev/null @@ -1,22 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { - getGlobalMiddlewareContext, - makeDocumentMarker, - type GlobalMiddlewareContext, -} from '../../../shared' - -export const Route = createFileRoute('/page/$id')({ - beforeLoad: ({ serverContext }) => ({ - globalMiddlewareContext: (serverContext ?? {}) as GlobalMiddlewareContext, - }), - loader: ({ params, context }) => ({ - marker: makeDocumentMarker(params.id, getGlobalMiddlewareContext(context)), - }), - component: PageComponent, -}) - -function PageComponent() { - const data = Route.useLoaderData() - - return
{data.marker}
-} diff --git a/benchmarks/ssr/scenarios/global-middleware/react/src/start.ts b/benchmarks/ssr/scenarios/global-middleware/react/src/start.ts deleted file mode 100644 index 8dfb2dd3c4..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/src/start.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { createMiddleware, createStart } from '@tanstack/react-start' -import { getRequestMiddlewareCount } from '../../shared' -import type { GlobalMiddlewareContext } from '../../shared' - -function appendTrace( - trace: string | undefined, - fallback: string, - label: string, -) { - return `${trace ?? fallback}.${label}` -} - -const requestMiddlewareA = createMiddleware({ type: 'request' }).server( - ({ next, context }) => { - const ctx = (context ?? {}) as GlobalMiddlewareContext - - return next({ - context: { - requestTrace: appendTrace(ctx.requestTrace, 'req', 'r1'), - requestTotal: (ctx.requestTotal ?? 0) + 1, - }, - }) - }, -) - -const requestMiddlewareB = createMiddleware({ type: 'request' }).server( - ({ next, context }) => { - const ctx = (context ?? {}) as GlobalMiddlewareContext - - return next({ - context: { - requestTrace: appendTrace(ctx.requestTrace, 'req', 'r2'), - requestTotal: (ctx.requestTotal ?? 0) + 2, - }, - }) - }, -) - -const requestMiddlewareC = createMiddleware({ type: 'request' }).server( - ({ next, context }) => { - const ctx = (context ?? {}) as GlobalMiddlewareContext - - return next({ - context: { - requestTrace: appendTrace(ctx.requestTrace, 'req', 'r3'), - requestTotal: (ctx.requestTotal ?? 0) + 3, - }, - }) - }, -) - -const requestMiddlewareSets: Array> = [ - [], - [requestMiddlewareA], - [requestMiddlewareA, requestMiddlewareB], - [requestMiddlewareA, requestMiddlewareB, requestMiddlewareC], -] - -const functionMiddlewareA = createMiddleware({ type: 'function' }).server( - ({ next, context }) => { - const ctx = (context ?? {}) as GlobalMiddlewareContext - - return next({ - context: { - functionTrace: appendTrace(ctx.functionTrace, 'fn', 'f1'), - functionTotal: (ctx.functionTotal ?? 0) + 10, - }, - }) - }, -) - -const functionMiddlewareB = createMiddleware({ type: 'function' }).server( - ({ next, context }) => { - const ctx = (context ?? {}) as GlobalMiddlewareContext - - return next({ - context: { - functionTrace: appendTrace(ctx.functionTrace, 'fn', 'f2'), - functionTotal: (ctx.functionTotal ?? 0) + 20, - }, - }) - }, -) - -export const startInstance = createStart(() => ({ - 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 deleted file mode 100644 index de4a3204b9..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed*.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../shared.ts", - "../bench.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/global-middleware/react/vite.config.ts b/benchmarks/ssr/scenarios/global-middleware/react/vite.config.ts deleted file mode 100644 index 968a8a24e9..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - 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 deleted file mode 100644 index 8fbe788911..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/shared.ts +++ /dev/null @@ -1,77 +0,0 @@ -export interface GlobalMiddlewareContext { - requestTrace?: string - requestTotal?: number - functionTrace?: string - functionTotal?: number -} - -export interface GlobalMiddlewareRouteContext extends GlobalMiddlewareContext { - serverContext?: 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, -) { - return `document:${context.requestTrace}:${id}:${context.requestTotal}` -} - -export function getGlobalMiddlewareContext(context: unknown) { - const routeContext = (context ?? {}) as GlobalMiddlewareRouteContext - - return ( - routeContext.globalMiddlewareContext ?? - routeContext.serverContext ?? - routeContext - ) -} - -export function makeServerRouteMarker( - id: string, - context: GlobalMiddlewareContext, -) { - return `route:${context.requestTrace}:${id}:${context.requestTotal}` -} - -export function makeServerFnMarker( - q: string, - context: GlobalMiddlewareContext, -) { - return `fn:${context.requestTrace}:${context.functionTrace}:${q}:${context.requestTotal}:${context.functionTotal}` -} diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/project.json b/benchmarks/ssr/scenarios/global-middleware/solid/project.json deleted file mode 100644 index d325c15527..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-global-middleware-solid", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/speed.bench.ts b/benchmarks/ssr/scenarios/global-middleware/solid/speed.bench.ts deleted file mode 100644 index 0e5f504090..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/speed.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareDocumentLoop, - 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 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 deleted file mode 100644 index 915507ef9f..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-fn.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index a791145935..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-0-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 0 middleware (solid)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 0), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-1-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-1-middleware.bench.ts deleted file mode 100644 index 1baab0f344..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-1-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 1 middleware (solid)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 1), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-2-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-2-middleware.bench.ts deleted file mode 100644 index d6fde20764..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-2-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 2 middlewares (solid)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 2), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route.bench.ts b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route.bench.ts deleted file mode 100644 index 558ebeb9a4..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 3 middlewares (solid)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 3), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/src/fns.ts b/benchmarks/ssr/scenarios/global-middleware/solid/src/fns.ts deleted file mode 100644 index 667baf9f54..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/src/fns.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { createServerFn } from '@tanstack/solid-start' -import { makeServerFnMarker, type GlobalMiddlewareContext } from '../../shared' - -type Payload = { q: string; n: number; nested: { list: Array } } - -const validate = (input: unknown): Payload => { - const payload = input as Payload - - if ( - typeof payload?.q !== 'string' || - typeof payload?.n !== 'number' || - !Array.isArray(payload?.nested?.list) - ) { - throw new Error('invalid payload') - } - - return payload -} - -export const echoPost = createServerFn({ method: 'POST' }) - .validator(validate) - .handler(({ data, context }) => { - const middlewareContext = (context ?? {}) as GlobalMiddlewareContext - - return { - echoed: data, - marker: makeServerFnMarker(data.q, middlewareContext), - sum: - data.n + - (middlewareContext.requestTotal ?? 0) + - (middlewareContext.functionTotal ?? 0), - list: data.nested.list.map((item) => `global-${item}`), - } - }) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/global-middleware/solid/src/routeTree.gen.ts deleted file mode 100644 index 65f7fa5848..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,123 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ - id: '/api/fn-urls', - path: '/api/fn-urls', - getParentRoute: () => rootRouteImport, -} as any) -const PageIdRoute = PageIdRouteImport.update({ - id: '/page/$id', - path: '/page/$id', - getParentRoute: () => rootRouteImport, -} as any) -const ApiPingIdRoute = ApiPingIdRouteImport.update({ - id: '/api/ping/$id', - path: '/api/ping/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute - '/page/$id': typeof PageIdRoute - '/api/ping/$id': typeof ApiPingIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute - '/page/$id': typeof PageIdRoute - '/api/ping/$id': typeof ApiPingIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute - '/page/$id': typeof PageIdRoute - '/api/ping/$id': typeof ApiPingIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/api/fn-urls' | '/page/$id' | '/api/ping/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/api/fn-urls' | '/page/$id' | '/api/ping/$id' - id: '__root__' | '/' | '/api/fn-urls' | '/page/$id' | '/api/ping/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ApiFnUrlsRoute: typeof ApiFnUrlsRoute - PageIdRoute: typeof PageIdRoute - ApiPingIdRoute: typeof ApiPingIdRoute -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/api/fn-urls': { - id: '/api/fn-urls' - path: '/api/fn-urls' - fullPath: '/api/fn-urls' - preLoaderRoute: typeof ApiFnUrlsRouteImport - parentRoute: typeof rootRouteImport - } - '/page/$id': { - id: '/page/$id' - path: '/page/$id' - fullPath: '/page/$id' - preLoaderRoute: typeof PageIdRouteImport - parentRoute: typeof rootRouteImport - } - '/api/ping/$id': { - id: '/api/ping/$id' - path: '/api/ping/$id' - fullPath: '/api/ping/$id' - preLoaderRoute: typeof ApiPingIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ApiFnUrlsRoute: ApiFnUrlsRoute, - PageIdRoute: PageIdRoute, - ApiPingIdRoute: ApiPingIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { startInstance } from './start.ts' -declare module '@tanstack/solid-start' { - interface Register { - ssr: true - router: Awaited> - config: Awaited> - } -} diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/src/router.tsx b/benchmarks/ssr/scenarios/global-middleware/solid/src/router.tsx deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/__root.tsx b/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/__root.tsx deleted file mode 100644 index e59de72236..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/solid-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/api.fn-urls.ts b/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/api.fn-urls.ts deleted file mode 100644 index 7166ea3030..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/api.fn-urls.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { echoPost } from '../fns' - -export const Route = createFileRoute('/api/fn-urls')({ - server: { - handlers: { - GET: () => Response.json({ post: echoPost.url }), - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/api.ping.$id.ts b/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/api.ping.$id.ts deleted file mode 100644 index b92bcea5b0..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/api.ping.$id.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { - makeServerRouteMarker, - type GlobalMiddlewareContext, -} from '../../../shared' - -export const Route = createFileRoute('/api/ping/$id')({ - server: { - handlers: { - GET: ({ params, context }) => { - const middlewareContext = (context ?? {}) as GlobalMiddlewareContext - - return Response.json({ - id: params.id, - marker: makeServerRouteMarker(params.id, middlewareContext), - requestTrace: middlewareContext.requestTrace, - requestTotal: middlewareContext.requestTotal, - }) - }, - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/index.tsx b/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/index.tsx deleted file mode 100644 index c293004539..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/index.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { echoPost } from '../fns' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
global-middleware
-} diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/page.$id.tsx b/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/page.$id.tsx deleted file mode 100644 index a5781b1a6a..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/page.$id.tsx +++ /dev/null @@ -1,22 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { - getGlobalMiddlewareContext, - makeDocumentMarker, - type GlobalMiddlewareContext, -} from '../../../shared' - -export const Route = createFileRoute('/page/$id')({ - beforeLoad: ({ serverContext }) => ({ - globalMiddlewareContext: (serverContext ?? {}) as GlobalMiddlewareContext, - }), - loader: ({ params, context }) => ({ - marker: makeDocumentMarker(params.id, getGlobalMiddlewareContext(context)), - }), - component: PageComponent, -}) - -function PageComponent() { - const data = Route.useLoaderData() - - return
{data().marker}
-} diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/src/start.ts b/benchmarks/ssr/scenarios/global-middleware/solid/src/start.ts deleted file mode 100644 index a6f6214b82..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/src/start.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { createMiddleware, createStart } from '@tanstack/solid-start' -import { getRequestMiddlewareCount } from '../../shared' -import type { GlobalMiddlewareContext } from '../../shared' - -function appendTrace( - trace: string | undefined, - fallback: string, - label: string, -) { - return `${trace ?? fallback}.${label}` -} - -const requestMiddlewareA = createMiddleware({ type: 'request' }).server( - ({ next, context }) => { - const ctx = (context ?? {}) as GlobalMiddlewareContext - - return next({ - context: { - requestTrace: appendTrace(ctx.requestTrace, 'req', 'r1'), - requestTotal: (ctx.requestTotal ?? 0) + 1, - }, - }) - }, -) - -const requestMiddlewareB = createMiddleware({ type: 'request' }).server( - ({ next, context }) => { - const ctx = (context ?? {}) as GlobalMiddlewareContext - - return next({ - context: { - requestTrace: appendTrace(ctx.requestTrace, 'req', 'r2'), - requestTotal: (ctx.requestTotal ?? 0) + 2, - }, - }) - }, -) - -const requestMiddlewareC = createMiddleware({ type: 'request' }).server( - ({ next, context }) => { - const ctx = (context ?? {}) as GlobalMiddlewareContext - - return next({ - context: { - requestTrace: appendTrace(ctx.requestTrace, 'req', 'r3'), - requestTotal: (ctx.requestTotal ?? 0) + 3, - }, - }) - }, -) - -const requestMiddlewareSets: Array> = [ - [], - [requestMiddlewareA], - [requestMiddlewareA, requestMiddlewareB], - [requestMiddlewareA, requestMiddlewareB, requestMiddlewareC], -] - -const functionMiddlewareA = createMiddleware({ type: 'function' }).server( - ({ next, context }) => { - const ctx = (context ?? {}) as GlobalMiddlewareContext - - return next({ - context: { - functionTrace: appendTrace(ctx.functionTrace, 'fn', 'f1'), - functionTotal: (ctx.functionTotal ?? 0) + 10, - }, - }) - }, -) - -const functionMiddlewareB = createMiddleware({ type: 'function' }).server( - ({ next, context }) => { - const ctx = (context ?? {}) as GlobalMiddlewareContext - - return next({ - context: { - functionTrace: appendTrace(ctx.functionTrace, 'fn', 'f2'), - functionTotal: (ctx.functionTotal ?? 0) + 20, - }, - }) - }, -) - -export const startInstance = createStart(() => ({ - 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 deleted file mode 100644 index dce3ceae30..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed*.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../shared.ts", - "../bench.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/vite.config.ts b/benchmarks/ssr/scenarios/global-middleware/solid/vite.config.ts deleted file mode 100644 index f3597b25d5..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - solid({ ssr: true, hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - execArgv: cpuSimulationExecArgv(), - isolate: true, - name: '@benchmarks/ssr global-middleware (solid)', - watch: false, - environment: 'node', - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/project.json b/benchmarks/ssr/scenarios/global-middleware/vue/project.json deleted file mode 100644 index 6dbc003aae..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-global-middleware-vue", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/speed.bench.ts b/benchmarks/ssr/scenarios/global-middleware/vue/speed.bench.ts deleted file mode 100644 index 9660f29d07..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/speed.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareDocumentLoop, - 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 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 deleted file mode 100644 index 297e8cee7b..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-fn.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index d023dd458a..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-0-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 0 middleware (vue)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 0), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-1-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-1-middleware.bench.ts deleted file mode 100644 index 5018163631..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-1-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 1 middleware (vue)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 1), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-2-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-2-middleware.bench.ts deleted file mode 100644 index f9abd8eb60..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-2-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 2 middlewares (vue)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 2), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route.bench.ts b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route.bench.ts deleted file mode 100644 index adcec3019f..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { test } from 'vitest' -import { - assertGlobalMiddlewareScenario, - globalMiddlewareBenchOptions, - runGlobalMiddlewareServerRouteLoop, - setupGlobalMiddlewareBench, -} from '../bench' -import type { StartRequestHandler } from '../bench' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} -const context = await setupGlobalMiddlewareBench(handler) - -await assertGlobalMiddlewareScenario(handler, context) - -test('ssr', async ({ bench }) => { - await bench('ssr global-mw server-route 3 middlewares (vue)', async () => - runGlobalMiddlewareServerRouteLoop(handler, 3), - ).run(globalMiddlewareBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/src/fns.ts b/benchmarks/ssr/scenarios/global-middleware/vue/src/fns.ts deleted file mode 100644 index 557f6ee849..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/src/fns.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { createServerFn } from '@tanstack/vue-start' -import { makeServerFnMarker, type GlobalMiddlewareContext } from '../../shared' - -type Payload = { q: string; n: number; nested: { list: Array } } - -const validate = (input: unknown): Payload => { - const payload = input as Payload - - if ( - typeof payload?.q !== 'string' || - typeof payload?.n !== 'number' || - !Array.isArray(payload?.nested?.list) - ) { - throw new Error('invalid payload') - } - - return payload -} - -export const echoPost = createServerFn({ method: 'POST' }) - .validator(validate) - .handler(({ data, context }) => { - const middlewareContext = (context ?? {}) as GlobalMiddlewareContext - - return { - echoed: data, - marker: makeServerFnMarker(data.q, middlewareContext), - sum: - data.n + - (middlewareContext.requestTotal ?? 0) + - (middlewareContext.functionTotal ?? 0), - list: data.nested.list.map((item) => `global-${item}`), - } - }) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/global-middleware/vue/src/routeTree.gen.ts deleted file mode 100644 index 3118848e4d..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,123 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ - id: '/api/fn-urls', - path: '/api/fn-urls', - getParentRoute: () => rootRouteImport, -} as any) -const PageIdRoute = PageIdRouteImport.update({ - id: '/page/$id', - path: '/page/$id', - getParentRoute: () => rootRouteImport, -} as any) -const ApiPingIdRoute = ApiPingIdRouteImport.update({ - id: '/api/ping/$id', - path: '/api/ping/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute - '/page/$id': typeof PageIdRoute - '/api/ping/$id': typeof ApiPingIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute - '/page/$id': typeof PageIdRoute - '/api/ping/$id': typeof ApiPingIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute - '/page/$id': typeof PageIdRoute - '/api/ping/$id': typeof ApiPingIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/api/fn-urls' | '/page/$id' | '/api/ping/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/api/fn-urls' | '/page/$id' | '/api/ping/$id' - id: '__root__' | '/' | '/api/fn-urls' | '/page/$id' | '/api/ping/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ApiFnUrlsRoute: typeof ApiFnUrlsRoute - PageIdRoute: typeof PageIdRoute - ApiPingIdRoute: typeof ApiPingIdRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/api/fn-urls': { - id: '/api/fn-urls' - path: '/api/fn-urls' - fullPath: '/api/fn-urls' - preLoaderRoute: typeof ApiFnUrlsRouteImport - parentRoute: typeof rootRouteImport - } - '/page/$id': { - id: '/page/$id' - path: '/page/$id' - fullPath: '/page/$id' - preLoaderRoute: typeof PageIdRouteImport - parentRoute: typeof rootRouteImport - } - '/api/ping/$id': { - id: '/api/ping/$id' - path: '/api/ping/$id' - fullPath: '/api/ping/$id' - preLoaderRoute: typeof ApiPingIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ApiFnUrlsRoute: ApiFnUrlsRoute, - PageIdRoute: PageIdRoute, - ApiPingIdRoute: ApiPingIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { startInstance } from './start.ts' -declare module '@tanstack/vue-start' { - interface Register { - ssr: true - router: Awaited> - config: Awaited> - } -} diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/src/router.tsx b/benchmarks/ssr/scenarios/global-middleware/vue/src/router.tsx deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/__root.tsx b/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/__root.tsx deleted file mode 100644 index 49422aac38..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/__root.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { - Body, - HeadContent, - Html, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/vue-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/api.fn-urls.ts b/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/api.fn-urls.ts deleted file mode 100644 index af51ea6aa3..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/api.fn-urls.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' -import { echoPost } from '../fns' - -export const Route = createFileRoute('/api/fn-urls')({ - server: { - handlers: { - GET: () => Response.json({ post: echoPost.url }), - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/api.ping.$id.ts b/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/api.ping.$id.ts deleted file mode 100644 index f599ce1e49..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/api.ping.$id.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' -import { - makeServerRouteMarker, - type GlobalMiddlewareContext, -} from '../../../shared' - -export const Route = createFileRoute('/api/ping/$id')({ - server: { - handlers: { - GET: ({ params, context }) => { - const middlewareContext = (context ?? {}) as GlobalMiddlewareContext - - return Response.json({ - id: params.id, - marker: makeServerRouteMarker(params.id, middlewareContext), - requestTrace: middlewareContext.requestTrace, - requestTotal: middlewareContext.requestTotal, - }) - }, - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/index.tsx b/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/index.tsx deleted file mode 100644 index 85d3de69a4..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/index.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' -import { echoPost } from '../fns' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return
global-middleware
-} 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 deleted file mode 100644 index 6e837ef0a0..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/page.$id.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { defineComponent } from 'vue' -import { createFileRoute } from '@tanstack/vue-router' -import { - getGlobalMiddlewareContext, - makeDocumentMarker, - 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, - }), - loader: ({ params, context }) => ({ - marker: makeDocumentMarker(params.id, getGlobalMiddlewareContext(context)), - }), - component: PageComponent, -}) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/src/start.ts b/benchmarks/ssr/scenarios/global-middleware/vue/src/start.ts deleted file mode 100644 index 6e4eb2c5ef..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/src/start.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { createMiddleware, createStart } from '@tanstack/vue-start' -import { getRequestMiddlewareCount } from '../../shared' -import type { GlobalMiddlewareContext } from '../../shared' - -function appendTrace( - trace: string | undefined, - fallback: string, - label: string, -) { - return `${trace ?? fallback}.${label}` -} - -const requestMiddlewareA = createMiddleware({ type: 'request' }).server( - ({ next, context }) => { - const ctx = (context ?? {}) as GlobalMiddlewareContext - - return next({ - context: { - requestTrace: appendTrace(ctx.requestTrace, 'req', 'r1'), - requestTotal: (ctx.requestTotal ?? 0) + 1, - }, - }) - }, -) - -const requestMiddlewareB = createMiddleware({ type: 'request' }).server( - ({ next, context }) => { - const ctx = (context ?? {}) as GlobalMiddlewareContext - - return next({ - context: { - requestTrace: appendTrace(ctx.requestTrace, 'req', 'r2'), - requestTotal: (ctx.requestTotal ?? 0) + 2, - }, - }) - }, -) - -const requestMiddlewareC = createMiddleware({ type: 'request' }).server( - ({ next, context }) => { - const ctx = (context ?? {}) as GlobalMiddlewareContext - - return next({ - context: { - requestTrace: appendTrace(ctx.requestTrace, 'req', 'r3'), - requestTotal: (ctx.requestTotal ?? 0) + 3, - }, - }) - }, -) - -const requestMiddlewareSets: Array> = [ - [], - [requestMiddlewareA], - [requestMiddlewareA, requestMiddlewareB], - [requestMiddlewareA, requestMiddlewareB, requestMiddlewareC], -] - -const functionMiddlewareA = createMiddleware({ type: 'function' }).server( - ({ next, context }) => { - const ctx = (context ?? {}) as GlobalMiddlewareContext - - return next({ - context: { - functionTrace: appendTrace(ctx.functionTrace, 'fn', 'f1'), - functionTotal: (ctx.functionTotal ?? 0) + 10, - }, - }) - }, -) - -const functionMiddlewareB = createMiddleware({ type: 'function' }).server( - ({ next, context }) => { - const ctx = (context ?? {}) as GlobalMiddlewareContext - - return next({ - context: { - functionTrace: appendTrace(ctx.functionTrace, 'fn', 'f2'), - functionTotal: (ctx.functionTotal ?? 0) + 20, - }, - }) - }, -) - -export const startInstance = createStart(() => ({ - 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 deleted file mode 100644 index 56800fd29e..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed*.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../shared.ts", - "../bench.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/vite.config.ts b/benchmarks/ssr/scenarios/global-middleware/vue/vite.config.ts deleted file mode 100644 index 8e29c5ee98..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - 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/project.json b/benchmarks/ssr/scenarios/head/react/project.json deleted file mode 100644 index 093046fe39..0000000000 --- a/benchmarks/ssr/scenarios/head/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-head-react", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/head/react/speed.bench.ts b/benchmarks/ssr/scenarios/head/react/speed.bench.ts deleted file mode 100644 index f75008506e..0000000000 --- a/benchmarks/ssr/scenarios/head/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { assertHeadSanity, headBenchOptions, runHeadLoop } 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 assertHeadSanity(handler) - -test('ssr', async ({ bench }) => { - await bench('ssr head (react)', async () => runHeadLoop(handler)).run( - headBenchOptions, - ) -}) diff --git a/benchmarks/ssr/scenarios/head/react/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/head/react/src/routeTree.gen.ts deleted file mode 100644 index 3786e2137d..0000000000 --- a/benchmarks/ssr/scenarios/head/react/src/routeTree.gen.ts +++ /dev/null @@ -1,120 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as HARouteImport } from './routes/h.$a' -import { Route as HABRouteImport } from './routes/h.$a.$b' -import { Route as HABCRouteImport } from './routes/h.$a.$b.$c' - -const HARoute = HARouteImport.update({ - id: '/h/$a', - path: '/h/$a', - getParentRoute: () => rootRouteImport, -} as any) -const HABRoute = HABRouteImport.update({ - id: '/$b', - path: '/$b', - getParentRoute: () => HARoute, -} as any) -const HABCRoute = HABCRouteImport.update({ - id: '/$c', - path: '/$c', - getParentRoute: () => HABRoute, -} as any) - -export interface FileRoutesByFullPath { - '/h/$a': typeof HARouteWithChildren - '/h/$a/$b': typeof HABRouteWithChildren - '/h/$a/$b/$c': typeof HABCRoute -} -export interface FileRoutesByTo { - '/h/$a': typeof HARouteWithChildren - '/h/$a/$b': typeof HABRouteWithChildren - '/h/$a/$b/$c': typeof HABCRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/h/$a': typeof HARouteWithChildren - '/h/$a/$b': typeof HABRouteWithChildren - '/h/$a/$b/$c': typeof HABCRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/h/$a' | '/h/$a/$b' | '/h/$a/$b/$c' - fileRoutesByTo: FileRoutesByTo - to: '/h/$a' | '/h/$a/$b' | '/h/$a/$b/$c' - id: '__root__' | '/h/$a' | '/h/$a/$b' | '/h/$a/$b/$c' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - HARoute: typeof HARouteWithChildren -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/h/$a': { - id: '/h/$a' - path: '/h/$a' - fullPath: '/h/$a' - preLoaderRoute: typeof HARouteImport - parentRoute: typeof rootRouteImport - } - '/h/$a/$b': { - id: '/h/$a/$b' - path: '/$b' - fullPath: '/h/$a/$b' - preLoaderRoute: typeof HABRouteImport - parentRoute: typeof HARoute - } - '/h/$a/$b/$c': { - id: '/h/$a/$b/$c' - path: '/$c' - fullPath: '/h/$a/$b/$c' - preLoaderRoute: typeof HABCRouteImport - parentRoute: typeof HABRoute - } - } -} - -interface HABRouteChildren { - HABCRoute: typeof HABCRoute -} - -const HABRouteChildren: HABRouteChildren = { - HABCRoute: HABCRoute, -} - -const HABRouteWithChildren = HABRoute._addFileChildren(HABRouteChildren) - -interface HARouteChildren { - HABRoute: typeof HABRouteWithChildren -} - -const HARouteChildren: HARouteChildren = { - HABRoute: HABRouteWithChildren, -} - -const HARouteWithChildren = HARoute._addFileChildren(HARouteChildren) - -const rootRouteChildren: RootRouteChildren = { - HARoute: HARouteWithChildren, -} -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/benchmarks/ssr/scenarios/head/react/src/router.tsx b/benchmarks/ssr/scenarios/head/react/src/router.tsx deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/ssr/scenarios/head/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/head/react/src/routes/__root.tsx b/benchmarks/ssr/scenarios/head/react/src/routes/__root.tsx deleted file mode 100644 index 93f68352ab..0000000000 --- a/benchmarks/ssr/scenarios/head/react/src/routes/__root.tsx +++ /dev/null @@ -1,35 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' - -export const Route = createRootRoute({ - head: () => ({ - meta: [ - { charSet: 'utf-8' }, - { name: 'viewport', content: 'width=device-width, initial-scale=1' }, - { name: 'application-name', content: 'SSR head benchmark' }, - { name: 'description', content: 'Head-heavy SSR benchmark scenario' }, - { name: 'theme-color', content: '#111827' }, - { property: 'og:type', content: 'website' }, - ], - }), - component: RootComponent, - validateSearch: (s) => s as { q?: string }, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/head/react/src/routes/h.$a.$b.$c.tsx b/benchmarks/ssr/scenarios/head/react/src/routes/h.$a.$b.$c.tsx deleted file mode 100644 index ee39349452..0000000000 --- a/benchmarks/ssr/scenarios/head/react/src/routes/h.$a.$b.$c.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -const dedupedMetaName = 'head-benchmark-shared' - -export const Route = createFileRoute('/h/$a/$b/$c')({ - head: ({ params }) => ({ - meta: [ - { title: `SSR Head L3 ${params.a} ${params.b} ${params.c}` }, - ...Array.from({ length: 10 }, (_, index) => ({ - name: index === 0 ? dedupedMetaName : `level-3-meta-${index}`, - content: - index === 0 ? `shared-${params.c}-level-3` : `c-${params.c}-${index}`, - })), - ], - links: Array.from({ length: 4 }, (_, index) => ({ - rel: 'preload', - as: 'image', - href: `/img/${params.c}-${index}.png`, - })), - }), - component: LevelCComponent, -}) - -function LevelCComponent() { - return

head-level-c

-} diff --git a/benchmarks/ssr/scenarios/head/react/src/routes/h.$a.$b.tsx b/benchmarks/ssr/scenarios/head/react/src/routes/h.$a.$b.tsx deleted file mode 100644 index b0658c87eb..0000000000 --- a/benchmarks/ssr/scenarios/head/react/src/routes/h.$a.$b.tsx +++ /dev/null @@ -1,31 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' - -const dedupedMetaName = 'head-benchmark-shared' - -export const Route = createFileRoute('/h/$a/$b')({ - head: ({ params }) => ({ - meta: [ - { title: `SSR Head L2 ${params.a} ${params.b}` }, - ...Array.from({ length: 10 }, (_, index) => ({ - name: index === 0 ? dedupedMetaName : `level-2-meta-${index}`, - content: - index === 0 ? `shared-${params.b}-level-2` : `c-${params.b}-${index}`, - })), - ], - links: Array.from({ length: 4 }, (_, index) => ({ - rel: 'preload', - as: 'image', - href: `/img/${params.b}-${index}.png`, - })), - }), - component: LevelBComponent, -}) - -function LevelBComponent() { - return ( - <> -

head-level-b

- - - ) -} diff --git a/benchmarks/ssr/scenarios/head/react/src/routes/h.$a.tsx b/benchmarks/ssr/scenarios/head/react/src/routes/h.$a.tsx deleted file mode 100644 index acd5f3c3ce..0000000000 --- a/benchmarks/ssr/scenarios/head/react/src/routes/h.$a.tsx +++ /dev/null @@ -1,31 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' - -const dedupedMetaName = 'head-benchmark-shared' - -export const Route = createFileRoute('/h/$a')({ - head: ({ params }) => ({ - meta: [ - { title: `SSR Head L1 ${params.a}` }, - ...Array.from({ length: 10 }, (_, index) => ({ - name: index === 0 ? dedupedMetaName : `level-1-meta-${index}`, - content: - index === 0 ? `shared-${params.a}-level-1` : `c-${params.a}-${index}`, - })), - ], - links: Array.from({ length: 4 }, (_, index) => ({ - rel: 'preload', - as: 'image', - href: `/img/${params.a}-${index}.png`, - })), - }), - component: LevelAComponent, -}) - -function LevelAComponent() { - return ( - <> -

head-level-a

- - - ) -} diff --git a/benchmarks/ssr/scenarios/head/react/tsconfig.json b/benchmarks/ssr/scenarios/head/react/tsconfig.json deleted file mode 100644 index 91027bfc88..0000000000 --- a/benchmarks/ssr/scenarios/head/react/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/head/react/vite.config.ts b/benchmarks/ssr/scenarios/head/react/vite.config.ts deleted file mode 100644 index d24fc850a1..0000000000 --- a/benchmarks/ssr/scenarios/head/react/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - execArgv: cpuSimulationExecArgv(), - isolate: true, - name: '@benchmarks/ssr head (react)', - watch: false, - environment: 'node', - }, -}) diff --git a/benchmarks/ssr/scenarios/head/shared.ts b/benchmarks/ssr/scenarios/head/shared.ts deleted file mode 100644 index 033ca47c22..0000000000 --- a/benchmarks/ssr/scenarios/head/shared.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { expect } from 'vitest' -import { randomSegment, runRequestLoop } from '../../bench-utils' -import type { StartRequestHandler } from '../../bench-utils' - -export type { StartRequestHandler } - -const benchmarkSeed = 0xdecafbad -const origin = 'http://localhost' -const dedupedMetaName = 'head-benchmark-shared' -const headLoopTotalRequests = 32 - -const requestInit = { - method: 'GET', - headers: { - accept: 'text/html', - }, -} satisfies RequestInit - -export const headBenchOptions = { - warmupIterations: 100, - time: 10_000, - throws: true, -} - -function buildHeadRequest(random: () => number) { - return new Request( - `${origin}/h/${randomSegment(random)}/${randomSegment(random)}/${randomSegment(random)}`, - requestInit, - ) -} - -export function runHeadLoop(handler: StartRequestHandler) { - return runRequestLoop(handler, { - seed: benchmarkSeed, - concurrency: 16, - totalRequests: headLoopTotalRequests, - buildRequest: buildHeadRequest, - }) -} - -export async function assertHeadSanity(handler: StartRequestHandler) { - const a = 'sanity-a' - const b = 'sanity-b' - const c = 'sanity-c' - const response = await handler.fetch( - new Request(`${origin}/h/${a}/${b}/${c}`, requestInit), - ) - const body = await response.text() - const dedupedMetaCount = body.split(dedupedMetaName).length - 1 - - expect(response.status).toBe(200) - expect(body).toContain(`c-${c}-9`) - expect(dedupedMetaCount).toBe(1) - expect(body).toContain(`SSR Head L3 ${a} ${b} ${c}`) -} diff --git a/benchmarks/ssr/scenarios/head/solid/project.json b/benchmarks/ssr/scenarios/head/solid/project.json deleted file mode 100644 index c6df39998b..0000000000 --- a/benchmarks/ssr/scenarios/head/solid/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-head-solid", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/head/solid/speed.bench.ts b/benchmarks/ssr/scenarios/head/solid/speed.bench.ts deleted file mode 100644 index 333e2f091b..0000000000 --- a/benchmarks/ssr/scenarios/head/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { assertHeadSanity, headBenchOptions, runHeadLoop } 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 assertHeadSanity(handler) - -test('ssr', async ({ bench }) => { - await bench('ssr head (solid)', async () => runHeadLoop(handler)).run( - headBenchOptions, - ) -}) diff --git a/benchmarks/ssr/scenarios/head/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/head/solid/src/routeTree.gen.ts deleted file mode 100644 index ceba45e94d..0000000000 --- a/benchmarks/ssr/scenarios/head/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,120 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as HARouteImport } from './routes/h.$a' -import { Route as HABRouteImport } from './routes/h.$a.$b' -import { Route as HABCRouteImport } from './routes/h.$a.$b.$c' - -const HARoute = HARouteImport.update({ - id: '/h/$a', - path: '/h/$a', - getParentRoute: () => rootRouteImport, -} as any) -const HABRoute = HABRouteImport.update({ - id: '/$b', - path: '/$b', - getParentRoute: () => HARoute, -} as any) -const HABCRoute = HABCRouteImport.update({ - id: '/$c', - path: '/$c', - getParentRoute: () => HABRoute, -} as any) - -export interface FileRoutesByFullPath { - '/h/$a': typeof HARouteWithChildren - '/h/$a/$b': typeof HABRouteWithChildren - '/h/$a/$b/$c': typeof HABCRoute -} -export interface FileRoutesByTo { - '/h/$a': typeof HARouteWithChildren - '/h/$a/$b': typeof HABRouteWithChildren - '/h/$a/$b/$c': typeof HABCRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/h/$a': typeof HARouteWithChildren - '/h/$a/$b': typeof HABRouteWithChildren - '/h/$a/$b/$c': typeof HABCRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/h/$a' | '/h/$a/$b' | '/h/$a/$b/$c' - fileRoutesByTo: FileRoutesByTo - to: '/h/$a' | '/h/$a/$b' | '/h/$a/$b/$c' - id: '__root__' | '/h/$a' | '/h/$a/$b' | '/h/$a/$b/$c' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - HARoute: typeof HARouteWithChildren -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/h/$a': { - id: '/h/$a' - path: '/h/$a' - fullPath: '/h/$a' - preLoaderRoute: typeof HARouteImport - parentRoute: typeof rootRouteImport - } - '/h/$a/$b': { - id: '/h/$a/$b' - path: '/$b' - fullPath: '/h/$a/$b' - preLoaderRoute: typeof HABRouteImport - parentRoute: typeof HARoute - } - '/h/$a/$b/$c': { - id: '/h/$a/$b/$c' - path: '/$c' - fullPath: '/h/$a/$b/$c' - preLoaderRoute: typeof HABCRouteImport - parentRoute: typeof HABRoute - } - } -} - -interface HABRouteChildren { - HABCRoute: typeof HABCRoute -} - -const HABRouteChildren: HABRouteChildren = { - HABCRoute: HABCRoute, -} - -const HABRouteWithChildren = HABRoute._addFileChildren(HABRouteChildren) - -interface HARouteChildren { - HABRoute: typeof HABRouteWithChildren -} - -const HARouteChildren: HARouteChildren = { - HABRoute: HABRouteWithChildren, -} - -const HARouteWithChildren = HARoute._addFileChildren(HARouteChildren) - -const rootRouteChildren: RootRouteChildren = { - HARoute: HARouteWithChildren, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/solid-start' -declare module '@tanstack/solid-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/benchmarks/ssr/scenarios/head/solid/src/router.tsx b/benchmarks/ssr/scenarios/head/solid/src/router.tsx deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/ssr/scenarios/head/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/head/solid/src/routes/__root.tsx b/benchmarks/ssr/scenarios/head/solid/src/routes/__root.tsx deleted file mode 100644 index 2dde9d0ddf..0000000000 --- a/benchmarks/ssr/scenarios/head/solid/src/routes/__root.tsx +++ /dev/null @@ -1,35 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/solid-router' - -export const Route = createRootRoute({ - head: () => ({ - meta: [ - { charSet: 'utf-8' }, - { name: 'viewport', content: 'width=device-width, initial-scale=1' }, - { name: 'application-name', content: 'SSR head benchmark' }, - { name: 'description', content: 'Head-heavy SSR benchmark scenario' }, - { name: 'theme-color', content: '#111827' }, - { property: 'og:type', content: 'website' }, - ], - }), - component: RootComponent, - validateSearch: (s) => s as { q?: string }, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/head/solid/src/routes/h.$a.$b.$c.tsx b/benchmarks/ssr/scenarios/head/solid/src/routes/h.$a.$b.$c.tsx deleted file mode 100644 index 7ec132e9a6..0000000000 --- a/benchmarks/ssr/scenarios/head/solid/src/routes/h.$a.$b.$c.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -const dedupedMetaName = 'head-benchmark-shared' - -export const Route = createFileRoute('/h/$a/$b/$c')({ - head: ({ params }) => ({ - meta: [ - { title: `SSR Head L3 ${params.a} ${params.b} ${params.c}` }, - ...Array.from({ length: 10 }, (_, index) => ({ - name: index === 0 ? dedupedMetaName : `level-3-meta-${index}`, - content: - index === 0 ? `shared-${params.c}-level-3` : `c-${params.c}-${index}`, - })), - ], - links: Array.from({ length: 4 }, (_, index) => ({ - rel: 'preload', - as: 'image', - href: `/img/${params.c}-${index}.png`, - })), - }), - component: LevelCComponent, -}) - -function LevelCComponent() { - return

head-level-c

-} diff --git a/benchmarks/ssr/scenarios/head/solid/src/routes/h.$a.$b.tsx b/benchmarks/ssr/scenarios/head/solid/src/routes/h.$a.$b.tsx deleted file mode 100644 index 25d443ad4e..0000000000 --- a/benchmarks/ssr/scenarios/head/solid/src/routes/h.$a.$b.tsx +++ /dev/null @@ -1,31 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' - -const dedupedMetaName = 'head-benchmark-shared' - -export const Route = createFileRoute('/h/$a/$b')({ - head: ({ params }) => ({ - meta: [ - { title: `SSR Head L2 ${params.a} ${params.b}` }, - ...Array.from({ length: 10 }, (_, index) => ({ - name: index === 0 ? dedupedMetaName : `level-2-meta-${index}`, - content: - index === 0 ? `shared-${params.b}-level-2` : `c-${params.b}-${index}`, - })), - ], - links: Array.from({ length: 4 }, (_, index) => ({ - rel: 'preload', - as: 'image', - href: `/img/${params.b}-${index}.png`, - })), - }), - component: LevelBComponent, -}) - -function LevelBComponent() { - return ( - <> -

head-level-b

- - - ) -} diff --git a/benchmarks/ssr/scenarios/head/solid/src/routes/h.$a.tsx b/benchmarks/ssr/scenarios/head/solid/src/routes/h.$a.tsx deleted file mode 100644 index 6c994ffed6..0000000000 --- a/benchmarks/ssr/scenarios/head/solid/src/routes/h.$a.tsx +++ /dev/null @@ -1,31 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' - -const dedupedMetaName = 'head-benchmark-shared' - -export const Route = createFileRoute('/h/$a')({ - head: ({ params }) => ({ - meta: [ - { title: `SSR Head L1 ${params.a}` }, - ...Array.from({ length: 10 }, (_, index) => ({ - name: index === 0 ? dedupedMetaName : `level-1-meta-${index}`, - content: - index === 0 ? `shared-${params.a}-level-1` : `c-${params.a}-${index}`, - })), - ], - links: Array.from({ length: 4 }, (_, index) => ({ - rel: 'preload', - as: 'image', - href: `/img/${params.a}-${index}.png`, - })), - }), - component: LevelAComponent, -}) - -function LevelAComponent() { - return ( - <> -

head-level-a

- - - ) -} diff --git a/benchmarks/ssr/scenarios/head/solid/tsconfig.json b/benchmarks/ssr/scenarios/head/solid/tsconfig.json deleted file mode 100644 index b1806caa67..0000000000 --- a/benchmarks/ssr/scenarios/head/solid/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/head/solid/vite.config.ts b/benchmarks/ssr/scenarios/head/solid/vite.config.ts deleted file mode 100644 index 7a870bbd77..0000000000 --- a/benchmarks/ssr/scenarios/head/solid/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - solid({ ssr: true, hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - execArgv: cpuSimulationExecArgv(), - isolate: true, - name: '@benchmarks/ssr head (solid)', - watch: false, - environment: 'node', - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/head/vue/project.json b/benchmarks/ssr/scenarios/head/vue/project.json deleted file mode 100644 index 62b17b1216..0000000000 --- a/benchmarks/ssr/scenarios/head/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-head-vue", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/head/vue/speed.bench.ts b/benchmarks/ssr/scenarios/head/vue/speed.bench.ts deleted file mode 100644 index 936735a909..0000000000 --- a/benchmarks/ssr/scenarios/head/vue/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { test } from 'vitest' -import { assertHeadSanity, headBenchOptions, runHeadLoop } 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 assertHeadSanity(handler) - -test('ssr', async ({ bench }) => { - await bench('ssr head (vue)', async () => runHeadLoop(handler)).run( - headBenchOptions, - ) -}) diff --git a/benchmarks/ssr/scenarios/head/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/head/vue/src/routeTree.gen.ts deleted file mode 100644 index 9ec1029664..0000000000 --- a/benchmarks/ssr/scenarios/head/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,120 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as HARouteImport } from './routes/h.$a' -import { Route as HABRouteImport } from './routes/h.$a.$b' -import { Route as HABCRouteImport } from './routes/h.$a.$b.$c' - -const HARoute = HARouteImport.update({ - id: '/h/$a', - path: '/h/$a', - getParentRoute: () => rootRouteImport, -} as any) -const HABRoute = HABRouteImport.update({ - id: '/$b', - path: '/$b', - getParentRoute: () => HARoute, -} as any) -const HABCRoute = HABCRouteImport.update({ - id: '/$c', - path: '/$c', - getParentRoute: () => HABRoute, -} as any) - -export interface FileRoutesByFullPath { - '/h/$a': typeof HARouteWithChildren - '/h/$a/$b': typeof HABRouteWithChildren - '/h/$a/$b/$c': typeof HABCRoute -} -export interface FileRoutesByTo { - '/h/$a': typeof HARouteWithChildren - '/h/$a/$b': typeof HABRouteWithChildren - '/h/$a/$b/$c': typeof HABCRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/h/$a': typeof HARouteWithChildren - '/h/$a/$b': typeof HABRouteWithChildren - '/h/$a/$b/$c': typeof HABCRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/h/$a' | '/h/$a/$b' | '/h/$a/$b/$c' - fileRoutesByTo: FileRoutesByTo - to: '/h/$a' | '/h/$a/$b' | '/h/$a/$b/$c' - id: '__root__' | '/h/$a' | '/h/$a/$b' | '/h/$a/$b/$c' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - HARoute: typeof HARouteWithChildren -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/h/$a': { - id: '/h/$a' - path: '/h/$a' - fullPath: '/h/$a' - preLoaderRoute: typeof HARouteImport - parentRoute: typeof rootRouteImport - } - '/h/$a/$b': { - id: '/h/$a/$b' - path: '/$b' - fullPath: '/h/$a/$b' - preLoaderRoute: typeof HABRouteImport - parentRoute: typeof HARoute - } - '/h/$a/$b/$c': { - id: '/h/$a/$b/$c' - path: '/$c' - fullPath: '/h/$a/$b/$c' - preLoaderRoute: typeof HABCRouteImport - parentRoute: typeof HABRoute - } - } -} - -interface HABRouteChildren { - HABCRoute: typeof HABCRoute -} - -const HABRouteChildren: HABRouteChildren = { - HABCRoute: HABCRoute, -} - -const HABRouteWithChildren = HABRoute._addFileChildren(HABRouteChildren) - -interface HARouteChildren { - HABRoute: typeof HABRouteWithChildren -} - -const HARouteChildren: HARouteChildren = { - HABRoute: HABRouteWithChildren, -} - -const HARouteWithChildren = HARoute._addFileChildren(HARouteChildren) - -const rootRouteChildren: RootRouteChildren = { - HARoute: HARouteWithChildren, -} -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/benchmarks/ssr/scenarios/head/vue/src/router.tsx b/benchmarks/ssr/scenarios/head/vue/src/router.tsx deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/ssr/scenarios/head/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/head/vue/src/routes/__root.tsx b/benchmarks/ssr/scenarios/head/vue/src/routes/__root.tsx deleted file mode 100644 index 9b95d2c48e..0000000000 --- a/benchmarks/ssr/scenarios/head/vue/src/routes/__root.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import { - Body, - HeadContent, - Html, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/vue-router' - -export const Route = createRootRoute({ - head: () => ({ - meta: [ - { charSet: 'utf-8' }, - { name: 'viewport', content: 'width=device-width, initial-scale=1' }, - { name: 'application-name', content: 'SSR head benchmark' }, - { name: 'description', content: 'Head-heavy SSR benchmark scenario' }, - { name: 'theme-color', content: '#111827' }, - { property: 'og:type', content: 'website' }, - ], - }), - component: RootComponent, - validateSearch: (s) => s as { q?: string }, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/head/vue/src/routes/h.$a.$b.$c.tsx b/benchmarks/ssr/scenarios/head/vue/src/routes/h.$a.$b.$c.tsx deleted file mode 100644 index 91b8f03f7d..0000000000 --- a/benchmarks/ssr/scenarios/head/vue/src/routes/h.$a.$b.$c.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' - -const dedupedMetaName = 'head-benchmark-shared' - -export const Route = createFileRoute('/h/$a/$b/$c')({ - head: ({ params }) => ({ - meta: [ - { title: `SSR Head L3 ${params.a} ${params.b} ${params.c}` }, - ...Array.from({ length: 10 }, (_, index) => ({ - name: index === 0 ? dedupedMetaName : `level-3-meta-${index}`, - content: - index === 0 ? `shared-${params.c}-level-3` : `c-${params.c}-${index}`, - })), - ], - links: Array.from({ length: 4 }, (_, index) => ({ - rel: 'preload', - as: 'image', - href: `/img/${params.c}-${index}.png`, - })), - }), - component: LevelCComponent, -}) - -function LevelCComponent() { - return

head-level-c

-} diff --git a/benchmarks/ssr/scenarios/head/vue/src/routes/h.$a.$b.tsx b/benchmarks/ssr/scenarios/head/vue/src/routes/h.$a.$b.tsx deleted file mode 100644 index e92a619435..0000000000 --- a/benchmarks/ssr/scenarios/head/vue/src/routes/h.$a.$b.tsx +++ /dev/null @@ -1,31 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/vue-router' - -const dedupedMetaName = 'head-benchmark-shared' - -export const Route = createFileRoute('/h/$a/$b')({ - head: ({ params }) => ({ - meta: [ - { title: `SSR Head L2 ${params.a} ${params.b}` }, - ...Array.from({ length: 10 }, (_, index) => ({ - name: index === 0 ? dedupedMetaName : `level-2-meta-${index}`, - content: - index === 0 ? `shared-${params.b}-level-2` : `c-${params.b}-${index}`, - })), - ], - links: Array.from({ length: 4 }, (_, index) => ({ - rel: 'preload', - as: 'image', - href: `/img/${params.b}-${index}.png`, - })), - }), - component: LevelBComponent, -}) - -function LevelBComponent() { - return ( - <> -

head-level-b

- - - ) -} diff --git a/benchmarks/ssr/scenarios/head/vue/src/routes/h.$a.tsx b/benchmarks/ssr/scenarios/head/vue/src/routes/h.$a.tsx deleted file mode 100644 index ddf407e9ae..0000000000 --- a/benchmarks/ssr/scenarios/head/vue/src/routes/h.$a.tsx +++ /dev/null @@ -1,31 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/vue-router' - -const dedupedMetaName = 'head-benchmark-shared' - -export const Route = createFileRoute('/h/$a')({ - head: ({ params }) => ({ - meta: [ - { title: `SSR Head L1 ${params.a}` }, - ...Array.from({ length: 10 }, (_, index) => ({ - name: index === 0 ? dedupedMetaName : `level-1-meta-${index}`, - content: - index === 0 ? `shared-${params.a}-level-1` : `c-${params.a}-${index}`, - })), - ], - links: Array.from({ length: 4 }, (_, index) => ({ - rel: 'preload', - as: 'image', - href: `/img/${params.a}-${index}.png`, - })), - }), - component: LevelAComponent, -}) - -function LevelAComponent() { - return ( - <> -

head-level-a

- - - ) -} diff --git a/benchmarks/ssr/scenarios/head/vue/tsconfig.json b/benchmarks/ssr/scenarios/head/vue/tsconfig.json deleted file mode 100644 index 4fe3ccecb1..0000000000 --- a/benchmarks/ssr/scenarios/head/vue/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/head/vue/vite.config.ts b/benchmarks/ssr/scenarios/head/vue/vite.config.ts deleted file mode 100644 index 1434d26069..0000000000 --- a/benchmarks/ssr/scenarios/head/vue/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - execArgv: cpuSimulationExecArgv(), - isolate: true, - name: '@benchmarks/ssr head (vue)', - watch: false, - environment: 'node', - }, -}) diff --git a/benchmarks/ssr/scenarios/loaders/react/project.json b/benchmarks/ssr/scenarios/loaders/react/project.json deleted file mode 100644 index 0455f80c87..0000000000 --- a/benchmarks/ssr/scenarios/loaders/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-loaders-react", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/loaders/react/speed.bench.ts b/benchmarks/ssr/scenarios/loaders/react/speed.bench.ts deleted file mode 100644 index 7acd43c635..0000000000 --- a/benchmarks/ssr/scenarios/loaders/react/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertLoadersSanity, - benchOptions, - runLoadersLoop, - 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 assertLoadersSanity(handler) - -test('ssr', async ({ bench }) => { - await bench('ssr loaders (react)', async () => runLoadersLoop(handler)).run( - benchOptions, - ) -}) diff --git a/benchmarks/ssr/scenarios/loaders/react/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/loaders/react/src/routeTree.gen.ts deleted file mode 100644 index 068b5a5433..0000000000 --- a/benchmarks/ssr/scenarios/loaders/react/src/routeTree.gen.ts +++ /dev/null @@ -1,120 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as ARouteImport } from './routes/$a' -import { Route as ABRouteImport } from './routes/$a.$b' -import { Route as ABCRouteImport } from './routes/$a.$b.$c' - -const ARoute = ARouteImport.update({ - id: '/$a', - path: '/$a', - getParentRoute: () => rootRouteImport, -} as any) -const ABRoute = ABRouteImport.update({ - id: '/$b', - path: '/$b', - getParentRoute: () => ARoute, -} as any) -const ABCRoute = ABCRouteImport.update({ - id: '/$c', - path: '/$c', - getParentRoute: () => ABRoute, -} as any) - -export interface FileRoutesByFullPath { - '/$a': typeof ARouteWithChildren - '/$a/$b': typeof ABRouteWithChildren - '/$a/$b/$c': typeof ABCRoute -} -export interface FileRoutesByTo { - '/$a': typeof ARouteWithChildren - '/$a/$b': typeof ABRouteWithChildren - '/$a/$b/$c': typeof ABCRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/$a': typeof ARouteWithChildren - '/$a/$b': typeof ABRouteWithChildren - '/$a/$b/$c': typeof ABCRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/$a' | '/$a/$b' | '/$a/$b/$c' - fileRoutesByTo: FileRoutesByTo - to: '/$a' | '/$a/$b' | '/$a/$b/$c' - id: '__root__' | '/$a' | '/$a/$b' | '/$a/$b/$c' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - ARoute: typeof ARouteWithChildren -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/$a': { - id: '/$a' - path: '/$a' - fullPath: '/$a' - preLoaderRoute: typeof ARouteImport - parentRoute: typeof rootRouteImport - } - '/$a/$b': { - id: '/$a/$b' - path: '/$b' - fullPath: '/$a/$b' - preLoaderRoute: typeof ABRouteImport - parentRoute: typeof ARoute - } - '/$a/$b/$c': { - id: '/$a/$b/$c' - path: '/$c' - fullPath: '/$a/$b/$c' - preLoaderRoute: typeof ABCRouteImport - parentRoute: typeof ABRoute - } - } -} - -interface ABRouteChildren { - ABCRoute: typeof ABCRoute -} - -const ABRouteChildren: ABRouteChildren = { - ABCRoute: ABCRoute, -} - -const ABRouteWithChildren = ABRoute._addFileChildren(ABRouteChildren) - -interface ARouteChildren { - ABRoute: typeof ABRouteWithChildren -} - -const ARouteChildren: ARouteChildren = { - ABRoute: ABRouteWithChildren, -} - -const ARouteWithChildren = ARoute._addFileChildren(ARouteChildren) - -const rootRouteChildren: RootRouteChildren = { - ARoute: ARouteWithChildren, -} -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/benchmarks/ssr/scenarios/loaders/react/src/router.tsx b/benchmarks/ssr/scenarios/loaders/react/src/router.tsx deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/ssr/scenarios/loaders/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/loaders/react/src/routes/$a.$b.$c.tsx b/benchmarks/ssr/scenarios/loaders/react/src/routes/$a.$b.$c.tsx deleted file mode 100644 index 746a26aeb6..0000000000 --- a/benchmarks/ssr/scenarios/loaders/react/src/routes/$a.$b.$c.tsx +++ /dev/null @@ -1,32 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { makeLevelData } from '../../../shared-data' - -export const Route = createFileRoute('/$a/$b/$c')({ - beforeLoad: ({ params, context }) => { - void context - - return { ctxC: `v-${params.c}` } - }, - loaderDeps: ({ search }) => ({ page: search.page }), - loader: async ({ params, deps, context }) => { - void context - - return makeLevelData(params.c, deps.page) - }, - component: LevelCComponent, -}) - -function LevelCComponent() { - const data = Route.useLoaderData() - - return ( -
-

{data.meta.label}

-
    - {data.items.slice(0, 10).map((item) => ( -
  • {item.name}
  • - ))} -
-
- ) -} diff --git a/benchmarks/ssr/scenarios/loaders/react/src/routes/$a.$b.tsx b/benchmarks/ssr/scenarios/loaders/react/src/routes/$a.$b.tsx deleted file mode 100644 index 79c10c06b0..0000000000 --- a/benchmarks/ssr/scenarios/loaders/react/src/routes/$a.$b.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import { makeLevelData } from '../../../shared-data' - -export const Route = createFileRoute('/$a/$b')({ - beforeLoad: ({ params, context }) => { - void context - - return { ctxB: `v-${params.b}` } - }, - loaderDeps: ({ search }) => ({ page: search.page }), - loader: async ({ params, deps, context }) => { - void context - - return makeLevelData(params.b, deps.page) - }, - component: LevelBComponent, -}) - -function LevelBComponent() { - const data = Route.useLoaderData() - - return ( -
-

{data.meta.label}

-
    - {data.items.slice(0, 10).map((item) => ( -
  • {item.name}
  • - ))} -
- -
- ) -} diff --git a/benchmarks/ssr/scenarios/loaders/react/src/routes/$a.tsx b/benchmarks/ssr/scenarios/loaders/react/src/routes/$a.tsx deleted file mode 100644 index 980a495c32..0000000000 --- a/benchmarks/ssr/scenarios/loaders/react/src/routes/$a.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import { makeLevelData } from '../../../shared-data' - -export const Route = createFileRoute('/$a')({ - beforeLoad: ({ params, context }) => { - void context - - return { ctxA: `v-${params.a}` } - }, - loaderDeps: ({ search }) => ({ page: search.page }), - loader: async ({ params, deps, context }) => { - void context - - return makeLevelData(params.a, deps.page) - }, - component: LevelAComponent, -}) - -function LevelAComponent() { - const data = Route.useLoaderData() - - return ( -
-

{data.meta.label}

-
    - {data.items.slice(0, 10).map((item) => ( -
  • {item.name}
  • - ))} -
- -
- ) -} diff --git a/benchmarks/ssr/scenarios/loaders/react/src/routes/__root.tsx b/benchmarks/ssr/scenarios/loaders/react/src/routes/__root.tsx deleted file mode 100644 index 001639cb39..0000000000 --- a/benchmarks/ssr/scenarios/loaders/react/src/routes/__root.tsx +++ /dev/null @@ -1,28 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: RootComponent, - validateSearch: (s: Record) => ({ - page: typeof s.page === 'number' ? s.page : 0, - tags: Array.isArray(s.tags) ? (s.tags as Array) : [], - }), -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/loaders/react/tsconfig.json b/benchmarks/ssr/scenarios/loaders/react/tsconfig.json deleted file mode 100644 index 8800818162..0000000000 --- a/benchmarks/ssr/scenarios/loaders/react/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../shared-data.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/loaders/react/vite.config.ts b/benchmarks/ssr/scenarios/loaders/react/vite.config.ts deleted file mode 100644 index e761426c84..0000000000 --- a/benchmarks/ssr/scenarios/loaders/react/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - execArgv: cpuSimulationExecArgv(), - isolate: true, - name: '@benchmarks/ssr loaders (react)', - watch: false, - environment: 'node', - }, -}) diff --git a/benchmarks/ssr/scenarios/loaders/shared-bench.ts b/benchmarks/ssr/scenarios/loaders/shared-bench.ts deleted file mode 100644 index f52c51dccd..0000000000 --- a/benchmarks/ssr/scenarios/loaders/shared-bench.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { makeLevelData } from './shared-data' -import { randomSegment, runRequestLoop } from '../../bench-utils' -import type { StartRequestHandler } from '../../bench-utils' - -export type { StartRequestHandler } - -const benchmarkSeed = 0xdecafbad -const loadersLoopTotalRequests = 16 - -const requestInit = { - method: 'GET', - headers: { - accept: 'text/html', - }, -} satisfies RequestInit - -function buildLoaderRequest(random: () => number, index: number) { - const suffix = index.toString(36) - const a = `${randomSegment(random)}-${suffix}` - const b = `${randomSegment(random)}-${suffix}` - const c = `${randomSegment(random)}-${suffix}` - const page = Math.floor(random() * 10) - const tags = JSON.stringify([ - `t-${randomSegment(random)}-${suffix}`, - `t-${randomSegment(random)}-${suffix}`, - ]) - - return new Request( - `http://localhost/${a}/${b}/${c}?page=${page}&tags=${encodeURIComponent(tags)}`, - requestInit, - ) -} - -export async function assertLoadersSanity(handler: StartRequestHandler) { - const page = 3 - const leafSource = 'c-sanity' - const tags = JSON.stringify(['t-x', 't-y']) - const response = await handler.fetch( - new Request( - `http://localhost/a-sanity/b-sanity/${leafSource}?page=${page}&tags=${encodeURIComponent(tags)}`, - requestInit, - ), - ) - const body = await response.text() - const leafMarker = makeLevelData(leafSource, page).items[0]?.name - - if (response.status !== 200) { - throw new Error( - `Expected setup request status 200, received ${response.status}`, - ) - } - - if (!leafMarker || !body.includes(leafMarker)) { - throw new Error('Expected setup response to include the leaf loader item') - } - - if (!body.includes('$_TSR')) { - throw new Error('Expected setup response to include the dehydration marker') - } -} - -export const benchOptions = { - warmupIterations: 100, - time: 10_000, - throws: true, -} - -export function runLoadersLoop(handler: StartRequestHandler) { - return runRequestLoop(handler, { - seed: benchmarkSeed, - concurrency: 16, - totalRequests: loadersLoopTotalRequests, - buildRequest: buildLoaderRequest, - }) -} diff --git a/benchmarks/ssr/scenarios/loaders/shared-data.ts b/benchmarks/ssr/scenarios/loaders/shared-data.ts deleted file mode 100644 index d907f7d66c..0000000000 --- a/benchmarks/ssr/scenarios/loaders/shared-data.ts +++ /dev/null @@ -1,54 +0,0 @@ -export interface LevelDataItem { - id: string - name: string - flags: number -} - -export interface LevelData { - items: Array - meta: { - source: string - page: number - label: string - } -} - -function hashLevelInput(input: string, salt: number) { - let value = salt >>> 0 - - for (let index = 0; index < input.length; index++) { - value = (value * 33 + input.charCodeAt(index) + index) >>> 0 - } - - for (let index = 0; index < 16; index++) { - value = (value ^ (value << 13)) >>> 0 - value = (value ^ (value >> 17)) >>> 0 - value = (value ^ (value << 5)) >>> 0 - } - - return value -} - -export function makeLevelData(source: string, page: number): LevelData { - const safePage = page | 0 - const seedInput = `${source}:${safePage}` - const seed = hashLevelInput(seedInput, 0x9e3779b9) - - return { - items: Array.from({ length: 50 }, (_, index) => { - const hash = hashLevelInput(`${seedInput}:${index}`, seed + index) - const hashLabel = (hash & 0xffff).toString(36) - - return { - id: `${index.toString(36)}-${hashLabel}`, - name: `${source}:${safePage}:item-${index}`, - flags: hash & 15, - } - }), - meta: { - source, - page: safePage, - label: `source ${source} page ${safePage}`, - }, - } -} diff --git a/benchmarks/ssr/scenarios/loaders/solid/project.json b/benchmarks/ssr/scenarios/loaders/solid/project.json deleted file mode 100644 index 2cb0e92acd..0000000000 --- a/benchmarks/ssr/scenarios/loaders/solid/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-loaders-solid", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/loaders/solid/speed.bench.ts b/benchmarks/ssr/scenarios/loaders/solid/speed.bench.ts deleted file mode 100644 index 7fc8d88389..0000000000 --- a/benchmarks/ssr/scenarios/loaders/solid/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertLoadersSanity, - benchOptions, - runLoadersLoop, - 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 assertLoadersSanity(handler) - -test('ssr', async ({ bench }) => { - await bench('ssr loaders (solid)', async () => runLoadersLoop(handler)).run( - benchOptions, - ) -}) diff --git a/benchmarks/ssr/scenarios/loaders/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/loaders/solid/src/routeTree.gen.ts deleted file mode 100644 index 7b299cfcd1..0000000000 --- a/benchmarks/ssr/scenarios/loaders/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,120 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as ARouteImport } from './routes/$a' -import { Route as ABRouteImport } from './routes/$a.$b' -import { Route as ABCRouteImport } from './routes/$a.$b.$c' - -const ARoute = ARouteImport.update({ - id: '/$a', - path: '/$a', - getParentRoute: () => rootRouteImport, -} as any) -const ABRoute = ABRouteImport.update({ - id: '/$b', - path: '/$b', - getParentRoute: () => ARoute, -} as any) -const ABCRoute = ABCRouteImport.update({ - id: '/$c', - path: '/$c', - getParentRoute: () => ABRoute, -} as any) - -export interface FileRoutesByFullPath { - '/$a': typeof ARouteWithChildren - '/$a/$b': typeof ABRouteWithChildren - '/$a/$b/$c': typeof ABCRoute -} -export interface FileRoutesByTo { - '/$a': typeof ARouteWithChildren - '/$a/$b': typeof ABRouteWithChildren - '/$a/$b/$c': typeof ABCRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/$a': typeof ARouteWithChildren - '/$a/$b': typeof ABRouteWithChildren - '/$a/$b/$c': typeof ABCRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/$a' | '/$a/$b' | '/$a/$b/$c' - fileRoutesByTo: FileRoutesByTo - to: '/$a' | '/$a/$b' | '/$a/$b/$c' - id: '__root__' | '/$a' | '/$a/$b' | '/$a/$b/$c' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - ARoute: typeof ARouteWithChildren -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/$a': { - id: '/$a' - path: '/$a' - fullPath: '/$a' - preLoaderRoute: typeof ARouteImport - parentRoute: typeof rootRouteImport - } - '/$a/$b': { - id: '/$a/$b' - path: '/$b' - fullPath: '/$a/$b' - preLoaderRoute: typeof ABRouteImport - parentRoute: typeof ARoute - } - '/$a/$b/$c': { - id: '/$a/$b/$c' - path: '/$c' - fullPath: '/$a/$b/$c' - preLoaderRoute: typeof ABCRouteImport - parentRoute: typeof ABRoute - } - } -} - -interface ABRouteChildren { - ABCRoute: typeof ABCRoute -} - -const ABRouteChildren: ABRouteChildren = { - ABCRoute: ABCRoute, -} - -const ABRouteWithChildren = ABRoute._addFileChildren(ABRouteChildren) - -interface ARouteChildren { - ABRoute: typeof ABRouteWithChildren -} - -const ARouteChildren: ARouteChildren = { - ABRoute: ABRouteWithChildren, -} - -const ARouteWithChildren = ARoute._addFileChildren(ARouteChildren) - -const rootRouteChildren: RootRouteChildren = { - ARoute: ARouteWithChildren, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/solid-start' -declare module '@tanstack/solid-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/benchmarks/ssr/scenarios/loaders/solid/src/router.tsx b/benchmarks/ssr/scenarios/loaders/solid/src/router.tsx deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/ssr/scenarios/loaders/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/loaders/solid/src/routes/$a.$b.$c.tsx b/benchmarks/ssr/scenarios/loaders/solid/src/routes/$a.$b.$c.tsx deleted file mode 100644 index 9ead32440a..0000000000 --- a/benchmarks/ssr/scenarios/loaders/solid/src/routes/$a.$b.$c.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { makeLevelData } from '../../../shared-data' - -export const Route = createFileRoute('/$a/$b/$c')({ - beforeLoad: ({ params, context }) => { - void context - - return { ctxC: `v-${params.c}` } - }, - loaderDeps: ({ search }) => ({ page: search.page }), - loader: async ({ params, deps, context }) => { - void context - - return makeLevelData(params.c, deps.page) - }, - component: LevelCComponent, -}) - -function LevelCComponent() { - const data = Route.useLoaderData() - - return ( -
-

{data().meta.label}

-
    - {data() - .items.slice(0, 10) - .map((item) => ( -
  • {item.name}
  • - ))} -
-
- ) -} diff --git a/benchmarks/ssr/scenarios/loaders/solid/src/routes/$a.$b.tsx b/benchmarks/ssr/scenarios/loaders/solid/src/routes/$a.$b.tsx deleted file mode 100644 index c0abf3da87..0000000000 --- a/benchmarks/ssr/scenarios/loaders/solid/src/routes/$a.$b.tsx +++ /dev/null @@ -1,35 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' -import { makeLevelData } from '../../../shared-data' - -export const Route = createFileRoute('/$a/$b')({ - beforeLoad: ({ params, context }) => { - void context - - return { ctxB: `v-${params.b}` } - }, - loaderDeps: ({ search }) => ({ page: search.page }), - loader: async ({ params, deps, context }) => { - void context - - return makeLevelData(params.b, deps.page) - }, - component: LevelBComponent, -}) - -function LevelBComponent() { - const data = Route.useLoaderData() - - return ( -
-

{data().meta.label}

-
    - {data() - .items.slice(0, 10) - .map((item) => ( -
  • {item.name}
  • - ))} -
- -
- ) -} diff --git a/benchmarks/ssr/scenarios/loaders/solid/src/routes/$a.tsx b/benchmarks/ssr/scenarios/loaders/solid/src/routes/$a.tsx deleted file mode 100644 index d4608523b8..0000000000 --- a/benchmarks/ssr/scenarios/loaders/solid/src/routes/$a.tsx +++ /dev/null @@ -1,35 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' -import { makeLevelData } from '../../../shared-data' - -export const Route = createFileRoute('/$a')({ - beforeLoad: ({ params, context }) => { - void context - - return { ctxA: `v-${params.a}` } - }, - loaderDeps: ({ search }) => ({ page: search.page }), - loader: async ({ params, deps, context }) => { - void context - - return makeLevelData(params.a, deps.page) - }, - component: LevelAComponent, -}) - -function LevelAComponent() { - const data = Route.useLoaderData() - - return ( -
-

{data().meta.label}

-
    - {data() - .items.slice(0, 10) - .map((item) => ( -
  • {item.name}
  • - ))} -
- -
- ) -} diff --git a/benchmarks/ssr/scenarios/loaders/solid/src/routes/__root.tsx b/benchmarks/ssr/scenarios/loaders/solid/src/routes/__root.tsx deleted file mode 100644 index 2f4b1de410..0000000000 --- a/benchmarks/ssr/scenarios/loaders/solid/src/routes/__root.tsx +++ /dev/null @@ -1,28 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/solid-router' - -export const Route = createRootRoute({ - component: RootComponent, - validateSearch: (s: Record) => ({ - page: typeof s.page === 'number' ? s.page : 0, - tags: Array.isArray(s.tags) ? (s.tags as Array) : [], - }), -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/loaders/solid/tsconfig.json b/benchmarks/ssr/scenarios/loaders/solid/tsconfig.json deleted file mode 100644 index 47f264ba4f..0000000000 --- a/benchmarks/ssr/scenarios/loaders/solid/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../shared-data.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/loaders/solid/vite.config.ts b/benchmarks/ssr/scenarios/loaders/solid/vite.config.ts deleted file mode 100644 index 64f52159c3..0000000000 --- a/benchmarks/ssr/scenarios/loaders/solid/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - solid({ ssr: true, hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - execArgv: cpuSimulationExecArgv(), - isolate: true, - name: '@benchmarks/ssr loaders (solid)', - watch: false, - environment: 'node', - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/loaders/vue/project.json b/benchmarks/ssr/scenarios/loaders/vue/project.json deleted file mode 100644 index 2a98cb57f9..0000000000 --- a/benchmarks/ssr/scenarios/loaders/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-loaders-vue", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/loaders/vue/speed.bench.ts b/benchmarks/ssr/scenarios/loaders/vue/speed.bench.ts deleted file mode 100644 index 321350d98c..0000000000 --- a/benchmarks/ssr/scenarios/loaders/vue/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertLoadersSanity, - benchOptions, - runLoadersLoop, - 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 assertLoadersSanity(handler) - -test('ssr', async ({ bench }) => { - await bench('ssr loaders (vue)', async () => runLoadersLoop(handler)).run( - benchOptions, - ) -}) diff --git a/benchmarks/ssr/scenarios/loaders/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/loaders/vue/src/routeTree.gen.ts deleted file mode 100644 index 24ee6c3b9d..0000000000 --- a/benchmarks/ssr/scenarios/loaders/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,120 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as ARouteImport } from './routes/$a' -import { Route as ABRouteImport } from './routes/$a.$b' -import { Route as ABCRouteImport } from './routes/$a.$b.$c' - -const ARoute = ARouteImport.update({ - id: '/$a', - path: '/$a', - getParentRoute: () => rootRouteImport, -} as any) -const ABRoute = ABRouteImport.update({ - id: '/$b', - path: '/$b', - getParentRoute: () => ARoute, -} as any) -const ABCRoute = ABCRouteImport.update({ - id: '/$c', - path: '/$c', - getParentRoute: () => ABRoute, -} as any) - -export interface FileRoutesByFullPath { - '/$a': typeof ARouteWithChildren - '/$a/$b': typeof ABRouteWithChildren - '/$a/$b/$c': typeof ABCRoute -} -export interface FileRoutesByTo { - '/$a': typeof ARouteWithChildren - '/$a/$b': typeof ABRouteWithChildren - '/$a/$b/$c': typeof ABCRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/$a': typeof ARouteWithChildren - '/$a/$b': typeof ABRouteWithChildren - '/$a/$b/$c': typeof ABCRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/$a' | '/$a/$b' | '/$a/$b/$c' - fileRoutesByTo: FileRoutesByTo - to: '/$a' | '/$a/$b' | '/$a/$b/$c' - id: '__root__' | '/$a' | '/$a/$b' | '/$a/$b/$c' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - ARoute: typeof ARouteWithChildren -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/$a': { - id: '/$a' - path: '/$a' - fullPath: '/$a' - preLoaderRoute: typeof ARouteImport - parentRoute: typeof rootRouteImport - } - '/$a/$b': { - id: '/$a/$b' - path: '/$b' - fullPath: '/$a/$b' - preLoaderRoute: typeof ABRouteImport - parentRoute: typeof ARoute - } - '/$a/$b/$c': { - id: '/$a/$b/$c' - path: '/$c' - fullPath: '/$a/$b/$c' - preLoaderRoute: typeof ABCRouteImport - parentRoute: typeof ABRoute - } - } -} - -interface ABRouteChildren { - ABCRoute: typeof ABCRoute -} - -const ABRouteChildren: ABRouteChildren = { - ABCRoute: ABCRoute, -} - -const ABRouteWithChildren = ABRoute._addFileChildren(ABRouteChildren) - -interface ARouteChildren { - ABRoute: typeof ABRouteWithChildren -} - -const ARouteChildren: ARouteChildren = { - ABRoute: ABRouteWithChildren, -} - -const ARouteWithChildren = ARoute._addFileChildren(ARouteChildren) - -const rootRouteChildren: RootRouteChildren = { - ARoute: ARouteWithChildren, -} -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/benchmarks/ssr/scenarios/loaders/vue/src/router.tsx b/benchmarks/ssr/scenarios/loaders/vue/src/router.tsx deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/ssr/scenarios/loaders/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} 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 deleted file mode 100644 index 0a52b9c542..0000000000 --- a/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.$c.tsx +++ /dev/null @@ -1,35 +0,0 @@ -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 - - return { ctxC: `v-${params.c}` } - }, - loaderDeps: ({ search }) => ({ page: search.page }), - loader: async ({ params, deps, context }) => { - void context - - return makeLevelData(params.c, deps.page) - }, - component: LevelCComponent, -}) diff --git a/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.tsx b/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.tsx deleted file mode 100644 index f3943d58e7..0000000000 --- a/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.tsx +++ /dev/null @@ -1,36 +0,0 @@ -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 - - return { ctxB: `v-${params.b}` } - }, - loaderDeps: ({ search }) => ({ page: search.page }), - loader: async ({ params, deps, context }) => { - void context - - return makeLevelData(params.b, deps.page) - }, - component: LevelBComponent, -}) diff --git a/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.tsx b/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.tsx deleted file mode 100644 index 63bb36949f..0000000000 --- a/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.tsx +++ /dev/null @@ -1,36 +0,0 @@ -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 - - return { ctxA: `v-${params.a}` } - }, - loaderDeps: ({ search }) => ({ page: search.page }), - loader: async ({ params, deps, context }) => { - void context - - return makeLevelData(params.a, deps.page) - }, - component: LevelAComponent, -}) diff --git a/benchmarks/ssr/scenarios/loaders/vue/src/routes/__root.tsx b/benchmarks/ssr/scenarios/loaders/vue/src/routes/__root.tsx deleted file mode 100644 index 0479fb1af4..0000000000 --- a/benchmarks/ssr/scenarios/loaders/vue/src/routes/__root.tsx +++ /dev/null @@ -1,30 +0,0 @@ -import { - Body, - HeadContent, - Html, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/vue-router' - -export const Route = createRootRoute({ - component: RootComponent, - validateSearch: (s: Record) => ({ - page: typeof s.page === 'number' ? s.page : 0, - tags: Array.isArray(s.tags) ? (s.tags as Array) : [], - }), -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/loaders/vue/tsconfig.json b/benchmarks/ssr/scenarios/loaders/vue/tsconfig.json deleted file mode 100644 index c302f63770..0000000000 --- a/benchmarks/ssr/scenarios/loaders/vue/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../shared-data.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/loaders/vue/vite.config.ts b/benchmarks/ssr/scenarios/loaders/vue/vite.config.ts deleted file mode 100644 index 92bf3e60f0..0000000000 --- a/benchmarks/ssr/scenarios/loaders/vue/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - execArgv: cpuSimulationExecArgv(), - isolate: true, - name: '@benchmarks/ssr loaders (vue)', - watch: false, - environment: 'node', - }, -}) diff --git a/benchmarks/ssr/scenarios/rewrites/react/project.json b/benchmarks/ssr/scenarios/rewrites/react/project.json deleted file mode 100644 index 84d4846ec5..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-rewrites-react", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/rewrites/react/speed.bench.ts b/benchmarks/ssr/scenarios/rewrites/react/speed.bench.ts deleted file mode 100644 index 920186c5db..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/react/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertRewriteScenario, - rewriteBenchOptions, - runRewriteLocalizedLoop, -} 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 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 deleted file mode 100644 index f5d09089a6..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/react/speed.rewrite-passthrough.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/rewrites/react/src/routeTree.gen.ts deleted file mode 100644 index e893d06a57..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/react/src/routeTree.gen.ts +++ /dev/null @@ -1,94 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as PARouteImport } from './routes/p.$a' -import { Route as PABRouteImport } from './routes/p.$a.$b' - -const PARoute = PARouteImport.update({ - id: '/p/$a', - path: '/p/$a', - getParentRoute: () => rootRouteImport, -} as any) -const PABRoute = PABRouteImport.update({ - id: '/$b', - path: '/$b', - getParentRoute: () => PARoute, -} as any) - -export interface FileRoutesByFullPath { - '/p/$a': typeof PARouteWithChildren - '/p/$a/$b': typeof PABRoute -} -export interface FileRoutesByTo { - '/p/$a': typeof PARouteWithChildren - '/p/$a/$b': typeof PABRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/p/$a': typeof PARouteWithChildren - '/p/$a/$b': typeof PABRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/p/$a' | '/p/$a/$b' - fileRoutesByTo: FileRoutesByTo - to: '/p/$a' | '/p/$a/$b' - id: '__root__' | '/p/$a' | '/p/$a/$b' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - PARoute: typeof PARouteWithChildren -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/p/$a': { - id: '/p/$a' - path: '/p/$a' - fullPath: '/p/$a' - preLoaderRoute: typeof PARouteImport - parentRoute: typeof rootRouteImport - } - '/p/$a/$b': { - id: '/p/$a/$b' - path: '/$b' - fullPath: '/p/$a/$b' - preLoaderRoute: typeof PABRouteImport - parentRoute: typeof PARoute - } - } -} - -interface PARouteChildren { - PABRoute: typeof PABRoute -} - -const PARouteChildren: PARouteChildren = { - PABRoute: PABRoute, -} - -const PARouteWithChildren = PARoute._addFileChildren(PARouteChildren) - -const rootRouteChildren: RootRouteChildren = { - PARoute: PARouteWithChildren, -} -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/benchmarks/ssr/scenarios/rewrites/react/src/router.tsx b/benchmarks/ssr/scenarios/rewrites/react/src/router.tsx deleted file mode 100644 index e9e0b2ce9a..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/react/src/router.tsx +++ /dev/null @@ -1,42 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -const localePrefixRe = /^\/(fr|de|es)(\/.*)$/ - -export function getRouter() { - return createRouter({ - routeTree, - basepath: '/app', - defaultPreload: false, - scrollRestoration: false, - rewrite: { - input: ({ url }) => { - const match = url.pathname.match(localePrefixRe) - - if (match) { - url.pathname = match[2]! - url.searchParams.set('_locale', match[1]!) - return url - } - - return undefined - }, - output: ({ url }) => { - const locale = url.searchParams.get('_locale') - - if (locale) { - url.searchParams.delete('_locale') - url.pathname = `/${locale}${url.pathname}` - } - - return url - }, - }, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/rewrites/react/src/routes/__root.tsx b/benchmarks/ssr/scenarios/rewrites/react/src/routes/__root.tsx deleted file mode 100644 index 7cdcfe1a37..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/react/src/routes/__root.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: RootComponent, - validateSearch: (s: Record) => ({ - _locale: typeof s._locale === 'string' ? s._locale : undefined, - }), -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/rewrites/react/src/routes/p.$a.$b.tsx b/benchmarks/ssr/scenarios/rewrites/react/src/routes/p.$a.$b.tsx deleted file mode 100644 index 756109b844..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/react/src/routes/p.$a.$b.tsx +++ /dev/null @@ -1,39 +0,0 @@ -import { Link, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/p/$a/$b')({ - loader: ({ params }) => ({ - a: params.a, - b: params.b, - nextB: `next-${params.b}`, - }), - component: LeafComponent, -}) - -function LeafComponent() { - const data = Route.useLoaderData() - - return ( -
-

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

- - leaf-self-link - - - leaf-next-link - - - leaf-parent-link - -
- ) -} diff --git a/benchmarks/ssr/scenarios/rewrites/react/src/routes/p.$a.tsx b/benchmarks/ssr/scenarios/rewrites/react/src/routes/p.$a.tsx deleted file mode 100644 index 7b0a778a18..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/react/src/routes/p.$a.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/p/$a')({ - loader: ({ params }) => ({ - a: params.a, - nextB: `branch-${params.a}`, - }), - component: ParentComponent, -}) - -function ParentComponent() { - const data = Route.useLoaderData() - - return ( -
-

rewrite-parent {data.a}

- - parent-branch-link - - -
- ) -} diff --git a/benchmarks/ssr/scenarios/rewrites/react/tsconfig.json b/benchmarks/ssr/scenarios/rewrites/react/tsconfig.json deleted file mode 100644 index cf14e1d440..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/react/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "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 deleted file mode 100644 index 7b20340ec6..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/react/vite.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - router: { - basepath: '/app', - }, - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - execArgv: cpuSimulationExecArgv(), - isolate: true, - name: '@benchmarks/ssr rewrites (react)', - watch: false, - environment: 'node', - }, -}) diff --git a/benchmarks/ssr/scenarios/rewrites/shared.ts b/benchmarks/ssr/scenarios/rewrites/shared.ts deleted file mode 100644 index 9b29bc0249..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/shared.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { expect } from 'vitest' -import { randomSegment, runRequestLoop } from '../../bench-utils' -import type { StartRequestHandler } from '../../bench-utils' - -export type { StartRequestHandler } - -const benchmarkSeed = 0xdecafbad -const origin = 'http://localhost' -const localizedLoopTotalRequests = 32 -const passthroughLoopTotalRequests = 32 - -const requestInit = { - method: 'GET', - headers: { - accept: 'text/html', - }, -} satisfies RequestInit - -export const rewriteBenchOptions = { - warmupIterations: 100, - time: 10_000, - throws: true, -} - -function buildLocalizedRequest(random: () => number) { - return new Request( - `${origin}/app/fr/p/${randomSegment(random)}/${randomSegment(random)}`, - requestInit, - ) -} - -function buildPassthroughRequest(random: () => number) { - return new Request( - `${origin}/app/p/${randomSegment(random)}/${randomSegment(random)}`, - requestInit, - ) -} - -export function runRewriteLocalizedLoop(handler: StartRequestHandler) { - return runRequestLoop(handler, { - seed: benchmarkSeed, - concurrency: 16, - totalRequests: localizedLoopTotalRequests, - buildRequest: buildLocalizedRequest, - }) -} - -export function runRewritePassthroughLoop(handler: StartRequestHandler) { - return runRequestLoop(handler, { - seed: benchmarkSeed, - concurrency: 16, - totalRequests: passthroughLoopTotalRequests, - buildRequest: buildPassthroughRequest, - }) -} - -export async function assertRewriteScenario(handler: StartRequestHandler) { - const localizedResponse = await handler.fetch( - new Request(`${origin}/app/fr/p/sanity-a/sanity-b`, requestInit), - ) - const localizedBody = await localizedResponse.text() - - expect(localizedResponse.status).toBe(200) - expect(localizedBody).toContain('rewrite-leaf') - expect(localizedBody).toContain('sanity-a') - expect(localizedBody).toContain('sanity-b') - expect(localizedBody).toContain('href="/app/fr/p/sanity-a/sanity-b"') - expect(localizedBody).toContain('href="/app/fr/p/sanity-a/next-sanity-b"') - - const passthroughResponse = await handler.fetch( - new Request(`${origin}/app/p/sanity-a/sanity-b`, requestInit), - ) - const passthroughBody = await passthroughResponse.text() - - expect(passthroughResponse.status).toBe(200) - expect(passthroughBody).toContain('rewrite-leaf') - expect(passthroughBody).toContain('sanity-a') - expect(passthroughBody).toContain('sanity-b') - expect(passthroughBody).toContain('href="/app/fr/p/sanity-a/sanity-b"') - expect(passthroughBody).toContain('href="/app/fr/p/sanity-a/next-sanity-b"') - - const unprefixedResponse = await handler.fetch( - new Request(`${origin}/p/sanity-a/sanity-b`, requestInit), - ) - await unprefixedResponse.text() - - expect(unprefixedResponse.status).toBe(307) - expect(unprefixedResponse.headers.get('location')).toBe( - '/app/p/sanity-a/sanity-b', - ) -} diff --git a/benchmarks/ssr/scenarios/rewrites/solid/project.json b/benchmarks/ssr/scenarios/rewrites/solid/project.json deleted file mode 100644 index 7c993a1404..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/solid/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-rewrites-solid", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/rewrites/solid/speed.bench.ts b/benchmarks/ssr/scenarios/rewrites/solid/speed.bench.ts deleted file mode 100644 index 488fb2ca52..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/solid/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertRewriteScenario, - rewriteBenchOptions, - runRewriteLocalizedLoop, -} 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 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 deleted file mode 100644 index 7b86e2ba11..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/solid/speed.rewrite-passthrough.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/rewrites/solid/src/routeTree.gen.ts deleted file mode 100644 index b3b6b24a38..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,94 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as PARouteImport } from './routes/p.$a' -import { Route as PABRouteImport } from './routes/p.$a.$b' - -const PARoute = PARouteImport.update({ - id: '/p/$a', - path: '/p/$a', - getParentRoute: () => rootRouteImport, -} as any) -const PABRoute = PABRouteImport.update({ - id: '/$b', - path: '/$b', - getParentRoute: () => PARoute, -} as any) - -export interface FileRoutesByFullPath { - '/p/$a': typeof PARouteWithChildren - '/p/$a/$b': typeof PABRoute -} -export interface FileRoutesByTo { - '/p/$a': typeof PARouteWithChildren - '/p/$a/$b': typeof PABRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/p/$a': typeof PARouteWithChildren - '/p/$a/$b': typeof PABRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/p/$a' | '/p/$a/$b' - fileRoutesByTo: FileRoutesByTo - to: '/p/$a' | '/p/$a/$b' - id: '__root__' | '/p/$a' | '/p/$a/$b' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - PARoute: typeof PARouteWithChildren -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/p/$a': { - id: '/p/$a' - path: '/p/$a' - fullPath: '/p/$a' - preLoaderRoute: typeof PARouteImport - parentRoute: typeof rootRouteImport - } - '/p/$a/$b': { - id: '/p/$a/$b' - path: '/$b' - fullPath: '/p/$a/$b' - preLoaderRoute: typeof PABRouteImport - parentRoute: typeof PARoute - } - } -} - -interface PARouteChildren { - PABRoute: typeof PABRoute -} - -const PARouteChildren: PARouteChildren = { - PABRoute: PABRoute, -} - -const PARouteWithChildren = PARoute._addFileChildren(PARouteChildren) - -const rootRouteChildren: RootRouteChildren = { - PARoute: PARouteWithChildren, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/solid-start' -declare module '@tanstack/solid-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/benchmarks/ssr/scenarios/rewrites/solid/src/router.tsx b/benchmarks/ssr/scenarios/rewrites/solid/src/router.tsx deleted file mode 100644 index 9806e59d0e..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/solid/src/router.tsx +++ /dev/null @@ -1,42 +0,0 @@ -import { createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -const localePrefixRe = /^\/(fr|de|es)(\/.*)$/ - -export function getRouter() { - return createRouter({ - routeTree, - basepath: '/app', - defaultPreload: false, - scrollRestoration: false, - rewrite: { - input: ({ url }) => { - const match = url.pathname.match(localePrefixRe) - - if (match) { - url.pathname = match[2]! - url.searchParams.set('_locale', match[1]!) - return url - } - - return undefined - }, - output: ({ url }) => { - const locale = url.searchParams.get('_locale') - - if (locale) { - url.searchParams.delete('_locale') - url.pathname = `/${locale}${url.pathname}` - } - - return url - }, - }, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/rewrites/solid/src/routes/__root.tsx b/benchmarks/ssr/scenarios/rewrites/solid/src/routes/__root.tsx deleted file mode 100644 index 1a9cd6c423..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/solid/src/routes/__root.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/solid-router' - -export const Route = createRootRoute({ - component: RootComponent, - validateSearch: (s: Record) => ({ - _locale: typeof s._locale === 'string' ? s._locale : undefined, - }), -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/rewrites/solid/src/routes/p.$a.$b.tsx b/benchmarks/ssr/scenarios/rewrites/solid/src/routes/p.$a.$b.tsx deleted file mode 100644 index eacb45a841..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/solid/src/routes/p.$a.$b.tsx +++ /dev/null @@ -1,39 +0,0 @@ -import { Link, createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/p/$a/$b')({ - loader: ({ params }) => ({ - a: params.a, - b: params.b, - nextB: `next-${params.b}`, - }), - component: LeafComponent, -}) - -function LeafComponent() { - const data = Route.useLoaderData() - - return ( -
-

- rewrite-leaf {data().a} {data().b} -

- - leaf-self-link - - - leaf-next-link - - - leaf-parent-link - -
- ) -} diff --git a/benchmarks/ssr/scenarios/rewrites/solid/src/routes/p.$a.tsx b/benchmarks/ssr/scenarios/rewrites/solid/src/routes/p.$a.tsx deleted file mode 100644 index 1845e3ebba..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/solid/src/routes/p.$a.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/p/$a')({ - loader: ({ params }) => ({ - a: params.a, - nextB: `branch-${params.a}`, - }), - component: ParentComponent, -}) - -function ParentComponent() { - const data = Route.useLoaderData() - - return ( -
-

rewrite-parent {data().a}

- - parent-branch-link - - -
- ) -} diff --git a/benchmarks/ssr/scenarios/rewrites/solid/tsconfig.json b/benchmarks/ssr/scenarios/rewrites/solid/tsconfig.json deleted file mode 100644 index 42c3a2160f..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/solid/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "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 deleted file mode 100644 index 963fe7132b..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/solid/vite.config.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - router: { - basepath: '/app', - }, - }), - solid({ ssr: true, hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - execArgv: cpuSimulationExecArgv(), - isolate: true, - name: '@benchmarks/ssr rewrites (solid)', - watch: false, - environment: 'node', - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/rewrites/vue/project.json b/benchmarks/ssr/scenarios/rewrites/vue/project.json deleted file mode 100644 index 10fd6f4f34..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-rewrites-vue", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/rewrites/vue/speed.bench.ts b/benchmarks/ssr/scenarios/rewrites/vue/speed.bench.ts deleted file mode 100644 index 5fd4da9d3e..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/vue/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertRewriteScenario, - rewriteBenchOptions, - runRewriteLocalizedLoop, -} 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 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 deleted file mode 100644 index f3664b5f21..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/vue/speed.rewrite-passthrough.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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/routeTree.gen.ts b/benchmarks/ssr/scenarios/rewrites/vue/src/routeTree.gen.ts deleted file mode 100644 index 4440c1cfda..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,94 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as PARouteImport } from './routes/p.$a' -import { Route as PABRouteImport } from './routes/p.$a.$b' - -const PARoute = PARouteImport.update({ - id: '/p/$a', - path: '/p/$a', - getParentRoute: () => rootRouteImport, -} as any) -const PABRoute = PABRouteImport.update({ - id: '/$b', - path: '/$b', - getParentRoute: () => PARoute, -} as any) - -export interface FileRoutesByFullPath { - '/p/$a': typeof PARouteWithChildren - '/p/$a/$b': typeof PABRoute -} -export interface FileRoutesByTo { - '/p/$a': typeof PARouteWithChildren - '/p/$a/$b': typeof PABRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/p/$a': typeof PARouteWithChildren - '/p/$a/$b': typeof PABRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/p/$a' | '/p/$a/$b' - fileRoutesByTo: FileRoutesByTo - to: '/p/$a' | '/p/$a/$b' - id: '__root__' | '/p/$a' | '/p/$a/$b' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - PARoute: typeof PARouteWithChildren -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/p/$a': { - id: '/p/$a' - path: '/p/$a' - fullPath: '/p/$a' - preLoaderRoute: typeof PARouteImport - parentRoute: typeof rootRouteImport - } - '/p/$a/$b': { - id: '/p/$a/$b' - path: '/$b' - fullPath: '/p/$a/$b' - preLoaderRoute: typeof PABRouteImport - parentRoute: typeof PARoute - } - } -} - -interface PARouteChildren { - PABRoute: typeof PABRoute -} - -const PARouteChildren: PARouteChildren = { - PABRoute: PABRoute, -} - -const PARouteWithChildren = PARoute._addFileChildren(PARouteChildren) - -const rootRouteChildren: RootRouteChildren = { - PARoute: PARouteWithChildren, -} -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/benchmarks/ssr/scenarios/rewrites/vue/src/router.tsx b/benchmarks/ssr/scenarios/rewrites/vue/src/router.tsx deleted file mode 100644 index 3a7389a5be..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/vue/src/router.tsx +++ /dev/null @@ -1,42 +0,0 @@ -import { createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -const localePrefixRe = /^\/(fr|de|es)(\/.*)$/ - -export function getRouter() { - return createRouter({ - routeTree, - basepath: '/app', - defaultPreload: false, - scrollRestoration: false, - rewrite: { - input: ({ url }) => { - const match = url.pathname.match(localePrefixRe) - - if (match) { - url.pathname = match[2]! - url.searchParams.set('_locale', match[1]!) - return url - } - - return undefined - }, - output: ({ url }) => { - const locale = url.searchParams.get('_locale') - - if (locale) { - url.searchParams.delete('_locale') - url.pathname = `/${locale}${url.pathname}` - } - - return url - }, - }, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/rewrites/vue/src/routes/__root.tsx b/benchmarks/ssr/scenarios/rewrites/vue/src/routes/__root.tsx deleted file mode 100644 index ed4cf1300d..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/vue/src/routes/__root.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { - Body, - HeadContent, - Html, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/vue-router' - -export const Route = createRootRoute({ - component: RootComponent, - validateSearch: (s: Record) => ({ - _locale: typeof s._locale === 'string' ? s._locale : undefined, - }), -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} 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 deleted file mode 100644 index 3c9de1806e..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.$b.tsx +++ /dev/null @@ -1,46 +0,0 @@ -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, - b: params.b, - nextB: `next-${params.b}`, - }), - component: LeafComponent, -}) diff --git a/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.tsx b/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.tsx deleted file mode 100644 index 9702ebedd7..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.tsx +++ /dev/null @@ -1,30 +0,0 @@ -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, - nextB: `branch-${params.a}`, - }), - component: ParentComponent, -}) diff --git a/benchmarks/ssr/scenarios/rewrites/vue/tsconfig.json b/benchmarks/ssr/scenarios/rewrites/vue/tsconfig.json deleted file mode 100644 index 08c94853f4..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/vue/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "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 deleted file mode 100644 index 22399ec6b2..0000000000 --- a/benchmarks/ssr/scenarios/rewrites/vue/vite.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - router: { - basepath: '/app', - }, - }), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - 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/project.json b/benchmarks/ssr/scenarios/selective-ssr/react/project.json deleted file mode 100644 index 77858e2246..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-selective-ssr-react", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/selective-ssr/react/speed.bench.ts b/benchmarks/ssr/scenarios/selective-ssr/react/speed.bench.ts deleted file mode 100644 index ba6bd4a61d..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/react/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertSelectiveSanity, - benchOptions, - runSelectiveLoop, - 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 assertSelectiveSanity(handler) - -test('ssr', async ({ bench }) => { - await bench('ssr selective (react)', async () => - runSelectiveLoop(handler), - ).run(benchOptions) -}) diff --git a/benchmarks/ssr/scenarios/selective-ssr/react/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/selective-ssr/react/src/routeTree.gen.ts deleted file mode 100644 index 95395c294e..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/react/src/routeTree.gen.ts +++ /dev/null @@ -1,120 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as MixARouteImport } from './routes/mix.$a' -import { Route as MixABRouteImport } from './routes/mix.$a.$b' -import { Route as MixABCRouteImport } from './routes/mix.$a.$b.$c' - -const MixARoute = MixARouteImport.update({ - id: '/mix/$a', - path: '/mix/$a', - getParentRoute: () => rootRouteImport, -} as any) -const MixABRoute = MixABRouteImport.update({ - id: '/$b', - path: '/$b', - getParentRoute: () => MixARoute, -} as any) -const MixABCRoute = MixABCRouteImport.update({ - id: '/$c', - path: '/$c', - getParentRoute: () => MixABRoute, -} as any) - -export interface FileRoutesByFullPath { - '/mix/$a': typeof MixARouteWithChildren - '/mix/$a/$b': typeof MixABRouteWithChildren - '/mix/$a/$b/$c': typeof MixABCRoute -} -export interface FileRoutesByTo { - '/mix/$a': typeof MixARouteWithChildren - '/mix/$a/$b': typeof MixABRouteWithChildren - '/mix/$a/$b/$c': typeof MixABCRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/mix/$a': typeof MixARouteWithChildren - '/mix/$a/$b': typeof MixABRouteWithChildren - '/mix/$a/$b/$c': typeof MixABCRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/mix/$a' | '/mix/$a/$b' | '/mix/$a/$b/$c' - fileRoutesByTo: FileRoutesByTo - to: '/mix/$a' | '/mix/$a/$b' | '/mix/$a/$b/$c' - id: '__root__' | '/mix/$a' | '/mix/$a/$b' | '/mix/$a/$b/$c' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - MixARoute: typeof MixARouteWithChildren -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/mix/$a': { - id: '/mix/$a' - path: '/mix/$a' - fullPath: '/mix/$a' - preLoaderRoute: typeof MixARouteImport - parentRoute: typeof rootRouteImport - } - '/mix/$a/$b': { - id: '/mix/$a/$b' - path: '/$b' - fullPath: '/mix/$a/$b' - preLoaderRoute: typeof MixABRouteImport - parentRoute: typeof MixARoute - } - '/mix/$a/$b/$c': { - id: '/mix/$a/$b/$c' - path: '/$c' - fullPath: '/mix/$a/$b/$c' - preLoaderRoute: typeof MixABCRouteImport - parentRoute: typeof MixABRoute - } - } -} - -interface MixABRouteChildren { - MixABCRoute: typeof MixABCRoute -} - -const MixABRouteChildren: MixABRouteChildren = { - MixABCRoute: MixABCRoute, -} - -const MixABRouteWithChildren = MixABRoute._addFileChildren(MixABRouteChildren) - -interface MixARouteChildren { - MixABRoute: typeof MixABRouteWithChildren -} - -const MixARouteChildren: MixARouteChildren = { - MixABRoute: MixABRouteWithChildren, -} - -const MixARouteWithChildren = MixARoute._addFileChildren(MixARouteChildren) - -const rootRouteChildren: RootRouteChildren = { - MixARoute: MixARouteWithChildren, -} -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/benchmarks/ssr/scenarios/selective-ssr/react/src/router.tsx b/benchmarks/ssr/scenarios/selective-ssr/react/src/router.tsx deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/selective-ssr/react/src/routes/__root.tsx b/benchmarks/ssr/scenarios/selective-ssr/react/src/routes/__root.tsx deleted file mode 100644 index 1973ca20bb..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/react/src/routes/__root.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: RootComponent, - validateSearch: (s) => s as { q?: string }, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/selective-ssr/react/src/routes/mix.$a.$b.$c.tsx b/benchmarks/ssr/scenarios/selective-ssr/react/src/routes/mix.$a.$b.$c.tsx deleted file mode 100644 index e3df06149d..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/react/src/routes/mix.$a.$b.$c.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { makeLevelData } from '../../../../loaders/shared-data' - -export const Route = createFileRoute('/mix/$a/$b/$c')({ - ssr: false, - loader: async ({ params }) => { - return { - marker: `level-c-loader-${params.c}`, - data: makeLevelData(`level-c-data-${params.c}`, 3), - } - }, - component: LevelCComponent, -}) - -function LevelCComponent() { - const data = Route.useLoaderData() - const params = Route.useParams() - - return ( -
-

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

-

{data.marker}

-
- ) -} diff --git a/benchmarks/ssr/scenarios/selective-ssr/react/src/routes/mix.$a.$b.tsx b/benchmarks/ssr/scenarios/selective-ssr/react/src/routes/mix.$a.$b.tsx deleted file mode 100644 index 3fe26dd70e..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/react/src/routes/mix.$a.$b.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import { makeLevelData } from '../../../../loaders/shared-data' - -export const Route = createFileRoute('/mix/$a/$b')({ - ssr: 'data-only', - loader: async ({ params }) => { - return { - marker: `level-b-loader-${params.b}`, - data: makeLevelData(`level-b-data-${params.b}`, 2), - } - }, - component: LevelBComponent, -}) - -function LevelBComponent() { - const data = Route.useLoaderData() - const params = Route.useParams() - - return ( -
-

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

-

{data.marker}

- -
- ) -} diff --git a/benchmarks/ssr/scenarios/selective-ssr/react/src/routes/mix.$a.tsx b/benchmarks/ssr/scenarios/selective-ssr/react/src/routes/mix.$a.tsx deleted file mode 100644 index a06c9ad1b9..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/react/src/routes/mix.$a.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import { makeLevelData } from '../../../../loaders/shared-data' - -export const Route = createFileRoute('/mix/$a')({ - ssr: true, - loader: async ({ params }) => { - return makeLevelData(`level-a-loader-${params.a}`, 1) - }, - component: LevelAComponent, -}) - -function LevelAComponent() { - const data = Route.useLoaderData() - const params = Route.useParams() - - return ( -
-

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

-

{data.items[0]?.name}

- -
- ) -} diff --git a/benchmarks/ssr/scenarios/selective-ssr/react/tsconfig.json b/benchmarks/ssr/scenarios/selective-ssr/react/tsconfig.json deleted file mode 100644 index 399fe944f9..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/react/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../../loaders/shared-data.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/selective-ssr/react/vite.config.ts b/benchmarks/ssr/scenarios/selective-ssr/react/vite.config.ts deleted file mode 100644 index 70c67cff81..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/react/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - 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/shared-bench.ts b/benchmarks/ssr/scenarios/selective-ssr/shared-bench.ts deleted file mode 100644 index 5b2530ccab..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/shared-bench.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { makeLevelData } from '../loaders/shared-data' -import { randomSegment, runRequestLoop } from '../../bench-utils' -import type { StartRequestHandler } from '../../bench-utils' - -export type { StartRequestHandler } - -const benchmarkSeed = 0xdecafbad -const selectiveLoopTotalRequests = 32 - -const requestInit = { - method: 'GET', - headers: { - accept: 'text/html', - }, -} satisfies RequestInit - -function buildSelectiveRequest(random: () => number) { - const a = randomSegment(random) - const b = randomSegment(random) - const c = randomSegment(random) - - return new Request(`http://localhost/mix/${a}/${b}/${c}`, requestInit) -} - -export async function assertSelectiveSanity(handler: StartRequestHandler) { - const a = 'a-sanity' - const b = 'b-sanity' - const c = 'c-sanity' - const response = await handler.fetch( - new Request(`http://localhost/mix/${a}/${b}/${c}`, requestInit), - ) - const body = await response.text() - const levelARenderedMarker = `level-a-rendered-${a}` - const levelALoaderMarker = makeLevelData(`level-a-loader-${a}`, 1).items[0] - ?.name - const dataOnlyRenderedMarker = `data-only-rendered-${b}` - const levelBLoaderMarker = `level-b-loader-${b}` - const csrRenderedMarker = `csr-rendered-${c}` - const levelCLoaderMarker = `level-c-loader-${c}` - - if (response.status !== 200) { - throw new Error( - `Expected setup request status 200, received ${response.status}`, - ) - } - - if (!body.includes(levelARenderedMarker)) { - throw new Error( - 'Expected setup response to include level-a rendered content', - ) - } - - if (!levelALoaderMarker || !body.includes(levelALoaderMarker)) { - throw new Error('Expected setup response to include level-a loader content') - } - - if (body.includes(dataOnlyRenderedMarker)) { - throw new Error( - 'Expected data-only route component to be absent from SSR HTML', - ) - } - - const hydrationIndex = body.indexOf('$_TSR') - - if (hydrationIndex === -1) { - throw new Error('Expected setup response to include the dehydration marker') - } - - if (!body.slice(hydrationIndex).includes(levelBLoaderMarker)) { - throw new Error('Expected level-b loader marker in the dehydration payload') - } - - if (body.includes(csrRenderedMarker)) { - throw new Error('Expected csr route component to be absent from SSR HTML') - } - - if (body.includes(levelCLoaderMarker)) { - throw new Error('Expected level-c loader marker to be absent from SSR HTML') - } -} - -export const benchOptions = { - warmupIterations: 100, - time: 10_000, - throws: true, -} - -export function runSelectiveLoop(handler: StartRequestHandler) { - return runRequestLoop(handler, { - seed: benchmarkSeed, - concurrency: 16, - totalRequests: selectiveLoopTotalRequests, - buildRequest: buildSelectiveRequest, - }) -} diff --git a/benchmarks/ssr/scenarios/selective-ssr/solid/project.json b/benchmarks/ssr/scenarios/selective-ssr/solid/project.json deleted file mode 100644 index 358cc97323..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/solid/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-selective-ssr-solid", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/selective-ssr/solid/speed.bench.ts b/benchmarks/ssr/scenarios/selective-ssr/solid/speed.bench.ts deleted file mode 100644 index 76265397ab..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/solid/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertSelectiveSanity, - benchOptions, - runSelectiveLoop, - 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 assertSelectiveSanity(handler) - -test('ssr', async ({ bench }) => { - await bench('ssr selective (solid)', async () => - runSelectiveLoop(handler), - ).run(benchOptions) -}) diff --git a/benchmarks/ssr/scenarios/selective-ssr/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/selective-ssr/solid/src/routeTree.gen.ts deleted file mode 100644 index 22560063f6..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,120 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as MixARouteImport } from './routes/mix.$a' -import { Route as MixABRouteImport } from './routes/mix.$a.$b' -import { Route as MixABCRouteImport } from './routes/mix.$a.$b.$c' - -const MixARoute = MixARouteImport.update({ - id: '/mix/$a', - path: '/mix/$a', - getParentRoute: () => rootRouteImport, -} as any) -const MixABRoute = MixABRouteImport.update({ - id: '/$b', - path: '/$b', - getParentRoute: () => MixARoute, -} as any) -const MixABCRoute = MixABCRouteImport.update({ - id: '/$c', - path: '/$c', - getParentRoute: () => MixABRoute, -} as any) - -export interface FileRoutesByFullPath { - '/mix/$a': typeof MixARouteWithChildren - '/mix/$a/$b': typeof MixABRouteWithChildren - '/mix/$a/$b/$c': typeof MixABCRoute -} -export interface FileRoutesByTo { - '/mix/$a': typeof MixARouteWithChildren - '/mix/$a/$b': typeof MixABRouteWithChildren - '/mix/$a/$b/$c': typeof MixABCRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/mix/$a': typeof MixARouteWithChildren - '/mix/$a/$b': typeof MixABRouteWithChildren - '/mix/$a/$b/$c': typeof MixABCRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/mix/$a' | '/mix/$a/$b' | '/mix/$a/$b/$c' - fileRoutesByTo: FileRoutesByTo - to: '/mix/$a' | '/mix/$a/$b' | '/mix/$a/$b/$c' - id: '__root__' | '/mix/$a' | '/mix/$a/$b' | '/mix/$a/$b/$c' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - MixARoute: typeof MixARouteWithChildren -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/mix/$a': { - id: '/mix/$a' - path: '/mix/$a' - fullPath: '/mix/$a' - preLoaderRoute: typeof MixARouteImport - parentRoute: typeof rootRouteImport - } - '/mix/$a/$b': { - id: '/mix/$a/$b' - path: '/$b' - fullPath: '/mix/$a/$b' - preLoaderRoute: typeof MixABRouteImport - parentRoute: typeof MixARoute - } - '/mix/$a/$b/$c': { - id: '/mix/$a/$b/$c' - path: '/$c' - fullPath: '/mix/$a/$b/$c' - preLoaderRoute: typeof MixABCRouteImport - parentRoute: typeof MixABRoute - } - } -} - -interface MixABRouteChildren { - MixABCRoute: typeof MixABCRoute -} - -const MixABRouteChildren: MixABRouteChildren = { - MixABCRoute: MixABCRoute, -} - -const MixABRouteWithChildren = MixABRoute._addFileChildren(MixABRouteChildren) - -interface MixARouteChildren { - MixABRoute: typeof MixABRouteWithChildren -} - -const MixARouteChildren: MixARouteChildren = { - MixABRoute: MixABRouteWithChildren, -} - -const MixARouteWithChildren = MixARoute._addFileChildren(MixARouteChildren) - -const rootRouteChildren: RootRouteChildren = { - MixARoute: MixARouteWithChildren, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/solid-start' -declare module '@tanstack/solid-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/benchmarks/ssr/scenarios/selective-ssr/solid/src/router.tsx b/benchmarks/ssr/scenarios/selective-ssr/solid/src/router.tsx deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/selective-ssr/solid/src/routes/__root.tsx b/benchmarks/ssr/scenarios/selective-ssr/solid/src/routes/__root.tsx deleted file mode 100644 index 15de858e78..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/solid/src/routes/__root.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/solid-router' - -export const Route = createRootRoute({ - component: RootComponent, - validateSearch: (s) => s as { q?: string }, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/selective-ssr/solid/src/routes/mix.$a.$b.$c.tsx b/benchmarks/ssr/scenarios/selective-ssr/solid/src/routes/mix.$a.$b.$c.tsx deleted file mode 100644 index f6a85bfdc2..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/solid/src/routes/mix.$a.$b.$c.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { makeLevelData } from '../../../../loaders/shared-data' - -export const Route = createFileRoute('/mix/$a/$b/$c')({ - ssr: false, - loader: async ({ params }) => { - return { - marker: `level-c-loader-${params.c}`, - data: makeLevelData(`level-c-data-${params.c}`, 3), - } - }, - component: LevelCComponent, -}) - -function LevelCComponent() { - const data = Route.useLoaderData() - const params = Route.useParams() - - return ( -
-

{`csr-rendered-${params().c}`}

-

{data().marker}

-
- ) -} diff --git a/benchmarks/ssr/scenarios/selective-ssr/solid/src/routes/mix.$a.$b.tsx b/benchmarks/ssr/scenarios/selective-ssr/solid/src/routes/mix.$a.$b.tsx deleted file mode 100644 index f735b1395f..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/solid/src/routes/mix.$a.$b.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' -import { makeLevelData } from '../../../../loaders/shared-data' - -export const Route = createFileRoute('/mix/$a/$b')({ - ssr: 'data-only', - loader: async ({ params }) => { - return { - marker: `level-b-loader-${params.b}`, - data: makeLevelData(`level-b-data-${params.b}`, 2), - } - }, - component: LevelBComponent, -}) - -function LevelBComponent() { - const data = Route.useLoaderData() - const params = Route.useParams() - - return ( -
-

{`data-only-rendered-${params().b}`}

-

{data().marker}

- -
- ) -} diff --git a/benchmarks/ssr/scenarios/selective-ssr/solid/src/routes/mix.$a.tsx b/benchmarks/ssr/scenarios/selective-ssr/solid/src/routes/mix.$a.tsx deleted file mode 100644 index c8c80a7a6d..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/solid/src/routes/mix.$a.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' -import { makeLevelData } from '../../../../loaders/shared-data' - -export const Route = createFileRoute('/mix/$a')({ - ssr: true, - loader: async ({ params }) => { - return makeLevelData(`level-a-loader-${params.a}`, 1) - }, - component: LevelAComponent, -}) - -function LevelAComponent() { - const data = Route.useLoaderData() - const params = Route.useParams() - - return ( -
-

{`level-a-rendered-${params().a}`}

-

{data().items[0]?.name}

- -
- ) -} diff --git a/benchmarks/ssr/scenarios/selective-ssr/solid/tsconfig.json b/benchmarks/ssr/scenarios/selective-ssr/solid/tsconfig.json deleted file mode 100644 index f386c3f996..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/solid/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../../loaders/shared-data.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/selective-ssr/solid/vite.config.ts b/benchmarks/ssr/scenarios/selective-ssr/solid/vite.config.ts deleted file mode 100644 index 2c0042c1ed..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/solid/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - solid({ ssr: true, hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - execArgv: cpuSimulationExecArgv(), - isolate: true, - name: '@benchmarks/ssr selective-ssr (solid)', - watch: false, - environment: 'node', - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/selective-ssr/vue/project.json b/benchmarks/ssr/scenarios/selective-ssr/vue/project.json deleted file mode 100644 index 9ff4d99323..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-selective-ssr-vue", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/selective-ssr/vue/speed.bench.ts b/benchmarks/ssr/scenarios/selective-ssr/vue/speed.bench.ts deleted file mode 100644 index ff60341b27..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertSelectiveSanity, - benchOptions, - runSelectiveLoop, - 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 assertSelectiveSanity(handler) - -test('ssr', async ({ bench }) => { - await bench('ssr selective (vue)', async () => runSelectiveLoop(handler)).run( - benchOptions, - ) -}) diff --git a/benchmarks/ssr/scenarios/selective-ssr/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/selective-ssr/vue/src/routeTree.gen.ts deleted file mode 100644 index b77209b48b..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,120 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as MixARouteImport } from './routes/mix.$a' -import { Route as MixABRouteImport } from './routes/mix.$a.$b' -import { Route as MixABCRouteImport } from './routes/mix.$a.$b.$c' - -const MixARoute = MixARouteImport.update({ - id: '/mix/$a', - path: '/mix/$a', - getParentRoute: () => rootRouteImport, -} as any) -const MixABRoute = MixABRouteImport.update({ - id: '/$b', - path: '/$b', - getParentRoute: () => MixARoute, -} as any) -const MixABCRoute = MixABCRouteImport.update({ - id: '/$c', - path: '/$c', - getParentRoute: () => MixABRoute, -} as any) - -export interface FileRoutesByFullPath { - '/mix/$a': typeof MixARouteWithChildren - '/mix/$a/$b': typeof MixABRouteWithChildren - '/mix/$a/$b/$c': typeof MixABCRoute -} -export interface FileRoutesByTo { - '/mix/$a': typeof MixARouteWithChildren - '/mix/$a/$b': typeof MixABRouteWithChildren - '/mix/$a/$b/$c': typeof MixABCRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/mix/$a': typeof MixARouteWithChildren - '/mix/$a/$b': typeof MixABRouteWithChildren - '/mix/$a/$b/$c': typeof MixABCRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/mix/$a' | '/mix/$a/$b' | '/mix/$a/$b/$c' - fileRoutesByTo: FileRoutesByTo - to: '/mix/$a' | '/mix/$a/$b' | '/mix/$a/$b/$c' - id: '__root__' | '/mix/$a' | '/mix/$a/$b' | '/mix/$a/$b/$c' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - MixARoute: typeof MixARouteWithChildren -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/mix/$a': { - id: '/mix/$a' - path: '/mix/$a' - fullPath: '/mix/$a' - preLoaderRoute: typeof MixARouteImport - parentRoute: typeof rootRouteImport - } - '/mix/$a/$b': { - id: '/mix/$a/$b' - path: '/$b' - fullPath: '/mix/$a/$b' - preLoaderRoute: typeof MixABRouteImport - parentRoute: typeof MixARoute - } - '/mix/$a/$b/$c': { - id: '/mix/$a/$b/$c' - path: '/$c' - fullPath: '/mix/$a/$b/$c' - preLoaderRoute: typeof MixABCRouteImport - parentRoute: typeof MixABRoute - } - } -} - -interface MixABRouteChildren { - MixABCRoute: typeof MixABCRoute -} - -const MixABRouteChildren: MixABRouteChildren = { - MixABCRoute: MixABCRoute, -} - -const MixABRouteWithChildren = MixABRoute._addFileChildren(MixABRouteChildren) - -interface MixARouteChildren { - MixABRoute: typeof MixABRouteWithChildren -} - -const MixARouteChildren: MixARouteChildren = { - MixABRoute: MixABRouteWithChildren, -} - -const MixARouteWithChildren = MixARoute._addFileChildren(MixARouteChildren) - -const rootRouteChildren: RootRouteChildren = { - MixARoute: MixARouteWithChildren, -} -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/benchmarks/ssr/scenarios/selective-ssr/vue/src/router.tsx b/benchmarks/ssr/scenarios/selective-ssr/vue/src/router.tsx deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/__root.tsx b/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/__root.tsx deleted file mode 100644 index 4b03519823..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/__root.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import { - Body, - HeadContent, - Html, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/vue-router' - -export const Route = createRootRoute({ - component: RootComponent, - validateSearch: (s) => s as { q?: string }, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} 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 deleted file mode 100644 index 8ae7d468f1..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.$b.$c.tsx +++ /dev/null @@ -1,28 +0,0 @@ -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 }) => { - return { - marker: `level-c-loader-${params.c}`, - data: makeLevelData(`level-c-data-${params.c}`, 3), - } - }, - component: LevelCComponent, -}) 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 deleted file mode 100644 index c10751489e..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.$b.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 }) => { - return { - marker: `level-b-loader-${params.b}`, - data: makeLevelData(`level-b-data-${params.b}`, 2), - } - }, - component: LevelBComponent, -}) 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 deleted file mode 100644 index c96165c6d6..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.tsx +++ /dev/null @@ -1,26 +0,0 @@ -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 }) => { - return makeLevelData(`level-a-loader-${params.a}`, 1) - }, - component: LevelAComponent, -}) diff --git a/benchmarks/ssr/scenarios/selective-ssr/vue/tsconfig.json b/benchmarks/ssr/scenarios/selective-ssr/vue/tsconfig.json deleted file mode 100644 index 3f2809bd5a..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../../loaders/shared-data.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/selective-ssr/vue/vite.config.ts b/benchmarks/ssr/scenarios/selective-ssr/vue/vite.config.ts deleted file mode 100644 index 09bb36cb0b..0000000000 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - 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/project.json b/benchmarks/ssr/scenarios/serialization/react/project.json deleted file mode 100644 index 652f87cb44..0000000000 --- a/benchmarks/ssr/scenarios/serialization/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-serialization-react", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/serialization/react/speed.bench.ts b/benchmarks/ssr/scenarios/serialization/react/speed.bench.ts deleted file mode 100644 index 8be07d2643..0000000000 --- a/benchmarks/ssr/scenarios/serialization/react/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertSerializationScenario, - runRichSerializationLoop, - 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 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 deleted file mode 100644 index c70fddc6c4..0000000000 --- a/benchmarks/ssr/scenarios/serialization/react/speed.dehydrate-plain-control.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/serialization/react/src/routeTree.gen.ts deleted file mode 100644 index 49bdbd036b..0000000000 --- a/benchmarks/ssr/scenarios/serialization/react/src/routeTree.gen.ts +++ /dev/null @@ -1,87 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as PlainIdRouteImport } from './routes/plain.$id' -import { Route as RichIdRouteImport } from './routes/rich.$id' - -const PlainIdRoute = PlainIdRouteImport.update({ - id: '/plain/$id', - path: '/plain/$id', - getParentRoute: () => rootRouteImport, -} as any) -const RichIdRoute = RichIdRouteImport.update({ - id: '/rich/$id', - path: '/rich/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/plain/$id': typeof PlainIdRoute - '/rich/$id': typeof RichIdRoute -} -export interface FileRoutesByTo { - '/plain/$id': typeof PlainIdRoute - '/rich/$id': typeof RichIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/plain/$id': typeof PlainIdRoute - '/rich/$id': typeof RichIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/plain/$id' | '/rich/$id' - fileRoutesByTo: FileRoutesByTo - to: '/plain/$id' | '/rich/$id' - id: '__root__' | '/plain/$id' | '/rich/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - PlainIdRoute: typeof PlainIdRoute - RichIdRoute: typeof RichIdRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/plain/$id': { - id: '/plain/$id' - path: '/plain/$id' - fullPath: '/plain/$id' - preLoaderRoute: typeof PlainIdRouteImport - parentRoute: typeof rootRouteImport - } - '/rich/$id': { - id: '/rich/$id' - path: '/rich/$id' - fullPath: '/rich/$id' - preLoaderRoute: typeof RichIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - PlainIdRoute: PlainIdRoute, - RichIdRoute: RichIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { startInstance } from './start.tsx' -declare module '@tanstack/react-start' { - interface Register { - ssr: true - router: Awaited> - config: Awaited> - } -} diff --git a/benchmarks/ssr/scenarios/serialization/react/src/router.tsx b/benchmarks/ssr/scenarios/serialization/react/src/router.tsx deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/ssr/scenarios/serialization/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/serialization/react/src/routes/__root.tsx b/benchmarks/ssr/scenarios/serialization/react/src/routes/__root.tsx deleted file mode 100644 index ff1da4c304..0000000000 --- a/benchmarks/ssr/scenarios/serialization/react/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/serialization/react/src/routes/plain.$id.tsx b/benchmarks/ssr/scenarios/serialization/react/src/routes/plain.$id.tsx deleted file mode 100644 index 88a8a0e11f..0000000000 --- a/benchmarks/ssr/scenarios/serialization/react/src/routes/plain.$id.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { makePlainSerializationData } from '../../../shared-data' - -export const Route = createFileRoute('/plain/$id')({ - loader: ({ params }) => makePlainSerializationData(params.id), - component: PlainComponent, -}) - -function PlainComponent() { - const data = Route.useLoaderData() - const firstMapEntry = data.lookup[0]?.[1] - const firstTag = data.tags[0] - - return ( -
-

{data.label}

-

{data.createdAt}

-

{firstMapEntry?.label}

-

{firstTag}

-

{data.count}

-

{data.nested[0]?.id}

-

{data.points[0]?.label}

-

{data.problem.message}

-
- ) -} diff --git a/benchmarks/ssr/scenarios/serialization/react/src/routes/rich.$id.tsx b/benchmarks/ssr/scenarios/serialization/react/src/routes/rich.$id.tsx deleted file mode 100644 index a9bb264c48..0000000000 --- a/benchmarks/ssr/scenarios/serialization/react/src/routes/rich.$id.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { makeRichSerializationData } from '../../../shared-data' - -export const Route = createFileRoute('/rich/$id')({ - loader: ({ params }) => makeRichSerializationData(params.id), - component: RichComponent, -}) - -function RichComponent() { - const data = Route.useLoaderData() - const firstMapEntry = data.lookup.get('k0') - const firstTag = Array.from(data.tags)[0] - - return ( -
-

{data.label}

-

{data.createdAt.toISOString()}

-

{firstMapEntry?.label}

-

{firstTag}

-

{data.count.toString()}

-

{data.nested[0]?.id}

-

{data.points[0]?.label}

-

{data.problem.message}

-
- ) -} diff --git a/benchmarks/ssr/scenarios/serialization/react/src/serialization.ts b/benchmarks/ssr/scenarios/serialization/react/src/serialization.ts deleted file mode 100644 index 0a73c69be1..0000000000 --- a/benchmarks/ssr/scenarios/serialization/react/src/serialization.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { createSerializationAdapter } from '@tanstack/react-router' -import { BenchPoint, benchPointAdapterKey } from '../../shared-data' - -export const benchPointAdapter = createSerializationAdapter({ - key: benchPointAdapterKey, - test: (value): value is BenchPoint => value instanceof BenchPoint, - toSerializable: (point) => ({ x: point.x, y: point.y }), - fromSerializable: (value: { x: number; y: number }) => - new BenchPoint(value.x, value.y), -}) diff --git a/benchmarks/ssr/scenarios/serialization/react/src/start.tsx b/benchmarks/ssr/scenarios/serialization/react/src/start.tsx deleted file mode 100644 index ea4513df4d..0000000000 --- a/benchmarks/ssr/scenarios/serialization/react/src/start.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createStart } from '@tanstack/react-start' -import { benchPointAdapter } from './serialization' - -export const startInstance = createStart(() => { - return { - defaultSsr: true, - serializationAdapters: [benchPointAdapter], - } -}) diff --git a/benchmarks/ssr/scenarios/serialization/react/tsconfig.json b/benchmarks/ssr/scenarios/serialization/react/tsconfig.json deleted file mode 100644 index 59499356d6..0000000000 --- a/benchmarks/ssr/scenarios/serialization/react/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed*.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../shared-bench.ts", - "../shared-data.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/serialization/react/vite.config.ts b/benchmarks/ssr/scenarios/serialization/react/vite.config.ts deleted file mode 100644 index 64568ccb7e..0000000000 --- a/benchmarks/ssr/scenarios/serialization/react/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - execArgv: cpuSimulationExecArgv(), - isolate: true, - name: '@benchmarks/ssr serialization (react)', - watch: false, - environment: 'node', - }, -}) diff --git a/benchmarks/ssr/scenarios/serialization/shared-bench.ts b/benchmarks/ssr/scenarios/serialization/shared-bench.ts deleted file mode 100644 index 25ed478f03..0000000000 --- a/benchmarks/ssr/scenarios/serialization/shared-bench.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { benchPointAdapterKey, richDateIso } from './shared-data' -import { randomSegment, runRequestLoop } from '../../bench-utils' -import type { StartRequestHandler } from '../../bench-utils' - -export type { StartRequestHandler } - -const benchmarkSeed = 0xdecafbad -const richSerializationLoopTotalRequests = 32 -const plainSerializationLoopTotalRequests = 32 - -const requestInit = { - method: 'GET', - headers: { - accept: 'text/html', - }, -} satisfies RequestInit - -function buildSerializationRequest( - route: 'plain' | 'rich', - random: () => number, - index: number, -) { - const suffix = index.toString(36) - const id = `${randomSegment(random)}-${suffix}` - - return new Request(`http://localhost/${route}/${id}`, requestInit) -} - -async function fetchScenarioBody( - handler: StartRequestHandler, - route: 'plain' | 'rich', -) { - const response = await handler.fetch( - new Request(`http://localhost/${route}/sanity`, requestInit), - ) - const body = await response.text() - - if (response.status !== 200) { - throw new Error( - `Expected ${route} sanity request status 200, received ${response.status}: ${body}`, - ) - } - - if (!body.includes('$_TSR')) { - throw new Error(`Expected ${route} response to include dehydration marker`) - } - - return body -} - -function assertIncludes(body: string, marker: string, label: string) { - if (!body.includes(marker)) { - throw new Error(`Expected ${label} response to include ${marker}`) - } -} - -function assertExcludes(body: string, marker: string, label: string) { - if (body.includes(marker)) { - throw new Error(`Expected ${label} response not to include ${marker}`) - } -} - -export async function assertSerializationScenario( - handler: StartRequestHandler, -) { - const richBody = await fetchScenarioBody(handler, 'rich') - const plainBody = await fetchScenarioBody(handler, 'plain') - - assertIncludes(richBody, 'rich-sanity', 'rich') - assertIncludes(richBody, benchPointAdapterKey, 'rich') - assertIncludes(richBody, richDateIso, 'rich') - assertIncludes(richBody, 'new Date', 'rich') - assertIncludes(richBody, 'new Map', 'rich') - assertIncludes(richBody, 'new Error', 'rich') - - assertIncludes(plainBody, 'plain-sanity', 'plain') - assertExcludes(plainBody, benchPointAdapterKey, 'plain') - assertExcludes(plainBody, 'new Date', 'plain') - assertExcludes(plainBody, 'new Map', 'plain') - assertExcludes(plainBody, 'new Error', 'plain') -} - -export const serializationBenchOptions = { - warmupIterations: 100, - time: 10_000, - throws: true, -} - -export function runRichSerializationLoop(handler: StartRequestHandler) { - return runRequestLoop(handler, { - seed: benchmarkSeed, - concurrency: 16, - totalRequests: richSerializationLoopTotalRequests, - buildRequest: (random, index) => - buildSerializationRequest('rich', random, index), - }) -} - -export function runPlainSerializationLoop(handler: StartRequestHandler) { - return runRequestLoop(handler, { - seed: benchmarkSeed, - concurrency: 16, - totalRequests: plainSerializationLoopTotalRequests, - buildRequest: (random, index) => - buildSerializationRequest('plain', random, index), - }) -} diff --git a/benchmarks/ssr/scenarios/serialization/shared-data.ts b/benchmarks/ssr/scenarios/serialization/shared-data.ts deleted file mode 100644 index dc1dc90b1f..0000000000 --- a/benchmarks/ssr/scenarios/serialization/shared-data.ts +++ /dev/null @@ -1,101 +0,0 @@ -export class BenchPoint { - constructor( - public x: number, - public y: number, - ) {} - - get label() { - return `${this.x}:${this.y}` - } -} - -export interface PlainSerializationPayload { - label: string - createdAt: string - lookup: Array<[string, { index: number; label: string }]> - tags: Array - count: string - nested: Array<{ id: string; values: Array; flag: boolean }> - points: Array<{ x: number; y: number; label: string }> - problem: { message: string } -} - -export interface RichSerializationPayload { - label: string - createdAt: Date - lookup: Map - tags: Set - count: bigint - nested: Array<{ id: string; values: Array; flag: boolean }> - points: Array - problem: Error -} - -export const benchPointAdapterKey = '$bench/point' -export const richDateIso = '2024-02-03T04:05:06.000Z' - -function makeNested(id: string) { - return Array.from({ length: 16 }, (_, index) => ({ - id: `${id}-nested-${index}`, - values: [index, index + 1, index + 2], - flag: index % 2 === 0, - })) -} - -function makeLookup( - id: string, -): Array<[string, { index: number; label: string }]> { - return Array.from( - { length: 8 }, - (_, index): [string, { index: number; label: string }] => { - const key = `k${index}` - - return [key, { index, label: `${id}-map-${index}` }] - }, - ) -} - -function makeTags(id: string) { - return Array.from({ length: 8 }, (_, index) => `${id}-tag-${index}`) -} - -function makePlainPoints() { - return Array.from({ length: 4 }, (_, index) => { - const point = new BenchPoint(index * 10, index * 10 + 5) - - return { x: point.x, y: point.y, label: point.label } - }) -} - -export function makeRichSerializationData( - id: string, -): RichSerializationPayload { - return { - label: `rich-${id}`, - createdAt: new Date(richDateIso), - lookup: new Map(makeLookup(id)), - tags: new Set(makeTags(id)), - count: 9_007_199_254_740_993n, - nested: makeNested(id), - points: Array.from( - { length: 4 }, - (_, index) => new BenchPoint(index * 10, index * 10 + 5), - ), - problem: new Error(`rich-problem-${id}`), - } -} - -export function makePlainSerializationData( - id: string, -): PlainSerializationPayload { - return { - label: `plain-${id}`, - createdAt: richDateIso, - lookup: makeLookup(id), - tags: makeTags(id), - count: '9007199254740993', - nested: makeNested(id), - points: makePlainPoints(), - problem: { message: `rich-problem-${id}` }, - } -} diff --git a/benchmarks/ssr/scenarios/serialization/solid/project.json b/benchmarks/ssr/scenarios/serialization/solid/project.json deleted file mode 100644 index 80a4b146ac..0000000000 --- a/benchmarks/ssr/scenarios/serialization/solid/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-serialization-solid", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/serialization/solid/speed.bench.ts b/benchmarks/ssr/scenarios/serialization/solid/speed.bench.ts deleted file mode 100644 index 70bda8c7af..0000000000 --- a/benchmarks/ssr/scenarios/serialization/solid/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertSerializationScenario, - runRichSerializationLoop, - 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 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 deleted file mode 100644 index d7ccb16f6f..0000000000 --- a/benchmarks/ssr/scenarios/serialization/solid/speed.dehydrate-plain-control.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index b9e25f918e..0000000000 --- a/benchmarks/ssr/scenarios/serialization/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,87 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as PlainIdRouteImport } from './routes/plain.$id' -import { Route as RichIdRouteImport } from './routes/rich.$id' - -const PlainIdRoute = PlainIdRouteImport.update({ - id: '/plain/$id', - path: '/plain/$id', - getParentRoute: () => rootRouteImport, -} as any) -const RichIdRoute = RichIdRouteImport.update({ - id: '/rich/$id', - path: '/rich/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/plain/$id': typeof PlainIdRoute - '/rich/$id': typeof RichIdRoute -} -export interface FileRoutesByTo { - '/plain/$id': typeof PlainIdRoute - '/rich/$id': typeof RichIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/plain/$id': typeof PlainIdRoute - '/rich/$id': typeof RichIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/plain/$id' | '/rich/$id' - fileRoutesByTo: FileRoutesByTo - to: '/plain/$id' | '/rich/$id' - id: '__root__' | '/plain/$id' | '/rich/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - PlainIdRoute: typeof PlainIdRoute - RichIdRoute: typeof RichIdRoute -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/plain/$id': { - id: '/plain/$id' - path: '/plain/$id' - fullPath: '/plain/$id' - preLoaderRoute: typeof PlainIdRouteImport - parentRoute: typeof rootRouteImport - } - '/rich/$id': { - id: '/rich/$id' - path: '/rich/$id' - fullPath: '/rich/$id' - preLoaderRoute: typeof RichIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - PlainIdRoute: PlainIdRoute, - RichIdRoute: RichIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { startInstance } from './start.tsx' -declare module '@tanstack/solid-start' { - interface Register { - ssr: true - router: Awaited> - config: Awaited> - } -} diff --git a/benchmarks/ssr/scenarios/serialization/solid/src/router.tsx b/benchmarks/ssr/scenarios/serialization/solid/src/router.tsx deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/ssr/scenarios/serialization/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/serialization/solid/src/routes/__root.tsx b/benchmarks/ssr/scenarios/serialization/solid/src/routes/__root.tsx deleted file mode 100644 index e59de72236..0000000000 --- a/benchmarks/ssr/scenarios/serialization/solid/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/solid-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/serialization/solid/src/routes/plain.$id.tsx b/benchmarks/ssr/scenarios/serialization/solid/src/routes/plain.$id.tsx deleted file mode 100644 index c16f73dc3f..0000000000 --- a/benchmarks/ssr/scenarios/serialization/solid/src/routes/plain.$id.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { makePlainSerializationData } from '../../../shared-data' - -export const Route = createFileRoute('/plain/$id')({ - loader: ({ params }) => makePlainSerializationData(params.id), - component: PlainComponent, -}) - -function PlainComponent() { - const data = Route.useLoaderData() - const firstMapEntry = () => data().lookup[0]?.[1] - const firstTag = () => data().tags[0] - - return ( -
-

{data().label}

-

{data().createdAt}

-

{firstMapEntry()?.label}

-

{firstTag()}

-

{data().count}

-

{data().nested[0]?.id}

-

{data().points[0]?.label}

-

{data().problem.message}

-
- ) -} diff --git a/benchmarks/ssr/scenarios/serialization/solid/src/routes/rich.$id.tsx b/benchmarks/ssr/scenarios/serialization/solid/src/routes/rich.$id.tsx deleted file mode 100644 index e08b1e4834..0000000000 --- a/benchmarks/ssr/scenarios/serialization/solid/src/routes/rich.$id.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { makeRichSerializationData } from '../../../shared-data' - -export const Route = createFileRoute('/rich/$id')({ - loader: ({ params }) => makeRichSerializationData(params.id), - component: RichComponent, -}) - -function RichComponent() { - const data = Route.useLoaderData() - const firstMapEntry = () => data().lookup.get('k0') - const firstTag = () => Array.from(data().tags)[0] - - return ( -
-

{data().label}

-

{data().createdAt.toISOString()}

-

{firstMapEntry()?.label}

-

{firstTag()}

-

{data().count.toString()}

-

{data().nested[0]?.id}

-

{data().points[0]?.label}

-

{data().problem.message}

-
- ) -} diff --git a/benchmarks/ssr/scenarios/serialization/solid/src/serialization.ts b/benchmarks/ssr/scenarios/serialization/solid/src/serialization.ts deleted file mode 100644 index ae84f12c9f..0000000000 --- a/benchmarks/ssr/scenarios/serialization/solid/src/serialization.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { createSerializationAdapter } from '@tanstack/solid-router' -import { BenchPoint, benchPointAdapterKey } from '../../shared-data' - -export const benchPointAdapter = createSerializationAdapter({ - key: benchPointAdapterKey, - test: (value): value is BenchPoint => value instanceof BenchPoint, - toSerializable: (point) => ({ x: point.x, y: point.y }), - fromSerializable: (value: { x: number; y: number }) => - new BenchPoint(value.x, value.y), -}) diff --git a/benchmarks/ssr/scenarios/serialization/solid/src/start.tsx b/benchmarks/ssr/scenarios/serialization/solid/src/start.tsx deleted file mode 100644 index a539f2b168..0000000000 --- a/benchmarks/ssr/scenarios/serialization/solid/src/start.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createStart } from '@tanstack/solid-start' -import { benchPointAdapter } from './serialization' - -export const startInstance = createStart(() => { - return { - defaultSsr: true, - serializationAdapters: [benchPointAdapter], - } -}) diff --git a/benchmarks/ssr/scenarios/serialization/solid/tsconfig.json b/benchmarks/ssr/scenarios/serialization/solid/tsconfig.json deleted file mode 100644 index 3ea91b977f..0000000000 --- a/benchmarks/ssr/scenarios/serialization/solid/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed*.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../shared-bench.ts", - "../shared-data.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/serialization/solid/vite.config.ts b/benchmarks/ssr/scenarios/serialization/solid/vite.config.ts deleted file mode 100644 index db81e2ab74..0000000000 --- a/benchmarks/ssr/scenarios/serialization/solid/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - solid({ ssr: true, hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - execArgv: cpuSimulationExecArgv(), - isolate: true, - name: '@benchmarks/ssr serialization (solid)', - watch: false, - environment: 'node', - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/serialization/vue/project.json b/benchmarks/ssr/scenarios/serialization/vue/project.json deleted file mode 100644 index 728b5c15cc..0000000000 --- a/benchmarks/ssr/scenarios/serialization/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-serialization-vue", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/serialization/vue/speed.bench.ts b/benchmarks/ssr/scenarios/serialization/vue/speed.bench.ts deleted file mode 100644 index 7f733dd601..0000000000 --- a/benchmarks/ssr/scenarios/serialization/vue/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertSerializationScenario, - runRichSerializationLoop, - 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 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 deleted file mode 100644 index 8efdeb6c79..0000000000 --- a/benchmarks/ssr/scenarios/serialization/vue/speed.dehydrate-plain-control.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index cd7b0b449b..0000000000 --- a/benchmarks/ssr/scenarios/serialization/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,87 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as PlainIdRouteImport } from './routes/plain.$id' -import { Route as RichIdRouteImport } from './routes/rich.$id' - -const PlainIdRoute = PlainIdRouteImport.update({ - id: '/plain/$id', - path: '/plain/$id', - getParentRoute: () => rootRouteImport, -} as any) -const RichIdRoute = RichIdRouteImport.update({ - id: '/rich/$id', - path: '/rich/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/plain/$id': typeof PlainIdRoute - '/rich/$id': typeof RichIdRoute -} -export interface FileRoutesByTo { - '/plain/$id': typeof PlainIdRoute - '/rich/$id': typeof RichIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/plain/$id': typeof PlainIdRoute - '/rich/$id': typeof RichIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/plain/$id' | '/rich/$id' - fileRoutesByTo: FileRoutesByTo - to: '/plain/$id' | '/rich/$id' - id: '__root__' | '/plain/$id' | '/rich/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - PlainIdRoute: typeof PlainIdRoute - RichIdRoute: typeof RichIdRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/plain/$id': { - id: '/plain/$id' - path: '/plain/$id' - fullPath: '/plain/$id' - preLoaderRoute: typeof PlainIdRouteImport - parentRoute: typeof rootRouteImport - } - '/rich/$id': { - id: '/rich/$id' - path: '/rich/$id' - fullPath: '/rich/$id' - preLoaderRoute: typeof RichIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - PlainIdRoute: PlainIdRoute, - RichIdRoute: RichIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { startInstance } from './start.tsx' -declare module '@tanstack/vue-start' { - interface Register { - ssr: true - router: Awaited> - config: Awaited> - } -} diff --git a/benchmarks/ssr/scenarios/serialization/vue/src/router.tsx b/benchmarks/ssr/scenarios/serialization/vue/src/router.tsx deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/ssr/scenarios/serialization/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/serialization/vue/src/routes/__root.tsx b/benchmarks/ssr/scenarios/serialization/vue/src/routes/__root.tsx deleted file mode 100644 index 49422aac38..0000000000 --- a/benchmarks/ssr/scenarios/serialization/vue/src/routes/__root.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { - Body, - HeadContent, - Html, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/vue-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/serialization/vue/src/routes/plain.$id.tsx b/benchmarks/ssr/scenarios/serialization/vue/src/routes/plain.$id.tsx deleted file mode 100644 index 47fdeb971f..0000000000 --- a/benchmarks/ssr/scenarios/serialization/vue/src/routes/plain.$id.tsx +++ /dev/null @@ -1,27 +0,0 @@ -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, -}) diff --git a/benchmarks/ssr/scenarios/serialization/vue/src/routes/rich.$id.tsx b/benchmarks/ssr/scenarios/serialization/vue/src/routes/rich.$id.tsx deleted file mode 100644 index 1ee86cefd3..0000000000 --- a/benchmarks/ssr/scenarios/serialization/vue/src/routes/rich.$id.tsx +++ /dev/null @@ -1,27 +0,0 @@ -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, -}) diff --git a/benchmarks/ssr/scenarios/serialization/vue/src/serialization.ts b/benchmarks/ssr/scenarios/serialization/vue/src/serialization.ts deleted file mode 100644 index f8b2d8cb43..0000000000 --- a/benchmarks/ssr/scenarios/serialization/vue/src/serialization.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { createSerializationAdapter } from '@tanstack/vue-router' -import { BenchPoint, benchPointAdapterKey } from '../../shared-data' - -export const benchPointAdapter = createSerializationAdapter({ - key: benchPointAdapterKey, - test: (value): value is BenchPoint => value instanceof BenchPoint, - toSerializable: (point) => ({ x: point.x, y: point.y }), - fromSerializable: (value: { x: number; y: number }) => - new BenchPoint(value.x, value.y), -}) diff --git a/benchmarks/ssr/scenarios/serialization/vue/src/start.tsx b/benchmarks/ssr/scenarios/serialization/vue/src/start.tsx deleted file mode 100644 index ee27feb084..0000000000 --- a/benchmarks/ssr/scenarios/serialization/vue/src/start.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createStart } from '@tanstack/vue-start' -import { benchPointAdapter } from './serialization' - -export const startInstance = createStart(() => { - return { - defaultSsr: true, - serializationAdapters: [benchPointAdapter], - } -}) diff --git a/benchmarks/ssr/scenarios/serialization/vue/tsconfig.json b/benchmarks/ssr/scenarios/serialization/vue/tsconfig.json deleted file mode 100644 index 5d8c7b5b62..0000000000 --- a/benchmarks/ssr/scenarios/serialization/vue/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed*.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../shared-bench.ts", - "../shared-data.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/serialization/vue/vite.config.ts b/benchmarks/ssr/scenarios/serialization/vue/vite.config.ts deleted file mode 100644 index b89537fa18..0000000000 --- a/benchmarks/ssr/scenarios/serialization/vue/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - 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/bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/bench.ts deleted file mode 100644 index 4274c724ca..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/bench.ts +++ /dev/null @@ -1,556 +0,0 @@ -import { toJSONAsync } from 'seroval' -import { - createDeterministicRandom, - randomSegment, - runRequestLoop, -} from '../../bench-utils' -import type { StartRequestHandler } from '../../bench-utils' - -export type { StartRequestHandler } - -type FnUrls = { - form: string - raw: string - stream: string -} - -type MultipartPayloadSpec = { - alpha: string - beta: string - gamma: string - fileName: string - fileContents: string -} - -type MultipartPayload = MultipartPayloadSpec & { - body: ArrayBuffer - contentType: string -} - -type QueryPayload = { - query: string - expectedBody: string -} - -type FrameStats = { - jsonFrames: number - chunkFrames: number - endFrames: number - errorFrames: number - chunkBytes: number -} - -export type ServerFnTransportBenchContext = { - urls: FnUrls - multipartPayloads: Array - rawPayloads: Array - streamPayloads: Array - rawExpectedBodiesByUrl: Map -} - -const benchmarkSeed = 0xdecafbad -const origin = 'http://localhost' -const tssContentTypeFramed = 'application/x-tss-framed' -const xTssSerialized = 'x-tss-serialized' -const xTssRawResponse = 'x-tss-raw' -const acceptHeader = `${tssContentTypeFramed}, application/x-ndjson, application/json` -const frameHeaderSize = 9 -const frameTypeJson = 0 -const frameTypeChunk = 1 -const frameTypeEnd = 2 -const frameTypeError = 3 -const streamChunkCount = 8 -const streamChunkSize = 1024 -const multipartFileSize = 1024 -const commonHeaders = { - 'x-tsr-serverFn': 'true', - 'sec-fetch-site': 'same-origin', - accept: acceptHeader, -} satisfies HeadersInit -const serverFnMultipartLoopTotalRequests = 128 -const serverFnRawResponseLoopTotalRequests = 176 -const serverFnRawStreamLoopTotalRequests = 112 - -export const serverFnTransportBenchOptions = { - warmupIterations: 100, - time: 10_000, - throws: true, -} as const - -function makeFixedSizeString(seed: string, size: number) { - let value = '' - - while (value.length < size) { - value += `${seed}:${value.length.toString(36)};` - } - - return value.slice(0, size) -} - -function createMultipartPayloadSpecs() { - const random = createDeterministicRandom(benchmarkSeed) - - return Array.from({ length: 10 }, (_, index): MultipartPayloadSpec => { - const alpha = `alpha-${index}-${randomSegment(random)}` - const beta = `beta-${index}-${randomSegment(random)}` - const gamma = `gamma-${index}-${randomSegment(random)}` - - return { - alpha, - beta, - gamma, - fileName: `bench-${index}.txt`, - fileContents: makeFixedSizeString( - `${alpha}:${beta}:${gamma}`, - multipartFileSize, - ), - } - }) -} - -async function createMultipartPayload( - spec: MultipartPayloadSpec, -): Promise { - const formData = new FormData() - formData.set('alpha', spec.alpha) - formData.set('beta', spec.beta) - formData.set('gamma', spec.gamma) - formData.set( - 'upload', - new File([spec.fileContents], spec.fileName, { type: 'text/plain' }), - ) - - const request = new Request(`${origin}/__multipart-encode`, { - method: 'POST', - body: formData, - }) - const contentType = request.headers.get('content-type') - - if (!contentType?.includes('multipart/form-data')) { - throw new Error(`Expected multipart content type, received ${contentType}`) - } - - return { - ...spec, - body: await request.arrayBuffer(), - contentType, - } -} - -async function createMultipartPayloads() { - return await Promise.all( - createMultipartPayloadSpecs().map((spec) => createMultipartPayload(spec)), - ) -} - -function createTransportInputs(prefix: string) { - const random = createDeterministicRandom(benchmarkSeed ^ prefix.length) - - return Array.from( - { length: 10 }, - (_, index) => - `${prefix}-${index}-${randomSegment(random)}-${randomSegment(random)}`, - ) -} - -async function createQueryPayloads( - inputs: Array, - expectedBody: (input: string) => string, -) { - return await Promise.all( - inputs.map(async (input): Promise => { - const body = JSON.stringify(await toJSONAsync({ data: input })) - const query = `?${new URLSearchParams({ payload: body })}` - - return { - query, - expectedBody: expectedBody(input), - } - }), - ) -} - -async function discoverUrls(handler: StartRequestHandler) { - const response = await handler.fetch(new Request(`${origin}/api/fn-urls`)) - - if (response.status === 404) { - throw new Error('URL discovery route returned 404 for /api/fn-urls') - } - - if (response.status !== 200) { - throw new Error( - `URL discovery failed with status ${response.status}: ${await response.text()}`, - ) - } - - const urls = (await response.json()) as Partial - - if ( - typeof urls.form !== 'string' || - typeof urls.raw !== 'string' || - typeof urls.stream !== 'string' - ) { - throw new Error( - `URL discovery returned invalid payload: ${JSON.stringify(urls)}`, - ) - } - - return { form: urls.form, raw: urls.raw, stream: urls.stream } -} - -function buildMultipartRequest( - urls: FnUrls, - payloads: Array, - index: number, -) { - const payload = payloads[index % payloads.length]! - - return new Request(`${origin}${urls.form}`, { - method: 'POST', - headers: { - ...commonHeaders, - 'content-type': payload.contentType, - }, - body: payload.body, - }) -} - -function buildRawResponseRequest( - urls: FnUrls, - payloads: Array, - index: number, -) { - const payload = payloads[index % payloads.length]! - - return new Request(`${origin}${urls.raw}${payload.query}`, { - method: 'GET', - headers: commonHeaders, - }) -} - -function buildRawStreamRequest( - urls: FnUrls, - payloads: Array, - index: number, -) { - const payload = payloads[index % payloads.length]! - - return new Request(`${origin}${urls.stream}${payload.query}`, { - method: 'GET', - headers: commonHeaders, - }) -} - -async function assertSerializedResponse({ - response, - label, -}: { - response: Response - label: string -}) { - const text = await response.text() - - if (response.status === 403) { - throw new Error( - `${label} sanity check failed with 403. Check CSRF headers.`, - ) - } - - if (response.status === 404) { - throw new Error( - `${label} sanity check failed with 404. The discovered server function URL is stale.`, - ) - } - - if (response.status !== 200) { - throw new Error( - `${label} sanity check failed with status ${response.status}: ${text}`, - ) - } - - if (!response.headers.get(xTssSerialized)) { - throw new Error(`${label} sanity check missing ${xTssSerialized} header`) - } - - return text -} - -function assertMultipartBody(text: string, payload: MultipartPayload) { - const expectedMarkers = [ - payload.alpha, - payload.beta, - payload.gamma, - payload.fileName, - 'fileSize', - multipartFileSize.toString(), - ] - - for (const marker of expectedMarkers) { - if (!text.includes(marker)) { - throw new Error( - `Multipart sanity check missing marker ${marker}: ${text}`, - ) - } - } -} - -async function assertRawResponse(response: Response, expectedBody: string) { - const text = await response.text() - - if (response.status !== 200) { - throw new Error( - `raw-response sanity check failed with status ${response.status}: ${text}`, - ) - } - - if (response.headers.get(xTssRawResponse) !== 'true') { - throw new Error( - `raw-response sanity check missing ${xTssRawResponse} header`, - ) - } - - if (text !== expectedBody) { - throw new Error( - `raw-response sanity check expected ${expectedBody}, received ${text}`, - ) - } -} - -function readUint32(bytes: Uint8Array, offset: number) { - return ( - (((bytes[offset] ?? 0) << 24) | - ((bytes[offset + 1] ?? 0) << 16) | - ((bytes[offset + 2] ?? 0) << 8) | - (bytes[offset + 3] ?? 0)) >>> - 0 - ) -} - -function decodeFrameStats(buffer: ArrayBuffer): FrameStats { - const bytes = new Uint8Array(buffer) - let offset = 0 - const stats: FrameStats = { - jsonFrames: 0, - chunkFrames: 0, - endFrames: 0, - errorFrames: 0, - chunkBytes: 0, - } - - while (offset < bytes.length) { - if (offset + frameHeaderSize > bytes.length) { - throw new Error(`Incomplete frame header at byte ${offset}`) - } - - const type = bytes[offset] - const length = readUint32(bytes, offset + 5) - const payloadStart = offset + frameHeaderSize - const payloadEnd = payloadStart + length - - if (payloadEnd > bytes.length) { - throw new Error(`Incomplete frame payload at byte ${offset}`) - } - - if (type === frameTypeJson) { - stats.jsonFrames++ - } else if (type === frameTypeChunk) { - stats.chunkFrames++ - stats.chunkBytes += length - } else if (type === frameTypeEnd) { - stats.endFrames++ - } else if (type === frameTypeError) { - stats.errorFrames++ - } else { - throw new Error(`Unknown frame type ${type} at byte ${offset}`) - } - - offset = payloadEnd - } - - return stats -} - -async function assertRawStream(response: Response) { - if (response.status !== 200) { - throw new Error( - `raw-stream sanity check failed with status ${response.status}: ${await response.text()}`, - ) - } - - const contentType = response.headers.get('content-type') - if (!contentType?.includes(tssContentTypeFramed)) { - throw new Error( - `raw-stream sanity check expected framed content type, received ${contentType}`, - ) - } - - if (!response.headers.get(xTssSerialized)) { - throw new Error(`raw-stream sanity check missing ${xTssSerialized} header`) - } - - const stats = decodeFrameStats(await response.arrayBuffer()) - const expectedChunkBytes = streamChunkCount * streamChunkSize - - if (stats.jsonFrames < 1) { - throw new Error('raw-stream sanity check expected at least one JSON frame') - } - - if (stats.chunkFrames !== streamChunkCount) { - throw new Error( - `raw-stream sanity check expected ${streamChunkCount} chunk frames, received ${stats.chunkFrames}`, - ) - } - - if (stats.endFrames !== 1) { - throw new Error( - `raw-stream sanity check expected one END frame, received ${stats.endFrames}`, - ) - } - - if (stats.errorFrames !== 0) { - throw new Error( - `raw-stream sanity check received ${stats.errorFrames} ERROR frames`, - ) - } - - if (stats.chunkBytes !== expectedChunkBytes) { - throw new Error( - `raw-stream sanity check expected ${expectedChunkBytes} chunk bytes, received ${stats.chunkBytes}`, - ) - } -} - -function validateStatus(response: Response, request: Request) { - if (response.status !== 200) { - throw new Error( - `Request failed with non-200 status ${response.status} (${request.url})`, - ) - } -} - -function validateSerializedResponse(response: Response, request: Request) { - validateStatus(response, request) - - if (!response.headers.get(xTssSerialized)) { - throw new Error(`Request missing ${xTssSerialized} header (${request.url})`) - } -} - -function validateRawResponse(response: Response, request: Request) { - validateStatus(response, request) - - if (response.headers.get(xTssRawResponse) !== 'true') { - throw new Error( - `Request missing ${xTssRawResponse} header (${request.url})`, - ) - } -} - -function validateRawStreamResponse(response: Response, request: Request) { - validateSerializedResponse(response, request) - - const contentType = response.headers.get('content-type') - if (!contentType?.includes(tssContentTypeFramed)) { - throw new Error( - `Request missing framed content type (${request.url}): ${contentType}`, - ) - } -} - -export async function setupServerFnTransportBench( - handler: StartRequestHandler, -) { - const urls = await discoverUrls(handler) - const multipartPayloads = await createMultipartPayloads() - const rawPayloads = await createQueryPayloads( - createTransportInputs('raw'), - (input) => `raw-${input}`, - ) - const streamPayloads = await createQueryPayloads( - createTransportInputs('stream'), - (input) => `stream-${input}`, - ) - const rawExpectedBodiesByUrl = new Map( - rawPayloads.map((payload) => [ - `${origin}${urls.raw}${payload.query}`, - payload.expectedBody, - ]), - ) - - return { - urls, - multipartPayloads, - rawPayloads, - streamPayloads, - rawExpectedBodiesByUrl, - } -} - -export async function assertServerFnTransportScenario( - handler: StartRequestHandler, - context: ServerFnTransportBenchContext, -) { - const multipartPayload = context.multipartPayloads[0]! - const multipartText = await assertSerializedResponse({ - response: await handler.fetch( - buildMultipartRequest(context.urls, context.multipartPayloads, 0), - ), - label: 'multipart', - }) - assertMultipartBody(multipartText, multipartPayload) - - await assertRawResponse( - await handler.fetch( - buildRawResponseRequest(context.urls, context.rawPayloads, 0), - ), - context.rawPayloads[0]!.expectedBody, - ) - - await assertRawStream( - await handler.fetch( - buildRawStreamRequest(context.urls, context.streamPayloads, 0), - ), - ) -} - -export function runServerFnMultipartRequestLoop( - handler: StartRequestHandler, - context: ServerFnTransportBenchContext, -) { - return runRequestLoop(handler, { - seed: benchmarkSeed, - concurrency: 16, - totalRequests: serverFnMultipartLoopTotalRequests, - buildRequest: (_random, index) => - buildMultipartRequest(context.urls, context.multipartPayloads, index), - validateResponse: validateSerializedResponse, - }) -} - -export function runServerFnRawResponseRequestLoop( - handler: StartRequestHandler, - context: ServerFnTransportBenchContext, -) { - return runRequestLoop(handler, { - seed: benchmarkSeed, - concurrency: 16, - totalRequests: serverFnRawResponseLoopTotalRequests, - buildRequest: (_random, index) => - buildRawResponseRequest(context.urls, context.rawPayloads, index), - validateResponse: validateRawResponse, - }) -} - -export function runServerFnRawStreamRequestLoop( - handler: StartRequestHandler, - context: ServerFnTransportBenchContext, -) { - return runRequestLoop(handler, { - seed: benchmarkSeed, - concurrency: 16, - totalRequests: serverFnRawStreamLoopTotalRequests, - buildRequest: (_random, index) => - buildRawStreamRequest(context.urls, context.streamPayloads, index), - validateResponse: validateRawStreamResponse, - }) -} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/react/project.json b/benchmarks/ssr/scenarios/server-fn-transport/react/project.json deleted file mode 100644 index a3012549ca..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-server-fn-transport-react", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/react/speed.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/react/speed.bench.ts deleted file mode 100644 index fa80cdb690..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertServerFnTransportScenario, - runServerFnMultipartRequestLoop, - 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 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 deleted file mode 100644 index fd535ee313..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/speed.server-fn-raw-response.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 8fbce405dd..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/speed.server-fn-raw-stream.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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/src/fns.ts b/benchmarks/ssr/scenarios/server-fn-transport/react/src/fns.ts deleted file mode 100644 index 79ecb50e87..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/src/fns.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { RawStream, createServerFn } from '@tanstack/react-start' - -type FormEchoData = { - alpha: string - beta: string - gamma: string - upload: File -} - -const streamChunkCount = 8 -const streamChunkSize = 1024 - -function getStringField(formData: FormData, field: string) { - const value = formData.get(field) - - if (typeof value !== 'string') { - throw new Error(`Expected ${field} to be a string`) - } - - return value -} - -function validateFormData(input: unknown): FormEchoData { - if (!(input instanceof FormData)) { - throw new Error('Expected FormData input') - } - - const upload = input.get('upload') - if (!(upload instanceof File)) { - throw new Error('Expected upload to be a File') - } - - return { - alpha: getStringField(input, 'alpha'), - beta: getStringField(input, 'beta'), - gamma: getStringField(input, 'gamma'), - upload, - } -} - -function validateString(input: unknown) { - if (typeof input !== 'string' || input.length === 0) { - throw new Error('Expected non-empty string input') - } - - return input -} - -function createDeterministicStream(seed: string) { - return new ReadableStream({ - start(controller) { - for (let chunkIndex = 0; chunkIndex < streamChunkCount; chunkIndex++) { - const chunk = new Uint8Array(streamChunkSize) - - for (let byteIndex = 0; byteIndex < chunk.length; byteIndex++) { - chunk[byteIndex] = - (seed.charCodeAt(byteIndex % seed.length) + - byteIndex + - chunkIndex) & - 0xff - } - - controller.enqueue(chunk) - } - - controller.close() - }, - }) -} - -export const formEcho = createServerFn({ method: 'POST' }) - .validator(validateFormData) - .handler(async ({ data }) => { - const contents = await data.upload.text() - - return { - alpha: data.alpha, - beta: data.beta, - gamma: data.gamma, - fileName: data.upload.name, - fileSize: data.upload.size, - filePreview: contents.slice(0, 32), - } - }) - -export const rawResp = createServerFn({ method: 'GET' }) - .validator(validateString) - .handler(({ data }) => { - return new Response(`raw-${data}`, { - headers: { 'content-type': 'text/plain' }, - }) - }) - -export const streamOut = createServerFn({ method: 'GET' }) - .validator(validateString) - .handler(({ data }) => { - return { - label: `stream-${data}`, - data: new RawStream(createDeterministicStream(data)), - } - }) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/react/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/server-fn-transport/react/src/routeTree.gen.ts deleted file mode 100644 index 10e933da3d..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as ApiFnUrlsRouteImport } from './routes/api.fn-urls' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ - id: '/api/fn-urls', - path: '/api/fn-urls', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/api/fn-urls' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/api/fn-urls' - id: '__root__' | '/' | '/api/fn-urls' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ApiFnUrlsRoute: typeof ApiFnUrlsRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/api/fn-urls': { - id: '/api/fn-urls' - path: '/api/fn-urls' - fullPath: '/api/fn-urls' - preLoaderRoute: typeof ApiFnUrlsRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ApiFnUrlsRoute: ApiFnUrlsRoute, -} -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/benchmarks/ssr/scenarios/server-fn-transport/react/src/router.tsx b/benchmarks/ssr/scenarios/server-fn-transport/react/src/router.tsx deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/react/src/routes/__root.tsx b/benchmarks/ssr/scenarios/server-fn-transport/react/src/routes/__root.tsx deleted file mode 100644 index ff1da4c304..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/react/src/routes/api.fn-urls.ts b/benchmarks/ssr/scenarios/server-fn-transport/react/src/routes/api.fn-urls.ts deleted file mode 100644 index 02260e5098..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/src/routes/api.fn-urls.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { formEcho, rawResp, streamOut } from '../fns' - -export const Route = createFileRoute('/api/fn-urls')({ - server: { - handlers: { - GET: () => - Response.json({ - form: formEcho.url, - raw: rawResp.url, - stream: streamOut.url, - }), - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/react/src/routes/index.tsx b/benchmarks/ssr/scenarios/server-fn-transport/react/src/routes/index.tsx deleted file mode 100644 index baa0026378..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/src/routes/index.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { formEcho, rawResp, streamOut } from '../fns' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return ( -
- server-fn transport benchmark -
- ) -} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/react/tsconfig.json b/benchmarks/ssr/scenarios/server-fn-transport/react/tsconfig.json deleted file mode 100644 index 4f3cc314af..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed*.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../bench.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/react/vite.config.ts b/benchmarks/ssr/scenarios/server-fn-transport/react/vite.config.ts deleted file mode 100644 index c37fde0c4b..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - 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/project.json b/benchmarks/ssr/scenarios/server-fn-transport/solid/project.json deleted file mode 100644 index 16fc151b11..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-server-fn-transport-solid", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.bench.ts deleted file mode 100644 index adac07cb22..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertServerFnTransportScenario, - runServerFnMultipartRequestLoop, - 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 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 deleted file mode 100644 index 843a4c97ce..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.server-fn-raw-response.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index aa24d55e79..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.server-fn-raw-stream.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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/src/fns.ts b/benchmarks/ssr/scenarios/server-fn-transport/solid/src/fns.ts deleted file mode 100644 index 3c586fa2ee..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/src/fns.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { RawStream, createServerFn } from '@tanstack/solid-start' - -type FormEchoData = { - alpha: string - beta: string - gamma: string - upload: File -} - -const streamChunkCount = 8 -const streamChunkSize = 1024 - -function getStringField(formData: FormData, field: string) { - const value = formData.get(field) - - if (typeof value !== 'string') { - throw new Error(`Expected ${field} to be a string`) - } - - return value -} - -function validateFormData(input: unknown): FormEchoData { - if (!(input instanceof FormData)) { - throw new Error('Expected FormData input') - } - - const upload = input.get('upload') - if (!(upload instanceof File)) { - throw new Error('Expected upload to be a File') - } - - return { - alpha: getStringField(input, 'alpha'), - beta: getStringField(input, 'beta'), - gamma: getStringField(input, 'gamma'), - upload, - } -} - -function validateString(input: unknown) { - if (typeof input !== 'string' || input.length === 0) { - throw new Error('Expected non-empty string input') - } - - return input -} - -function createDeterministicStream(seed: string) { - return new ReadableStream({ - start(controller) { - for (let chunkIndex = 0; chunkIndex < streamChunkCount; chunkIndex++) { - const chunk = new Uint8Array(streamChunkSize) - - for (let byteIndex = 0; byteIndex < chunk.length; byteIndex++) { - chunk[byteIndex] = - (seed.charCodeAt(byteIndex % seed.length) + - byteIndex + - chunkIndex) & - 0xff - } - - controller.enqueue(chunk) - } - - controller.close() - }, - }) -} - -export const formEcho = createServerFn({ method: 'POST' }) - .validator(validateFormData) - .handler(async ({ data }) => { - const contents = await data.upload.text() - - return { - alpha: data.alpha, - beta: data.beta, - gamma: data.gamma, - fileName: data.upload.name, - fileSize: data.upload.size, - filePreview: contents.slice(0, 32), - } - }) - -export const rawResp = createServerFn({ method: 'GET' }) - .validator(validateString) - .handler(({ data }) => { - return new Response(`raw-${data}`, { - headers: { 'content-type': 'text/plain' }, - }) - }) - -export const streamOut = createServerFn({ method: 'GET' }) - .validator(validateString) - .handler(({ data }) => { - return { - label: `stream-${data}`, - data: new RawStream(createDeterministicStream(data)), - } - }) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/server-fn-transport/solid/src/routeTree.gen.ts deleted file mode 100644 index 298ac3168d..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as ApiFnUrlsRouteImport } from './routes/api.fn-urls' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ - id: '/api/fn-urls', - path: '/api/fn-urls', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/api/fn-urls' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/api/fn-urls' - id: '__root__' | '/' | '/api/fn-urls' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ApiFnUrlsRoute: typeof ApiFnUrlsRoute -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/api/fn-urls': { - id: '/api/fn-urls' - path: '/api/fn-urls' - fullPath: '/api/fn-urls' - preLoaderRoute: typeof ApiFnUrlsRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ApiFnUrlsRoute: ApiFnUrlsRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/solid-start' -declare module '@tanstack/solid-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/solid/src/router.tsx b/benchmarks/ssr/scenarios/server-fn-transport/solid/src/router.tsx deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/solid/src/routes/__root.tsx b/benchmarks/ssr/scenarios/server-fn-transport/solid/src/routes/__root.tsx deleted file mode 100644 index e59de72236..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/solid-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/solid/src/routes/api.fn-urls.ts b/benchmarks/ssr/scenarios/server-fn-transport/solid/src/routes/api.fn-urls.ts deleted file mode 100644 index 353a732637..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/src/routes/api.fn-urls.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { formEcho, rawResp, streamOut } from '../fns' - -export const Route = createFileRoute('/api/fn-urls')({ - server: { - handlers: { - GET: () => - Response.json({ - form: formEcho.url, - raw: rawResp.url, - stream: streamOut.url, - }), - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/solid/src/routes/index.tsx b/benchmarks/ssr/scenarios/server-fn-transport/solid/src/routes/index.tsx deleted file mode 100644 index 6e0e5d8d6b..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/src/routes/index.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { formEcho, rawResp, streamOut } from '../fns' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return ( -
- server-fn transport benchmark -
- ) -} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/solid/tsconfig.json b/benchmarks/ssr/scenarios/server-fn-transport/solid/tsconfig.json deleted file mode 100644 index 0af78df33d..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed*.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../bench.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/solid/vite.config.ts b/benchmarks/ssr/scenarios/server-fn-transport/solid/vite.config.ts deleted file mode 100644 index a8af4a6b50..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - solid({ ssr: true, hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - execArgv: cpuSimulationExecArgv(), - isolate: true, - name: '@benchmarks/ssr server-fn-transport (solid)', - watch: false, - environment: 'node', - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/vue/project.json b/benchmarks/ssr/scenarios/server-fn-transport/vue/project.json deleted file mode 100644 index abdd85c6b7..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-server-fn-transport-vue", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.bench.ts deleted file mode 100644 index 24305cf1bc..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertServerFnTransportScenario, - runServerFnMultipartRequestLoop, - 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 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 deleted file mode 100644 index 2eeb9a4f6b..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.server-fn-raw-response.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index a73905004d..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.server-fn-raw-stream.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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/src/fns.ts b/benchmarks/ssr/scenarios/server-fn-transport/vue/src/fns.ts deleted file mode 100644 index f7e1a1217a..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/src/fns.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { RawStream, createServerFn } from '@tanstack/vue-start' - -type FormEchoData = { - alpha: string - beta: string - gamma: string - upload: File -} - -const streamChunkCount = 8 -const streamChunkSize = 1024 - -function getStringField(formData: FormData, field: string) { - const value = formData.get(field) - - if (typeof value !== 'string') { - throw new Error(`Expected ${field} to be a string`) - } - - return value -} - -function validateFormData(input: unknown): FormEchoData { - if (!(input instanceof FormData)) { - throw new Error('Expected FormData input') - } - - const upload = input.get('upload') - if (!(upload instanceof File)) { - throw new Error('Expected upload to be a File') - } - - return { - alpha: getStringField(input, 'alpha'), - beta: getStringField(input, 'beta'), - gamma: getStringField(input, 'gamma'), - upload, - } -} - -function validateString(input: unknown) { - if (typeof input !== 'string' || input.length === 0) { - throw new Error('Expected non-empty string input') - } - - return input -} - -function createDeterministicStream(seed: string) { - return new ReadableStream({ - start(controller) { - for (let chunkIndex = 0; chunkIndex < streamChunkCount; chunkIndex++) { - const chunk = new Uint8Array(streamChunkSize) - - for (let byteIndex = 0; byteIndex < chunk.length; byteIndex++) { - chunk[byteIndex] = - (seed.charCodeAt(byteIndex % seed.length) + - byteIndex + - chunkIndex) & - 0xff - } - - controller.enqueue(chunk) - } - - controller.close() - }, - }) -} - -export const formEcho = createServerFn({ method: 'POST' }) - .validator(validateFormData) - .handler(async ({ data }) => { - const contents = await data.upload.text() - - return { - alpha: data.alpha, - beta: data.beta, - gamma: data.gamma, - fileName: data.upload.name, - fileSize: data.upload.size, - filePreview: contents.slice(0, 32), - } - }) - -export const rawResp = createServerFn({ method: 'GET' }) - .validator(validateString) - .handler(({ data }) => { - return new Response(`raw-${data}`, { - headers: { 'content-type': 'text/plain' }, - }) - }) - -export const streamOut = createServerFn({ method: 'GET' }) - .validator(validateString) - .handler(({ data }) => { - return { - label: `stream-${data}`, - data: new RawStream(createDeterministicStream(data)), - } - }) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/server-fn-transport/vue/src/routeTree.gen.ts deleted file mode 100644 index b226f0a25a..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as ApiFnUrlsRouteImport } from './routes/api.fn-urls' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ - id: '/api/fn-urls', - path: '/api/fn-urls', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/api/fn-urls' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/api/fn-urls' - id: '__root__' | '/' | '/api/fn-urls' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ApiFnUrlsRoute: typeof ApiFnUrlsRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/api/fn-urls': { - id: '/api/fn-urls' - path: '/api/fn-urls' - fullPath: '/api/fn-urls' - preLoaderRoute: typeof ApiFnUrlsRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ApiFnUrlsRoute: ApiFnUrlsRoute, -} -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/benchmarks/ssr/scenarios/server-fn-transport/vue/src/router.tsx b/benchmarks/ssr/scenarios/server-fn-transport/vue/src/router.tsx deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/vue/src/routes/__root.tsx b/benchmarks/ssr/scenarios/server-fn-transport/vue/src/routes/__root.tsx deleted file mode 100644 index 49422aac38..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/src/routes/__root.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { - Body, - HeadContent, - Html, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/vue-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/vue/src/routes/api.fn-urls.ts b/benchmarks/ssr/scenarios/server-fn-transport/vue/src/routes/api.fn-urls.ts deleted file mode 100644 index 2db00972bb..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/src/routes/api.fn-urls.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' -import { formEcho, rawResp, streamOut } from '../fns' - -export const Route = createFileRoute('/api/fn-urls')({ - server: { - handlers: { - GET: () => - Response.json({ - form: formEcho.url, - raw: rawResp.url, - stream: streamOut.url, - }), - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/vue/src/routes/index.tsx b/benchmarks/ssr/scenarios/server-fn-transport/vue/src/routes/index.tsx deleted file mode 100644 index d53731eb23..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/src/routes/index.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' -import { formEcho, rawResp, streamOut } from '../fns' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return ( -
- server-fn transport benchmark -
- ) -} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/vue/tsconfig.json b/benchmarks/ssr/scenarios/server-fn-transport/vue/tsconfig.json deleted file mode 100644 index 5b7742b414..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed*.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../bench.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/vue/vite.config.ts b/benchmarks/ssr/scenarios/server-fn-transport/vue/vite.config.ts deleted file mode 100644 index 0f3e2ce84d..0000000000 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - 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/bench.ts b/benchmarks/ssr/scenarios/server-fns/bench.ts deleted file mode 100644 index 1461ce2bfd..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/bench.ts +++ /dev/null @@ -1,533 +0,0 @@ -import { fromCrossJSON, toJSONAsync } from 'seroval' -import { - createDeterministicRandom, - randomSegment, - runRequestLoop, -} from '../../bench-utils' -import type { StartRequestHandler } from '../../bench-utils' -import type { SerovalNode } from 'seroval' - -export type { StartRequestHandler } - -type Payload = { - q: string - n: number - nested: { list: Array } -} - -type FnUrls = { - get: string - post: string - redirect: string - notFound: string - context: string -} - -export type ServerFnBenchContext = { - urls: FnUrls - bodies: Array - getQueries: Array - expectedMarker: string - contextBodies: Array - contextExpectedMarkers: Array - contextExpectedStamps: Array -} - -const benchmarkSeed = 0xdecafbad -const origin = 'http://localhost' -const tssContentTypeFramed = 'application/x-tss-framed' -const xTssSerialized = 'x-tss-serialized' -const acceptHeader = `${tssContentTypeFramed}, application/x-ndjson, application/json` -const commonHeaders = { - 'x-tsr-serverFn': 'true', - 'sec-fetch-site': 'same-origin', - accept: acceptHeader, -} satisfies HeadersInit -const postHeaders = { - ...commonHeaders, - 'content-type': 'application/json', -} satisfies HeadersInit -const documentRequestInit = { - method: 'GET', - headers: { - accept: 'text/html', - }, -} satisfies RequestInit -const serverFnGetLoopTotalRequests = 112 -const serverFnPostLoopTotalRequests = 160 -const serverFnRedirectLoopTotalRequests = 128 -const serverFnNotFoundLoopTotalRequests = 208 -const serverFnSendContextLoopTotalRequests = 176 -const serverFnDocumentSsrLoopTotalRequests = 48 - -export const serverFnBenchOptions = { - warmupIterations: 100, - time: 10_000, - throws: true, -} as const - -function createPayloads() { - const random = createDeterministicRandom(benchmarkSeed) - - return Array.from({ length: 10 }, (_, index): Payload => { - const queryParts = Array.from({ length: 6 }, () => randomSegment(random)) - - return { - q: `q-${index}-${queryParts.join('-')}`, - n: 100 + index, - nested: { - list: Array.from( - { length: 5 }, - () => `l-${index}-${randomSegment(random)}-${randomSegment(random)}`, - ), - }, - } - }) -} - -async function createBodies(payloads: Array) { - return await Promise.all( - payloads.map(async (payload) => - JSON.stringify(await toJSONAsync({ data: payload })), - ), - ) -} - -function createContextToken(payload: Payload) { - return `token-${payload.q}-${payload.nested.list[0]}` -} - -async function createContextFixtures(payloads: Array) { - return await Promise.all( - payloads.map(async (payload) => { - const token = createContextToken(payload) - - return { - body: JSON.stringify( - await toJSONAsync({ data: payload, context: { token } }), - ), - marker: `ctx-${token}-${payload.nested.list[0]}`, - stamp: `stamp-${token}`, - } - }), - ) -} - -function createGetQueries(bodies: Array) { - return bodies.map((body) => `?${new URLSearchParams({ payload: body })}`) -} - -async function discoverUrls(handler: StartRequestHandler) { - const response = await handler.fetch(new Request(`${origin}/api/fn-urls`)) - - if (response.status === 404) { - throw new Error('URL discovery route returned 404 for /api/fn-urls') - } - - if (response.status !== 200) { - throw new Error( - `URL discovery failed with status ${response.status}: ${await response.text()}`, - ) - } - - const urls = (await response.json()) as Partial - const requiredKeys = [ - 'get', - 'post', - 'redirect', - 'notFound', - 'context', - ] as const - - for (const key of requiredKeys) { - if (typeof urls[key] !== 'string') { - throw new Error( - `URL discovery returned invalid payload: ${JSON.stringify(urls)}`, - ) - } - } - - return urls as FnUrls -} - -function validateSerializedResponse(response: Response, label: string) { - if (response.status === 403) { - throw new Error( - `${label} sanity check failed with 403. Check CSRF headers.`, - ) - } - - if (response.status === 404) { - throw new Error( - `${label} sanity check failed with 404. The discovered server function URL is stale.`, - ) - } - - if (response.status !== 200) { - throw new Error(`${label} request failed with status ${response.status}`) - } - - if (!response.headers.get(xTssSerialized)) { - throw new Error(`${label} response missing ${xTssSerialized} header`) - } -} - -function validateRedirectResponse(response: Response) { - if (response.status !== 200) { - throw new Error(`redirect request failed with status ${response.status}`) - } - - const contentType = response.headers.get('content-type') - - if (!contentType?.includes('application/json')) { - throw new Error(`redirect response was not JSON: ${contentType}`) - } -} - -function validateDocumentResponse(response: Response) { - if (response.status !== 200) { - throw new Error(`document request failed with status ${response.status}`) - } - - const contentType = response.headers.get('content-type') - - if (!contentType?.includes('text/html')) { - throw new Error(`document response was not HTML: ${contentType}`) - } -} - -async function readSerializedServerFnResult(response: Response, label: string) { - const text = await response.text() - - validateSerializedResponse(response, label) - - let json: unknown - - try { - json = JSON.parse(text) - } catch (error) { - throw new Error(`${label} sanity check returned invalid JSON: ${text}`, { - cause: error, - }) - } - - return { text, decoded: fromCrossJSON(json as SerovalNode, {}) } -} - -async function assertServerFnResponse({ - response, - label, - expectedMarker, -}: { - response: Response - label: string - expectedMarker: string -}) { - const { text } = await readSerializedServerFnResult(response, label) - - if (!text.includes(expectedMarker)) { - throw new Error( - `${label} sanity check did not include expected marker ${expectedMarker}: ${text}`, - ) - } -} - -async function assertServerFnRedirectResponse(response: Response) { - const text = await response.text() - - if (response.status !== 200) { - throw new Error( - `redirect sanity check failed with status ${response.status}: ${text}`, - ) - } - - let payload: { - href?: string - isSerializedRedirect?: boolean - statusCode?: number - } - - try { - payload = JSON.parse(text) as typeof payload - } catch (error) { - throw new Error(`redirect sanity check returned invalid JSON: ${text}`, { - cause: error, - }) - } - - if ( - payload.href !== '/' || - payload.statusCode !== 307 || - payload.isSerializedRedirect !== true - ) { - throw new Error( - `redirect sanity check expected serialized redirect to /, got ${text}`, - ) - } -} - -async function assertServerFnNotFoundResponse(response: Response) { - const { decoded } = await readSerializedServerFnResult(response, 'not-found') - const payload = decoded as { error?: { isNotFound?: boolean } } - - if (payload.error?.isNotFound !== true) { - throw new Error( - `not-found sanity check did not include isNotFound error: ${JSON.stringify(decoded)}`, - ) - } -} - -async function assertServerFnContextResponse({ - response, - expectedMarker, - expectedStamp, -}: { - response: Response - expectedMarker: string - expectedStamp: string -}) { - const { decoded } = await readSerializedServerFnResult( - response, - 'send-context', - ) - const payload = decoded as { - result?: { marker?: string; token?: string } - context?: { stamp?: string } - } - - if (payload.result?.marker !== expectedMarker) { - throw new Error( - `send-context sanity check expected result marker ${expectedMarker}, got ${JSON.stringify(decoded)}`, - ) - } - - if (payload.context?.stamp !== expectedStamp) { - throw new Error( - `send-context sanity check expected response context ${expectedStamp}, got ${JSON.stringify(decoded)}`, - ) - } -} - -async function assertDocumentServerFnCallResponse(response: Response) { - const text = await response.text() - const expectedMarker = 'out-ssr-call-sanity-ssr' - - if (response.status !== 200) { - throw new Error( - `SSR-call sanity check failed with status ${response.status}: ${text}`, - ) - } - - const contentType = response.headers.get('content-type') - - if (!contentType?.includes('text/html')) { - throw new Error(`SSR-call sanity check was not HTML: ${contentType}`) - } - - if (response.headers.get(xTssSerialized)) { - throw new Error('SSR-call sanity check returned a server-fn RPC response') - } - - if (!text.includes('data-bench="server-fn-ssr-call"')) { - throw new Error('SSR-call sanity check missing document marker') - } - - if (!text.includes(expectedMarker)) { - throw new Error( - `SSR-call sanity check missing expected marker ${expectedMarker}`, - ) - } -} - -function buildGetRequest(urls: FnUrls, queries: Array, index: number) { - return new Request(`${origin}${urls.get}${queries[index % queries.length]}`, { - method: 'GET', - headers: commonHeaders, - }) -} - -function buildPostUrlRequest( - url: string, - bodies: Array, - index: number, -) { - return new Request(`${origin}${url}`, { - method: 'POST', - headers: postHeaders, - body: bodies[index % bodies.length], - }) -} - -function buildPostRequest(urls: FnUrls, bodies: Array, index: number) { - return buildPostUrlRequest(urls.post, bodies, index) -} - -function buildRedirectRequest( - urls: FnUrls, - bodies: Array, - index: number, -) { - return buildPostUrlRequest(urls.redirect, bodies, index) -} - -function buildNotFoundRequest( - urls: FnUrls, - bodies: Array, - index: number, -) { - return buildPostUrlRequest(urls.notFound, bodies, index) -} - -function buildContextRequest( - urls: FnUrls, - contextBodies: Array, - index: number, -) { - return buildPostUrlRequest(urls.context, contextBodies, index) -} - -function buildSsrCallRequest(random: () => number) { - return new Request( - `${origin}/ssr-call/${randomSegment(random)}`, - documentRequestInit, - ) -} - -export async function setupServerFnBench(handler: StartRequestHandler) { - const urls = await discoverUrls(handler) - const payloads = createPayloads() - const bodies = await createBodies(payloads) - const contextFixtures = await createContextFixtures(payloads) - const getQueries = createGetQueries(bodies) - const expectedMarker = `out-${payloads[0]!.nested.list[0]}` - - return { - urls, - bodies, - getQueries, - expectedMarker, - contextBodies: contextFixtures.map((fixture) => fixture.body), - contextExpectedMarkers: contextFixtures.map((fixture) => fixture.marker), - contextExpectedStamps: contextFixtures.map((fixture) => fixture.stamp), - } -} - -export async function assertServerFnScenario( - handler: StartRequestHandler, - context: ServerFnBenchContext, -) { - await assertServerFnResponse({ - response: await handler.fetch( - buildGetRequest(context.urls, context.getQueries, 0), - ), - label: 'GET', - expectedMarker: context.expectedMarker, - }) - await assertServerFnResponse({ - response: await handler.fetch( - buildPostRequest(context.urls, context.bodies, 0), - ), - label: 'POST', - expectedMarker: context.expectedMarker, - }) - await assertServerFnRedirectResponse( - await handler.fetch(buildRedirectRequest(context.urls, context.bodies, 0)), - ) - await assertServerFnNotFoundResponse( - await handler.fetch(buildNotFoundRequest(context.urls, context.bodies, 0)), - ) - await assertServerFnContextResponse({ - response: await handler.fetch( - buildContextRequest(context.urls, context.contextBodies, 0), - ), - expectedMarker: context.contextExpectedMarkers[0]!, - expectedStamp: context.contextExpectedStamps[0]!, - }) - await assertDocumentServerFnCallResponse( - await handler.fetch( - new Request(`${origin}/ssr-call/sanity-ssr`, documentRequestInit), - ), - ) -} - -export function runServerFnGetRequestLoop( - handler: StartRequestHandler, - context: ServerFnBenchContext, -) { - return runRequestLoop(handler, { - seed: benchmarkSeed, - concurrency: 16, - totalRequests: serverFnGetLoopTotalRequests, - buildRequest: (_random, index) => - buildGetRequest(context.urls, context.getQueries, index), - }) -} - -export function runServerFnPostRequestLoop( - handler: StartRequestHandler, - context: ServerFnBenchContext, -) { - return runRequestLoop(handler, { - seed: benchmarkSeed, - concurrency: 16, - totalRequests: serverFnPostLoopTotalRequests, - buildRequest: (_random, index) => - buildPostRequest(context.urls, context.bodies, index), - }) -} - -export function runServerFnRedirectRequestLoop( - handler: StartRequestHandler, - context: ServerFnBenchContext, -) { - return runRequestLoop(handler, { - seed: benchmarkSeed, - concurrency: 16, - totalRequests: serverFnRedirectLoopTotalRequests, - buildRequest: (_random, index) => - buildRedirectRequest(context.urls, context.bodies, index), - validateResponse: validateRedirectResponse, - }) -} - -export function runServerFnNotFoundRequestLoop( - handler: StartRequestHandler, - context: ServerFnBenchContext, -) { - return runRequestLoop(handler, { - seed: benchmarkSeed, - concurrency: 16, - totalRequests: serverFnNotFoundLoopTotalRequests, - buildRequest: (_random, index) => - buildNotFoundRequest(context.urls, context.bodies, index), - validateResponse: (response) => - validateSerializedResponse(response, 'not-found'), - }) -} - -export function runServerFnSendContextRequestLoop( - handler: StartRequestHandler, - context: ServerFnBenchContext, -) { - return runRequestLoop(handler, { - seed: benchmarkSeed, - concurrency: 16, - totalRequests: serverFnSendContextLoopTotalRequests, - buildRequest: (_random, index) => - buildContextRequest(context.urls, context.contextBodies, index), - validateResponse: (response) => - validateSerializedResponse(response, 'send-context'), - }) -} - -export function runServerFnDocumentSsrRequestLoop( - handler: StartRequestHandler, -) { - return runRequestLoop(handler, { - seed: benchmarkSeed, - concurrency: 16, - totalRequests: serverFnDocumentSsrLoopTotalRequests, - buildRequest: buildSsrCallRequest, - validateResponse: validateDocumentResponse, - }) -} diff --git a/benchmarks/ssr/scenarios/server-fns/react/project.json b/benchmarks/ssr/scenarios/server-fns/react/project.json deleted file mode 100644 index 8858309f35..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-server-fns-react", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/server-fns/react/speed.bench.ts b/benchmarks/ssr/scenarios/server-fns/react/speed.bench.ts deleted file mode 100644 index c876772ad1..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertServerFnScenario, - runServerFnGetRequestLoop, - 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 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 deleted file mode 100644 index 6a0cb55f78..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-during-document-ssr.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 96f1160078..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-not-found.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index e85d5debd3..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-post.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 5dae598549..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-redirect.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 40d6961206..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-send-context.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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/src/fns.ts b/benchmarks/ssr/scenarios/server-fns/react/src/fns.ts deleted file mode 100644 index ce2ba48c5b..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/src/fns.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { createMiddleware, createServerFn } from '@tanstack/react-start' -import { notFound, redirect } from '@tanstack/react-router' - -const mwA = createMiddleware({ type: 'function' }).server(({ next }) => - next({ context: { a: 1 } }), -) -const mwB = createMiddleware({ type: 'function' }).server(({ next }) => - next({ context: { b: 2 } }), -) - -const sendContextMw = createMiddleware({ type: 'function' }) - .client(({ data, next }) => { - return next({ - sendContext: { token: createContextToken(data as unknown as Payload) }, - }) - }) - .server(({ context, next }) => { - const { token } = context as { token?: string } - - if (typeof token !== 'string') { - throw new Error('missing sendContext token') - } - - return next({ - context: { token }, - sendContext: { stamp: `stamp-${token}` }, - }) - }) - -type Payload = { q: string; n: number; nested: { list: Array } } - -function createContextToken(data: Payload) { - return `token-${data.q}-${data.nested.list[0]}` -} - -const validate = (input: unknown): Payload => { - const p = input as Payload - - if ( - typeof p?.q !== 'string' || - typeof p?.n !== 'number' || - !Array.isArray(p?.nested?.list) - ) { - throw new Error('invalid payload') - } - - return p -} - -function echo(data: Payload, context: { a: number; b: number }) { - return { - echoed: data, - sum: data.n + context.a + context.b, - list: data.nested.list.map((s) => `out-${s}`), - } -} - -export const echoGet = createServerFn({ method: 'GET' }) - .middleware([mwA, mwB]) - .validator(validate) - .handler(({ data, context }) => echo(data, context)) - -export const echoPost = createServerFn({ method: 'POST' }) - .middleware([mwA, mwB]) - .validator(validate) - .handler(({ data, context }) => echo(data, context)) - -export const redirector = createServerFn({ method: 'POST' }).handler(() => { - throw redirect({ to: '/', statusCode: 307 }) -}) - -export const notFounder = createServerFn({ method: 'POST' }).handler(() => { - throw notFound() -}) - -export const ctxEcho = createServerFn({ method: 'POST' }) - .middleware([sendContextMw]) - .validator(validate) - .handler(({ data, context }) => { - const { token } = context as { token: string } - - return { - marker: `ctx-${token}-${data.nested.list[0]}`, - q: data.q, - token, - } - }) diff --git a/benchmarks/ssr/scenarios/server-fns/react/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/server-fns/react/src/routeTree.gen.ts deleted file mode 100644 index 4daa5f03b0..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/src/routeTree.gen.ts +++ /dev/null @@ -1,104 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 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 - '/api/fn-urls': typeof ApiFnUrlsRoute - '/ssr-call/$id': typeof SsrCallIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute - '/ssr-call/$id': typeof SsrCallIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute - '/ssr-call/$id': typeof SsrCallIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/api/fn-urls' | '/ssr-call/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/api/fn-urls' | '/ssr-call/$id' - id: '__root__' | '/' | '/api/fn-urls' | '/ssr-call/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ApiFnUrlsRoute: typeof ApiFnUrlsRoute - SsrCallIdRoute: typeof SsrCallIdRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/api/fn-urls': { - id: '/api/fn-urls' - path: '/api/fn-urls' - fullPath: '/api/fn-urls' - preLoaderRoute: typeof ApiFnUrlsRouteImport - parentRoute: typeof rootRouteImport - } - '/ssr-call/$id': { - id: '/ssr-call/$id' - path: '/ssr-call/$id' - fullPath: '/ssr-call/$id' - preLoaderRoute: typeof SsrCallIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ApiFnUrlsRoute: ApiFnUrlsRoute, - SsrCallIdRoute: SsrCallIdRoute, -} -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/benchmarks/ssr/scenarios/server-fns/react/src/router.tsx b/benchmarks/ssr/scenarios/server-fns/react/src/router.tsx deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/server-fns/react/src/routes/__root.tsx b/benchmarks/ssr/scenarios/server-fns/react/src/routes/__root.tsx deleted file mode 100644 index ff1da4c304..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/server-fns/react/src/routes/api.fn-urls.ts b/benchmarks/ssr/scenarios/server-fns/react/src/routes/api.fn-urls.ts deleted file mode 100644 index ed3d9a9b7b..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/src/routes/api.fn-urls.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { ctxEcho, echoGet, echoPost, notFounder, redirector } from '../fns' - -export const Route = createFileRoute('/api/fn-urls')({ - server: { - handlers: { - GET: () => - Response.json({ - get: echoGet.url, - post: echoPost.url, - redirect: redirector.url, - notFound: notFounder.url, - context: ctxEcho.url, - }), - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/server-fns/react/src/routes/index.tsx b/benchmarks/ssr/scenarios/server-fns/react/src/routes/index.tsx deleted file mode 100644 index 45636ef30e..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/src/routes/index.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { echoGet, echoPost } from '../fns' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return ( -
- server-fns -
- ) -} diff --git a/benchmarks/ssr/scenarios/server-fns/react/src/routes/ssr-call.$id.tsx b/benchmarks/ssr/scenarios/server-fns/react/src/routes/ssr-call.$id.tsx deleted file mode 100644 index 0f8a39f69d..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/src/routes/ssr-call.$id.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { echoGet } from '../fns' - -export const Route = createFileRoute('/ssr-call/$id')({ - loader: async ({ params }) => { - const result = await echoGet({ - data: { - q: `ssr-${params.id}`, - n: 300, - nested: { list: [`ssr-call-${params.id}`] }, - }, - }) - - return { marker: result.list[0] } - }, - component: SsrCallComponent, -}) - -function SsrCallComponent() { - const data = Route.useLoaderData() - - return
{data.marker}
-} diff --git a/benchmarks/ssr/scenarios/server-fns/react/tsconfig.json b/benchmarks/ssr/scenarios/server-fns/react/tsconfig.json deleted file mode 100644 index cf14e1d440..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "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 deleted file mode 100644 index cd56edda95..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/react/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - 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/project.json b/benchmarks/ssr/scenarios/server-fns/solid/project.json deleted file mode 100644 index f1e9581897..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-server-fns-solid", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/server-fns/solid/speed.bench.ts b/benchmarks/ssr/scenarios/server-fns/solid/speed.bench.ts deleted file mode 100644 index f6bbdc9e73..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertServerFnScenario, - runServerFnGetRequestLoop, - 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 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 deleted file mode 100644 index 933f61b59c..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-during-document-ssr.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 513b69f4ba..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-not-found.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index e2ce8ad9ee..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-post.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 14353f1290..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-redirect.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 76d3a554bd..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-send-context.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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/fns.ts b/benchmarks/ssr/scenarios/server-fns/solid/src/fns.ts deleted file mode 100644 index e9a81ad06e..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/src/fns.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { createMiddleware, createServerFn } from '@tanstack/solid-start' -import { notFound, redirect } from '@tanstack/solid-router' - -const mwA = createMiddleware({ type: 'function' }).server(({ next }) => - next({ context: { a: 1 } }), -) -const mwB = createMiddleware({ type: 'function' }).server(({ next }) => - next({ context: { b: 2 } }), -) - -const sendContextMw = createMiddleware({ type: 'function' }) - .client(({ data, next }) => { - return next({ - sendContext: { token: createContextToken(data as unknown as Payload) }, - }) - }) - .server(({ context, next }) => { - const { token } = context as { token?: string } - - if (typeof token !== 'string') { - throw new Error('missing sendContext token') - } - - return next({ - context: { token }, - sendContext: { stamp: `stamp-${token}` }, - }) - }) - -type Payload = { q: string; n: number; nested: { list: Array } } - -function createContextToken(data: Payload) { - return `token-${data.q}-${data.nested.list[0]}` -} - -const validate = (input: unknown): Payload => { - const p = input as Payload - - if ( - typeof p?.q !== 'string' || - typeof p?.n !== 'number' || - !Array.isArray(p?.nested?.list) - ) { - throw new Error('invalid payload') - } - - return p -} - -function echo(data: Payload, context: { a: number; b: number }) { - return { - echoed: data, - sum: data.n + context.a + context.b, - list: data.nested.list.map((s) => `out-${s}`), - } -} - -export const echoGet = createServerFn({ method: 'GET' }) - .middleware([mwA, mwB]) - .validator(validate) - .handler(({ data, context }) => echo(data, context)) - -export const echoPost = createServerFn({ method: 'POST' }) - .middleware([mwA, mwB]) - .validator(validate) - .handler(({ data, context }) => echo(data, context)) - -export const redirector = createServerFn({ method: 'POST' }).handler(() => { - throw redirect({ to: '/', statusCode: 307 }) -}) - -export const notFounder = createServerFn({ method: 'POST' }).handler(() => { - throw notFound() -}) - -export const ctxEcho = createServerFn({ method: 'POST' }) - .middleware([sendContextMw]) - .validator(validate) - .handler(({ data, context }) => { - const { token } = context as { token: string } - - return { - marker: `ctx-${token}-${data.nested.list[0]}`, - q: data.q, - token, - } - }) diff --git a/benchmarks/ssr/scenarios/server-fns/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/server-fns/solid/src/routeTree.gen.ts deleted file mode 100644 index 3d0bd34eaa..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,104 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 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 - '/api/fn-urls': typeof ApiFnUrlsRoute - '/ssr-call/$id': typeof SsrCallIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute - '/ssr-call/$id': typeof SsrCallIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute - '/ssr-call/$id': typeof SsrCallIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/api/fn-urls' | '/ssr-call/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/api/fn-urls' | '/ssr-call/$id' - id: '__root__' | '/' | '/api/fn-urls' | '/ssr-call/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ApiFnUrlsRoute: typeof ApiFnUrlsRoute - SsrCallIdRoute: typeof SsrCallIdRoute -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/api/fn-urls': { - id: '/api/fn-urls' - path: '/api/fn-urls' - fullPath: '/api/fn-urls' - preLoaderRoute: typeof ApiFnUrlsRouteImport - parentRoute: typeof rootRouteImport - } - '/ssr-call/$id': { - id: '/ssr-call/$id' - path: '/ssr-call/$id' - fullPath: '/ssr-call/$id' - preLoaderRoute: typeof SsrCallIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ApiFnUrlsRoute: ApiFnUrlsRoute, - SsrCallIdRoute: SsrCallIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/solid-start' -declare module '@tanstack/solid-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/benchmarks/ssr/scenarios/server-fns/solid/src/router.tsx b/benchmarks/ssr/scenarios/server-fns/solid/src/router.tsx deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/server-fns/solid/src/routes/__root.tsx b/benchmarks/ssr/scenarios/server-fns/solid/src/routes/__root.tsx deleted file mode 100644 index e59de72236..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/solid-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/server-fns/solid/src/routes/api.fn-urls.ts b/benchmarks/ssr/scenarios/server-fns/solid/src/routes/api.fn-urls.ts deleted file mode 100644 index 7e18f6a03b..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/src/routes/api.fn-urls.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { ctxEcho, echoGet, echoPost, notFounder, redirector } from '../fns' - -export const Route = createFileRoute('/api/fn-urls')({ - server: { - handlers: { - GET: () => - Response.json({ - get: echoGet.url, - post: echoPost.url, - redirect: redirector.url, - notFound: notFounder.url, - context: ctxEcho.url, - }), - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/server-fns/solid/src/routes/index.tsx b/benchmarks/ssr/scenarios/server-fns/solid/src/routes/index.tsx deleted file mode 100644 index 83e7b22372..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/src/routes/index.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { echoGet, echoPost } from '../fns' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return ( -
- server-fns -
- ) -} diff --git a/benchmarks/ssr/scenarios/server-fns/solid/src/routes/ssr-call.$id.tsx b/benchmarks/ssr/scenarios/server-fns/solid/src/routes/ssr-call.$id.tsx deleted file mode 100644 index abc5571a59..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/src/routes/ssr-call.$id.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { echoGet } from '../fns' - -export const Route = createFileRoute('/ssr-call/$id')({ - loader: async ({ params }) => { - const result = await echoGet({ - data: { - q: `ssr-${params.id}`, - n: 300, - nested: { list: [`ssr-call-${params.id}`] }, - }, - }) - - return { marker: result.list[0] } - }, - component: SsrCallComponent, -}) - -function SsrCallComponent() { - const data = Route.useLoaderData() - - return
{data().marker}
-} diff --git a/benchmarks/ssr/scenarios/server-fns/solid/tsconfig.json b/benchmarks/ssr/scenarios/server-fns/solid/tsconfig.json deleted file mode 100644 index 42c3a2160f..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "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 deleted file mode 100644 index 2f2f78b75c..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/solid/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - solid({ ssr: true, hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - execArgv: cpuSimulationExecArgv(), - isolate: true, - name: '@benchmarks/ssr server-fns (solid)', - watch: false, - environment: 'node', - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/server-fns/vue/project.json b/benchmarks/ssr/scenarios/server-fns/vue/project.json deleted file mode 100644 index ad6f053838..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-server-fns-vue", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/server-fns/vue/speed.bench.ts b/benchmarks/ssr/scenarios/server-fns/vue/speed.bench.ts deleted file mode 100644 index 3f67c1a500..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertServerFnScenario, - runServerFnGetRequestLoop, - 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 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 deleted file mode 100644 index 56c9addca5..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-during-document-ssr.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index e9a6e31617..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-not-found.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index df9312ccd1..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-post.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 67c4611644..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-redirect.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 6f51ef4bab..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-send-context.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -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/fns.ts b/benchmarks/ssr/scenarios/server-fns/vue/src/fns.ts deleted file mode 100644 index fc08b2b9bf..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/src/fns.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { createMiddleware, createServerFn } from '@tanstack/vue-start' -import { notFound, redirect } from '@tanstack/vue-router' - -const mwA = createMiddleware({ type: 'function' }).server(({ next }) => - next({ context: { a: 1 } }), -) -const mwB = createMiddleware({ type: 'function' }).server(({ next }) => - next({ context: { b: 2 } }), -) - -const sendContextMw = createMiddleware({ type: 'function' }) - .client(({ data, next }) => { - return next({ - sendContext: { token: createContextToken(data as unknown as Payload) }, - }) - }) - .server(({ context, next }) => { - const { token } = context as { token?: string } - - if (typeof token !== 'string') { - throw new Error('missing sendContext token') - } - - return next({ - context: { token }, - sendContext: { stamp: `stamp-${token}` }, - }) - }) - -type Payload = { q: string; n: number; nested: { list: Array } } - -function createContextToken(data: Payload) { - return `token-${data.q}-${data.nested.list[0]}` -} - -const validate = (input: unknown): Payload => { - const p = input as Payload - - if ( - typeof p?.q !== 'string' || - typeof p?.n !== 'number' || - !Array.isArray(p?.nested?.list) - ) { - throw new Error('invalid payload') - } - - return p -} - -function echo(data: Payload, context: { a: number; b: number }) { - return { - echoed: data, - sum: data.n + context.a + context.b, - list: data.nested.list.map((s) => `out-${s}`), - } -} - -export const echoGet = createServerFn({ method: 'GET' }) - .middleware([mwA, mwB]) - .validator(validate) - .handler(({ data, context }) => echo(data, context)) - -export const echoPost = createServerFn({ method: 'POST' }) - .middleware([mwA, mwB]) - .validator(validate) - .handler(({ data, context }) => echo(data, context)) - -export const redirector = createServerFn({ method: 'POST' }).handler(() => { - throw redirect({ to: '/', statusCode: 307 }) -}) - -export const notFounder = createServerFn({ method: 'POST' }).handler(() => { - throw notFound() -}) - -export const ctxEcho = createServerFn({ method: 'POST' }) - .middleware([sendContextMw]) - .validator(validate) - .handler(({ data, context }) => { - const { token } = context as { token: string } - - return { - marker: `ctx-${token}-${data.nested.list[0]}`, - q: data.q, - token, - } - }) diff --git a/benchmarks/ssr/scenarios/server-fns/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/server-fns/vue/src/routeTree.gen.ts deleted file mode 100644 index 0e24cd9c15..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,104 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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 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 - '/api/fn-urls': typeof ApiFnUrlsRoute - '/ssr-call/$id': typeof SsrCallIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute - '/ssr-call/$id': typeof SsrCallIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/api/fn-urls': typeof ApiFnUrlsRoute - '/ssr-call/$id': typeof SsrCallIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/api/fn-urls' | '/ssr-call/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/api/fn-urls' | '/ssr-call/$id' - id: '__root__' | '/' | '/api/fn-urls' | '/ssr-call/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ApiFnUrlsRoute: typeof ApiFnUrlsRoute - SsrCallIdRoute: typeof SsrCallIdRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/api/fn-urls': { - id: '/api/fn-urls' - path: '/api/fn-urls' - fullPath: '/api/fn-urls' - preLoaderRoute: typeof ApiFnUrlsRouteImport - parentRoute: typeof rootRouteImport - } - '/ssr-call/$id': { - id: '/ssr-call/$id' - path: '/ssr-call/$id' - fullPath: '/ssr-call/$id' - preLoaderRoute: typeof SsrCallIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ApiFnUrlsRoute: ApiFnUrlsRoute, - SsrCallIdRoute: SsrCallIdRoute, -} -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/benchmarks/ssr/scenarios/server-fns/vue/src/router.tsx b/benchmarks/ssr/scenarios/server-fns/vue/src/router.tsx deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/server-fns/vue/src/routes/__root.tsx b/benchmarks/ssr/scenarios/server-fns/vue/src/routes/__root.tsx deleted file mode 100644 index 49422aac38..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/src/routes/__root.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { - Body, - HeadContent, - Html, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/vue-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/server-fns/vue/src/routes/api.fn-urls.ts b/benchmarks/ssr/scenarios/server-fns/vue/src/routes/api.fn-urls.ts deleted file mode 100644 index 0199e7f1d3..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/src/routes/api.fn-urls.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' -import { ctxEcho, echoGet, echoPost, notFounder, redirector } from '../fns' - -export const Route = createFileRoute('/api/fn-urls')({ - server: { - handlers: { - GET: () => - Response.json({ - get: echoGet.url, - post: echoPost.url, - redirect: redirector.url, - notFound: notFounder.url, - context: ctxEcho.url, - }), - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/server-fns/vue/src/routes/index.tsx b/benchmarks/ssr/scenarios/server-fns/vue/src/routes/index.tsx deleted file mode 100644 index e72e667bc5..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/src/routes/index.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' -import { echoGet, echoPost } from '../fns' - -export const Route = createFileRoute('/')({ - component: IndexComponent, -}) - -function IndexComponent() { - return ( -
- server-fns -
- ) -} 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 deleted file mode 100644 index 45fad23dc0..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/src/routes/ssr-call.$id.tsx +++ /dev/null @@ -1,28 +0,0 @@ -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({ - data: { - q: `ssr-${params.id}`, - n: 300, - nested: { list: [`ssr-call-${params.id}`] }, - }, - }) - - return { marker: result.list[0] } - }, - component: SsrCallComponent, -}) diff --git a/benchmarks/ssr/scenarios/server-fns/vue/tsconfig.json b/benchmarks/ssr/scenarios/server-fns/vue/tsconfig.json deleted file mode 100644 index 08c94853f4..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "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 deleted file mode 100644 index 5f3e3ca4b5..0000000000 --- a/benchmarks/ssr/scenarios/server-fns/vue/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - 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/project.json b/benchmarks/ssr/scenarios/server-routes-middleware/react/project.json deleted file mode 100644 index e5f11d0a57..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-server-routes-middleware-react", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/react/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes-middleware/react/speed.bench.ts deleted file mode 100644 index 6331216522..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/react/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertServerRouteMiddlewareResponse, - runServerRouteMiddlewareLoop, - serverRouteMiddlewareBenchOptions, -} 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 assertServerRouteMiddlewareResponse(handler) - -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/src/middleware.ts b/benchmarks/ssr/scenarios/server-routes-middleware/react/src/middleware.ts deleted file mode 100644 index 1e8c428696..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/react/src/middleware.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { createMiddleware } from '@tanstack/react-start' - -const make = (key: TKey, value: number) => - createMiddleware({ type: 'request' }).server(({ next }) => - next({ context: { [key]: value } as Record }), - ) - -export const routeMws = [ - make('r1', 1), - make('r2', 2), - make('r3', 3), - make('r4', 4), - make('r5', 5), -] as const - -export const methodMws = [make('m1', 6), make('m2', 7)] as const diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/react/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/server-routes-middleware/react/src/routeTree.gen.ts deleted file mode 100644 index 7a63a799a1..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/react/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as ApiChainIdRouteImport } from './routes/api.chain.$id' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ApiChainIdRoute = ApiChainIdRouteImport.update({ - id: '/api/chain/$id', - path: '/api/chain/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/api/chain/$id': typeof ApiChainIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/api/chain/$id': typeof ApiChainIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/api/chain/$id': typeof ApiChainIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/api/chain/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/api/chain/$id' - id: '__root__' | '/' | '/api/chain/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ApiChainIdRoute: typeof ApiChainIdRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/api/chain/$id': { - id: '/api/chain/$id' - path: '/api/chain/$id' - fullPath: '/api/chain/$id' - preLoaderRoute: typeof ApiChainIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ApiChainIdRoute: ApiChainIdRoute, -} -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/benchmarks/ssr/scenarios/server-routes-middleware/react/src/router.tsx b/benchmarks/ssr/scenarios/server-routes-middleware/react/src/router.tsx deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/react/src/routes/__root.tsx b/benchmarks/ssr/scenarios/server-routes-middleware/react/src/routes/__root.tsx deleted file mode 100644 index ff1da4c304..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/react/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/react/src/routes/api.chain.$id.ts b/benchmarks/ssr/scenarios/server-routes-middleware/react/src/routes/api.chain.$id.ts deleted file mode 100644 index 5a9f5d5035..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/react/src/routes/api.chain.$id.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { methodMws, routeMws } from '../middleware' - -const allMws = [...routeMws, ...methodMws] as const - -export const Route = createFileRoute('/api/chain/$id')({ - server: { - middleware: allMws, - handlers: { - GET: ({ params, context }) => - Response.json({ - id: params.id, - total: - context.r1 + - context.r2 + - context.r3 + - context.r4 + - context.r5 + - context.m1 + - context.m2, - }), - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/react/src/routes/index.tsx b/benchmarks/ssr/scenarios/server-routes-middleware/react/src/routes/index.tsx deleted file mode 100644 index 9fe98b6851..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/react/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: Home, -}) - -function Home() { - return
server routes middleware
-} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/react/tsconfig.json b/benchmarks/ssr/scenarios/server-routes-middleware/react/tsconfig.json deleted file mode 100644 index 91027bfc88..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/react/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/react/vite.config.ts b/benchmarks/ssr/scenarios/server-routes-middleware/react/vite.config.ts deleted file mode 100644 index f6998c2ac8..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/react/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - 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/shared.ts b/benchmarks/ssr/scenarios/server-routes-middleware/shared.ts deleted file mode 100644 index 663ca09294..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/shared.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { randomSegment, runRequestLoop } from '../../bench-utils' -import type { StartRequestHandler } from '../../bench-utils' - -export type { StartRequestHandler } - -const benchmarkSeed = 0xdecafbad -const loopTotalRequests = 160 - -const apiRequestInit = { - method: 'GET', - headers: { - accept: 'application/json', - }, -} satisfies RequestInit - -export const serverRouteMiddlewareBenchOptions = { - warmupIterations: 100, - time: 10_000, - throws: true, -} - -export function runServerRouteMiddlewareLoop(handler: StartRequestHandler) { - return runRequestLoop(handler, { - seed: benchmarkSeed, - concurrency: 16, - totalRequests: loopTotalRequests, - buildRequest: (random) => - new Request( - `http://localhost/api/chain/${randomSegment(random)}`, - apiRequestInit, - ), - }) -} - -export async function assertServerRouteMiddlewareResponse( - handler: StartRequestHandler, -) { - const id = 'sanity' - const response = await handler.fetch( - new Request(`http://localhost/api/chain/${id}`, apiRequestInit), - ) - - if (response.status !== 200) { - throw new Error(`Expected status 200, received ${response.status}`) - } - - const contentType = response.headers.get('content-type') - - if (!contentType?.includes('application/json')) { - throw new Error(`Expected JSON response, received ${contentType}`) - } - - const body = (await response.json()) as { total?: number } - - if (body.total !== 28) { - throw new Error(`Expected total 28, received ${body.total}`) - } -} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/solid/project.json b/benchmarks/ssr/scenarios/server-routes-middleware/solid/project.json deleted file mode 100644 index 0bde91f794..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/solid/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-server-routes-middleware-solid", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/solid/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes-middleware/solid/speed.bench.ts deleted file mode 100644 index 77d58e7b19..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/solid/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertServerRouteMiddlewareResponse, - runServerRouteMiddlewareLoop, - serverRouteMiddlewareBenchOptions, -} 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 assertServerRouteMiddlewareResponse(handler) - -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/src/middleware.ts b/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/middleware.ts deleted file mode 100644 index fcaf3d08f7..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/middleware.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { createMiddleware } from '@tanstack/solid-start' - -const make = (key: TKey, value: number) => - createMiddleware({ type: 'request' }).server(({ next }) => - next({ context: { [key]: value } as Record }), - ) - -export const routeMws = [ - make('r1', 1), - make('r2', 2), - make('r3', 3), - make('r4', 4), - make('r5', 5), -] as const - -export const methodMws = [make('m1', 6), make('m2', 7)] as const diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/routeTree.gen.ts deleted file mode 100644 index b8c91b9134..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as ApiChainIdRouteImport } from './routes/api.chain.$id' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ApiChainIdRoute = ApiChainIdRouteImport.update({ - id: '/api/chain/$id', - path: '/api/chain/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/api/chain/$id': typeof ApiChainIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/api/chain/$id': typeof ApiChainIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/api/chain/$id': typeof ApiChainIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/api/chain/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/api/chain/$id' - id: '__root__' | '/' | '/api/chain/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ApiChainIdRoute: typeof ApiChainIdRoute -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/api/chain/$id': { - id: '/api/chain/$id' - path: '/api/chain/$id' - fullPath: '/api/chain/$id' - preLoaderRoute: typeof ApiChainIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ApiChainIdRoute: ApiChainIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/solid-start' -declare module '@tanstack/solid-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/router.tsx b/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/router.tsx deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/routes/__root.tsx b/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/routes/__root.tsx deleted file mode 100644 index e59de72236..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/solid-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/routes/api.chain.$id.ts b/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/routes/api.chain.$id.ts deleted file mode 100644 index fabdb9de85..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/routes/api.chain.$id.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { methodMws, routeMws } from '../middleware' - -const allMws = [...routeMws, ...methodMws] as const - -export const Route = createFileRoute('/api/chain/$id')({ - server: { - middleware: allMws, - handlers: { - GET: ({ params, context }) => - Response.json({ - id: params.id, - total: - context.r1 + - context.r2 + - context.r3 + - context.r4 + - context.r5 + - context.m1 + - context.m2, - }), - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/routes/index.tsx b/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/routes/index.tsx deleted file mode 100644 index e2357b558d..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/')({ - component: Home, -}) - -function Home() { - return
server routes middleware
-} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/solid/tsconfig.json b/benchmarks/ssr/scenarios/server-routes-middleware/solid/tsconfig.json deleted file mode 100644 index b1806caa67..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/solid/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/solid/vite.config.ts b/benchmarks/ssr/scenarios/server-routes-middleware/solid/vite.config.ts deleted file mode 100644 index 800cf9db9f..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/solid/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - solid({ ssr: true, hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - execArgv: cpuSimulationExecArgv(), - isolate: true, - name: '@benchmarks/ssr server-routes-middleware (solid)', - watch: false, - environment: 'node', - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/vue/project.json b/benchmarks/ssr/scenarios/server-routes-middleware/vue/project.json deleted file mode 100644 index 2a21b81bf9..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-server-routes-middleware-vue", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/vue/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes-middleware/vue/speed.bench.ts deleted file mode 100644 index 3d03b9c1fa..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/vue/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertServerRouteMiddlewareResponse, - runServerRouteMiddlewareLoop, - serverRouteMiddlewareBenchOptions, -} 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 assertServerRouteMiddlewareResponse(handler) - -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/src/middleware.ts b/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/middleware.ts deleted file mode 100644 index 05e7a86be9..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/middleware.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { createMiddleware } from '@tanstack/vue-start' - -const make = (key: TKey, value: number) => - createMiddleware({ type: 'request' }).server(({ next }) => - next({ context: { [key]: value } as Record }), - ) - -export const routeMws = [ - make('r1', 1), - make('r2', 2), - make('r3', 3), - make('r4', 4), - make('r5', 5), -] as const - -export const methodMws = [make('m1', 6), make('m2', 7)] as const diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/routeTree.gen.ts deleted file mode 100644 index db4f072a69..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as ApiChainIdRouteImport } from './routes/api.chain.$id' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ApiChainIdRoute = ApiChainIdRouteImport.update({ - id: '/api/chain/$id', - path: '/api/chain/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/api/chain/$id': typeof ApiChainIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/api/chain/$id': typeof ApiChainIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/api/chain/$id': typeof ApiChainIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/api/chain/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/api/chain/$id' - id: '__root__' | '/' | '/api/chain/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ApiChainIdRoute: typeof ApiChainIdRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/api/chain/$id': { - id: '/api/chain/$id' - path: '/api/chain/$id' - fullPath: '/api/chain/$id' - preLoaderRoute: typeof ApiChainIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ApiChainIdRoute: ApiChainIdRoute, -} -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/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/router.tsx b/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/router.tsx deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/routes/__root.tsx b/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/routes/__root.tsx deleted file mode 100644 index 49422aac38..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/routes/__root.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { - Body, - HeadContent, - Html, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/vue-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/routes/api.chain.$id.ts b/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/routes/api.chain.$id.ts deleted file mode 100644 index d643a339c5..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/routes/api.chain.$id.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' -import { methodMws, routeMws } from '../middleware' - -const allMws = [...routeMws, ...methodMws] as const - -export const Route = createFileRoute('/api/chain/$id')({ - server: { - middleware: allMws, - handlers: { - GET: ({ params, context }) => - Response.json({ - id: params.id, - total: - context.r1 + - context.r2 + - context.r3 + - context.r4 + - context.r5 + - context.m1 + - context.m2, - }), - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/routes/index.tsx b/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/routes/index.tsx deleted file mode 100644 index 60e9d08e6d..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' - -export const Route = createFileRoute('/')({ - component: Home, -}) - -function Home() { - return
server routes middleware
-} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/vue/tsconfig.json b/benchmarks/ssr/scenarios/server-routes-middleware/vue/tsconfig.json deleted file mode 100644 index 4fe3ccecb1..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/vue/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/vue/vite.config.ts b/benchmarks/ssr/scenarios/server-routes-middleware/vue/vite.config.ts deleted file mode 100644 index 909b7cca50..0000000000 --- a/benchmarks/ssr/scenarios/server-routes-middleware/vue/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - 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/project.json b/benchmarks/ssr/scenarios/server-routes/react/project.json deleted file mode 100644 index a16cb3e537..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-server-routes-react", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/server-routes/react/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes/react/speed.bench.ts deleted file mode 100644 index 631314148a..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/react/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertServerRouteResponse, - runServerRouteLoop, - serverRouteBenchOptions, -} 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 assertServerRouteResponse(handler) - -test('ssr', async ({ bench }) => { - await bench('ssr server-route (react)', async () => - runServerRouteLoop(handler), - ).run(serverRouteBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/server-routes/react/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/server-routes/react/src/routeTree.gen.ts deleted file mode 100644 index 6615cc0611..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/react/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as ApiUsersIdRouteImport } from './routes/api.users.$id' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ - id: '/api/users/$id', - path: '/api/users/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/api/users/$id': typeof ApiUsersIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/api/users/$id': typeof ApiUsersIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/api/users/$id': typeof ApiUsersIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/api/users/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/api/users/$id' - id: '__root__' | '/' | '/api/users/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ApiUsersIdRoute: typeof ApiUsersIdRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/api/users/$id': { - id: '/api/users/$id' - path: '/api/users/$id' - fullPath: '/api/users/$id' - preLoaderRoute: typeof ApiUsersIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ApiUsersIdRoute: ApiUsersIdRoute, -} -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/benchmarks/ssr/scenarios/server-routes/react/src/router.tsx b/benchmarks/ssr/scenarios/server-routes/react/src/router.tsx deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/server-routes/react/src/routes/__root.tsx b/benchmarks/ssr/scenarios/server-routes/react/src/routes/__root.tsx deleted file mode 100644 index ff1da4c304..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/react/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/server-routes/react/src/routes/api.users.$id.ts b/benchmarks/ssr/scenarios/server-routes/react/src/routes/api.users.$id.ts deleted file mode 100644 index b43275a5c6..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/react/src/routes/api.users.$id.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/api/users/$id')({ - server: { - handlers: { - GET: ({ params }) => - Response.json({ - id: params.id, - name: `user-${params.id}`, - roles: ['a', 'b', 'c'], - }), - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/server-routes/react/src/routes/index.tsx b/benchmarks/ssr/scenarios/server-routes/react/src/routes/index.tsx deleted file mode 100644 index f5a19839f9..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/react/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: Home, -}) - -function Home() { - return
server routes
-} diff --git a/benchmarks/ssr/scenarios/server-routes/react/tsconfig.json b/benchmarks/ssr/scenarios/server-routes/react/tsconfig.json deleted file mode 100644 index 91027bfc88..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/react/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/server-routes/react/vite.config.ts b/benchmarks/ssr/scenarios/server-routes/react/vite.config.ts deleted file mode 100644 index 2c723c749c..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/react/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - 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/shared.ts b/benchmarks/ssr/scenarios/server-routes/shared.ts deleted file mode 100644 index ce33faaefe..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/shared.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { randomSegment, runRequestLoop } from '../../bench-utils' -import type { StartRequestHandler } from '../../bench-utils' - -export type { StartRequestHandler } - -const benchmarkSeed = 0xdecafbad -const loopTotalRequests = 208 - -const apiRequestInit = { - method: 'GET', - headers: { - accept: 'application/json', - }, -} satisfies RequestInit - -export const serverRouteBenchOptions = { - warmupIterations: 100, - time: 10_000, - throws: true, -} - -export function runServerRouteLoop(handler: StartRequestHandler) { - return runRequestLoop(handler, { - seed: benchmarkSeed, - concurrency: 16, - totalRequests: loopTotalRequests, - buildRequest: (random) => - new Request( - `http://localhost/api/users/${randomSegment(random)}`, - apiRequestInit, - ), - }) -} - -export async function assertServerRouteResponse(handler: StartRequestHandler) { - const id = 'sanity' - const response = await handler.fetch( - new Request(`http://localhost/api/users/${id}`, apiRequestInit), - ) - - if (response.status !== 200) { - throw new Error(`Expected status 200, received ${response.status}`) - } - - const contentType = response.headers.get('content-type') - - if (!contentType?.includes('application/json')) { - throw new Error(`Expected JSON response, received ${contentType}`) - } - - const body = (await response.json()) as { name?: string } - - if (body.name !== `user-${id}`) { - throw new Error(`Expected user-${id}, received ${body.name}`) - } -} diff --git a/benchmarks/ssr/scenarios/server-routes/solid/project.json b/benchmarks/ssr/scenarios/server-routes/solid/project.json deleted file mode 100644 index 9c4bf7e230..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/solid/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-server-routes-solid", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/server-routes/solid/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes/solid/speed.bench.ts deleted file mode 100644 index 4788d31854..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/solid/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertServerRouteResponse, - runServerRouteLoop, - serverRouteBenchOptions, -} 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 assertServerRouteResponse(handler) - -test('ssr', async ({ bench }) => { - await bench('ssr server-route (solid)', async () => - runServerRouteLoop(handler), - ).run(serverRouteBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/server-routes/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/server-routes/solid/src/routeTree.gen.ts deleted file mode 100644 index 1d7fee0d2b..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as ApiUsersIdRouteImport } from './routes/api.users.$id' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ - id: '/api/users/$id', - path: '/api/users/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/api/users/$id': typeof ApiUsersIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/api/users/$id': typeof ApiUsersIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/api/users/$id': typeof ApiUsersIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/api/users/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/api/users/$id' - id: '__root__' | '/' | '/api/users/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ApiUsersIdRoute: typeof ApiUsersIdRoute -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/api/users/$id': { - id: '/api/users/$id' - path: '/api/users/$id' - fullPath: '/api/users/$id' - preLoaderRoute: typeof ApiUsersIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ApiUsersIdRoute: ApiUsersIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/solid-start' -declare module '@tanstack/solid-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/benchmarks/ssr/scenarios/server-routes/solid/src/router.tsx b/benchmarks/ssr/scenarios/server-routes/solid/src/router.tsx deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/server-routes/solid/src/routes/__root.tsx b/benchmarks/ssr/scenarios/server-routes/solid/src/routes/__root.tsx deleted file mode 100644 index e59de72236..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/solid/src/routes/__root.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/solid-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/server-routes/solid/src/routes/api.users.$id.ts b/benchmarks/ssr/scenarios/server-routes/solid/src/routes/api.users.$id.ts deleted file mode 100644 index 516af1cc15..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/solid/src/routes/api.users.$id.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/api/users/$id')({ - server: { - handlers: { - GET: ({ params }) => - Response.json({ - id: params.id, - name: `user-${params.id}`, - roles: ['a', 'b', 'c'], - }), - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/server-routes/solid/src/routes/index.tsx b/benchmarks/ssr/scenarios/server-routes/solid/src/routes/index.tsx deleted file mode 100644 index 87eb6a178f..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/solid/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' - -export const Route = createFileRoute('/')({ - component: Home, -}) - -function Home() { - return
server routes
-} diff --git a/benchmarks/ssr/scenarios/server-routes/solid/tsconfig.json b/benchmarks/ssr/scenarios/server-routes/solid/tsconfig.json deleted file mode 100644 index b1806caa67..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/solid/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/server-routes/solid/vite.config.ts b/benchmarks/ssr/scenarios/server-routes/solid/vite.config.ts deleted file mode 100644 index 994e04f1d6..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/solid/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - solid({ ssr: true, hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - execArgv: cpuSimulationExecArgv(), - isolate: true, - name: '@benchmarks/ssr server-routes (solid)', - watch: false, - environment: 'node', - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/server-routes/vue/project.json b/benchmarks/ssr/scenarios/server-routes/vue/project.json deleted file mode 100644 index a92a9ad40e..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-server-routes-vue", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/server-routes/vue/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes/vue/speed.bench.ts deleted file mode 100644 index 09c0bbe90b..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/vue/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertServerRouteResponse, - runServerRouteLoop, - serverRouteBenchOptions, -} 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 assertServerRouteResponse(handler) - -test('ssr', async ({ bench }) => { - await bench('ssr server-route (vue)', async () => - runServerRouteLoop(handler), - ).run(serverRouteBenchOptions) -}) diff --git a/benchmarks/ssr/scenarios/server-routes/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/server-routes/vue/src/routeTree.gen.ts deleted file mode 100644 index b12a446b9f..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as ApiUsersIdRouteImport } from './routes/api.users.$id' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ - id: '/api/users/$id', - path: '/api/users/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/api/users/$id': typeof ApiUsersIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/api/users/$id': typeof ApiUsersIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/api/users/$id': typeof ApiUsersIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/api/users/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/api/users/$id' - id: '__root__' | '/' | '/api/users/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ApiUsersIdRoute: typeof ApiUsersIdRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/api/users/$id': { - id: '/api/users/$id' - path: '/api/users/$id' - fullPath: '/api/users/$id' - preLoaderRoute: typeof ApiUsersIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ApiUsersIdRoute: ApiUsersIdRoute, -} -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/benchmarks/ssr/scenarios/server-routes/vue/src/router.tsx b/benchmarks/ssr/scenarios/server-routes/vue/src/router.tsx deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/server-routes/vue/src/routes/__root.tsx b/benchmarks/ssr/scenarios/server-routes/vue/src/routes/__root.tsx deleted file mode 100644 index 49422aac38..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/vue/src/routes/__root.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { - Body, - HeadContent, - Html, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/vue-router' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/server-routes/vue/src/routes/api.users.$id.ts b/benchmarks/ssr/scenarios/server-routes/vue/src/routes/api.users.$id.ts deleted file mode 100644 index 7766b52acc..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/vue/src/routes/api.users.$id.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' - -export const Route = createFileRoute('/api/users/$id')({ - server: { - handlers: { - GET: ({ params }) => - Response.json({ - id: params.id, - name: `user-${params.id}`, - roles: ['a', 'b', 'c'], - }), - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/server-routes/vue/src/routes/index.tsx b/benchmarks/ssr/scenarios/server-routes/vue/src/routes/index.tsx deleted file mode 100644 index 39d1e2f935..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/vue/src/routes/index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' - -export const Route = createFileRoute('/')({ - component: Home, -}) - -function Home() { - return
server routes
-} diff --git a/benchmarks/ssr/scenarios/server-routes/vue/tsconfig.json b/benchmarks/ssr/scenarios/server-routes/vue/tsconfig.json deleted file mode 100644 index 4fe3ccecb1..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/vue/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/server-routes/vue/vite.config.ts b/benchmarks/ssr/scenarios/server-routes/vue/vite.config.ts deleted file mode 100644 index 0457453532..0000000000 --- a/benchmarks/ssr/scenarios/server-routes/vue/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - 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/project.json b/benchmarks/ssr/scenarios/streaming/react/project.json deleted file mode 100644 index a905aa3474..0000000000 --- a/benchmarks/ssr/scenarios/streaming/react/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-streaming-react", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/react-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/streaming/react/speed.bench.ts b/benchmarks/ssr/scenarios/streaming/react/speed.bench.ts deleted file mode 100644 index eb4c9dc1d6..0000000000 --- a/benchmarks/ssr/scenarios/streaming/react/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertStreamingSanity, - benchOptions, - runStreamingLoop, - 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 assertStreamingSanity(handler) - -test('ssr', async ({ bench }) => { - await bench('ssr streaming deferred (react)', async () => - runStreamingLoop(handler), - ).run(benchOptions) -}) diff --git a/benchmarks/ssr/scenarios/streaming/react/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/streaming/react/src/routeTree.gen.ts deleted file mode 100644 index eb1af78a41..0000000000 --- a/benchmarks/ssr/scenarios/streaming/react/src/routeTree.gen.ts +++ /dev/null @@ -1,68 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as StreamIdRouteImport } from './routes/stream.$id' - -const StreamIdRoute = StreamIdRouteImport.update({ - id: '/stream/$id', - path: '/stream/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/stream/$id': typeof StreamIdRoute -} -export interface FileRoutesByTo { - '/stream/$id': typeof StreamIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/stream/$id': typeof StreamIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/stream/$id' - fileRoutesByTo: FileRoutesByTo - to: '/stream/$id' - id: '__root__' | '/stream/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - StreamIdRoute: typeof StreamIdRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/stream/$id': { - id: '/stream/$id' - path: '/stream/$id' - fullPath: '/stream/$id' - preLoaderRoute: typeof StreamIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - StreamIdRoute: StreamIdRoute, -} -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/benchmarks/ssr/scenarios/streaming/react/src/router.tsx b/benchmarks/ssr/scenarios/streaming/react/src/router.tsx deleted file mode 100644 index 7c4eb0babe..0000000000 --- a/benchmarks/ssr/scenarios/streaming/react/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/streaming/react/src/routes/__root.tsx b/benchmarks/ssr/scenarios/streaming/react/src/routes/__root.tsx deleted file mode 100644 index 1973ca20bb..0000000000 --- a/benchmarks/ssr/scenarios/streaming/react/src/routes/__root.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' - -export const Route = createRootRoute({ - component: RootComponent, - validateSearch: (s) => s as { q?: string }, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/streaming/react/src/routes/stream.$id.tsx b/benchmarks/ssr/scenarios/streaming/react/src/routes/stream.$id.tsx deleted file mode 100644 index 342f7ceb0c..0000000000 --- a/benchmarks/ssr/scenarios/streaming/react/src/routes/stream.$id.tsx +++ /dev/null @@ -1,39 +0,0 @@ -import { Await, createFileRoute } from '@tanstack/react-router' -import { Suspense } from 'react' -import { makeBigPayload, sleep0 } from '../../../shared-data' - -export const Route = createFileRoute('/stream/$id')({ - loader: ({ params }) => ({ - fast: { label: `fast-${params.id}` }, - slowSmall: sleep0().then(() => ({ label: `slow-small-${params.id}` })), - slowBig: sleep0().then(() => makeBigPayload(params.id)), - }), - component: StreamComponent, -}) - -function StreamComponent() { - const data = Route.useLoaderData() - - return ( - <> -

{data.fast.label}

-

loading-small

- - {(d) =>

{d.label}

}
-
-

loading-big

- - - {(d) => ( -
-

{d.label}

- {d.chunks.map((chunk) => ( -

{chunk.value}

- ))} -
- )} -
-
- - ) -} diff --git a/benchmarks/ssr/scenarios/streaming/react/tsconfig.json b/benchmarks/ssr/scenarios/streaming/react/tsconfig.json deleted file mode 100644 index 8800818162..0000000000 --- a/benchmarks/ssr/scenarios/streaming/react/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "jsxImportSource": "react", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../shared-data.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/streaming/react/vite.config.ts b/benchmarks/ssr/scenarios/streaming/react/vite.config.ts deleted file mode 100644 index e1cc5f534b..0000000000 --- a/benchmarks/ssr/scenarios/streaming/react/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - react(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - execArgv: cpuSimulationExecArgv(), - isolate: true, - name: '@benchmarks/ssr streaming (react)', - watch: false, - environment: 'node', - }, -}) diff --git a/benchmarks/ssr/scenarios/streaming/shared-bench.ts b/benchmarks/ssr/scenarios/streaming/shared-bench.ts deleted file mode 100644 index cc45062e1b..0000000000 --- a/benchmarks/ssr/scenarios/streaming/shared-bench.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { expect } from 'vitest' -import { streamChunkCount } from './shared-data' -import { randomSegment, runRequestLoop } from '../../bench-utils' -import type { StartRequestHandler } from '../../bench-utils' - -export type { StartRequestHandler } - -const benchmarkSeed = 0xdecafbad - -export const CHROME_UA = - 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36' - -const requestInit = { - method: 'GET', - headers: { - accept: 'text/html', - 'user-agent': CHROME_UA, - }, -} satisfies RequestInit - -function buildStreamingRequest(random: () => number) { - return new Request( - `http://localhost/stream/${randomSegment(random)}`, - requestInit, - ) -} - -function getMarkerIndexes(body: string, marker: string) { - const indexes: Array = [] - let index = body.indexOf(marker) - - while (index !== -1) { - indexes.push(index) - index = body.indexOf(marker, index + marker.length) - } - - return indexes -} - -export async function assertStreamingSanity(handler: StartRequestHandler) { - const id = 'sanity-stream' - const response = await handler.fetch( - new Request(`http://localhost/stream/${id}`, requestInit), - ) - const body = await response.text() - const loadingSmallIndexes = getMarkerIndexes(body, 'loading-small') - const loadingBigIndexes = getMarkerIndexes(body, 'loading-big') - const tsrIndex = body.indexOf('$_TSR') - - expect(response.status).toBe(200) - expect(loadingSmallIndexes).toHaveLength(1) - expect(loadingBigIndexes).toHaveLength(1) - expect(body).toContain(`slow-small-${id}`) - expect(body).toContain(`slow-big-${id}`) - expect(body).toContain(`${id}:0:`) - expect(body).toContain(`${id}:${streamChunkCount - 1}:`) - - const loadingSmallIndex = loadingSmallIndexes[0]! - const loadingBigIndex = loadingBigIndexes[0]! - - expect(loadingBigIndex).toBeGreaterThan(loadingSmallIndex) - expect(tsrIndex).toBeGreaterThan(loadingBigIndex) -} - -export const benchOptions = { - warmupIterations: 100, - time: 10_000, - throws: true, -} - -export function runStreamingLoop(handler: StartRequestHandler) { - return runRequestLoop(handler, { - seed: benchmarkSeed, - concurrency: 16, - totalRequests: 16, - buildRequest: buildStreamingRequest, - }) -} diff --git a/benchmarks/ssr/scenarios/streaming/shared-data.ts b/benchmarks/ssr/scenarios/streaming/shared-data.ts deleted file mode 100644 index 695ed107c6..0000000000 --- a/benchmarks/ssr/scenarios/streaming/shared-data.ts +++ /dev/null @@ -1,69 +0,0 @@ -export interface SmallPayload { - label: string -} - -export interface BigPayload { - label: string - chunks: Array<{ - index: number - value: string - }> -} - -const alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789' -export const streamChunkCount = 96 -export const streamChunkLength = 192 - -export function sleep0() { - // 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) { - let state = 2166136261 - - for (let index = 0; index < id.length; index++) { - state ^= id.charCodeAt(index) - state = Math.imul(state, 16777619) >>> 0 - } - - return state || 1 -} - -function nextState(state: number) { - return (state * 1664525 + 1013904223) >>> 0 -} - -function makeChunk(seed: number) { - let state = seed - let value = '' - - for (let index = 0; index < streamChunkLength; index++) { - state = nextState(state) - value += alphabet[state % alphabet.length] - } - - return { state, value } -} - -export function makeBigPayload(id: string): BigPayload { - let state = hashId(id) - const chunks: BigPayload['chunks'] = [] - - for (let index = 0; index < streamChunkCount; index++) { - const chunk = makeChunk(state + index) - state = chunk.state - chunks.push({ - index, - value: `${id}:${index}:${chunk.value}`, - }) - } - - return { - label: `slow-big-${id}`, - chunks, - } -} diff --git a/benchmarks/ssr/scenarios/streaming/solid/project.json b/benchmarks/ssr/scenarios/streaming/solid/project.json deleted file mode 100644 index 15e5f21103..0000000000 --- a/benchmarks/ssr/scenarios/streaming/solid/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-streaming-solid", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/streaming/solid/speed.bench.ts b/benchmarks/ssr/scenarios/streaming/solid/speed.bench.ts deleted file mode 100644 index 19d5817d32..0000000000 --- a/benchmarks/ssr/scenarios/streaming/solid/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertStreamingSanity, - benchOptions, - runStreamingLoop, - 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 assertStreamingSanity(handler) - -test('ssr', async ({ bench }) => { - await bench('ssr streaming deferred (solid)', async () => - runStreamingLoop(handler), - ).run(benchOptions) -}) diff --git a/benchmarks/ssr/scenarios/streaming/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/streaming/solid/src/routeTree.gen.ts deleted file mode 100644 index e015aee737..0000000000 --- a/benchmarks/ssr/scenarios/streaming/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,68 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as StreamIdRouteImport } from './routes/stream.$id' - -const StreamIdRoute = StreamIdRouteImport.update({ - id: '/stream/$id', - path: '/stream/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/stream/$id': typeof StreamIdRoute -} -export interface FileRoutesByTo { - '/stream/$id': typeof StreamIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/stream/$id': typeof StreamIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/stream/$id' - fileRoutesByTo: FileRoutesByTo - to: '/stream/$id' - id: '__root__' | '/stream/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - StreamIdRoute: typeof StreamIdRoute -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/stream/$id': { - id: '/stream/$id' - path: '/stream/$id' - fullPath: '/stream/$id' - preLoaderRoute: typeof StreamIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - StreamIdRoute: StreamIdRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/solid-start' -declare module '@tanstack/solid-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/benchmarks/ssr/scenarios/streaming/solid/src/router.tsx b/benchmarks/ssr/scenarios/streaming/solid/src/router.tsx deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/ssr/scenarios/streaming/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/streaming/solid/src/routes/__root.tsx b/benchmarks/ssr/scenarios/streaming/solid/src/routes/__root.tsx deleted file mode 100644 index 15de858e78..0000000000 --- a/benchmarks/ssr/scenarios/streaming/solid/src/routes/__root.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/solid-router' - -export const Route = createRootRoute({ - component: RootComponent, - validateSearch: (s) => s as { q?: string }, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/streaming/solid/src/routes/stream.$id.tsx b/benchmarks/ssr/scenarios/streaming/solid/src/routes/stream.$id.tsx deleted file mode 100644 index 1a65fff950..0000000000 --- a/benchmarks/ssr/scenarios/streaming/solid/src/routes/stream.$id.tsx +++ /dev/null @@ -1,39 +0,0 @@ -import { Await, createFileRoute } from '@tanstack/solid-router' -import { Suspense } from 'solid-js' -import { makeBigPayload, sleep0 } from '../../../shared-data' - -export const Route = createFileRoute('/stream/$id')({ - loader: ({ params }) => ({ - fast: { label: `fast-${params.id}` }, - slowSmall: sleep0().then(() => ({ label: `slow-small-${params.id}` })), - slowBig: sleep0().then(() => makeBigPayload(params.id)), - }), - component: StreamComponent, -}) - -function StreamComponent() { - const data = Route.useLoaderData() - - return ( - <> -

{data().fast.label}

-

loading-small

- - {(d) =>

{d.label}

}
-
-

loading-big

- - - {(d) => ( -
-

{d.label}

- {d.chunks.map((chunk) => ( -

{chunk.value}

- ))} -
- )} -
-
- - ) -} diff --git a/benchmarks/ssr/scenarios/streaming/solid/tsconfig.json b/benchmarks/ssr/scenarios/streaming/solid/tsconfig.json deleted file mode 100644 index 47f264ba4f..0000000000 --- a/benchmarks/ssr/scenarios/streaming/solid/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../shared-data.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/streaming/solid/vite.config.ts b/benchmarks/ssr/scenarios/streaming/solid/vite.config.ts deleted file mode 100644 index 353c21f552..0000000000 --- a/benchmarks/ssr/scenarios/streaming/solid/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - solid({ ssr: true, hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - execArgv: cpuSimulationExecArgv(), - isolate: true, - name: '@benchmarks/ssr streaming (solid)', - watch: false, - environment: 'node', - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/ssr/scenarios/streaming/vue/project.json b/benchmarks/ssr/scenarios/streaming/vue/project.json deleted file mode 100644 index acaa7c460c..0000000000 --- a/benchmarks/ssr/scenarios/streaming/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-streaming-vue", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/scenarios/streaming/vue/speed.bench.ts b/benchmarks/ssr/scenarios/streaming/vue/speed.bench.ts deleted file mode 100644 index 42473fc694..0000000000 --- a/benchmarks/ssr/scenarios/streaming/vue/speed.bench.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { test } from 'vitest' -import { - assertStreamingSanity, - benchOptions, - runStreamingLoop, - 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 assertStreamingSanity(handler) - -test('ssr', async ({ bench }) => { - await bench('ssr streaming deferred (vue)', async () => - runStreamingLoop(handler), - ).run(benchOptions) -}) diff --git a/benchmarks/ssr/scenarios/streaming/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/streaming/vue/src/routeTree.gen.ts deleted file mode 100644 index 2ec10975f2..0000000000 --- a/benchmarks/ssr/scenarios/streaming/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,68 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as StreamIdRouteImport } from './routes/stream.$id' - -const StreamIdRoute = StreamIdRouteImport.update({ - id: '/stream/$id', - path: '/stream/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/stream/$id': typeof StreamIdRoute -} -export interface FileRoutesByTo { - '/stream/$id': typeof StreamIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/stream/$id': typeof StreamIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/stream/$id' - fileRoutesByTo: FileRoutesByTo - to: '/stream/$id' - id: '__root__' | '/stream/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - StreamIdRoute: typeof StreamIdRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/stream/$id': { - id: '/stream/$id' - path: '/stream/$id' - fullPath: '/stream/$id' - preLoaderRoute: typeof StreamIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - StreamIdRoute: StreamIdRoute, -} -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/benchmarks/ssr/scenarios/streaming/vue/src/router.tsx b/benchmarks/ssr/scenarios/streaming/vue/src/router.tsx deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/ssr/scenarios/streaming/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/scenarios/streaming/vue/src/routes/__root.tsx b/benchmarks/ssr/scenarios/streaming/vue/src/routes/__root.tsx deleted file mode 100644 index 4b03519823..0000000000 --- a/benchmarks/ssr/scenarios/streaming/vue/src/routes/__root.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import { - Body, - HeadContent, - Html, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/vue-router' - -export const Route = createRootRoute({ - component: RootComponent, - validateSearch: (s) => s as { q?: string }, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/scenarios/streaming/vue/src/routes/stream.$id.tsx b/benchmarks/ssr/scenarios/streaming/vue/src/routes/stream.$id.tsx deleted file mode 100644 index d627fa56c9..0000000000 --- a/benchmarks/ssr/scenarios/streaming/vue/src/routes/stream.$id.tsx +++ /dev/null @@ -1,56 +0,0 @@ -import { Await, createFileRoute } from '@tanstack/vue-router' -import { Suspense, defineComponent } from 'vue' -import { makeBigPayload, sleep0 } from '../../../shared-data' -import type { BigPayload, SmallPayload } from '../../../shared-data' - -const StreamComponent = defineComponent({ - setup() { - const data = Route.useLoaderData() - - return () => ( - <> -

{data.value.fast.label}

-

loading-small

- - {{ - default: () => ( -

{d.label}

} - /> - ), - fallback: () => null, - }} -
-

loading-big

- - {{ - default: () => ( - ( -
-

{d.label}

- {d.chunks.map((chunk) => ( -

{chunk.value}

- ))} -
- )} - /> - ), - fallback: () => null, - }} -
- - ) - }, -}) - -export const Route = createFileRoute('/stream/$id')({ - loader: ({ params }) => ({ - fast: { label: `fast-${params.id}` }, - slowSmall: sleep0().then(() => ({ label: `slow-small-${params.id}` })), - slowBig: sleep0().then(() => makeBigPayload(params.id)), - }), - component: StreamComponent, -}) diff --git a/benchmarks/ssr/scenarios/streaming/vue/tsconfig.json b/benchmarks/ssr/scenarios/streaming/vue/tsconfig.json deleted file mode 100644 index c302f63770..0000000000 --- a/benchmarks/ssr/scenarios/streaming/vue/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "../../../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "vite.config.ts", - "../../../bench-utils.ts", - "../shared-data.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/scenarios/streaming/vue/vite.config.ts b/benchmarks/ssr/scenarios/streaming/vue/vite.config.ts deleted file mode 100644 index a09a30076f..0000000000 --- a/benchmarks/ssr/scenarios/streaming/vue/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - execArgv: cpuSimulationExecArgv(), - isolate: true, - name: '@benchmarks/ssr streaming (vue)', - watch: false, - environment: 'node', - }, -}) diff --git a/benchmarks/ssr/solid/project.json b/benchmarks/ssr/solid/project.json deleted file mode 100644 index 0f19144d3b..0000000000 --- a/benchmarks/ssr/solid/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-solid", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/solid-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/solid/speed.bench.ts b/benchmarks/ssr/solid/speed.bench.ts deleted file mode 100644 index 2f72977612..0000000000 --- a/benchmarks/ssr/solid/speed.bench.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { test } from 'vitest' -import { runSsrRequestLoop } from '../bench-utils' -import type { StartRequestHandler } from '../bench-utils' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href -const benchmarkSeed = 0xcafebabe - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} - -test('ssr', async ({ bench }) => { - await bench('ssr request loop (solid)', async () => - runSsrRequestLoop(handler, { seed: benchmarkSeed }), - ).run({ - warmupIterations: 100, - time: 10_000, - throws: true, - }) -}) diff --git a/benchmarks/ssr/solid/src/routeTree.gen.ts b/benchmarks/ssr/solid/src/routeTree.gen.ts deleted file mode 100644 index 27cbe59476..0000000000 --- a/benchmarks/ssr/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,146 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as ARouteImport } from './routes/$a' -import { Route as ABRouteImport } from './routes/$a.$b' -import { Route as ABCRouteImport } from './routes/$a.$b.$c' -import { Route as ABCDRouteImport } from './routes/$a.$b.$c.$d' - -const ARoute = ARouteImport.update({ - id: '/$a', - path: '/$a', - getParentRoute: () => rootRouteImport, -} as any) -const ABRoute = ABRouteImport.update({ - id: '/$b', - path: '/$b', - getParentRoute: () => ARoute, -} as any) -const ABCRoute = ABCRouteImport.update({ - id: '/$c', - path: '/$c', - getParentRoute: () => ABRoute, -} as any) -const ABCDRoute = ABCDRouteImport.update({ - id: '/$d', - path: '/$d', - getParentRoute: () => ABCRoute, -} as any) - -export interface FileRoutesByFullPath { - '/$a': typeof ARouteWithChildren - '/$a/$b': typeof ABRouteWithChildren - '/$a/$b/$c': typeof ABCRouteWithChildren - '/$a/$b/$c/$d': typeof ABCDRoute -} -export interface FileRoutesByTo { - '/$a': typeof ARouteWithChildren - '/$a/$b': typeof ABRouteWithChildren - '/$a/$b/$c': typeof ABCRouteWithChildren - '/$a/$b/$c/$d': typeof ABCDRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/$a': typeof ARouteWithChildren - '/$a/$b': typeof ABRouteWithChildren - '/$a/$b/$c': typeof ABCRouteWithChildren - '/$a/$b/$c/$d': typeof ABCDRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/$a' | '/$a/$b' | '/$a/$b/$c' | '/$a/$b/$c/$d' - fileRoutesByTo: FileRoutesByTo - to: '/$a' | '/$a/$b' | '/$a/$b/$c' | '/$a/$b/$c/$d' - id: '__root__' | '/$a' | '/$a/$b' | '/$a/$b/$c' | '/$a/$b/$c/$d' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - ARoute: typeof ARouteWithChildren -} - -declare module '@tanstack/solid-router' { - interface FileRoutesByPath { - '/$a': { - id: '/$a' - path: '/$a' - fullPath: '/$a' - preLoaderRoute: typeof ARouteImport - parentRoute: typeof rootRouteImport - } - '/$a/$b': { - id: '/$a/$b' - path: '/$b' - fullPath: '/$a/$b' - preLoaderRoute: typeof ABRouteImport - parentRoute: typeof ARoute - } - '/$a/$b/$c': { - id: '/$a/$b/$c' - path: '/$c' - fullPath: '/$a/$b/$c' - preLoaderRoute: typeof ABCRouteImport - parentRoute: typeof ABRoute - } - '/$a/$b/$c/$d': { - id: '/$a/$b/$c/$d' - path: '/$d' - fullPath: '/$a/$b/$c/$d' - preLoaderRoute: typeof ABCDRouteImport - parentRoute: typeof ABCRoute - } - } -} - -interface ABCRouteChildren { - ABCDRoute: typeof ABCDRoute -} - -const ABCRouteChildren: ABCRouteChildren = { - ABCDRoute: ABCDRoute, -} - -const ABCRouteWithChildren = ABCRoute._addFileChildren(ABCRouteChildren) - -interface ABRouteChildren { - ABCRoute: typeof ABCRouteWithChildren -} - -const ABRouteChildren: ABRouteChildren = { - ABCRoute: ABCRouteWithChildren, -} - -const ABRouteWithChildren = ABRoute._addFileChildren(ABRouteChildren) - -interface ARouteChildren { - ABRoute: typeof ABRouteWithChildren -} - -const ARouteChildren: ARouteChildren = { - ABRoute: ABRouteWithChildren, -} - -const ARouteWithChildren = ARoute._addFileChildren(ARouteChildren) - -const rootRouteChildren: RootRouteChildren = { - ARoute: ARouteWithChildren, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/solid-start' -declare module '@tanstack/solid-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/benchmarks/ssr/solid/src/router.tsx b/benchmarks/ssr/solid/src/router.tsx deleted file mode 100644 index 038ec0ab5e..0000000000 --- a/benchmarks/ssr/solid/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/solid-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/solid/src/routes/$a.$b.$c.$d.tsx b/benchmarks/ssr/solid/src/routes/$a.$b.$c.$d.tsx deleted file mode 100644 index 9bab038f37..0000000000 --- a/benchmarks/ssr/solid/src/routes/$a.$b.$c.$d.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { RouteWorkload } from '../workload' - -export const Route = createFileRoute('/$a/$b/$c/$d')({ - component: LevelDComponent, -}) - -function LevelDComponent() { - return -} diff --git a/benchmarks/ssr/solid/src/routes/$a.$b.$c.tsx b/benchmarks/ssr/solid/src/routes/$a.$b.$c.tsx deleted file mode 100644 index e10b9da6df..0000000000 --- a/benchmarks/ssr/solid/src/routes/$a.$b.$c.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' -import { RouteWorkload } from '../workload' - -export const Route = createFileRoute('/$a/$b/$c')({ - component: LevelCComponent, -}) - -function LevelCComponent() { - return ( - <> - - - - ) -} diff --git a/benchmarks/ssr/solid/src/routes/$a.$b.tsx b/benchmarks/ssr/solid/src/routes/$a.$b.tsx deleted file mode 100644 index cd2d0e9754..0000000000 --- a/benchmarks/ssr/solid/src/routes/$a.$b.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' -import { RouteWorkload } from '../workload' - -export const Route = createFileRoute('/$a/$b')({ - component: LevelBComponent, -}) - -function LevelBComponent() { - return ( - <> - - - - ) -} diff --git a/benchmarks/ssr/solid/src/routes/$a.tsx b/benchmarks/ssr/solid/src/routes/$a.tsx deleted file mode 100644 index a2f0200882..0000000000 --- a/benchmarks/ssr/solid/src/routes/$a.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/solid-router' -import { RouteWorkload } from '../workload' - -export const Route = createFileRoute('/$a')({ - component: LevelAComponent, -}) - -function LevelAComponent() { - return ( - <> - - - - ) -} diff --git a/benchmarks/ssr/solid/src/routes/__root.tsx b/benchmarks/ssr/solid/src/routes/__root.tsx deleted file mode 100644 index 15de858e78..0000000000 --- a/benchmarks/ssr/solid/src/routes/__root.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/solid-router' - -export const Route = createRootRoute({ - component: RootComponent, - validateSearch: (s) => s as { q?: string }, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/solid/src/workload.tsx b/benchmarks/ssr/solid/src/workload.tsx deleted file mode 100644 index 76fcae555a..0000000000 --- a/benchmarks/ssr/solid/src/workload.tsx +++ /dev/null @@ -1,81 +0,0 @@ -import { For, createEffect } from 'solid-js' -import { Link, useParams, useSearch } from '@tanstack/solid-router' - -const probes = Array.from({ length: 10 }, (_, index) => index) - -function runSelectorWork(input: string, salt: number) { - let value = salt - - for (let index = 0; index < input.length; index++) { - value = (value * 33 + input.charCodeAt(index) + index) >>> 0 - } - - for (let index = 0; index < 16; index++) { - value = (value ^ (value << 13)) >>> 0 - value = (value ^ (value >> 17)) >>> 0 - value = (value ^ (value << 5)) >>> 0 - } - - return value -} - -function ParamsProbe(props: { salt: number }) { - const params = useParams({ - strict: false, - select: (nextParams) => - runSelectorWork( - `${nextParams.a ?? ''}/${nextParams.b ?? ''}/${nextParams.c ?? ''}/${nextParams.d ?? ''}`, - props.salt, - ), - }) - - createEffect(() => { - void params() - }) - - return null -} - -function SearchProbe(props: { salt: number }) { - const search = useSearch({ - strict: false, - select: (nextSearch) => - runSelectorWork(String(nextSearch.q ?? ''), props.salt), - }) - - createEffect(() => { - void search() - }) - - return null -} - -function LinkProbe(props: { salt: number }) { - const value = String((props.salt % 97) + 1) - - return ( - - Link - - ) -} - -export function RouteWorkload() { - return ( - <> - {(probe) => } - {(probe) => } - {(probe) => } - - ) -} diff --git a/benchmarks/ssr/solid/tsconfig.json b/benchmarks/ssr/solid/tsconfig.json deleted file mode 100644 index 6c87e995c7..0000000000 --- a/benchmarks/ssr/solid/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "solid-js", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "vite.config.ts", - "../bench-utils.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/solid/vite.config.ts b/benchmarks/ssr/solid/vite.config.ts deleted file mode 100644 index dfd82d9192..0000000000 --- a/benchmarks/ssr/solid/vite.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - solid({ ssr: true, hot: false, dev: false }), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - }, - test: { - execArgv: cpuSimulationExecArgv(), - isolate: true, - name: '@benchmarks/ssr (solid)', - watch: false, - environment: 'node', - server: { - deps: { - inline: [/@solidjs/, /@tanstack\/solid-store/], - }, - }, - }, -}) diff --git a/benchmarks/ssr/tsconfig.json b/benchmarks/ssr/tsconfig.json deleted file mode 100644 index 7279177023..0000000000 --- a/benchmarks/ssr/tsconfig.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "extends": "../../tsconfig.json", - "compilerOptions": { - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "bench-utils.ts", - "bench-utils.test.ts", - "scenarios/streaming/shared-data.ts", - "vitest.unit.config.ts" - ] -} diff --git a/benchmarks/ssr/vitest.config.ts b/benchmarks/ssr/vitest.config.ts deleted file mode 100644 index a91eae4967..0000000000 --- a/benchmarks/ssr/vitest.config.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { defineConfig } from 'vitest/config' - -export default defineConfig({ - test: { - watch: false, - projects: [ - './react/vite.config.ts', - './solid/vite.config.ts', - './vue/vite.config.ts', - './scenarios/*/*/vite.config.ts', - ], - }, -}) diff --git a/benchmarks/ssr/vitest.react.config.ts b/benchmarks/ssr/vitest.react.config.ts deleted file mode 100644 index a397ad929e..0000000000 --- a/benchmarks/ssr/vitest.react.config.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { defineConfig } from 'vitest/config' - -export default defineConfig({ - test: { - watch: false, - projects: ['./react/vite.config.ts', './scenarios/*/react/vite.config.ts'], - }, -}) diff --git a/benchmarks/ssr/vitest.solid.config.ts b/benchmarks/ssr/vitest.solid.config.ts deleted file mode 100644 index b8827b86aa..0000000000 --- a/benchmarks/ssr/vitest.solid.config.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { defineConfig } from 'vitest/config' - -export default defineConfig({ - test: { - watch: false, - projects: ['./solid/vite.config.ts', './scenarios/*/solid/vite.config.ts'], - }, -}) diff --git a/benchmarks/ssr/vitest.unit.config.ts b/benchmarks/ssr/vitest.unit.config.ts deleted file mode 100644 index cbba6db9ef..0000000000 --- a/benchmarks/ssr/vitest.unit.config.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { defineConfig } from 'vitest/config' - -export default defineConfig({ - test: { - name: '@benchmarks/ssr unit', - environment: 'node', - include: ['bench-utils.test.ts'], - }, -}) diff --git a/benchmarks/ssr/vitest.vue.config.ts b/benchmarks/ssr/vitest.vue.config.ts deleted file mode 100644 index 17960d7569..0000000000 --- a/benchmarks/ssr/vitest.vue.config.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { defineConfig } from 'vitest/config' - -export default defineConfig({ - test: { - watch: false, - projects: ['./vue/vite.config.ts', './scenarios/*/vue/vite.config.ts'], - }, -}) diff --git a/benchmarks/ssr/vue/project.json b/benchmarks/ssr/vue/project.json deleted file mode 100644 index 930d6c2e22..0000000000 --- a/benchmarks/ssr/vue/project.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@benchmarks/ssr-vue", - "projectType": "application", - "targets": { - "build:ssr": { - "executor": "nx:run-commands", - "cache": false, - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" - } - }, - "test:types:ssr": { - "executor": "nx:run-commands", - "dependsOn": [ - { - "projects": ["@tanstack/vue-start"], - "target": "build" - } - ], - "options": { - "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" - } - } - } -} diff --git a/benchmarks/ssr/vue/speed.bench.ts b/benchmarks/ssr/vue/speed.bench.ts deleted file mode 100644 index 57b59e0504..0000000000 --- a/benchmarks/ssr/vue/speed.bench.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { test } from 'vitest' -import { runSsrRequestLoop } from '../bench-utils' -import type { StartRequestHandler } from '../bench-utils' - -const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href -const benchmarkSeed = 0xdeadbeef - -const { default: handler } = (await import( - /* @vite-ignore */ appModuleUrl -)) as { - default: StartRequestHandler -} - -test('ssr', async ({ bench }) => { - await bench('ssr request loop (vue)', async () => - runSsrRequestLoop(handler, { seed: benchmarkSeed }), - ).run({ - warmupIterations: 100, - time: 10_000, - throws: true, - }) -}) diff --git a/benchmarks/ssr/vue/src/routeTree.gen.ts b/benchmarks/ssr/vue/src/routeTree.gen.ts deleted file mode 100644 index a6dfb5853e..0000000000 --- a/benchmarks/ssr/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,146 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as ARouteImport } from './routes/$a' -import { Route as ABRouteImport } from './routes/$a.$b' -import { Route as ABCRouteImport } from './routes/$a.$b.$c' -import { Route as ABCDRouteImport } from './routes/$a.$b.$c.$d' - -const ARoute = ARouteImport.update({ - id: '/$a', - path: '/$a', - getParentRoute: () => rootRouteImport, -} as any) -const ABRoute = ABRouteImport.update({ - id: '/$b', - path: '/$b', - getParentRoute: () => ARoute, -} as any) -const ABCRoute = ABCRouteImport.update({ - id: '/$c', - path: '/$c', - getParentRoute: () => ABRoute, -} as any) -const ABCDRoute = ABCDRouteImport.update({ - id: '/$d', - path: '/$d', - getParentRoute: () => ABCRoute, -} as any) - -export interface FileRoutesByFullPath { - '/$a': typeof ARouteWithChildren - '/$a/$b': typeof ABRouteWithChildren - '/$a/$b/$c': typeof ABCRouteWithChildren - '/$a/$b/$c/$d': typeof ABCDRoute -} -export interface FileRoutesByTo { - '/$a': typeof ARouteWithChildren - '/$a/$b': typeof ABRouteWithChildren - '/$a/$b/$c': typeof ABCRouteWithChildren - '/$a/$b/$c/$d': typeof ABCDRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/$a': typeof ARouteWithChildren - '/$a/$b': typeof ABRouteWithChildren - '/$a/$b/$c': typeof ABCRouteWithChildren - '/$a/$b/$c/$d': typeof ABCDRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/$a' | '/$a/$b' | '/$a/$b/$c' | '/$a/$b/$c/$d' - fileRoutesByTo: FileRoutesByTo - to: '/$a' | '/$a/$b' | '/$a/$b/$c' | '/$a/$b/$c/$d' - id: '__root__' | '/$a' | '/$a/$b' | '/$a/$b/$c' | '/$a/$b/$c/$d' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - ARoute: typeof ARouteWithChildren -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/$a': { - id: '/$a' - path: '/$a' - fullPath: '/$a' - preLoaderRoute: typeof ARouteImport - parentRoute: typeof rootRouteImport - } - '/$a/$b': { - id: '/$a/$b' - path: '/$b' - fullPath: '/$a/$b' - preLoaderRoute: typeof ABRouteImport - parentRoute: typeof ARoute - } - '/$a/$b/$c': { - id: '/$a/$b/$c' - path: '/$c' - fullPath: '/$a/$b/$c' - preLoaderRoute: typeof ABCRouteImport - parentRoute: typeof ABRoute - } - '/$a/$b/$c/$d': { - id: '/$a/$b/$c/$d' - path: '/$d' - fullPath: '/$a/$b/$c/$d' - preLoaderRoute: typeof ABCDRouteImport - parentRoute: typeof ABCRoute - } - } -} - -interface ABCRouteChildren { - ABCDRoute: typeof ABCDRoute -} - -const ABCRouteChildren: ABCRouteChildren = { - ABCDRoute: ABCDRoute, -} - -const ABCRouteWithChildren = ABCRoute._addFileChildren(ABCRouteChildren) - -interface ABRouteChildren { - ABCRoute: typeof ABCRouteWithChildren -} - -const ABRouteChildren: ABRouteChildren = { - ABCRoute: ABCRouteWithChildren, -} - -const ABRouteWithChildren = ABRoute._addFileChildren(ABRouteChildren) - -interface ARouteChildren { - ABRoute: typeof ABRouteWithChildren -} - -const ARouteChildren: ARouteChildren = { - ABRoute: ABRouteWithChildren, -} - -const ARouteWithChildren = ARoute._addFileChildren(ARouteChildren) - -const rootRouteChildren: RootRouteChildren = { - ARoute: ARouteWithChildren, -} -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/benchmarks/ssr/vue/src/router.tsx b/benchmarks/ssr/vue/src/router.tsx deleted file mode 100644 index 4290e7cdd3..0000000000 --- a/benchmarks/ssr/vue/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - defaultPreload: false, - scrollRestoration: false, - }) -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} diff --git a/benchmarks/ssr/vue/src/routes/$a.$b.$c.$d.tsx b/benchmarks/ssr/vue/src/routes/$a.$b.$c.$d.tsx deleted file mode 100644 index 36c2896840..0000000000 --- a/benchmarks/ssr/vue/src/routes/$a.$b.$c.$d.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' -import { RouteWorkload } from '../workload' - -export const Route = createFileRoute('/$a/$b/$c/$d')({ - component: LevelDComponent, -}) - -function LevelDComponent() { - return -} diff --git a/benchmarks/ssr/vue/src/routes/$a.$b.$c.tsx b/benchmarks/ssr/vue/src/routes/$a.$b.$c.tsx deleted file mode 100644 index 3249876970..0000000000 --- a/benchmarks/ssr/vue/src/routes/$a.$b.$c.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/vue-router' -import { RouteWorkload } from '../workload' - -export const Route = createFileRoute('/$a/$b/$c')({ - component: LevelCComponent, -}) - -function LevelCComponent() { - return ( - <> - - - - ) -} diff --git a/benchmarks/ssr/vue/src/routes/$a.$b.tsx b/benchmarks/ssr/vue/src/routes/$a.$b.tsx deleted file mode 100644 index fe50f88736..0000000000 --- a/benchmarks/ssr/vue/src/routes/$a.$b.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/vue-router' -import { RouteWorkload } from '../workload' - -export const Route = createFileRoute('/$a/$b')({ - component: LevelBComponent, -}) - -function LevelBComponent() { - return ( - <> - - - - ) -} diff --git a/benchmarks/ssr/vue/src/routes/$a.tsx b/benchmarks/ssr/vue/src/routes/$a.tsx deleted file mode 100644 index 51310ce063..0000000000 --- a/benchmarks/ssr/vue/src/routes/$a.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/vue-router' -import { RouteWorkload } from '../workload' - -export const Route = createFileRoute('/$a')({ - component: LevelAComponent, -}) - -function LevelAComponent() { - return ( - <> - - - - ) -} diff --git a/benchmarks/ssr/vue/src/routes/__root.tsx b/benchmarks/ssr/vue/src/routes/__root.tsx deleted file mode 100644 index 4b03519823..0000000000 --- a/benchmarks/ssr/vue/src/routes/__root.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import { - Body, - HeadContent, - Html, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/vue-router' - -export const Route = createRootRoute({ - component: RootComponent, - validateSearch: (s) => s as { q?: string }, -}) - -function RootComponent() { - return ( - - - - - - - - - - ) -} diff --git a/benchmarks/ssr/vue/src/workload.tsx b/benchmarks/ssr/vue/src/workload.tsx deleted file mode 100644 index 3266aff694..0000000000 --- a/benchmarks/ssr/vue/src/workload.tsx +++ /dev/null @@ -1,111 +0,0 @@ -import * as Vue from 'vue' -import { Link, useParams, useSearch } from '@tanstack/vue-router' - -const probes = Array.from({ length: 10 }, (_, index) => index) - -function runSelectorWork(input: string, salt: number) { - let value = salt - - for (let index = 0; index < input.length; index++) { - value = (value * 33 + input.charCodeAt(index) + index) >>> 0 - } - - for (let index = 0; index < 16; index++) { - value = (value ^ (value << 13)) >>> 0 - value = (value ^ (value >> 17)) >>> 0 - value = (value ^ (value << 5)) >>> 0 - } - - return value -} - -const ParamsProbe = Vue.defineComponent({ - props: { - salt: { - type: Number, - required: true, - }, - }, - setup(props) { - const params = useParams({ - strict: false, - select: (nextParams) => - runSelectorWork( - `${nextParams.a ?? ''}/${nextParams.b ?? ''}/${nextParams.c ?? ''}/${nextParams.d ?? ''}`, - props.salt, - ), - }) - - return () => { - void params.value - return null - } - }, -}) - -const SearchProbe = Vue.defineComponent({ - props: { - salt: { - type: Number, - required: true, - }, - }, - setup(props) { - const search = useSearch({ - strict: false, - select: (nextSearch) => - runSelectorWork(String(nextSearch.q ?? ''), props.salt), - }) - - return () => { - void search.value - return null - } - }, -}) - -const LinkProbe = Vue.defineComponent({ - props: { - salt: { - type: Number, - required: true, - }, - }, - setup(props) { - const value = String((props.salt % 97) + 1) - - return () => ( - - Link - - ) - }, -}) - -export const RouteWorkload = Vue.defineComponent({ - setup() { - return () => ( - <> - {probes.map((probe) => ( - - ))} - {probes.map((probe) => ( - - ))} - {probes.map((probe) => ( - - ))} - - ) - }, -}) diff --git a/benchmarks/ssr/vue/tsconfig.json b/benchmarks/ssr/vue/tsconfig.json deleted file mode 100644 index 1895164239..0000000000 --- a/benchmarks/ssr/vue/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "../../../tsconfig.json", - "compilerOptions": { - "jsx": "preserve", - "jsxImportSource": "vue", - "types": ["node", "vite/client", "vitest/globals"] - }, - "include": [ - "speed.bench.ts", - "vite.config.ts", - "../bench-utils.ts", - "./src/**/*" - ] -} diff --git a/benchmarks/ssr/vue/vite.config.ts b/benchmarks/ssr/vue/vite.config.ts deleted file mode 100644 index b2b9fc8a09..0000000000 --- a/benchmarks/ssr/vue/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { fileURLToPath } from 'node:url' -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)) - -export default defineConfig({ - root: rootDir, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackStart({ - srcDirectory: 'src', - }), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - 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 deleted file mode 100644 index 5e9ff9a8e1..0000000000 --- a/benchmarks/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "../tsconfig.json", - "compilerOptions": { - "types": ["node"] - }, - "include": ["cpu-simulation.ts"] -} diff --git a/docs/AGENTS.md b/docs/AGENTS.md deleted file mode 100644 index ab2d4117e2..0000000000 --- a/docs/AGENTS.md +++ /dev/null @@ -1,4 +0,0 @@ -# Documentation - -- Register new published pages in `router/config.json` or `start/config.json`; drafts need not be registered. -- Run `pnpm test:docs` from the repository root for Markdown link validation. It checks `docs/**/*.md`, not Markdown elsewhere. Relative links resolve from the containing file. diff --git a/docs/router/api/file-based-routing.md b/docs/router/api/file-based-routing.md index 7c94d484d1..7de532e72f 100644 --- a/docs/router/api/file-based-routing.md +++ b/docs/router/api/file-based-routing.md @@ -188,7 +188,7 @@ By default, this value is set to `false`. ### `autoCodeSplitting` -This feature is only available if you are using the TanStack Router Bundler Plugin with Vite, Rspack/Rsbuild or Webpack. With Esbuild, setting it to `true` is an error. +This feature is only available if you are using the TanStack Router Bundler Plugin. This option is used to enable automatic code-splitting for non-critical route configuration items. See the "Automatic Code-Splitting" guide for more information. @@ -207,23 +207,9 @@ By default, this value is set to `false`. ### `addExtensions` -- Type: `boolean | string` -- Default: `false` +This option adds file extensions to the route names in the generated route tree. -This option controls file extensions on import paths in the generated route tree. - -- `false` — Extensions are stripped from import paths (e.g. `'./routes/posts'`) -- `true` — The original file extensions are kept (e.g. `'./routes/posts.tsx'`) -- `string` — The original extension is replaced with the provided one (e.g. `'js'` produces `'./routes/posts.js'`) - -Passing a string is useful when your project uses ESM, since Node.js ESM requires `.js` extensions for imports even when the source files are `.ts` or `.tsx`. - -```ts -// Example: replace .tsx/.ts extensions with .js in generated imports -TanStackRouterVite({ - addExtensions: 'js', -}) -``` +By default, this value is set to `false`. ### `disableLogging` diff --git a/docs/router/api/router/LinkOptionsType.md b/docs/router/api/router/LinkOptionsType.md index 9d3d3fe8d8..481a5b4a3d 100644 --- a/docs/router/api/router/LinkOptionsType.md +++ b/docs/router/api/router/LinkOptionsType.md @@ -9,7 +9,7 @@ The `LinkOptions` type extends the [`NavigateOptions`](./NavigateOptionsType.md) type LinkOptions = NavigateOptions & { target?: HTMLAnchorElement['target'] activeOptions?: ActiveOptions - preload?: false | 'intent' | 'viewport' | 'render' + preload?: false | 'intent' preloadDelay?: number disabled?: boolean } @@ -42,7 +42,7 @@ The `LinkOptions` object accepts/contains the following properties: - Type: `number` - Optional -- Delay focus, hover, and viewport preloading by this many milliseconds. Touch intent preloads immediately. If focus or hover ends, or the link leaves the viewport before the delay, the preload will be cancelled. +- Delay intent preloading by this many milliseconds. If the intent exits before this delay, the preload will be cancelled. ### `disabled` diff --git a/docs/router/api/router/NotFoundErrorType.md b/docs/router/api/router/NotFoundErrorType.md index 1f4fbe4c74..6d8b00a84b 100644 --- a/docs/router/api/router/NotFoundErrorType.md +++ b/docs/router/api/router/NotFoundErrorType.md @@ -29,7 +29,7 @@ The `NotFoundError` object accepts/contains the following properties: - Type: `any` - Optional -- Custom data that is passed into `notFoundComponent` when the not-found error is handled +- Custom data that is passed into to `notFoundComponent` when the not-found error is handled ### `throw` property diff --git a/docs/router/api/router/RouteMatchType.md b/docs/router/api/router/RouteMatchType.md index b5009ebe68..251c2c031e 100644 --- a/docs/router/api/router/RouteMatchType.md +++ b/docs/router/api/router/RouteMatchType.md @@ -11,8 +11,9 @@ interface RouteMatch { routeId: string pathname: string params: Route['allParams'] - status: 'pending' | 'success' | 'error' | 'notFound' + status: 'pending' | 'success' | 'error' | 'redirected' | 'notFound' isFetching: false | 'beforeLoad' | 'loader' + showPending: boolean error: unknown paramsError: unknown searchError: unknown @@ -20,17 +21,9 @@ interface RouteMatch { loaderData?: Route['loaderData'] context: Route['allContext'] search: Route['fullSearchSchema'] + fetchedAt: number abortController: AbortController - cause: 'preload' | 'enter' | 'stay' + cause: 'enter' | 'stay' ssr?: boolean | 'data-only' } ``` - -`status` describes the match's render state. `isFetching` independently exposes -active `beforeLoad` or loader work. In particular, a successful match can report -`isFetching: 'loader'` while stale data remains visible during a background -reload. - -The router state can contain matches below the pending, error, or not-found -boundary. Those matches remain observable as part of the structurally matched -lane even though the route renderer stops at the boundary. diff --git a/docs/router/api/router/RouteOptionsType.md b/docs/router/api/router/RouteOptionsType.md index 2adfc6e5c6..215e21c9ef 100644 --- a/docs/router/api/router/RouteOptionsType.md +++ b/docs/router/api/router/RouteOptionsType.md @@ -56,7 +56,6 @@ The `RouteOptions` type accepts an object with the following properties: - Type: `(rawSearchParams: unknown) => TSearchSchema` - Optional - A function that will be called when this route is matched and passed the raw search params from the current location and return valid parsed search params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function does not throw, its return value will be used as the route's search params and the return type will be inferred into the rest of the router. -- This is a planning callback. It must be deterministic and side-effect-free for the same input; do not navigate or mutate application/router state from it. - Optionally, the parameter type can be tagged with the `SearchSchemaInput` type like this: `(searchParams: TSearchSchemaInput & SearchSchemaInput) => TSearchSchema`. If this tag is present, `TSearchSchemaInput` will be used to type the `search` property of `` and `navigate()` **instead of** `TSearchSchema`. The difference between `TSearchSchemaInput` and `TSearchSchema` can be useful, for example, to express optional search parameters. ### `search.middlewares` property @@ -71,7 +70,6 @@ The `RouteOptions` type accepts an object with the following properties: - Type: `(rawParams: Record) => TParams` - Optional - A function that will be called when this route is matched and passed the raw params from the current location and return valid parsed params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function does not throw, its return value will be used as the route's params and the return type will be inferred into the rest of the router. -- This is a planning callback. It must be deterministic and side-effect-free for the same input. ### `stringifyParams` method (⚠️ deprecated, use `params.stringify` instead) @@ -81,19 +79,9 @@ The `RouteOptions` type accepts an object with the following properties: ### `params.parse` method -- Type: `(rawParams: Record) => TParams | false` +- Type: `(rawParams: Record) => TParams` - Optional -- A function that will be called when this route is matched and passed the raw params from the current location and return valid parsed params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function returns parsed params, its return value will be used as the route's params and the return type will be inferred into the rest of the router. -- This is a planning callback. It must be deterministic and side-effect-free for the same input. -- Experimental: returning `false` during incoming route matching skips this route and allows matching to continue to another candidate route. - -### `params.priority` property - -- Type: `number` -- Optional -- Defaults to `0` -- Controls the matching order when multiple route candidates with `params.parse` can match the same URL segment. Higher numbers are tried first. If a higher-priority route's `params.parse` returns `false`, matching continues to the next candidate. -- This only affects competing candidates that use `params.parse`; normal route specificity still applies, so static routes continue to match before dynamic, optional, or wildcard routes. +- A function that will be called when this route is matched and passed the raw params from the current location and return valid parsed params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function does not throw, its return value will be used as the route's params and the return type will be inferred into the rest of the router. ### `params.stringify` method @@ -115,14 +103,14 @@ type beforeLoad = ( location: ParsedLocation navigate: NavigateFn // @deprecated buildLocation: BuildLocationFn - cause: 'preload' | 'enter' | 'stay' + cause: 'enter' | 'stay' }, ) => Promise | TRouteContext | void ``` - Optional - [`ParsedLocation`](./ParsedLocationType.md) -- This async function is called before a route is loaded. If it fails, the route's loader and its descendants will not run. During navigation, ordinary errors become the match's error state and are passed to the `onError` function. During a preload, ordinary errors and not-found results are represented in the returned speculative match lane instead of rejecting the `preloadRoute` promise. +- This async function is called before a route is loaded. If an error is thrown here, the route's loader will not be called and the route will not render. If thrown during a navigation, the navigation will be canceled and the error will be passed to the `onError` function. If thrown during a preload event, the error will be logged to the console and the preload will fail. - If this function returns a promise, the route will be put into a pending state and cause rendering to suspend until the promise resolves. If this route's pendingMs threshold is reached, the `pendingComponent` will be shown until it resolves. If the promise rejects, the route will be put into an error state and the error will be thrown during render. - If this function returns a `TRouteContext` object, that object will be merged into the route's context and be made available in the `loader` and other related route components/methods. - It's common to use this function to check if a user is authenticated and redirect them to a login page if they are not. To do this, you can either return or throw a `redirect` object from this function. @@ -134,7 +122,7 @@ type beforeLoad = ( - Type: ```tsx -type loaderFn = ( +type loader = ( opts: RouteMatch & { abortController: AbortController cause: 'preload' | 'enter' | 'stay' @@ -148,24 +136,14 @@ type loaderFn = ( route: AnyRoute }, ) => Promise | TLoaderData | void - -type loader = - | loaderFn - | { - handler: loaderFn - staleReloadMode?: 'background' | 'blocking' - } ``` - Optional - [`ParsedLocation`](./ParsedLocationType.md) -- This async function is called when a route is matched and passed the route's match object. During navigation, ordinary errors become the match's error state and are passed to the `onError` function. During a preload, ordinary errors and not-found results are represented in the returned speculative match lane instead of rejecting the `preloadRoute` promise. +- This async function is called when a route is matched and passed the route's match object. If an error is thrown here, the route will be put into an error state and the error will be thrown during render. If thrown during a navigation, the navigation will be canceled and the error will be passed to the `onError` function. If thrown during a preload event, the error will be logged to the console and the preload will fail. - If this function returns a promise, the route will be put into a pending state and cause rendering to suspend until the promise resolves. If this route's pendingMs threshold is reached, the `pendingComponent` will be shown until it resolves. If the promise rejects, the route will be put into an error state and the error will be thrown during render. -- If this function returns a `TLoaderData` object, that object will be stored on the route match and can remain available in the in-memory cache after the match becomes inactive. Navigation-owned data uses `gcTime` for retention, while preload-owned data uses `preloadGcTime`. It can be accessed using the `useLoaderData` hook in any component that is a child of the route match before another `` is rendered. +- If this function returns a `TLoaderData` object, that object will be stored on the route match until the route match is no longer active. It can be accessed using the `useLoaderData` hook in any component that is a child of the route match before another `` is rendered. - Deps must be returned by your `loaderDeps` function in order to appear. -- Use the object form to configure loader-specific behavior like `staleReloadMode`. -- `staleReloadMode: 'background'` preserves stale-while-revalidate behavior for stale successful matches. -- `staleReloadMode: 'blocking'` waits for the stale loader reload to complete before continuing. > 🚧 `opts.navigate` has been deprecated and will be removed in the next major release. Use `throw redirect({ to: '/somewhere' })` instead. Read more about the `redirect` function [here](./redirectFunction.md). @@ -179,7 +157,6 @@ type loaderDeps = (opts: { search: TFullSearchSchema }) => Record - Optional - A function that will be called before this route is matched to provide additional unique identification to the route match and serve as a dependency tracker for when the match should be reloaded. It should return any serializable value that can uniquely identify the route match from navigation to navigation. -- This is a planning callback and cache-key function. It must be deterministic and side-effect-free for the same validated search input. The returned value and any serialization methods on it, such as `toJSON`, must also be side-effect-free. - By default, path params are already used to uniquely identify a route match, so it's unnecessary to return these here. - If your route match relies on search params for unique identification, it's required that you return them here so they can be made available in the `loader`'s `deps` argument. @@ -190,26 +167,19 @@ type loaderDeps = (opts: { search: TFullSearchSchema }) => Record - Defaults to `routerOptions.defaultStaleTime`, which defaults to `0` - The amount of time in milliseconds that a route match's loader data will be considered fresh. If a route match is matched again within this time frame, its loader data will not be reloaded. -### `preload` property - -- Type: `boolean` -- Optional -- Defaults to `true` -- If `false`, speculative preloads still run this route's `beforeLoad` function but skip its `loader`. A navigation runs both `beforeLoad` and the skipped `loader` normally. - ### `preloadStaleTime` property - Type: `number` - Optional - Defaults to `routerOptions.defaultPreloadStaleTime`, which defaults to `30_000` ms (30 seconds) -- The amount of time in milliseconds that loader data produced by a preload is considered fresh. Another preload or the first navigation can reuse it within this interval. After navigation accepts the generation, subsequent freshness uses `staleTime`. +- The amount of time in milliseconds that a route match's loader data will be considered fresh when preloading. If a route match is preloaded again within this time frame, its loader data will not be reloaded. If a route match is loaded (for navigation) within this time frame, the normal `staleTime` is used instead. ### `gcTime` property - Type: `number` - Optional -- Defaults to `routerOptions.defaultGcTime`, which defaults to 5 minutes. -- The retention window in milliseconds for unused loader data from an ordinary load. Once the data is older than this value, it is eligible for pruning during a later cache reconciliation. +- Defaults to `routerOptions.defaultGcTime`, which defaults to 30 minutes. +- The amount of time in milliseconds that a route match's loader data will be kept in memory after a preload or it is no longer in use. ### `shouldReload` property @@ -245,12 +215,12 @@ type loaderDeps = (opts: { search: TFullSearchSchema }) => Record - Defaults to `routerOptions.defaultPendingMinMs` which defaults to `500` - The minimum amount of time in milliseconds that the pending component will be shown for if it is shown. This is useful to prevent the pending component from flashing on the screen for a split second. -### `preloadGcTime` property +### `preloadMaxAge` property - Type: `number` - Optional -- Defaults to `routerOptions.defaultPreloadGcTime`, which defaults to 5 minutes. -- The retention window in milliseconds for unused loader data produced by a preload. Once the data is older than this value, it is eligible for pruning during a later cache reconciliation. Use `preloadStaleTime` to control whether retained data is fresh enough to reuse without reloading. +- Defaults to `30_000` ms (30 seconds) +- The maximum amount of time in milliseconds that a route's preloaded route data will be cached for. If a route is not matched within this time frame, its loader data will be discarded. ### `preSearchFilters` property (⚠️ deprecated, use `search.middlewares` instead) @@ -273,33 +243,29 @@ type loaderDeps = (opts: { search: TFullSearchSchema }) => Record - Type: `(error: any) => void` - Optional - A function that will be called when an error is thrown during a navigation or preload event. -- If this function throws a [`redirect`](./redirectFunction.md), the redirect replaces the original error and becomes control flow for the current navigation or preload operation. If it throws a not-found result, that result replaces the original error in the current match lane. +- If this function throws a [`redirect`](./redirectFunction.md), then the router will process and apply the redirect immediately. ### `onEnter` property - 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: unknown) => void` in React and Vue; `(error: Error) => void` in Solid +- Type: `(error: Error, errorInfo: ErrorInfo) => void` - 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 c27887fba1..45d6431cdf 100644 --- a/docs/router/api/router/RouterEventsType.md +++ b/docs/router/api/router/RouterEventsType.md @@ -13,7 +13,6 @@ type RouterEvents = { toLocation: ParsedLocation pathChanged: boolean hrefChanged: boolean - hashChanged: boolean } onBeforeLoad: { type: 'onBeforeLoad' @@ -21,7 +20,6 @@ type RouterEvents = { toLocation: ParsedLocation pathChanged: boolean hrefChanged: boolean - hashChanged: boolean } onLoad: { type: 'onLoad' @@ -29,7 +27,6 @@ type RouterEvents = { toLocation: ParsedLocation pathChanged: boolean hrefChanged: boolean - hashChanged: boolean } onResolved: { type: 'onResolved' @@ -37,7 +34,6 @@ type RouterEvents = { toLocation: ParsedLocation pathChanged: boolean hrefChanged: boolean - hashChanged: boolean } onBeforeRouteMount: { type: 'onBeforeRouteMount' @@ -45,15 +41,14 @@ type RouterEvents = { toLocation: ParsedLocation pathChanged: boolean hrefChanged: boolean - hashChanged: boolean + } + onInjectedHtml: { + type: 'onInjectedHtml' } onRendered: { type: 'onRendered' fromLocation?: ParsedLocation toLocation: ParsedLocation - pathChanged: boolean - hrefChanged: boolean - hashChanged: boolean } } ``` @@ -64,7 +59,7 @@ Once an event is emitted, the following properties will be present on the event ### `type` property -- Type: `onBeforeNavigate | onBeforeLoad | onLoad | onBeforeRouteMount | onResolved | onRendered` +- Type: `onBeforeNavigate | onBeforeLoad | onLoad | onBeforeRouteMount | onResolved` - The type of the event - This is useful for discriminating between events in a listener function. @@ -88,11 +83,6 @@ Once an event is emitted, the following properties will be present on the event - Type: `boolean` - `true` if the href has changed between the `fromLocation` and `toLocation`. -### `hashChanged` property - -- Type: `boolean` -- `true` if the hash has changed between the `fromLocation` and `toLocation`. - ## Example ```tsx diff --git a/docs/router/api/router/RouterOptionsType.md b/docs/router/api/router/RouterOptionsType.md index 31f410b208..49ff706d2b 100644 --- a/docs/router/api/router/RouterOptionsType.md +++ b/docs/router/api/router/RouterOptionsType.md @@ -59,7 +59,7 @@ The `RouterOptions` type accepts an object with the following properties and met - Type: `number` - Optional - Defaults to `50` -- The delay in milliseconds before intent focus/hover and viewport preloading. Touch intent preloads immediately. +- The delay in milliseconds that a route must be hovered over or touched before it is preloaded. ### `defaultComponent` property @@ -109,15 +109,6 @@ The `RouterOptions` type accepts an object with the following properties and met - Defaults to `0` - The default `staleTime` a route should use if no staleTime is provided. -### `defaultStaleReloadMode` property - -- Type: `'background' | 'blocking'` -- Optional -- Defaults to `'background'` -- Controls how stale successful loader data is revalidated by default. -- `'background'` preserves stale-while-revalidate behavior. -- `'blocking'` waits for the stale loader reload to finish before navigation resolves. - ### `defaultPreloadStaleTime` property - Type: `number` @@ -129,19 +120,19 @@ The `RouterOptions` type accepts an object with the following properties and met - Type: `number` - Optional -- Defaults to 5 minutes. +- Defaults to `routerOptions.defaultGcTime`, which defaults to 30 minutes. - The default `preloadGcTime` a route should use if no preloadGcTime is provided. ### `defaultGcTime` property - Type: `number` - Optional -- Defaults to 5 minutes. +- Defaults to 30 minutes. - The default `gcTime` a route should use if no gcTime is provided. ### `defaultOnCatch` property -- Type: `(error: unknown, errorInfo: ErrorInfo) => void` +- Type: `(error: Error, errorInfo: ErrorInfo) => void` - Optional - The default `onCatch` handler for errors caught by the Router ErrorBoundary @@ -223,13 +214,6 @@ const router = createRouter({ - Defaults to `/` - The basepath for the entire router. This is useful for mounting a router instance at a subpath. -### `origin` property - -- Type: `string` -- Optional -- The origin used to resolve URLs. Defaults to the browser origin, or `http://localhost` on the server and in browsers with an opaque origin. -- Pass a normalized origin, such as `https://example.com` or `http://localhost:3000`, without a path or trailing slash. The router uses this value as provided; if you have a full URL, normalize it with `new URL(url).origin` before passing it to the router. - ### `rewrite` property - Type: `LocationRewrite` @@ -306,7 +290,7 @@ When both `basepath` and `rewrite` are configured, they are automatically compos - Type: `boolean` - Optional - Defaults to `false` -- If `true`, route masks will, by default, be removed when the page is reloaded. This can be overridden on a per-mask basis by setting `unmaskOnReload` on the mask, or on a per-navigation basis by setting `mask.unmaskOnReload` in [`NavigateOptions`](./NavigateOptionsType.md). +- If `true`, route masks will, by default, be removed when the page is reloaded. This can be overridden on a per-mask basis by setting the `unmaskOnReload` option on the mask, or on a per-navigation basis by setting the `unmaskOnReload` option in the `Navigate` options. ### `Wrap` property @@ -375,10 +359,9 @@ const router = createRouter({ ### `pathParamsAllowedCharacters` property -- Type: `ReadonlyArray<';' | ':' | '@' | '&' | '=' | '+' | '$' | ','>` +- Type: `Array<';' | ':' | '@' | '&' | '=' | '+' | '$' | ','>` - Optional - Configures which URI characters are allowed in path params that would ordinarily be escaped by encodeURIComponent. -- Read only when the router is created. To change these characters, create a new router instance. Router option updates and provider props do not change this setting. ### `defaultStructuralSharing` property diff --git a/docs/router/api/router/RouterStateType.md b/docs/router/api/router/RouterStateType.md index 4da9cd9bb6..6c4d2aca93 100644 --- a/docs/router/api/router/RouterStateType.md +++ b/docs/router/api/router/RouterStateType.md @@ -3,17 +3,17 @@ id: RouterStateType title: RouterState type --- -The `RouterState` type represents the observable state of the router, including -the requested and resolved locations, match presentation, and foreground loading -status. +The `RouterState` type represents shape of the internal state of the router. The Router's internal state is useful, if you need to access certain internals of the router, such as any pending matches, is the router in its loading state, etc. ```tsx type RouterState = { status: 'pending' | 'idle' isLoading: boolean + isTransitioning: boolean matches: Array + pendingMatches: Array location: ParsedLocation - resolvedLocation?: ParsedLocation + resolvedLocation: ParsedLocation } ``` @@ -24,24 +24,27 @@ The `RouterState` type contains all of the properties that are available on the ### `status` property - Type: `'pending' | 'idle'` -- The current foreground status of the router. `pending` means the requested route is still loading or waiting for its framework transition to settle. +- The current status of the router. If the router is pending, it means that it is currently loading a route or the router is still transitioning to the new route. ### `isLoading` property - Type: `boolean` -- `true` when `status` is `pending`. -- Background loader refreshes do not change this value. Inspect each match's `isFetching` field to observe foreground `beforeLoad`/loader work and background loader work. +- `true` if the router is currently loading a route or waiting for a route to finish loading. + +### `isTransitioning` property + +- Type: `boolean` +- `true` if the router is currently transitioning to a new route. ### `matches` property - Type: [`Array`](./RouteMatchType.md) -- The match presentation currently exposed to the application. -- A navigation can keep the previous presentation visible until pending UI is - published. Once the destination is presented, this contains its complete - structurally matched lane, including descendants that are still loading. -- Error and not-found results also preserve the complete structurally matched - lane. Rendering stops at the selected pending or terminal boundary; it does - not truncate this array. +- An array of all of the route matches that have been resolved and are currently active. + +### `pendingMatches` property + +- Type: [`Array`](./RouteMatchType.md) +- An array of all of the route matches that are currently pending. ### `location` property @@ -50,5 +53,5 @@ The `RouterState` type contains all of the properties that are available on the ### `resolvedLocation` property -- Type: [`ParsedLocation`](./ParsedLocationType.md) | `undefined` -- The location whose load and framework transition have settled. It is `undefined` before the initial location resolves. +- Type: [`ParsedLocation`](./ParsedLocationType.md) +- The location that the router has resolved and loaded. diff --git a/docs/router/api/router/RouterType.md b/docs/router/api/router/RouterType.md index 3fde90e32e..c5736638a0 100644 --- a/docs/router/api/router/RouterType.md +++ b/docs/router/api/router/RouterType.md @@ -11,9 +11,8 @@ An instance of the `Router` has the following properties and methods: ### `.update` method -- Type: `(newOptions: Omit) => void` +- Type: `(newOptions: RouterOptions) => void` - Updates the router instance with new options. -- Initialization-only options such as `pathParamsAllowedCharacters` cannot be updated. Create a new router instance to change them. ### `state` property @@ -24,11 +23,10 @@ An instance of the `Router` has the following properties and methods: ### `.subscribe` method -- Type: `(eventType: TType, fn: ListenerFn) => () => void` +- Type: `(eventType: TType, fn: ListenerFn) => (event: RouterEvent) => void` - Subscribes to a [`RouterEvent`](./RouterEventsType.md). - Returns a function that can be used to unsubscribe from the event. -- The listener will be called with the event payload whenever that event is emitted. -- See the [Router Events guide](../../guide/router-events.md) for lifecycle ordering and usage patterns. +- The callback provided to the returned function will be called with the event that was emitted. ### `.matchRoutes` method @@ -36,6 +34,16 @@ An instance of the `Router` has the following properties and methods: - Matches a pathname and search params against the router's route tree and returns an array of route matches. - If `opts.throwOnError` is `true`, any errors that occur during the matching process will be thrown (in addition to being returned in the route match's `error` property). +### `.cancelMatch` method + +- Type: `(matchId: string) => void` +- Cancels a route match that is currently pending by calling `match.abortController.abort()`. + +### `.cancelMatches` method + +- Type: `() => void` +- Cancels all route matches that are currently pending by calling `match.abortController.abort()` on each one. + ### `.buildLocation` method Builds a new parsed location object that can be used later to navigate to a new location. @@ -73,7 +81,7 @@ Builds a new parsed location object that can be used later to navigate to a new - `unmaskOnReload` - Type: `boolean` - Optional - - If `true`, the route mask will be removed when the page is reloaded. This can be overridden on a per-navigation basis by setting `mask.unmaskOnReload` in [`NavigateOptions`](./NavigateOptionsType.md). + - If `true`, the route mask will be removed when the page is reloaded. This can be overridden on a per-navigation basis by setting the `unmaskOnReload` option in the `Navigate` options. ### `.commitLocation` method @@ -129,33 +137,29 @@ Navigates to a new location. ### `.invalidate` method -Invalidates selected route-match generations, reruns their loading lifecycle, -reruns `beforeLoad`, and reloads their loaders through the normal loading -protocol. +Invalidates route matches by forcing their `beforeLoad` and `load` functions to be called again. - Type: `(opts?: {filter?: (d: MakeRouteMatchUnion) => boolean, sync?: boolean, forcePending?: boolean }) => Promise` - This is useful any time your loader data might be out of date or stale. For example, if you have a route that displays a list of posts, and you have a loader function that fetches the list of posts from an API, you might want to invalidate the route matches for that route any time a new post is created so that the list of posts is always up-to-date. -- If `filter` is not supplied, all committed, cached, and in-flight match generations are invalidated. -- If `filter` is supplied, it is evaluated against committed, cached, and in-flight matches. Selecting one generation invalidates every committed, cached, or in-flight generation with the same match ID. -- Invalidation reruns `beforeLoad`; reusable loader data is marked stale and reloads through the normal loading protocol. Route-level `context` remains reusable while the match ID is unchanged. -- If `sync` is `true`, stale loader work is blocking and the returned promise resolves after it finishes instead of leaving a background refresh detached. -- If `forcePending` is `true`, selected routes that need loading enter the normal pending protocol even when successful data was already available. +- if `filter` is not supplied, all matches will be invalidated +- if `filter` is supplied, only matches for which `filter` returns `true` will be invalidated. +- if `sync` is true, the promise returned by this function will only resolve once all loaders have finished. +- if `forcePending` is true, the invalidated matches will be put into `'pending'` state regardless whether they are in `'error'` state or not. - You might also want to invalidate the Router if you imperatively `reset` the router's `CatchBoundary` to trigger loaders again. ### `.clearCache` method -Remove cached route matches and matching active preloads. +Remove cached route matches. - Type: `(opts?: {filter?: (d: MakeRouteMatchUnion) => boolean}) => void` -- If `filter` is not supplied, all cached matches and active preload lanes are removed. -- If `filter` is supplied, matching cached matches are removed. An active preload lane is canceled when any match in that lane passes the filter. -- Current committed and presented matches are not removed. +- if `filter` is not supplied, all cached matches will be removed +- if `filter` is supplied, only matches for which `filter` returns `true` will be removed. ### `.load` method Loads all of the currently matched route matches and resolves when they are all loaded and ready to be rendered. -> ⚠️⚠️⚠️ **`router.load()` respects `route.staleTime`: fresh matches stay fresh, but stale matches are revalidated even if their loader key did not change. If you need to forcefully reload all active matches regardless of freshness, use `router.invalidate()` instead.** +> ⚠️⚠️⚠️ **`router.load()` respects `route.staleTime` and will not forcefully reload a route match if it is still fresh. If you need to forcefully reload a route match, use `router.invalidate()` instead.** - Type: `(opts?: {sync?: boolean}) => Promise` - if `sync` is true, the promise returned by this function will only resolve once all loaders have finished. @@ -165,28 +169,16 @@ Loads all of the currently matched route matches and resolves when they are all Preloads all of the matches that match the provided `NavigateOptions`. -An active preload is speculative and is not published as the current match -presentation. Successful loader data can enter the normal in-memory route -cache. Its freshness follows `preloadStaleTime`; once unused and older than -`preloadGcTime`, it is eligible for pruning during a later cache -reconciliation. +> ⚠️⚠️⚠️ **Preloaded route matches are not stored long-term in the router state. They are only stored until the next attempted navigation action.** -Every preload and navigation runs its own `beforeLoad` chain. A later lane can -reuse successful settled loader data or join loader work that is still in -flight, but it never reuses `beforeLoad` context or an already-settled -redirect, error, or not-found result. If joined loader work later produces a -terminal outcome, all current consumers of that flight observe it. - -- Type: `(opts: NavigateOptions) => Promise` +- Type: `(opts?: NavigateOptions) => Promise` - Properties - `opts` - Type: `NavigateOptions` - - Required. + - Optional, defaults to the current location. - The options that will be used to determine which route matches to preload. - Returns - - A promise that resolves with the speculative route-match lane. An ordinary error or not-found is represented by a terminal match array rather than a rejected promise. - - It resolves with `undefined` when cancellation or control flow does not produce a reusable lane. - - The method is also available on server router instances. It remains speculative and does not change the request's current location or presented matches. + - A promise that resolves with an array of all of the route matches that were preloaded. ### `.loadRouteChunk` method diff --git a/docs/router/api/router/ToMaskOptionsType.md b/docs/router/api/router/ToMaskOptionsType.md index 9f40103ff5..fa0140fec2 100644 --- a/docs/router/api/router/ToMaskOptionsType.md +++ b/docs/router/api/router/ToMaskOptionsType.md @@ -3,18 +3,12 @@ id: ToMaskOptionsType title: ToMaskOptions type --- -The `ToMaskOptions` type includes the same destination fields as [`ToOptions`](./ToOptionsType.md), excluding `mask`, and adds options specific to route masking. +The `ToMaskOptions` type extends the [`ToOptions`](./ToOptionsType.md) type and describes additional options available when using route masks. ```tsx -type ToMaskOptions = { - from?: ValidRoutePath | string - to?: ValidRoutePath | string - hash?: true | string | ((prev?: string) => string) - state?: true | HistoryState | ((prev: HistoryState) => HistoryState) -} & SearchParamOptions & - PathParamOptions & { - unmaskOnReload?: boolean - } +type ToMaskOptions = ToOptions & { + unmaskOnReload?: boolean +} ``` - [`ToOptions`](./ToOptionsType.md) diff --git a/docs/router/api/router/ToOptionsType.md b/docs/router/api/router/ToOptionsType.md index 909d2bbe28..abae49bf33 100644 --- a/docs/router/api/router/ToOptionsType.md +++ b/docs/router/api/router/ToOptionsType.md @@ -3,7 +3,7 @@ id: ToOptionsType title: ToOptions type --- -The `ToOptions` type contains several properties that can be used to describe a router destination, including `mask` for route masking. +The `ToOptions` type contains several properties that can be used to describe a router destination. ```tsx type ToOptions = { @@ -12,8 +12,7 @@ type ToOptions = { hash?: true | string | ((prev?: string) => string) state?: true | HistoryState | ((prev: HistoryState) => HistoryState) } & SearchParamOptions & - PathParamOptions & - MaskOptions + PathParamOptions type SearchParamOptions = { search?: true | TToSearch | ((prev: TFromSearch) => TToSearch) @@ -25,8 +24,4 @@ type PathParamOptions = { | Record | ((prev: TFromParams) => TToParams) } - -type MaskOptions = { - mask?: ToMaskOptions -} ``` diff --git a/docs/router/api/router/catchBoundaryComponent.md b/docs/router/api/router/catchBoundaryComponent.md index aa2f6eb7ce..deef0ffa22 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: unknown, errorInfo: ErrorInfo) => void` in React; `(error: unknown) => void` in Vue; `(error: Error) => void` in Solid +- Type: `(error: any) => void` - 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/createLazyFileRouteFunction.md b/docs/router/api/router/createLazyFileRouteFunction.md index 750e38dd24..87e1743ed1 100644 --- a/docs/router/api/router/createLazyFileRouteFunction.md +++ b/docs/router/api/router/createLazyFileRouteFunction.md @@ -3,7 +3,7 @@ id: createLazyFileRouteFunction title: createLazyFileRoute function --- -The `createLazyFileRoute` function is used for creating a partial file-based route instance that is lazily loaded when matched. This route instance can only be used to configure the [non-critical properties](../../guide/code-splitting.md#how-does-tanstack-router-split-code) of the route, such as `component`, `pendingComponent`, `errorComponent`, and the `notFoundComponent`. +The `createLazyFileRoute` function is used for creating a partial file-based route route instance that is lazily loaded when matched. This route instance can only be used to configure the [non-critical properties](../../guide/code-splitting.md#how-does-tanstack-router-split-code) of the route, such as `component`, `pendingComponent`, `errorComponent`, and the `notFoundComponent`. ## createLazyFileRoute options diff --git a/docs/router/api/router/createLazyRouteFunction.md b/docs/router/api/router/createLazyRouteFunction.md index 553e2f36a2..48c100c352 100644 --- a/docs/router/api/router/createLazyRouteFunction.md +++ b/docs/router/api/router/createLazyRouteFunction.md @@ -3,7 +3,7 @@ id: createLazyRouteFunction title: createLazyRoute function --- -The `createLazyRoute` function is used for creating a partial code-based route instance that is lazily loaded when matched. This route instance can only be used to configure the [non-critical properties](../../guide/code-splitting.md#how-does-tanstack-router-split-code) of the route, such as `component`, `pendingComponent`, `errorComponent`, and the `notFoundComponent`. +The `createLazyRoute` function is used for creating a partial code-based route route instance that is lazily loaded when matched. This route instance can only be used to configure the [non-critical properties](../../guide/code-splitting.md#how-does-tanstack-router-split-code) of the route, such as `component`, `pendingComponent`, `errorComponent`, and the `notFoundComponent`. ## createLazyRoute options diff --git a/docs/router/api/router/errorComponentComponent.md b/docs/router/api/router/errorComponentComponent.md index 07d7187580..04399f124d 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 renders an error notice and optional details about the thrown value. +The `ErrorComponent` component is a component that renders an error message and optionally the error's message. ## ErrorComponent props @@ -11,8 +11,8 @@ The `ErrorComponent` component accepts the following props: ### `props.error` prop -- 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`. +- Type: `TError` (defaults to `Error`) +- The error that was thrown by the component's children ### `props.info` prop @@ -27,6 +27,6 @@ The `ErrorComponent` component accepts the following props: ## ErrorComponent returns -- Displays an error notice, with details when the thrown value has a nonempty `message`. Values without a message still display the error notice. +- Returns a formatted error message with the error's message if it exists. - 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 478271a208..a8227913b5 100644 --- a/docs/router/api/router/linkComponent.md +++ b/docs/router/api/router/linkComponent.md @@ -43,7 +43,7 @@ By default, param values with characters such as `@` will be encoded in the URL: ``` -To opt out, set [pathParamsAllowedCharacters](../router/RouterOptionsType#pathparamsallowedcharacters-property) when creating the router. This setting cannot be changed on an existing router instance. +To opt-out, update the [pathParamsAllowedCharacters](../router/RouterOptionsType#pathparamsallowedcharacters-property) config on the router ```tsx import { createRouter } from '@tanstack/react-router' diff --git a/docs/router/api/router/retainSearchParamsFunction.md b/docs/router/api/router/retainSearchParamsFunction.md index 18600fd346..eeac38bcd7 100644 --- a/docs/router/api/router/retainSearchParamsFunction.md +++ b/docs/router/api/router/retainSearchParamsFunction.md @@ -15,14 +15,14 @@ If `true` is passed in, all search params will be retained. ```tsx import { z } from 'zod' import { createRootRoute, retainSearchParams } from '@tanstack/react-router' +import { zodValidator } from '@tanstack/zod-adapter' const searchSchema = z.object({ rootValue: z.string().optional(), }) export const Route = createRootRoute({ - // Use the schema directly for Zod v4 - validateSearch: searchSchema, + validateSearch: zodValidator(searchSchema), search: { middlewares: [retainSearchParams(['rootValue'])], }, @@ -32,6 +32,7 @@ export const Route = createRootRoute({ ```tsx import { z } from 'zod' import { createFileRoute, retainSearchParams } from '@tanstack/react-router' +import { zodValidator } from '@tanstack/zod-adapter' const searchSchema = z.object({ one: z.string().optional(), @@ -39,8 +40,7 @@ const searchSchema = z.object({ }) export const Route = createFileRoute('/')({ - // Use the schema directly for Zod v4 - validateSearch: searchSchema, + validateSearch: zodValidator(searchSchema), search: { middlewares: [retainSearchParams(true)], }, diff --git a/docs/router/api/router/stripSearchParamsFunction.md b/docs/router/api/router/stripSearchParamsFunction.md index 08164c39ba..bfbb57a740 100644 --- a/docs/router/api/router/stripSearchParamsFunction.md +++ b/docs/router/api/router/stripSearchParamsFunction.md @@ -18,6 +18,7 @@ title: Search middleware to strip search params ```tsx import { z } from 'zod' import { createFileRoute, stripSearchParams } from '@tanstack/react-router' +import { zodValidator } from '@tanstack/zod-adapter' const defaultValues = { one: 'abc', @@ -30,8 +31,7 @@ const searchSchema = z.object({ }) export const Route = createFileRoute('/')({ - // for Zod v4, use the schema directly - validateSearch: searchSchema, + validateSearch: zodValidator(searchSchema), search: { // strip default values middlewares: [stripSearchParams(defaultValues)], @@ -42,6 +42,7 @@ export const Route = createFileRoute('/')({ ```tsx import { z } from 'zod' import { createRootRoute, stripSearchParams } from '@tanstack/react-router' +import { zodValidator } from '@tanstack/zod-adapter' const searchSchema = z.object({ hello: z.string().default('world'), @@ -49,8 +50,7 @@ const searchSchema = z.object({ }) export const Route = createRootRoute({ - // for Zod v4, use the schema directly - validateSearch: searchSchema, + validateSearch: zodValidator(searchSchema), search: { // always remove `hello` middlewares: [stripSearchParams(['hello'])], @@ -61,6 +61,7 @@ export const Route = createRootRoute({ ```tsx import { z } from 'zod' import { createFileRoute, stripSearchParams } from '@tanstack/react-router' +import { zodValidator } from '@tanstack/zod-adapter' const searchSchema = z.object({ one: z.string().default('abc'), @@ -68,8 +69,7 @@ const searchSchema = z.object({ }) export const Route = createFileRoute('/')({ - // for Zod v4, use the schema directly - validateSearch: searchSchema, + validateSearch: zodValidator(searchSchema), search: { // remove all search params middlewares: [stripSearchParams(true)], diff --git a/docs/router/api/router/useBlockerHook.md b/docs/router/api/router/useBlockerHook.md index 3d9c00d602..98d4a06c3b 100644 --- a/docs/router/api/router/useBlockerHook.md +++ b/docs/router/api/router/useBlockerHook.md @@ -20,7 +20,7 @@ The `useBlocker` hook accepts a single _required_ argument, an option object: - Think of this function as telling the router if it should block the navigation, so returning `true` mean that it should block the navigation and `false` meaning that it should be allowed ```ts -type ShouldBlockFnLocation<...> = { +interface ShouldBlockFnLocation<...> { routeId: TRouteId fullPath: TFullPath pathname: string diff --git a/docs/router/api/router/useChildMatchesHook.md b/docs/router/api/router/useChildMatchesHook.md index 13212e61e0..cf31d21016 100644 --- a/docs/router/api/router/useChildMatchesHook.md +++ b/docs/router/api/router/useChildMatchesHook.md @@ -5,9 +5,8 @@ title: useChildMatches hook The `useChildMatches` hook returns all of the child [`RouteMatch`](./RouteMatchType.md) objects from the closest match down to the leaf-most match. **It does not include the current match, which can be obtained using the `useMatch` hook.** -The result is derived from the router's current match presentation. It can -include still-loading descendants and descendants below the current render -boundary. +> [!IMPORTANT] +> If the router has pending matches and they are showing their pending component fallbacks, `router.state.pendingMatches` will used instead of `router.state.matches`. ## useChildMatches options diff --git a/docs/router/api/router/useLoaderDataHook.md b/docs/router/api/router/useLoaderDataHook.md index b551d613fc..dfcf2d3758 100644 --- a/docs/router/api/router/useLoaderDataHook.md +++ b/docs/router/api/router/useLoaderDataHook.md @@ -15,13 +15,13 @@ The `useLoaderData` hook accepts an `options` object. - The route id of the closest parent match - Optional, but recommended for full type safety. - If `opts.strict` is `true`, TypeScript will warn for this option if it is not provided. -- If `opts.strict` is `false`, TypeScript will provide loosened types for the returned loader data. +- If `opts.strict` is `false`, TypeScript will provided loosened types for the returned loader data. ### `opts.strict` option - Type: `boolean` - Optional - `default: true` -- If `false`, the `opts.from` option will be ignored and types will be loosened to reflect the shared types of all possible loader data. +- If `false`, the `opts.from` option will be ignored and types will be loosened to to reflect the shared types of all possible loader data. ### `opts.select` option diff --git a/docs/router/api/router/useMatchRouteHook.md b/docs/router/api/router/useMatchRouteHook.md index e67ccb6cbd..01c26d07c6 100644 --- a/docs/router/api/router/useMatchRouteHook.md +++ b/docs/router/api/router/useMatchRouteHook.md @@ -3,9 +3,7 @@ id: useMatchRouteHook title: useMatchRoute hook --- -The `useMatchRoute` hook returns a `matchRoute` function that can be used to match a route against either the current or pending location. The hook subscribes the component to changes in the router state used for matching, making it useful when the match result affects what the component renders. - -The `matchRoute` function's identity changes when that router state changes. For an imperative check, such as one performed in an event handler, use [`useRouter`](./useRouterHook.md) and call `router.matchRoute` instead. The router instance is stable, and this avoids subscribing the component to router state that it does not use while rendering. +The `useMatchRoute` hook is a hook that returns a `matchRoute` function that can be used to match a route against either the current or pending location. ## useMatchRoute returns @@ -27,8 +25,6 @@ The `matchRoute` function accepts a single argument, an `options` object. ## Examples -Use `useMatchRoute` when the result determines the rendered output: - ```tsx import { useMatchRoute } from '@tanstack/react-router' @@ -37,36 +33,7 @@ function Component() { const matchRoute = useMatchRoute() const params = matchRoute({ to: '/posts/$postId' }) // ^ { postId: '123' } - - return params ? : } -``` - -For a check made at the time of an event, call `router.matchRoute` directly: - -```tsx -import { useRouter } from '@tanstack/react-router' - -function Component() { - const router = useRouter() - - return ( - - ) -} -``` - -Additional matching examples: - -```tsx -import { useMatchRoute } from '@tanstack/react-router' // Current location: /posts/123 function Component() { diff --git a/docs/router/api/router/useMatchesHook.md b/docs/router/api/router/useMatchesHook.md index e57c6c2c7e..d7a1be8dc3 100644 --- a/docs/router/api/router/useMatchesHook.md +++ b/docs/router/api/router/useMatchesHook.md @@ -3,7 +3,7 @@ id: useMatchesHook title: useMatches hook --- -The `useMatches` hook returns the router's complete presented array of [`RouteMatch`](./RouteMatchType.md) objects **regardless of its caller's position in the component tree**. The array can include still-loading descendants or matches below a pending/error/not-found render boundary. +The `useMatches` hook returns all of the [`RouteMatch`](./RouteMatchType.md) objects from the router **regardless of its callers position in the React component tree**. > [!TIP] > If you only want the parent or child matches, then you can use the [`useParentMatches`](./useParentMatchesHook.md) or the [`useChildMatches`](./useChildMatchesHook.md) based on the selection you need. diff --git a/docs/router/api/router/useParamsHook.md b/docs/router/api/router/useParamsHook.md index 4ac93a0b70..0f3ca88fca 100644 --- a/docs/router/api/router/useParamsHook.md +++ b/docs/router/api/router/useParamsHook.md @@ -37,7 +37,7 @@ The `useParams` hook accepts an optional `options` object. ## useParams returns -- An object of the match's and parent match path params or `TSelected` if a `select` function is provided. +- An object of of the match's and parent match path params or `TSelected` if a `select` function is provided. ## Examples diff --git a/docs/router/api/router/useParentMatchesHook.md b/docs/router/api/router/useParentMatchesHook.md index a0ce985411..fe4068f397 100644 --- a/docs/router/api/router/useParentMatchesHook.md +++ b/docs/router/api/router/useParentMatchesHook.md @@ -5,9 +5,8 @@ title: useParentMatches hook The `useParentMatches` hook returns all of the parent [`RouteMatch`](./RouteMatchType.md) objects from the root down to the immediate parent of the current match in context. **It does not include the current match, which can be obtained using the `useMatch` hook.** -The result is derived from the router's current match presentation. During a -navigation that may still be the previous presentation; after pending UI is -published it is the destination's complete structurally matched lane. +> [!IMPORTANT] +> If the router has pending matches and they are showing their pending component fallbacks, `router.state.pendingMatches` will used instead of `router.state.matches`. ## useParentMatches options diff --git a/docs/router/api/router/useRouterStateHook.md b/docs/router/api/router/useRouterStateHook.md index 24fd8f94b2..bcded1d415 100644 --- a/docs/router/api/router/useRouterStateHook.md +++ b/docs/router/api/router/useRouterStateHook.md @@ -6,7 +6,7 @@ title: useRouterState hook The `useRouterState` method is a hook that returns the current internal state of the router. This hook is useful for accessing the current state of the router in a component. > [!TIP] -> If you want to access the current location or the current matches, you should try out the [`useLocation`](./useLocationHook.md) and [`useMatches`](./useMatchesHook.md) hooks first. These hooks are designed to be more performant, more ergonomic and easier to use than accessing the router state directly. +> If you want to access the current location or the current matches, you should try out the [`useLocation`](./useLocationHook.md) and [`useMatches`](./useMatchesHook.md) hooks first. These hooks are designed to be more ergonomic and easier to use than accessing the router state directly. ## useRouterState options diff --git a/docs/router/comparison.md b/docs/router/comparison.md index 8eaef776f3..84a2119162 100644 --- a/docs/router/comparison.md +++ b/docs/router/comparison.md @@ -80,7 +80,7 @@ Feature/Capability Key: | React Server Function Middleware | ✅ | 🛑 | 🛑 | | API Routes | ✅ | ✅ | ✅ | | API Middleware | ✅ | ✅ | ✅ | -| React Server Components | 🟡 (Experimental) | 🟡 (Experimental) | ✅ | +| React Server Components | 🛑 | 🟡 (Experimental) | ✅ | | `
` API | 🛑 | ✅ | ✅ | [bp-tanstack-router]: https://badgen.net/bundlephobia/minzip/@tanstack/react-router diff --git a/docs/router/config.json b/docs/router/config.json index 1258ddd817..2957e04035 100644 --- a/docs/router/config.json +++ b/docs/router/config.json @@ -25,6 +25,10 @@ "label": "Decisions on DX", "to": "decisions-on-dx" }, + { + "label": "LLM Assistance Support", + "to": "llm-support" + }, { "label": "Comparison", "to": "comparison" @@ -79,11 +83,11 @@ "children": [ { "label": "Migrate from React Router", - "to": "installation/migrate-from-react-router" + "to": "framework/react/installation/migrate-from-react-router" }, { "label": "Migrate from React Location", - "to": "installation/migrate-from-react-location" + "to": "framework/react/installation/migrate-from-react-location" } ] }, @@ -94,7 +98,7 @@ ] }, { - "label": "Core Routing", + "label": "Routing", "children": [ { "label": "Routing Concepts", @@ -123,10 +127,6 @@ { "label": "File Naming Conventions", "to": "routing/file-naming-conventions" - }, - { - "label": "URL Rewrites", - "to": "guide/url-rewrites" } ], "frameworks": [ @@ -141,21 +141,28 @@ ] }, { - "label": "Navigation & URL State", - "collapsible": true, + "label": "Guides", "children": [ + { + "label": "Code Splitting", + "to": "guide/code-splitting" + }, + { + "label": "Automatic Code Splitting", + "to": "guide/automatic-code-splitting" + }, + { + "label": "Creating a Router", + "to": "guide/creating-a-router" + }, + { + "label": "Outlets", + "to": "guide/outlets" + }, { "label": "Navigation", "to": "guide/navigation" }, - { - "label": "Link Options", - "to": "guide/link-options" - }, - { - "label": "Custom Links", - "to": "guide/custom-link" - }, { "label": "Path Params", "to": "guide/path-params" @@ -165,52 +172,12 @@ "to": "guide/search-params" }, { - "label": "Custom Search Param Serialization", - "to": "guide/custom-search-param-serialization" + "label": "Link Options", + "to": "guide/link-options" }, { - "label": "Route Masking", - "to": "guide/route-masking" - }, - { - "label": "Navigation Blocking", - "to": "guide/navigation-blocking" - }, - { - "label": "History Types", - "to": "guide/history-types" - }, - { - "label": "Scroll Restoration", - "to": "guide/scroll-restoration" - }, - { - "label": "Internationalization", - "to": "guide/internationalization-i18n" - } - ], - "frameworks": [ - { - "label": "react", - "children": [] - }, - { - "label": "solid", - "children": [] - } - ] - }, - { - "label": "Data & Rendering", - "collapsible": true, - "children": [ - { - "label": "Code Splitting", - "to": "guide/code-splitting" - }, - { - "label": "Automatic Code Splitting", - "to": "guide/automatic-code-splitting" + "label": "Custom Links", + "to": "guide/custom-link" }, { "label": "Data Loading", @@ -228,6 +195,14 @@ "label": "Data Mutations", "to": "guide/data-mutations" }, + { + "label": "Type Safety", + "to": "guide/type-safety" + }, + { + "label": "Type Utilities", + "to": "guide/type-utilities" + }, { "label": "Preloading", "to": "guide/preloading" @@ -237,48 +212,20 @@ "to": "guide/document-head-management" }, { - "label": "SSR", - "to": "guide/ssr" + "label": "Route Masking", + "to": "guide/route-masking" }, { - "label": "Render Optimizations", - "to": "guide/render-optimizations" - } - ], - "frameworks": [ - { - "label": "react", - "children": [] + "label": "Navigation Blocking", + "to": "guide/navigation-blocking" }, { - "label": "solid", - "children": [] - } - ] - }, - { - "label": "Router Configuration", - "collapsible": true, - "children": [ - { - "label": "Creating a Router", - "to": "guide/creating-a-router" + "label": "Custom Search Param Serialization", + "to": "guide/custom-search-param-serialization" }, { - "label": "Outlets", - "to": "guide/outlets" - }, - { - "label": "Router Events", - "to": "guide/router-events" - }, - { - "label": "Type Safety", - "to": "guide/type-safety" - }, - { - "label": "Type Utilities", - "to": "guide/type-utilities" + "label": "History Types", + "to": "guide/history-types" }, { "label": "Router Context", @@ -292,9 +239,21 @@ "label": "Authenticated Routes", "to": "guide/authenticated-routes" }, + { + "label": "Scroll Restoration", + "to": "guide/scroll-restoration" + }, { "label": "Static Route Data", "to": "guide/static-route-data" + }, + { + "label": "SSR", + "to": "guide/ssr" + }, + { + "label": "Render Optimizations", + "to": "guide/render-optimizations" } ], "frameworks": [ diff --git a/docs/router/decisions-on-dx.md b/docs/router/decisions-on-dx.md index a06ec4b331..26c366a9da 100644 --- a/docs/router/decisions-on-dx.md +++ b/docs/router/decisions-on-dx.md @@ -39,7 +39,7 @@ But to achieve this, we had to make some decisions that deviate from the norms i ## Why is the Router's configuration done this way? -When you want to leverage TypeScript's inference features to its fullest, you'll quickly realize that _Generics_ are your best friend. And so, TanStack Router uses Generics everywhere to ensure that the types of your routes are inferred as much as possible. +When you want to leverage the TypeScript's inference features to its fullest, you'll quickly realize that _Generics_ are your best friend. And so, TanStack Router uses Generics everywhere to ensure that the types of your routes are inferred as much as possible. This means that you have to define your routes in a way that allows TypeScript to infer the types of your routes as much as possible. @@ -219,7 +219,7 @@ TanStack Router's file-based routing is designed to solve all of these issues. I The file-based routing approach is powered by the TanStack Router Bundler Plugin. It performs 3 essential tasks that solve the pain points in route configuration when using code-based routing: 1. **Route configuration boilerplate**: It generates the boilerplate for your route configurations. -2. **Route tree stitching**: It stitches together your route configurations into a single cohesive route-tree. Also in the background, it correctly updates the route configurations to define the `getParentRoute` function and so matches the routes with their parent routes. +2. **Route tree stitching**: It stitches together your route configurations into a single cohesive route-tree. Also in the background, it correctly updates the route configurations to define the `getParentRoute` function match the routes with their parent routes. 3. **Code-splitting**: It automatically code-splits your route content components and updates the route configurations with the correct component. Additionally, at runtime, it ensures that the correct component is loaded when the route is visited. Let's take a look at how the route configuration for the previous example would look like with file-based routing. diff --git a/docs/router/eslint/create-route-property-order.md b/docs/router/eslint/create-route-property-order.md index 453fd64acc..d568666186 100644 --- a/docs/router/eslint/create-route-property-order.md +++ b/docs/router/eslint/create-route-property-order.md @@ -36,13 +36,10 @@ Examples of **incorrect** code for this rule: import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/path')({ - loader: async ({ context }) => { - await context.queryClient.query({ - ...getQueryOptions(context.hello), - staleTime: 'static', - }) + loader: async ({context}) => { + await context.queryClient.ensureQueryData(getQueryOptions(context.hello)), }, - beforeLoad: () => ({ hello: 'world' }), + beforeLoad: () => ({hello: 'world'}) }) ``` @@ -57,13 +54,10 @@ export const Route = createFileRoute('/path')({ import { createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/path')({ - loader: async ({ context }) => { - await context.queryClient.query({ - ...getQueryOptions(context.hello), - staleTime: 'static', - }) + loader: async ({context}) => { + await context.queryClient.ensureQueryData(getQueryOptions(context.hello)), }, - beforeLoad: () => ({ hello: 'world' }), + beforeLoad: () => ({hello: 'world'}) }) ``` @@ -84,13 +78,10 @@ Examples of **correct** code for this rule: import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/path')({ - beforeLoad: () => ({ hello: 'world' }), - loader: async ({ context }) => { - await context.queryClient.query({ - ...getQueryOptions(context.hello), - staleTime: 'static', - }) - }, + beforeLoad: () => ({hello: 'world'}), + loader: async ({context}) => { + await context.queryClient.ensureQueryData(getQueryOptions(context.hello)), + } }) ``` @@ -105,13 +96,10 @@ export const Route = createFileRoute('/path')({ import { createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/path')({ - beforeLoad: () => ({ hello: 'world' }), - loader: async ({ context }) => { - await context.queryClient.query({ - ...getQueryOptions(context.hello), - staleTime: 'static', - }) - }, + beforeLoad: () => ({hello: 'world'}), + loader: async ({context}) => { + await context.queryClient.ensureQueryData(getQueryOptions(context.hello)), + } }) ``` diff --git a/docs/router/eslint/eslint-plugin-router.md b/docs/router/eslint/eslint-plugin-router.md index 6af6103031..b355a83a25 100644 --- a/docs/router/eslint/eslint-plugin-router.md +++ b/docs/router/eslint/eslint-plugin-router.md @@ -103,7 +103,7 @@ If you have other ESLint plugins installed, they may rules that conflict with th The [`@typescript-eslint/only-throw-error`](https://typescript-eslint.io/rules/only-throw-error/) rule, enabled by default in the `recommended-type-checked` and `strict-type-checked` rulesets, disallows the throwing of non-Error values as exceptions, which is considered a good practice. -To ensure it does not conflict with TanStack Router, you should allow `redirect` and `notFound` as throwable objects. +To make sure it that it does not conflict with TanStack Router, you should add `redirect` to the allowed as a throwable objects. ```json { @@ -116,11 +116,6 @@ To ensure it does not conflict with TanStack Router, you should allow `redirect` "from": "package", "package": "@tanstack/router-core", "name": "Redirect" - }, - { - "from": "package", - "package": "@tanstack/router-core", - "name": "NotFoundError" } ] } diff --git a/docs/router/installation/migrate-from-react-location.md b/docs/router/framework/react/installation/migrate-from-react-location.md similarity index 79% rename from docs/router/installation/migrate-from-react-location.md rename to docs/router/framework/react/installation/migrate-from-react-location.md index 762570b6d8..788b6c71a7 100644 --- a/docs/router/installation/migrate-from-react-location.md +++ b/docs/router/framework/react/installation/migrate-from-react-location.md @@ -2,27 +2,27 @@ title: Migration from React Location --- -Before you begin your journey in migrating from React Location, it's important that you have a good understanding of the [Routing Concepts](../routing/routing-concepts.md) and [Design Decisions](../decisions-on-dx.md) used by TanStack Router. +Before you begin your journey in migrating from React Location, it's important that you have a good understanding of the [Routing Concepts](../../../routing/routing-concepts.md) and [Design Decisions](../../../decisions-on-dx.md) used by TanStack Router. ## Differences between React Location and TanStack Router React Location and TanStack Router share much of same design decisions concepts, but there are some key differences that you should be aware of. - React Location uses _generics_ to infer types for routes, while TanStack Router uses _module declaration merging_ to infer types. -- Route configuration in React Location is done using a single array of route definitions, while in TanStack Router, route configuration is done using a tree of route definitions starting with the [root route](../routing/routing-concepts.md#the-root-route). -- [File-based routing](../routing/file-based-routing.md) is the recommended way to define routes in TanStack Router, while React Location only allows you to define routes in a single file using a code-based approach. - - TanStack Router does support a [code-based approach](../routing/code-based-routing.md) to defining routes, but it is not recommended for most use cases. You can read more about why, over here: [why is file-based routing the preferred way to define routes?](../decisions-on-dx.md#why-is-file-based-routing-the-preferred-way-to-define-routes) +- Route configuration in React Location is done using a single array of route definitions, while in TanStack Router, route configuration is done using a tree of route definitions starting with the [root route](../../../routing/routing-concepts.md#the-root-route). +- [File-based routing](../../../routing/file-based-routing.md) is the recommended way to define routes in TanStack Router, while React Location only allows you to define routes in a single file using a code-based approach. + - TanStack Router does support a [code-based approach](../../../routing/code-based-routing.md) to defining routes, but it is not recommended for most use cases. You can read more about why, over here: [why is file-based routing the preferred way to define routes?](../../../decisions-on-dx.md#why-is-file-based-routing-the-preferred-way-to-define-routes) ## Migration guide In this guide we'll go over the process of migrating the [React Location Basic example](https://github.com/TanStack/router/tree/react-location/examples/basic) over to TanStack Router using file-based routing, with the end goal of having the same functionality as the original example (styling and other non-routing related code will be omitted). > [!TIP] -> To use a code-based approach for defining your routes, you can read the [code-based Routing](../routing/code-based-routing.md) guide. +> To use a code-based approach for defining your routes, you can read the [code-based Routing](../../../routing/code-based-routing.md) guide. ### Step 1: Swap over to TanStack Router's dependencies -First, we need to install the dependencies for TanStack Router. For detailed installation instructions, see our [How to Install TanStack Router](../how-to/install.md) guide. +First, we need to install the dependencies for TanStack Router. For detailed installation instructions, see our [How to Install TanStack Router](../../../how-to/install.md) guide. ```sh npm install @tanstack/react-router @tanstack/router-devtools @@ -57,7 +57,7 @@ export default defineConfig({ }) ``` -However, if your application does not use Vite, you use one of our other [supported bundlers](../routing/file-based-routing.md#getting-started-with-file-based-routing), or you can use the `@tanstack/router-cli` package to watch for changes in your routes files and automatically update the routes configuration. +However, if your application does not use Vite, you use one of our other [supported bundlers](../../../routing/file-based-routing.md#getting-started-with-file-based-routing), or you can use the `@tanstack/router-cli` package to watch for changes in your routes files and automatically update the routes configuration. ### Step 3: Add the file-based configuration file to your project @@ -70,7 +70,7 @@ Create a `tsr.config.json` file in the root of your project with the following c } ``` -You can find the full list of options for the `tsr.config.json` file in the [File-Based Routing](../routing/file-based-routing.md) guide. +You can find the full list of options for the `tsr.config.json` file [here](../../../routing/file-based-routing.md). ### Step 4: Create the routes directory @@ -249,19 +249,19 @@ You should now have successfully migrated your application from React Location t React Location also has a few more features that you might be using in your application. Here are some guides to help you migrate those features: -- [Search params](../guide/search-params.md) -- [Data loading](../guide/data-loading.md) -- [History types](../guide/history-types.md) -- [Wildcard / Splat / Catch-all routes](../routing/routing-concepts.md#splat--catch-all-routes) -- [Authenticated routes](../guide/authenticated-routes.md) +- [Search params](../../../guide/search-params.md) +- [Data loading](../../../guide/data-loading.md) +- [History types](../../../guide/history-types.md) +- [Wildcard / Splat / Catch-all routes](../../../routing/routing-concepts.md#splat--catch-all-routes) +- [Authenticated routes](../../../guide/authenticated-routes.md) TanStack Router also has a few more features that you might want to explore: -- [Router Context](../guide/router-context.md) -- [Preloading](../guide/preloading.md) -- [Pathless Layout Routes](../routing/routing-concepts.md#pathless-layout-routes) -- [Route masking](../guide/route-masking.md) -- [SSR](../guide/ssr.md) +- [Router Context](../../../guide/router-context.md) +- [Preloading](../../../guide/preloading.md) +- [Pathless Layout Routes](../../../routing/routing-concepts.md#pathless-layout-routes) +- [Route masking](../../../guide/route-masking.md) +- [SSR](../../../guide/ssr.md) - ... and more! If you are facing any issues or have any questions, feel free to ask for help in the TanStack Discord. diff --git a/docs/router/installation/migrate-from-react-router.md b/docs/router/framework/react/installation/migrate-from-react-router.md similarity index 98% rename from docs/router/installation/migrate-from-react-router.md rename to docs/router/framework/react/installation/migrate-from-react-router.md index 6903673bf7..9e6cb618ae 100644 --- a/docs/router/installation/migrate-from-react-router.md +++ b/docs/router/framework/react/installation/migrate-from-react-router.md @@ -7,7 +7,7 @@ toc: false Here is the [example repo](https://github.com/Benanna2019/SickFitsForEveryone/tree/migrate-to-tanstack/router/React-Router) -- [ ] Install Router - `npm i @tanstack/react-router` (see [detailed installation guide](../how-to/install.md)) +- [ ] Install Router - `npm i @tanstack/react-router` (see [detailed installation guide](../../../how-to/install.md)) - [ ] **Optional:** Uninstall React Router to get TypeScript errors on imports. - At this point I don’t know if you can do a gradual migration, but it seems likely you could have multiple router providers, not desirable. - The api’s between React Router and TanStack Router are very similar and could most likely be handled in a sprint cycle or two if that is your companies way of doing things. diff --git a/docs/router/guide/authenticated-routes.md b/docs/router/guide/authenticated-routes.md index 5e96fff2ca..e4885e983a 100644 --- a/docs/router/guide/authenticated-routes.md +++ b/docs/router/guide/authenticated-routes.md @@ -5,8 +5,6 @@ title: Authenticated Routes Authentication is an extremely common requirement for web applications. In this guide, we'll walk through how to use TanStack Router to build protected routes, and how to redirect users to login if they try to access them. -> **A route guard is not a data authorization boundary.** This guide shows how to gate a route's UI behind `beforeLoad`. Any server function, server route, or API endpoint that returns private data must authorize the request itself, because it can be requested independently of the route that calls it. See [Authentication Server Primitives](../../start/framework/react/guide/authentication-server-primitives.md) in the Start docs. - ## The `route.beforeLoad` Option The `route.beforeLoad` option allows you to specify a function that will be called before a route is loaded. It receives all of the same arguments that the `route.loader` function does. This is a great place to check if a user is authenticated, and redirect them to a login page if they are not. @@ -159,7 +157,7 @@ If your authentication flow relies on interactions with React context and/or hoo We'll cover the `router.context` options in-detail in the [Router Context](./router-context.md) section. -Here's an example that uses React context and hooks for protecting authenticated routes in TanStack Router. See the entire working setup in the [Authenticated Routes example](https://github.com/TanStack/router/tree/main/examples/react/authenticated-routes). +Here's an example that uses React context and hooks for protecting authenticated routes in TanStack Router. See a reference implementation in the [Authenticated Routes example](https://github.com/TanStack/router/tree/main/examples/react/authenticated-routes). @@ -337,4 +335,4 @@ Working authentication examples are available in the repository: - [Basic Authentication Example](https://github.com/TanStack/router/tree/main/examples/react/authenticated-routes) - Simple authentication with context - [Firebase Authentication](https://github.com/TanStack/router/tree/main/examples/react/authenticated-routes-firebase) - Firebase Auth integration -- [TanStack Start Auth Examples](https://github.com/TanStack/router/tree/main/examples/react) - Various auth implementations with TanStack Start +- [TanStack Start Authentication Overview](/router/latest/docs/framework/react/start/guide/authentication-overview) - Compare hosted, OSS, and DIY auth approaches for Start diff --git a/docs/router/guide/automatic-code-splitting.md b/docs/router/guide/automatic-code-splitting.md index 859a19ff09..4612c298c6 100644 --- a/docs/router/guide/automatic-code-splitting.md +++ b/docs/router/guide/automatic-code-splitting.md @@ -4,7 +4,7 @@ title: Automatic Code Splitting The automatic code splitting feature in TanStack Router allows you to optimize your application's bundle size by lazily loading route components and their associated data. This is particularly useful for large applications where you want to minimize the initial load time by only loading the necessary code for the current route. -To turn this feature on, simply set the `autoCodeSplitting` option to `true` in your bundler plugin configuration. This enables the router to automatically handle code splitting for your routes without requiring any additional setup. It is available with Vite, Rspack/Rsbuild and Webpack, not with Esbuild. +To turn this feature on, simply set the `autoCodeSplitting` option to `true` in your bundler plugin configuration. This enables the router to automatically handle code splitting for your routes without requiring any additional setup. ```ts // vite.config.ts @@ -35,7 +35,7 @@ This happens seamlessly, without requiring you to manually split your code or ma ### The transformation process -When you enable automatic code splitting, the bundler plugin does this by using static code analysis to look at the code in your route files and to transform them into optimized outputs. +When you enable automatic code splitting, the bundler plugin does this by using static code analysis look at your the code in your route files to transform them into optimized outputs. This transformation process produces two key outputs when each of your route files are processed: @@ -48,7 +48,7 @@ This process ensures that your original code remains clean and readable, while t The decision of what to split into separate chunks is crucial for optimizing your application's performance. TanStack Router uses a concept called "**Split Groupings**" to determine how different parts of your route should be bundled together. -Split groupings are arrays of properties that tell TanStack Router how to bundle different parts of your route together. Each grouping is a list of property names that you want to bundle together into a single lazy-loaded chunk. +Split groupings are arrays of properties that tell TanStack Router how to bundle different parts of your route together. Each grouping is an list of property names that you want to bundle together into a single lazy-loaded chunk. The available properties to split are: @@ -76,7 +76,7 @@ This means that it creates three separate lazy-loaded chunks for each route. Res ### Rules of Splitting -For automatic code splitting to work, there are some rules in place to make sure that this process can happen reliably and predictably. +For automatic code splitting to work, there are some rules in-place to make sure that this process can reliably and predictably happen. #### Do not export route properties diff --git a/docs/router/guide/code-splitting.md b/docs/router/guide/code-splitting.md index b1423253be..698bf262b5 100644 --- a/docs/router/guide/code-splitting.md +++ b/docs/router/guide/code-splitting.md @@ -115,7 +115,7 @@ These are the only options that `createLazyFileRoute` supports: ### Example code splitting with `.lazy.tsx` -When you are using `.lazy.tsx`, you can split your route into two files to enable code splitting: +When you are using `.lazy.tsx` you can split your route into two files to enable code splitting: **Before (Single File)** diff --git a/docs/router/guide/custom-link.md b/docs/router/guide/custom-link.md index dd7038cecd..24c2c2b5e3 100644 --- a/docs/router/guide/custom-link.md +++ b/docs/router/guide/custom-link.md @@ -174,7 +174,7 @@ export const CustomLink: LinkComponent = ( ### MUI example -There is an [example](https://github.com/TanStack/router/tree/main/examples/react/start-material-ui) available which uses these patterns. +These patterns are designed to work directly with MUI's `Link`/`Button` components in your app. #### `Link` diff --git a/docs/router/guide/data-loading.md b/docs/router/guide/data-loading.md index 6b9fd42777..80e85c1366 100644 --- a/docs/router/guide/data-loading.md +++ b/docs/router/guide/data-loading.md @@ -57,7 +57,7 @@ The router cache is built-in and is as easy as returning data from any route's ` ## Route `loader`s -Route `loader` functions are called when a route match is loaded. They are called with a single parameter which is an object containing many helpful properties. We'll go over those in a bit, but first, let's look at the two supported `loader` forms: +Route `loader` functions are called when a route match is loaded. They are called with a single parameter which is an object containing many helpful properties. We'll go over those in a bit, but first, let's look at an example of a route `loader` function: ```tsx // src/routes/posts.tsx @@ -66,22 +66,11 @@ export const Route = createFileRoute('/posts')({ }) ``` -```tsx -// src/routes/posts.tsx -export const Route = createFileRoute('/posts')({ - loader: { - handler: () => fetchPosts(), - }, -}) -``` - -Use the object form when you want to configure loader-specific behavior such as `staleReloadMode`. - ## `loader` Parameters The `loader` function receives a single object with the following properties: -- `abortController` - The controller for this shareable loader invocation. A preload and navigation can share the same in-flight loader work. Its signal is cancelled after the invocation becomes outdated and no consumer still needs it. +- `abortController` - The route's abortController. Its signal is cancelled when the route is unloaded or when the Route is no longer relevant and the current invocation of the `loader` function becomes outdated. - `cause` - The cause of the current route match. Can be either one of the following: - `enter` - When the route is matched and loaded after not being matched in the previous location. - `preload` - When the route is being preloaded. @@ -150,7 +139,7 @@ Using these dependencies as keys, TanStack Router will cache the data returned f To control router dependencies and "freshness", TanStack Router provides a plethora of options to control the keying and caching behavior of your route loaders. Let's take a look at them in the order that you are most likely to use them: - `routeOptions.loaderDeps` - - A deterministic, side-effect-free function that supplies you the validated search params for a router and returns a serializable object of dependencies for use in your `loader` function. When these deps change from navigation to navigation, it will cause the route to reload regardless of `staleTime`s. The deps are compared using a deep equality check. + - A function that supplies you the search params for a router and returns an object of dependencies for use in your `loader` function. When these deps changed from navigation to navigation, it will cause the route to reload regardless of `staleTime`s. The deps are compared using a deep equality check. - `routeOptions.staleTime` - `routerOptions.defaultStaleTime` - The number of milliseconds that a route's data should be considered fresh when attempting to load. @@ -162,17 +151,13 @@ To control router dependencies and "freshness", TanStack Router provides a pleth - The number of milliseconds that a route's data should be kept in the cache before being garbage collected. - `routeOptions.shouldReload` - A function that receives the same `beforeLoad` and `loaderContext` parameters and returns a boolean indicating if the route should reload. This offers one more level of control over when a route should reload beyond `staleTime` and `loaderDeps` and can be used to implement patterns similar to Remix's `shouldLoad` option. -- `routeOptions.loader.staleReloadMode` -- `routerOptions.defaultStaleReloadMode` - - Controls what happens when a matched route already has stale successful data. Use `'background'` for stale-while-revalidate, or `'blocking'` to wait for the stale loader reload to finish before continuing. ### ⚠️ Some Important Defaults -- By default, `staleTime` is set to `0`, so reusable successful data is immediately considered stale. When the same loader key is entered again or `router.load()` is called explicitly, stale data revalidates in the background by default. A different loader key identifies a separate cache entry and must load if it has no reusable data. -- By default, loader data produced by a preload is considered fresh for **30 seconds**. Every preload and navigation still runs its own `beforeLoad` chain, but a later preload and the first navigation can reuse the preload's loader data or in-flight loader work during that interval. After navigation accepts that loader generation, subsequent freshness checks use the standard `staleTime`. -- By default, `gcTime` and `preloadGcTime` define **5-minute** retention windows. Once unused data is older than its applicable window, it is eligible for pruning during a later cache reconciliation. The two windows can be configured independently. -- By default, `staleReloadMode` is `'background'`, so stale successful matches keep rendering with their existing `loaderData` while the loader revalidates in the background. -- `router.invalidate()` selects matching committed, cached, and in-flight loader generations for invalidation and retires matching active preload lanes. Current active routes reload through the normal loading protocol; cached inactive data remains marked stale and reloads when it is reused. By default, stale successful loader data revalidates in the background unless `sync: true` is requested. +- By default, the `staleTime` is set to `0`, meaning that the route's data will always be considered stale and will always be reloaded in the background when the route is rematched. +- By default, a previously preloaded route is considered fresh for **30 seconds**. This means if a route is preloaded, then preloaded again within 30 seconds, the second preload will be ignored. This prevents unnecessary preloads from happening too frequently. **When a route is loaded normally, the standard `staleTime` is used.** +- By default, the `gcTime` is set to **30 minutes**, meaning that any route data that has not been accessed in 30 minutes will be garbage collected and removed from the cache. +- `router.invalidate()` will force all active routes to reload their loaders immediately and mark every cached route's data as stale. ### Using `loaderDeps` to access search params @@ -180,11 +165,6 @@ Imagine a `/posts` route supports some pagination via search params `offset` and Once we have these deps in place, the route will always reload when the deps change. -`loaderDeps` defines a cache key during route planning. For the same validated -search input it must return the same value without navigating or mutating state. -The returned value and custom serialization methods such as `toJSON` must also -be side-effect-free. - ```tsx // /routes/posts.tsx export const Route = createFileRoute('/posts')({ @@ -221,13 +201,7 @@ export const Route = createFileRoute('/posts')({ ### Using `staleTime` to control how long data is considered fresh -By default, `staleTime` for accepted navigation data is `0`ms, while -`preloadStaleTime` is 30 seconds. A successful preload can therefore provide -loader data to the first navigation during that interval. Once navigation -accepts that loader generation, normal navigation freshness applies. With the -default `staleTime`, the data is immediately stale for a later use of the same -loader key and revalidates in the background while cached data remains visible. -A different loader key identifies a separate cache entry. +By default, `staleTime` for navigations is set to `0`ms (and 30 seconds for preloads) which means that the route's data will always be considered stale and will always be reloaded in the background when the route is matched and navigated to. **This is a good default for most use cases, but you may find that some route data is more static or potentially expensive to load.** In these cases, you can use the `staleTime` option to control how long the route's data is considered fresh for navigations. Let's take a look at an example: @@ -242,36 +216,9 @@ export const Route = createFileRoute('/posts')({ By passing `10_000` to the `staleTime` option, we are telling the router to consider the route's data fresh for 10 seconds. This means that if the user navigates to `/posts` from `/about` within 10 seconds of the last loader result, the route's data will not be reloaded. If the user then navigates to `/posts` from `/about` after 10 seconds, the route's data will be reloaded **in the background**. -## Choosing background vs blocking stale reloads +## Turning off stale-while-revalidate caching -By default, stale successful matches use stale-while-revalidate behavior. That means the router can render with the existing `loaderData` immediately and then refresh it in the background. - -If you want a specific loader to wait for a stale reload to finish before continuing, use the object form and set `staleReloadMode: 'blocking'`: - -```tsx -// /routes/posts.tsx -export const Route = createFileRoute('/posts')({ - loader: { - handler: () => fetchPosts(), - staleReloadMode: 'blocking', - }, -}) -``` - -You can also change the default for the entire router: - -```tsx -const router = createRouter({ - routeTree, - defaultStaleReloadMode: 'blocking', -}) -``` - -Use `'background'` when showing stale data during revalidation is acceptable. Use `'blocking'` when you want stale matches to behave more like a fresh load and wait for the new loader result. - -## Turning off automatic stale reloads - -To disable automatic stale reloads for a route, set the `staleTime` option to `Infinity`: +To disable stale-while-revalidate caching for a route, set the `staleTime` option to `Infinity`: ```tsx // /routes/posts.tsx @@ -290,11 +237,6 @@ const router = createRouter({ }) ``` -This differs from `staleReloadMode: 'blocking'`: - -- `staleTime: Infinity` prevents the route from becoming stale in the first place -- `staleReloadMode: 'blocking'` still allows stale reloads, but waits for them instead of doing them in the background - ## Using `shouldReload` and `gcTime` to opt-out of caching Similar to Remix's default functionality, you may want to configure a route to only load on entry or when critical loader deps change. You can do this by using the `gcTime` option combined with the `shouldReload` option, which accepts either a `boolean` or a function that receives the same `beforeLoad` and `loaderContext` parameters and returns a boolean indicating if the route should reload. @@ -313,16 +255,9 @@ export const Route = createFileRoute('/posts')({ ### Opting out of caching while still preloading -Even though you may opt out of retaining ordinary route data, you can still get -the benefits of preloading. Preloaded results use `preloadGcTime` for retention -and `preloadStaleTime` for freshness, so the default settings keep a recent -preload in memory and let the first navigation reuse it without another loader -call. +Even though you may opt-out of short-term caching for your route data, you can still get the benefits of preloading! With the above configuration, preloading will still "just work" with the default `preloadGcTime`. This means that if a route is preloaded, then navigated to, the route's data will be considered fresh and will not be reloaded. -Use `routerOptions.defaultPreload` to control automatic link preloading. Setting -`routeOptions.preload` to `false` has a narrower effect: a speculative lane -still runs that route's `beforeLoad`, but skips its `loader`. Navigation runs -both normally. +To opt out of preloading, don't turn it on via the `routerOptions.defaultPreload` or `routeOptions.preload` options. ## Passing all loader events to an external cache @@ -335,11 +270,7 @@ const router = createRouter({ }) ``` -This makes settled preload data immediately stale in the Router, allowing your -external cache to decide whether to fetch. Retention still follows -`preloadGcTime`, and overlapping preload or navigation consumers can still -share in-flight loader work. A route's `shouldReload` option can also suppress -a loader call. +This will ensure that every preload, load, and reload event will trigger your `loader` functions, which can then be handled and deduped by your external cache. ## Using Router Context @@ -494,7 +425,7 @@ export const Route = createFileRoute('/posts')({ ## Using the Abort Signal -The `abortController` property of the `loader` function is an [AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) for that loader invocation. A preload and navigation can share an in-flight invocation, so its signal remains active while any consumer still needs the work. The signal is cancelled after the invocation becomes outdated and has no remaining consumers. Here is an example using it with a fetch call: +The `abortController` property of the `loader` function is an [AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController). Its signal is cancelled when the route is unloaded or when the `loader` call becomes outdated. This is useful for cancelling network requests when the route is unloaded or when the route's params change. Here is an example using it with a fetch call: ```tsx // src/routes/posts.tsx @@ -570,7 +501,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) => { + onCatch: ({ error, errorInfo }) => { // Log the error console.error(error) }, @@ -581,20 +512,16 @@ 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 caught value (`unknown` in React and Vue; `Error` in Solid) +- `error` - The error that occurred - `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 instanceof Error ? error.message : String(error)}
+ return
{error.message}
}, }) ``` @@ -608,7 +535,7 @@ export const Route = createFileRoute('/posts')({ errorComponent: ({ error, reset }) => { return (
- {error instanceof Error ? error.message : String(error)} + {error.message} - ) -} -``` - --- Phew! That's a lot of navigating! That said, hopefully you're feeling pretty good about getting around your application now. Let's move on! diff --git a/docs/router/guide/not-found-errors.md b/docs/router/guide/not-found-errors.md index 88b8767a00..b4c6bc59a6 100644 --- a/docs/router/guide/not-found-errors.md +++ b/docs/router/guide/not-found-errors.md @@ -10,13 +10,13 @@ There are 2 uses for not-found errors in TanStack Router: - **Non-matching route paths**: When a path does not match any known route matching pattern **OR** when it partially matches a route, but with extra path segments - The **router** will automatically throw a not-found error when a path does not match any known route matching pattern - - If the router's `notFoundMode` is set to `fuzzy`, the nearest matching route with a `notFoundComponent` will handle the error. If the router's `notFoundMode` is set to `root`, the root route will handle the error. + - If the router's `notFoundMode` is set to `fuzzy`, the nearest parent route with a `notFoundComponent` will handle the error. If the router's `notFoundMode` is set to `root`, the root route will handle the error. - Examples: - Attempting to access `/users` when there is no `/users` route - Attempting to access `/posts/1/edit` when the route tree only handles `/posts/$postId` - **Missing resources**: When a resource cannot be found, such as a post with a given ID or any asynchronous data that is not available or does not exist - **You, the developer** must throw a not-found error when a resource cannot be found. This can be done in the `beforeLoad` or `loader` functions using the `notFound` utility. - - Will be handled by the nearest matching route with a `notFoundComponent` (when `notFound` is called within `loader`) or the root route. + - Will be handled by the nearest parent route with a `notFoundComponent` (when `notFound` is called within `loader`) or the root route. - Examples: - Attempting to access `/posts/1` when the post with ID 1 does not exist - Attempting to access `/docs/path/to/document` when the document does not exist @@ -27,19 +27,20 @@ Under the hood, both of these cases are implemented using the same `notFound` fu When TanStack Router encounters a **pathname** that doesn't match any known route pattern **OR** partially matches a route pattern but with extra trailing pathname segments, it will automatically throw a not-found error. -Depending on the `notFoundMode` option, the router will handle these automatic errors differently: +Depending on the `notFoundMode` option, the router will handle these automatic errors differently:: - ["fuzzy" mode](#notfoundmode-fuzzy) (default): The router will intelligently find the closest matching suitable route and display the `notFoundComponent`. - ["root" mode](#notfoundmode-root): All not-found errors will be handled by the root route's `notFoundComponent`, regardless of the nearest matching route. ### `notFoundMode: 'fuzzy'` -By default, the router's `notFoundMode` is set to `fuzzy`, which indicates that if a pathname doesn't match any known route, the router will attempt to use the closest matching route with a configured `notFoundComponent`. +By default, the router's `notFoundMode` is set to `fuzzy`, which indicates that if a pathname doesn't match any known route, the router will attempt to use the closest matching route with children/(an outlet) and a configured not found component. > **❓ Why is this the default?** Fuzzy matching to preserve as much parent layout as possible for the user gives them more context to navigate to a useful location based on where they thought they would arrive. The nearest suitable route is found using the following criteria: +- The route must have children and therefore an `Outlet` to render the `notFoundComponent` - The route must have a `notFoundComponent` configured or the router must have a `defaultNotFoundComponent` configured For example, consider the following route tree: @@ -52,10 +53,9 @@ If provided the path of `/posts/1/edit`, the following component structure will - `` - `` - - `` - - `` + - `` -The `notFoundComponent` of the `$postId` route will be rendered because it is the **nearest matching route with a `notFoundComponent` configured**. +The `notFoundComponent` of the `posts` route will be rendered because it is the **nearest suitable parent route with children (and therefore an outlet) and a `notFoundComponent` configured**. ### `notFoundMode: 'root'` @@ -166,13 +166,7 @@ The not-found error above will be handled by the same route or nearest parent ro If neither the route nor any suitable parent route is found to handle the error, the root route will handle it using TanStack Router's **extremely basic (and purposefully undesirable)** default not-found component that simply renders `

Not Found

`. It's highly recommended to either attach at least one `notFoundComponent` to the root route or configure a router-wide `defaultNotFoundComponent` to handle not-found errors. -> ⚠️ When you throw `notFound()` in `beforeLoad`, TanStack Router resolves it the same way as other not-found errors: -> -> - If you pass `routeId`, that route (or the nearest valid ancestor boundary) handles it. -> - If you don't pass `routeId`, the nearest route/ancestor with a `notFoundComponent` handles it (based on the router's mode and matching rules). -> - If no suitable boundary is found, handling falls back to the root/default not-found behavior. -> -> For `beforeLoad`-thrown not-found errors, TanStack Router still runs required parent loaders so the selected not-found boundary can render with the loader data it depends on. +> ⚠️ Throwing a notFound error in a beforeLoad method will always trigger the \_\_root notFoundComponent. Since beforeLoad methods are run prior to the route loader methods, there is no guarantee that any required data for layouts have successfully loaded before the error is thrown. ## Specifying Which Routes Handle Not Found Errors diff --git a/docs/router/guide/path-params.md b/docs/router/guide/path-params.md index d326eabb4b..c92aabe843 100644 --- a/docs/router/guide/path-params.md +++ b/docs/router/guide/path-params.md @@ -131,32 +131,6 @@ function PostComponent() { -## Prioritizing Parsed Path Param Routes - -When multiple dynamic, optional, or wildcard routes can match the same URL, routes with `params.parse` are tried before equivalent routes without it. If multiple matching candidates use `params.parse`, you can use `params.priority` to control which candidate is tried first. - -Higher `params.priority` values are tried first. The default priority is `0`, and if a higher-priority route's `params.parse` returns `false`, matching continues to the next candidate route. - -`params.parse` runs during route planning and may be evaluated more than once. -It must be deterministic and side-effect-free for the same raw params. - -```tsx title="src/routes/posts.$postId.tsx" -export const Route = createFileRoute('/posts/$postId')({ - params: { - priority: 10, - parse: ({ postId }) => { - if (!/^\d+$/.test(postId)) return false - return { postId: Number(postId) } - }, - stringify: ({ postId }) => ({ postId: String(postId) }), - }, -}) -``` - -With a fallback `/posts/$slug` route, `/posts/123` can match the parsed numeric route first, while `/posts/hello-world` can fall through to the slug route when `params.parse` returns `false`. - -`params.priority` only affects competing candidates that use `params.parse`. It does not override normal route specificity, so static routes still match before dynamic, optional, or wildcard routes. - ## Navigating with Path Params When navigating to a route with path params, TypeScript will require you to pass the params either as an object or as a function that returns an object of params. @@ -229,7 +203,7 @@ function PostComponent() { -You can even combine prefixes with wildcard routes to create more complex patterns: +You can even combines prefixes with wildcard routes to create more complex patterns: @@ -308,7 +282,7 @@ You can also combine suffixes with wildcards for more complex routing patterns: # React ```tsx title="src/routes/files/{$}[.]txt.tsx" -export const Route = createFileRoute('/files/{$}.txt')({ +export const Route = createFileRoute('/files/{$fileName}[.]txt')({ component: FileComponent, }) @@ -322,7 +296,7 @@ function FileComponent() { # Solid ```tsx title="src/routes/files/{$}[.]txt.tsx" -export const Route = createFileRoute('/files/{$}.txt')({ +export const Route = createFileRoute('/files/{$fileName}[.]txt')({ component: FileComponent, }) @@ -343,7 +317,7 @@ You can combine both prefixes and suffixes to create very specific routing patte # React -```tsx title="src/routes/users/user-{$userId}[.]json.tsx" +```tsx title="src/routes/users/user-{$userId}.json" export const Route = createFileRoute('/users/user-{$userId}.json')({ component: UserComponent, }) @@ -357,7 +331,7 @@ function UserComponent() { # Solid -```tsx title="src/routes/users/user-{$userId}[.]json.tsx" +```tsx title="src/routes/users/user-{$userId}.json" export const Route = createFileRoute('/users/user-{$userId}.json')({ component: UserComponent, }) @@ -481,7 +455,7 @@ Optional parameters support prefix and suffix patterns: # React -```tsx title="src/routes/files/prefix{-$name}[.]txt.tsx" +```tsx title="src/routes/files/prefix{-$name}.txt" // Route: /files/prefix{-$name}.txt // Matches: /files/prefix.txt and /files/prefixdocument.txt export const Route = createFileRoute('/files/prefix{-$name}.txt')({ @@ -496,7 +470,7 @@ function FileComponent() { # Solid -```tsx title="src/routes/files/prefix{-$name}[.]txt.tsx" +```tsx title="src/routes/files/prefix{-$name}.txt" // Route: /files/prefix{-$name}.txt // Matches: /files/prefix.txt and /files/prefixdocument.txt export const Route = createFileRoute('/files/prefix{-$name}.txt')({ @@ -585,10 +559,10 @@ Optional parameters can be combined with wildcards for complex routing patterns: # React -```tsx title="src/routes/docs/v{-$version}/$.tsx" -// Route: /docs/v{-$version}/$ +```tsx title="src/routes/docs/{-$version}/$.tsx" +// Route: /docs/{-$version}/$ // Matches: /docs/extra/path, /docs/v2/extra/path -export const Route = createFileRoute('/docs/v{-$version}/$')({ +export const Route = createFileRoute('/docs/{-$version}/$')({ component: DocsComponent, }) @@ -598,7 +572,7 @@ function DocsComponent() { return (
- Version: {version ? `v${version}` : 'latest'} + Version: {version || 'latest'} Path: {_splat}
) @@ -607,10 +581,10 @@ function DocsComponent() { # Solid -```tsx title="src/routes/docs/v{-$version}/$.tsx" -// Route: /docs/v{-$version}/$ +```tsx title="src/routes/docs/{-$version}/$.tsx" +// Route: /docs/{-$version}/$ // Matches: /docs/extra/path, /docs/v2/extra/path -export const Route = createFileRoute('/docs/v{-$version}/$')({ +export const Route = createFileRoute('/docs/{-$version}/$')({ component: DocsComponent, }) @@ -619,7 +593,7 @@ function DocsComponent() { return (
- Version: {params().version ? `v${params().version}` : 'latest'} + Version: {params().version || 'latest'} Path: {params()._splat}
) @@ -1395,8 +1369,6 @@ const router = createRouter({ }) ``` -This setting is fixed when the router is created. To use different allowed characters, create a new router instance. - The following is the list of accepted allowed characters: - `;` diff --git a/docs/router/guide/preloading.md b/docs/router/guide/preloading.md index 7f48412ce6..453294ab6e 100644 --- a/docs/router/guide/preloading.md +++ b/docs/router/guide/preloading.md @@ -18,17 +18,10 @@ Preloading in TanStack Router is a way to load a route before the user actually ## How long does preloaded data stay in memory? -Successful preloaded loader results can enter the router's in-memory cache with -two independent policies: +Preloaded route matches are temporarily cached in memory with a few important caveats: -- **Freshness defaults to 30 seconds.** Configure it with - `defaultPreloadStaleTime` or a route's `preloadStaleTime`. -- **The unused retention window defaults to 5 minutes.** Configure it with - `defaultPreloadGcTime` or a route's `preloadGcTime`. Older unused entries - are eligible for pruning during a later cache reconciliation. -- **The speculative lane is never promoted into router state.** Navigation - creates its own presentation and runs its own `beforeLoad` chain. It can reuse - cached loader data or join a loader that is still in flight. +- **Unused preloaded data is removed after 30 seconds by default.** This can be configured by setting the `defaultPreloadMaxAge` option on your router. +- **Obviously, when a route is loaded, its preloaded version is promoted to the router's normal pending matches state.** If you need more control over preloading, caching and/or garbage collection of preloaded data, you should use an external caching library like [TanStack Query](https://tanstack.com/query). @@ -64,7 +57,7 @@ This will turn on `intent` preloading by default for all `` components in ## Preload Delay -By default, intent focus/hover and viewport preloading start after **50ms**. Pending preloads are cancelled if focus or hover ends, or the link leaves the viewport. Touch intent preloads immediately. You can change this delay by setting the `defaultPreloadDelay` option on your router: +By default, preloading will start after **50ms** of the user hovering or touching a `` component. You can change this delay by setting the `defaultPreloadDelay` option on your router: @@ -94,16 +87,9 @@ const router = createRouter({ You can also set the `preloadDelay` prop on individual `` components to override the default behavior on a per-link basis. -## Built-in Preloading, Freshness, and Retention +## Built-in Preloading & `preloadStaleTime` -If you're using the built-in loaders, you can control how long preloaded data is considered fresh by setting either `routerOptions.defaultPreloadStaleTime` or `routeOptions.preloadStaleTime` to a number of milliseconds. **By default, preloaded data is considered fresh for 30 seconds.** - -Freshness and retention are separate. `preloadStaleTime` controls whether the -retained loader result can be reused without another loader call. -`preloadGcTime` (or `defaultPreloadGcTime`) controls when an unused preload -result becomes eligible for pruning during a later cache reconciliation; it -does not schedule a timer to evict the result at that exact moment. Both preload -GC options default to 5 minutes. +If you're using the built-in loaders, you can control how long preloaded data is considered fresh until another preload is triggered by setting either `routerOptions.defaultPreloadStaleTime` or `routeOptions.preloadStaleTime` to a number of milliseconds. **By default, preloaded data is considered fresh for 30 seconds.**. To change this, you can set the `defaultPreloadStaleTime` option on your router: @@ -139,34 +125,16 @@ Or, you can use the `routeOptions.preloadStaleTime` option on individual routes: // src/routes/posts.$postId.tsx export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params }) => fetchPost(params.postId), - // Reload preloaded data when it is more than 10 seconds old + // Preload the route again if the preload cache is older than 10 seconds preloadStaleTime: 10_000, }) ``` -Client-side preloading runs each route's `beforeLoad` with `preload: true`. -Every later preload or navigation runs its own `beforeLoad` chain, so a -navigation observes `preload: false` even when an identical preload is still -active. A later lane can reuse successful settled loader data or join loader -work that is still in flight, but it never reuses `beforeLoad` context or an -already-settled redirect, error, or not-found result. If joined loader work -later produces a terminal outcome, all current consumers of that flight observe -it. The `shouldReload` option remains loader-only. - -If a route has `preload: false`, its speculative lane still runs `beforeLoad`, -but skips that route's loader. Navigation runs `beforeLoad` again and performs -the skipped loader work. - ## Preloading with External Libraries When integrating external caching libraries like React Query, which have their own mechanisms for determining stale data, you may want to override the default preloading and stale-while-revalidate logic of TanStack Router. These libraries often use options like staleTime to control the freshness of data. -To let an external cache make the freshness decision, set -`routerOptions.defaultPreloadStaleTime` or `routeOptions.preloadStaleTime` to -`0`. Settled preload data then becomes immediately stale in the Router, while -retention still follows `preloadGcTime`. Overlapping preload or navigation -consumers can still share in-flight loader work, and `shouldReload` can still -suppress a loader call. +To customize the preloading behavior in TanStack Router and fully leverage your external library's caching strategy, you can bypass the built-in caching by setting routerOptions.defaultPreloadStaleTime or routeOptions.preloadStaleTime to 0. This ensures that all preloads are marked as stale internally, and loaders are always invoked, allowing your external library, such as React Query, to manage data loading and caching. For example: @@ -200,38 +168,25 @@ This would then allow you, for instance, to use an option like React Query's `st ## Preloading Manually -If you need to manually preload a route, use the router's `preloadRoute` method. -It accepts a standard TanStack `NavigateOptions` object and returns the -speculative match lane. An ordinary error or not-found thrown while loading is -represented in that returned lane; cancellation or control flow that produces -no reusable lane can return `undefined`. +If you need to manually preload a route, you can use the router's `preloadRoute` method. It accepts a standard TanStack `NavigateOptions` object and returns a promise that resolves when the route is preloaded. # React ```tsx -import { isNotFound } from '@tanstack/react-router' - function Component() { const router = useRouter() useEffect(() => { async function preload() { - const matches = await router.preloadRoute({ - to: postRoute, - params: { id: 1 }, - }) - - const routeFailure = matches?.find( - (match) => - match.status === 'error' || - match.status === 'notFound' || - isNotFound(match.error), - ) - - if (routeFailure) { - // Inspect routeFailure.error + try { + const matches = await router.preloadRoute({ + to: postRoute, + params: { id: 1 }, + }) + } catch (err) { + // Failed to preload route } } @@ -245,27 +200,18 @@ function Component() { # Solid ```tsx -import { isNotFound } from '@tanstack/solid-router' - function Component() { const router = useRouter() createEffect(() => { async function preload() { - const matches = await router.preloadRoute({ - to: postRoute, - params: { id: 1 }, - }) - - const routeFailure = matches?.find( - (match) => - match.status === 'error' || - match.status === 'notFound' || - isNotFound(match.error), - ) - - if (routeFailure) { - // Inspect routeFailure.error + try { + const matches = await router.preloadRoute({ + to: postRoute, + params: { id: 1 }, + }) + } catch (err) { + // Failed to preload route } } diff --git a/docs/router/guide/router-context.md b/docs/router/guide/router-context.md index 347082106f..5fc4001010 100644 --- a/docs/router/guide/router-context.md +++ b/docs/router/guide/router-context.md @@ -278,10 +278,9 @@ Then, in your route: export const Route = createFileRoute('/todos')({ component: Todos, loader: async ({ context }) => { - await context.queryClient.query({ + await context.queryClient.ensureQueryData({ queryKey: ['todos', { userId: user.id }], queryFn: fetchTodos, - staleTime: 'static', }) }, }) diff --git a/docs/router/guide/router-events.md b/docs/router/guide/router-events.md deleted file mode 100644 index ca798a9676..0000000000 --- a/docs/router/guide/router-events.md +++ /dev/null @@ -1,129 +0,0 @@ ---- -title: Router Events ---- - -TanStack Router exposes router lifecycle events through `router.subscribe`. This is useful for imperative side effects like analytics, resetting external state, or running DOM-dependent logic after navigation. - -## Basic usage - -`router.subscribe` takes an event name and a listener, then returns an unsubscribe function: - -```tsx -const unsubscribe = router.subscribe('onResolved', (event) => { - console.info('Navigation finished:', event.toLocation.href) -}) - -// Later, clean up the listener -unsubscribe() -``` - -## When to use it - -`router.subscribe` is best for imperative integrations that need to observe navigation without driving rendering: - -- Analytics and pageview tracking -- Resetting external caches or mutation state -- Logging navigation timing and transitions -- Running DOM-dependent logic after routes render - -If you need reactive UI updates, prefer framework hooks like `useRouterState`, `useSearch`, and `useParams` instead of subscribing manually. - -## Available events - -TanStack Router emits these lifecycle events: - -- `onBeforeNavigate` - right before a navigation begins -- `onBeforeLoad` - before route loading starts -- `onLoad` - after the next location has committed and route matches have loaded -- `onBeforeRouteMount` - after loading finishes, just before route components mount -- `onResolved` - after the navigation has fully resolved -- `onRendered` - after the route has rendered - -For the full event payload types, see the [`RouterEvents` type](../api/router/RouterEventsType.md). - -## Typical event flow - -For a normal navigation, the events usually flow like this: - -1. `onBeforeNavigate` -2. `onBeforeLoad` -3. `onLoad` -4. `onBeforeRouteMount` -5. `onResolved` -6. `onRendered` - -You usually do not need every event. A good rule of thumb is: - -- Use `onBeforeNavigate` or `onBeforeLoad` to observe navigation start -- Use `onResolved` for analytics and cleanup after navigation finishes -- Use `onRendered` for DOM-dependent work - -## Event payload - -Navigation events receive location change metadata describing what changed: - -```tsx -const unsubscribe = router.subscribe('onBeforeNavigate', (event) => { - console.info({ - from: event.fromLocation?.href, - to: event.toLocation.href, - pathChanged: event.pathChanged, - hrefChanged: event.hrefChanged, - hashChanged: event.hashChanged, - }) -}) -``` - -A few useful details: - -- `fromLocation` can be `undefined` on the initial load -- `pathChanged` tells you whether the pathname changed -- `hrefChanged` includes pathname, search, and hash changes -- `hashChanged` is useful for distinguishing hash-only navigations - -## Common patterns - -### Track pageviews - -`onResolved` is a good default for analytics because it fires after navigation finishes: - -```tsx -const unsubscribe = router.subscribe('onResolved', ({ toLocation }) => { - analytics.track('page_view', { - path: toLocation.pathname, - href: toLocation.href, - }) -}) -``` - -### Clear external mutation state - -If you use a mutation library without keyed mutation state, clear it after navigation: - -```tsx -const unsubscribe = router.subscribe('onResolved', ({ pathChanged }) => { - if (pathChanged) { - mutationCache.clear() - } -}) -``` - -### Run DOM-dependent logic - -Use `onRendered` when your side effect depends on the new route content already being in the DOM: - -```tsx -const unsubscribe = router.subscribe('onRendered', ({ toLocation }) => { - focusPageHeading(toLocation.pathname) -}) -``` - -## Unsubscribing in components - -If you subscribe from a component or framework effect, always return the unsubscribe function from your cleanup so the listener is removed when the component unmounts. - -## Related APIs - -- [`Router` type](../api/router/RouterType.md) -- [`RouterEvents` type](../api/router/RouterEventsType.md) -- [Data Mutations](./data-mutations.md) diff --git a/docs/router/guide/search-params.md b/docs/router/guide/search-params.md index cbc84c5526..53e9cd1c8a 100644 --- a/docs/router/guide/search-params.md +++ b/docs/router/guide/search-params.md @@ -196,9 +196,7 @@ For validation libraries we recommend using adapters which infer the correct `in ### Zod -An adapter is provided for [Zod](https://zod.dev/) which will pipe through the correct `input` type and `output` type. - -For Zod v3: +An adapter is provided for [Zod](https://zod.dev/) which will pipe through the correct `input` type and `output` type ```tsx import { zodValidator } from '@tanstack/zod-adapter' @@ -215,30 +213,13 @@ export const Route = createFileRoute('/shop/products/')({ }) ``` -With Zod v4, you should directly use the schema in `validateSearch`: - -```tsx -import { z } from 'zod' - -const productSearchSchema = z.object({ - page: z.number().default(1), - filter: z.string().default(''), - sort: z.enum(['newest', 'oldest', 'price']).default('newest'), -}) - -export const Route = createFileRoute('/shop/products/')({ - // With Zod v4, we can use the schema without the adapter - validateSearch: productSearchSchema, -}) -``` - -The important part here is the following use of `Link` no longer requires `search` params: +The important part here is the following use of `Link` no longer requires `search` params ```tsx ``` -In Zod v3, the use of `catch` here overrides the types and makes `page`, `filter` and `sort` `unknown` causing type loss. We have handled this case by providing a `fallback` generic function which retains the types but provides a `fallback` value when validation fails: +However the use of `catch` here overrides the types and makes `page`, `filter` and `sort` `unknown` causing type loss. We have handled this case by providing a `fallback` generic function which retains the types but provides a `fallback` value when validation fails ```tsx import { fallback, zodValidator } from '@tanstack/zod-adapter' @@ -259,9 +240,7 @@ export const Route = createFileRoute('/shop/products/')({ Therefore when navigating to this route, `search` is optional and retains the correct types. -In Zod v4, schemas may use `catch` instead of the fallback and will retain type inference throughout. - -While not recommended, it is also possible to configure `input` and `output` type in case the `output` type is more accurate than the `input` type: +While not recommended, it is also possible to configure `input` and `output` type in case the `output` type is more accurate than the `input` type ```tsx const productSearchSchema = z.object({ @@ -478,7 +457,7 @@ Now that you've learned how to read your route's search params, you'll be happy The best way to update search params is to use the `search` prop on the `` component. -If the search for the current page shall be updated and the `from` prop is specified, the `to` prop can be omitted. +If the search for the current page shall be updated and the `from` prop is specified, the `to` prop can be omitted. Here's an example: ```tsx title="src/routes/shop/products.tsx" @@ -499,7 +478,7 @@ const ProductList = () => { If you want to update the search params in a generic component that is rendered on multiple routes, specifying `from` can be challenging. -In this scenario you can set `to="."` which will give you access to loosely typed search params. +In this scenario you can set `to="."` which will give you access to loosely typed search params. Here is an example that illustrates this: ```tsx diff --git a/docs/router/guide/ssr.md b/docs/router/guide/ssr.md index 46a0941e7c..b51f1f2f7d 100644 --- a/docs/router/guide/ssr.md +++ b/docs/router/guide/ssr.md @@ -8,8 +8,6 @@ title: SSR Server Side Rendering (SSR) is the process of rendering a component on the server and sending the HTML markup to the client. The client then hydrates the markup into a fully interactive component. -> **TanStack Router is not Next.js, Remix, or React Router DOM.** When generating routes or components, do **not** use `src/pages/`, `app/layout.tsx`, `_app/index.tsx`, `getServerSideProps`, `getStaticProps`, Remix-style `loader`/`action` exports, or imports from `react-router-dom` or `next/`. TanStack uses `src/routes/` with `createFileRoute`, `Link`/`useNavigate`/`redirect` from `@tanstack/react-router`, and (for Start) `createServerFn` from `@tanstack/-start`. Wrong-framework code typically fails to build or produces conflicting `/` routes at runtime. - There are usually two different flavors of SSR to be considered: - Non-streaming SSR @@ -60,9 +58,7 @@ To implement non-streaming SSR with TanStack Router, you will need the following ### Automatic Server History -On the client, Router defaults to using an instance of `createBrowserHistory`. On the server, the Router SSR request handler and TanStack Start automatically create a lightweight history containing only the request URL. This history does not keep a navigation stack or respond to `push`, `replace`, `go`, `back`, or `forward` calls. - -Server-side calls to `router.navigate()` and `router.commitLocation()` are also no-ops: their promises resolve without changing the request location or running another load. To redirect a request, use the dedicated [redirect API](../api/router/redirectFunction.md), such as `throw redirect({ to: '/login' })` in `beforeLoad` or a loader. +On the client, Router defaults to using an instance of `createBrowserHistory`, which is the preferred type of history to use on the client. On the server, however, you will want to use an instance of `createMemoryHistory` instead. This is because `createBrowserHistory` uses the `window` object, which does not exist on the server. This is handled automatically for you in the RouterServer component. ### Automatic Loader Dehydration/Hydration @@ -127,7 +123,7 @@ using `defaultRenderHandler` ```tsx title="src/entry-server.tsx" import { createRequestHandler, - defaultRenderHandler, + defaultRenderToString, } from '@tanstack/react-router/ssr/server' import { createRouter } from './router' @@ -143,7 +139,7 @@ export async function render({ request }: { request: Request }) { ```tsx title="src/entry-server.tsx" import { createRequestHandler, - defaultRenderHandler, + defaultRenderToString, } from '@tanstack/solid-router/ssr/server' import { createRouter } from './router' @@ -158,8 +154,6 @@ export async function render({ request }: { request: Request }) { using `renderRouterToString` -React and Solid use their native synchronous string renderers. Suspended components render their Suspense fallback without waiting for the component to resolve. The router still finishes serializing hydration data before returning the response. Use `renderRouterToStream` when you need the server to render suspended content after it resolves. - # React @@ -262,9 +256,6 @@ This pattern can be useful for pages that have slow or high-latency data fetchin > [!NOTE] > This streaming pattern is all automatic as long as you are using either `defaultStreamHandler` or `renderRouterToStream`. -> [!IMPORTANT] -> Render [``](./document-head-management.md#scripts) inside `` of your root route. It emits the route scripts and marks where the router inserts streamed hydration data. Without it the response still completes, but the page cannot hydrate. - using `defaultStreamHandler` diff --git a/docs/router/guide/type-safety.md b/docs/router/guide/type-safety.md index 3faaed79e7..2adffc58c5 100644 --- a/docs/router/guide/type-safety.md +++ b/docs/router/guide/type-safety.md @@ -137,13 +137,12 @@ As your application scales, TypeScript check times will naturally increase. Ther ### Only infer types you need -A great pattern with client side data caches (TanStack Query, etc.) is to prefetch data. For example with TanStack Query you might have a route which calls `queryClient.query` in a `loader`. +A great pattern with client side data caches (TanStack Query, etc.) is to prefetch data. For example with TanStack Query you might have a route which calls `queryClient.ensureQueryData` in a `loader`. ```tsx export const Route = createFileRoute('/posts/$postId/deep')({ - // (ctx: LoaderFnContext) => Promise loader: ({ context: { queryClient }, params: { postId } }) => - queryClient.query({ ...postQueryOptions(postId), staleTime: 'static' }), + queryClient.ensureQueryData(postQueryOptions(postId)), component: PostDeepComponent, }) @@ -155,16 +154,12 @@ function PostDeepComponent() { } ``` -This may look fine and for small route trees and you may not notice any TS performance issues. However in this case TS has to infer the loader's return type, despite it never being used in your route. If the loader data is a complex type with many routes that prefetch in this manner, it can slow down editor performance. In this case, the change is quite simple and let typescript infer `Promise`. +This may look fine and for small route trees and you may not notice any TS performance issues. However in this case TS has to infer the loader's return type, despite it never being used in your route. If the loader data is a complex type with many routes that prefetch in this manner, it can slow down editor performance. In this case, the change is quite simple and let typescript infer Promise. ```tsx export const Route = createFileRoute('/posts/$postId/deep')({ - // (ctx: LoaderFnContext) => Promise loader: async ({ context: { queryClient }, params: { postId } }) => { - await queryClient.query({ - ...postQueryOptions(postId), - staleTime: 'static', - }) + await queryClient.ensureQueryData(postQueryOptions(postId)) }, component: PostDeepComponent, }) diff --git a/docs/router/guide/url-rewrites.md b/docs/router/guide/url-rewrites.md index e780e01781..32aef6bdf4 100644 --- a/docs/router/guide/url-rewrites.md +++ b/docs/router/guide/url-rewrites.md @@ -343,8 +343,6 @@ const navigate = useNavigate() navigate({ to: '/about' }) ``` -When the final output URL has a different origin, programmatic navigation performs a full page load automatically. You do not need to set `reloadDocument: true` for cross-origin rewrites. If a route mask is applied, its output URL determines whether navigation stays on the current origin. - ### Hard Links for Cross-Origin Rewrites When an output rewrite changes the origin (hostname), the `` component automatically renders a standard anchor tag instead of using client-side navigation: @@ -490,9 +488,9 @@ const composedRewrite = composeRewrites([ ## Examples -Complete working examples are available in the TanStack Router repository: +Reference implementations and guides: - [React + Paraglide (Client-side i18n)](https://github.com/TanStack/router/tree/main/examples/react/i18n-paraglide) -- [React + TanStack Start + Paraglide (SSR i18n)](https://github.com/TanStack/router/tree/main/examples/react/start-i18n-paraglide) +- [React + TanStack Start + Paraglide (SSR i18n)](https://tanstack.com/router/latest/docs/framework/react/start/guide/middleware) - [Solid + Paraglide (Client-side i18n)](https://github.com/TanStack/router/tree/main/examples/solid/i18n-paraglide) -- [Solid + TanStack Start + Paraglide (SSR i18n)](https://github.com/TanStack/router/tree/main/examples/solid/start-i18n-paraglide) +- [Solid + TanStack Start + Paraglide (SSR i18n)](https://tanstack.com/router/latest/docs/framework/solid/start/guide/middleware) diff --git a/docs/router/how-to/arrays-objects-dates-search-params.md b/docs/router/how-to/arrays-objects-dates-search-params.md index 4efbdab30f..3c0613434e 100644 --- a/docs/router/how-to/arrays-objects-dates-search-params.md +++ b/docs/router/how-to/arrays-objects-dates-search-params.md @@ -165,7 +165,7 @@ const dashboardSchema = z.object({ columns: z.number().min(1).max(6).default(3), showDetails: z.boolean().default(false), }) - .prefault({}), + .default({}), filters: z .object({ @@ -176,9 +176,9 @@ const dashboardSchema = z.object({ before: z.string().optional(), }) .optional(), - metadata: z.record(z.string(), z.string()).optional(), // Dynamic object keys + metadata: z.record(z.string()).optional(), // Dynamic object keys }) - .prefault({}), + .default({}), }) export const Route = createFileRoute('/dashboard')({ @@ -459,7 +459,7 @@ const analyticsSchema = z.object({ gap: z.number().default(16), responsive: z.boolean().default(true), }) - .prefault({}), + .default({}), timeRange: z .object({ @@ -471,9 +471,9 @@ const analyticsSchema = z.object({ }) .optional(), }) - .prefault({}), + .default({}), }) - .prefault({}), + .default({}), }) export const Route = createFileRoute('/analytics')({ diff --git a/docs/router/how-to/debug-router-issues.md b/docs/router/how-to/debug-router-issues.md index 27dadd361f..b4d20ec72f 100644 --- a/docs/router/how-to/debug-router-issues.md +++ b/docs/router/how-to/debug-router-issues.md @@ -322,16 +322,11 @@ const route = createRoute({ ```tsx function DataLoadingDebug() { - const state = useRouterState() + const location = useLocation() console.log('Route status:', { - status: state.status, - isLoading: state.isLoading, - matches: state.matches.map((match) => ({ - routeId: match.routeId, - status: match.status, - isFetching: match.isFetching, - })), + isLoading: location.isLoading, + isTransitioning: location.isTransitioning, }) return null diff --git a/docs/router/how-to/setup-authentication.md b/docs/router/how-to/setup-authentication.md index 2ef819c676..f3f8d08df4 100644 --- a/docs/router/how-to/setup-authentication.md +++ b/docs/router/how-to/setup-authentication.md @@ -482,4 +482,4 @@ After setting up basic authentication, you might want to: - [Authenticated Routes Guide](../guide/authenticated-routes.md) - Detailed conceptual guide - [Router Context Guide](../guide/router-context.md) - Understanding context in TanStack Router -- [Authentication Examples](https://github.com/TanStack/router/tree/main/examples/react/authenticated-routes) - Complete working examples +- [Authenticated Routes Guide](../guide/authenticated-routes.md) - End-to-end route protection patterns diff --git a/docs/router/how-to/setup-basic-search-params.md b/docs/router/how-to/setup-basic-search-params.md index e85579f5f4..8c9cbbe2e8 100644 --- a/docs/router/how-to/setup-basic-search-params.md +++ b/docs/router/how-to/setup-basic-search-params.md @@ -10,16 +10,17 @@ Set up search parameters with schema validation (recommended for production): ```tsx import { createFileRoute } from '@tanstack/react-router' +import { zodValidator, fallback } from '@tanstack/zod-adapter' import { z } from 'zod' const productSearchSchema = z.object({ - page: z.number().default(1).catch(1), - category: z.string().default('all').catch('all'), - showSale: z.boolean().default(false).catch(false), + page: fallback(z.number(), 1).default(1), + category: fallback(z.string(), 'all').default('all'), + showSale: fallback(z.boolean(), false).default(false), }) export const Route = createFileRoute('/products')({ - validateSearch: productSearchSchema, + validateSearch: zodValidator(productSearchSchema), component: ProductsPage, }) @@ -49,25 +50,7 @@ function ProductsPage() { ## Validation Library Setup -TanStack Router supports any standard schema-compliant validation library. This guide focuses on Zod for examples, but you can use any validation library. - -Using Zod v4: - -```tsx -import { z } from 'zod' - -const searchSchema = z.object({ - page: z.number().default(1), - category: z.string().default('all').catch('all'), -}) - -export const Route = createFileRoute('/products')({ - validateSearch: searchSchema, - component: ProductsPage, -}) -``` - -For Zod v3: +TanStack Router supports any standard schema-compliant validation library. This guide focuses on Zod for examples, but you can use any validation library: ```bash npm install zod @tanstack/zod-adapter @@ -92,49 +75,58 @@ export const Route = createFileRoute('/products')({ ## Step-by-Step Setup with Zod -The rest of this guide uses Zod v4 for examples, but the patterns apply to any validation library. +The rest of this guide uses Zod for examples, but the patterns apply to any validation library. -### Step 1: Define Your Search Schema +### Step 1: Install Dependencies + +```bash +npm install zod @tanstack/zod-adapter +``` + +### Step 2: Define Your Search Schema Start by identifying what search parameters your route needs: ```tsx import { z } from 'zod' +import { fallback } from '@tanstack/zod-adapter' const shopSearchSchema = z.object({ // Pagination - page: z.number().default(1), - limit: z.number().default(20), + page: fallback(z.number(), 1).default(1), + limit: fallback(z.number(), 20).default(20), // Filtering - category: z.string().default('all'), - minPrice: z.number().default(0), - maxPrice: z.number().default(1000), + category: fallback(z.string(), 'all').default('all'), + minPrice: fallback(z.number(), 0).default(0), + maxPrice: fallback(z.number(), 1000).default(1000), // Settings - sort: z.enum(['name', 'price', 'date']).default('name'), - ascending: z.boolean().default(true), + sort: fallback(z.enum(['name', 'price', 'date']), 'name').default('name'), + ascending: fallback(z.boolean(), true).default(true), // Optional parameters searchTerm: z.string().optional(), - showOnlyInStock: z.boolean().default(false), + showOnlyInStock: fallback(z.boolean(), false).default(false), }) type ShopSearch = z.infer ``` -### Step 2: Add Schema Validation to Route +### Step 3: Add Schema Validation to Route -Connect your schema to the route: +Use the validation adapter to connect your schema to the route: ```tsx +import { zodValidator } from '@tanstack/zod-adapter' + export const Route = createFileRoute('/shop')({ - validateSearch: shopSearchSchema, + validateSearch: zodValidator(shopSearchSchema), component: ShopPage, }) ``` -### Step 3: Read Search Parameters in Components +### Step 4: Read Search Parameters in Components Use the route's `useSearch()` hook to access validated and typed search parameters: @@ -174,12 +166,12 @@ function ShopPage() { ```tsx const paginationSchema = z.object({ - page: z.number().min(1).default(1), - limit: z.number().min(10).max(100).default(20), + page: fallback(z.number().min(1), 1).default(1), + limit: fallback(z.number().min(10).max(100), 20).default(20), }) export const Route = createFileRoute('/posts')({ - validateSearch: paginationSchema, + validateSearch: zodValidator(paginationSchema), component: PostsPage, }) @@ -204,13 +196,16 @@ function PostsPage() { ```tsx const catalogSchema = z.object({ - sort: z.enum(['name', 'date', 'price']).default('name'), - category: z.enum(['electronics', 'clothing', 'books', 'all']).default('all'), - ascending: z.boolean().default(true), + sort: fallback(z.enum(['name', 'date', 'price']), 'name').default('name'), + category: fallback( + z.enum(['electronics', 'clothing', 'books', 'all']), + 'all', + ).default('all'), + ascending: fallback(z.boolean(), true).default(true), }) export const Route = createFileRoute('/catalog')({ - validateSearch: catalogSchema, + validateSearch: zodValidator(catalogSchema), component: CatalogPage, }) ``` @@ -220,24 +215,27 @@ export const Route = createFileRoute('/catalog')({ ```tsx const dashboardSchema = z.object({ // Numbers with validation - userId: z.number().positive().default(1), - refreshInterval: z.number().min(1000).max(60000).default(5000), + userId: fallback(z.number().positive(), 1).default(1), + refreshInterval: fallback(z.number().min(1000).max(60000), 5000).default( + 5000, + ), // Strings with validation - theme: z.enum(['light', 'dark']).default('light'), + theme: fallback(z.enum(['light', 'dark']), 'light').default('light'), timezone: z.string().optional(), // Arrays with validation - selectedIds: z.number().array().default([]), - tags: z.string().array().default([]), + selectedIds: fallback(z.number().array(), []).default([]), + tags: fallback(z.string().array(), []).default([]), // Objects with validation - filters: z - .object({ + filters: fallback( + z.object({ status: z.enum(['active', 'inactive']).optional(), type: z.string().optional(), - }) - .prefault({}), + }), + {}, + ).default({}), }) ``` @@ -247,8 +245,8 @@ const dashboardSchema = z.object({ const reportSchema = z.object({ startDate: z.string().pipe(z.coerce.date()).optional(), endDate: z.string().pipe(z.coerce.date()).optional(), - format: z.enum(['pdf', 'csv', 'excel']).default('pdf').catch('pdf'), - includeCharts: z.boolean().default(true), + format: fallback(z.enum(['pdf', 'csv', 'excel']), 'pdf').default('pdf'), + includeCharts: fallback(z.boolean(), true).default(true), }) ``` @@ -344,12 +342,12 @@ export const Route = createFileRoute('/page')({ // ✅ Complete schema with proper validation const searchSchema = z.object({ - page: z.number().default(1).catch(1), - category: z.string().default('all').catch('all'), + page: fallback(z.number(), 1).default(1), + category: fallback(z.string(), 'all').default('all'), }) export const Route = createFileRoute('/page')({ - validateSearch: searchSchema, + validateSearch: zodValidator(searchSchema), component: MyPage, }) ``` @@ -368,7 +366,7 @@ const schema = z.object({ // ✅ Graceful fallback handling const schema = z.object({ - page: z.number().default(1).catch(1), // Safe fallback to 1 + page: fallback(z.number(), 1).default(1), // Safe fallback to 1 }) ``` @@ -381,7 +379,7 @@ const schema = z.object({ ```tsx const schema = z.object({ // Required with default (navigation can omit, but always present in component) - page: z.number().default(1).catch(1), + page: fallback(z.number(), 1).default(1), // Truly optional (can be undefined in component) searchTerm: z.string().optional(), @@ -396,8 +394,8 @@ const schema = z.object({ ```tsx const schema = z.object({ - filters: z - .object({ + filters: fallback( + z.object({ status: z.enum(['active', 'inactive']).optional(), tags: z.string().array().optional(), dateRange: z @@ -406,9 +404,9 @@ const schema = z.object({ end: z.string().pipe(z.coerce.date()), }) .optional(), - }) - .prefault({}) - .catch({}), + }), + {}, + ).default({}), }) ``` diff --git a/docs/router/how-to/setup-ssr.md b/docs/router/how-to/setup-ssr.md index 08c1e4ca4b..6a72cc945a 100644 --- a/docs/router/how-to/setup-ssr.md +++ b/docs/router/how-to/setup-ssr.md @@ -163,7 +163,7 @@ export default defineConfig(({ isSsrBuild }) => ({ outDir: 'dist/server', emitAssets: true, copyPublicDir: false, - rolldownOptions: { + rollupOptions: { input: path.resolve(__dirname, 'src/entry-server.tsx'), output: { entryFileNames: '[name].js', @@ -177,7 +177,7 @@ export default defineConfig(({ isSsrBuild }) => ({ outDir: 'dist/client', emitAssets: true, copyPublicDir: true, - rolldownOptions: { + rollupOptions: { input: path.resolve(__dirname, 'src/entry-client.tsx'), output: { entryFileNames: '[name].js', @@ -530,7 +530,7 @@ const ssrConfig = { outDir: 'dist/server', ssrEmitAssets: true, // Important for asset handling copyPublicDir: false, - rolldownOptions: { + rollupOptions: { input: path.resolve(__dirname, 'src/entry-server.tsx'), external: ['express', 'compression'], // External deps }, diff --git a/docs/router/how-to/setup-testing.md b/docs/router/how-to/setup-testing.md index 104cbedc0d..72f40032cf 100644 --- a/docs/router/how-to/setup-testing.md +++ b/docs/router/how-to/setup-testing.md @@ -224,12 +224,8 @@ export function LoadingComponent() { return
Loading...
} -export function ErrorComponent({ error }: { error: unknown }) { - return ( -
- Error: {error instanceof Error ? error.message : String(error)} -
- ) +export function ErrorComponent({ error }: { error: Error }) { + return
Error: {error.message}
} ``` @@ -590,12 +586,8 @@ describe('Code-Based Route Data Loading', () => { return
{user.name}
} - function ErrorComponent({ error }: { error: unknown }) { - return ( -
- Error: {error instanceof Error ? error.message : String(error)} -
- ) + function ErrorComponent({ error }: { error: Error }) { + return
Error: {error.message}
} const userRoute = createRoute({ @@ -659,10 +651,9 @@ describe('React Query Integration', () => { path: '/posts', component: PostsList, loader: ({ context: { queryClient } }) => - queryClient.query({ + queryClient.ensureQueryData({ queryKey: ['posts'], queryFn: mockFetchPosts, - staleTime: 'static', }), }) diff --git a/docs/router/how-to/share-search-params-across-routes.md b/docs/router/how-to/share-search-params-across-routes.md index 23a202b176..145d1f089b 100644 --- a/docs/router/how-to/share-search-params-across-routes.md +++ b/docs/router/how-to/share-search-params-across-routes.md @@ -2,6 +2,8 @@ title: Share Search Parameters Across Routes --- +# How to Share Search Parameters Across Routes + Search parameters automatically inherit from parent routes in TanStack Router. When a parent route validates search parameters, child routes can access them via `Route.useSearch()` alongside their own parameters. ## How Parameter Inheritance Works @@ -19,6 +21,7 @@ Share parameters across your entire application by validating them in the root r ```tsx // routes/__root.tsx import { createRootRoute, Outlet } from '@tanstack/react-router' +import { zodValidator } from '@tanstack/zod-adapter' import { z } from 'zod' const globalSearchSchema = z.object({ @@ -28,7 +31,7 @@ const globalSearchSchema = z.object({ }) export const Route = createRootRoute({ - validateSearch: globalSearchSchema, + validateSearch: zodValidator(globalSearchSchema), component: RootComponent, }) @@ -47,6 +50,7 @@ function RootComponent() { ```tsx // routes/products/index.tsx import { createFileRoute } from '@tanstack/react-router' +import { zodValidator } from '@tanstack/zod-adapter' import { z } from 'zod' const productSearchSchema = z.object({ @@ -55,7 +59,7 @@ const productSearchSchema = z.object({ }) export const Route = createFileRoute('/products/')({ - validateSearch: productSearchSchema, + validateSearch: zodValidator(productSearchSchema), component: ProductsPage, }) @@ -80,6 +84,7 @@ Share parameters within a section of your app using layout routes: ```tsx // routes/_authenticated.tsx import { createFileRoute, Outlet } from '@tanstack/react-router' +import { zodValidator } from '@tanstack/zod-adapter' import { z } from 'zod' const authSearchSchema = z.object({ @@ -89,7 +94,7 @@ const authSearchSchema = z.object({ }) export const Route = createFileRoute('/_authenticated')({ - validateSearch: authSearchSchema, + validateSearch: zodValidator(authSearchSchema), component: AuthenticatedLayout, }) @@ -176,7 +181,7 @@ function ProductsPage() { ```tsx // ✅ Root route validates shared parameters export const Route = createRootRoute({ - validateSearch: globalSearchSchema, + validateSearch: zodValidator(globalSearchSchema), component: RootComponent, }) ``` diff --git a/docs/router/how-to/use-environment-variables.md b/docs/router/how-to/use-environment-variables.md index 4f6a764f28..2d35308158 100644 --- a/docs/router/how-to/use-environment-variables.md +++ b/docs/router/how-to/use-environment-variables.md @@ -164,7 +164,7 @@ const fetchPosts = async () => { export const Route = createFileRoute('/posts/')({ loader: fetchPosts, errorComponent: ({ error }) => ( -
Error loading posts: {error instanceof Error ? error.message : String(error)}
+
Error loading posts: {error.message}
), }) ``` diff --git a/docs/router/how-to/validate-search-params.md b/docs/router/how-to/validate-search-params.md index 15d3f9d6c8..bb141a5a19 100644 --- a/docs/router/how-to/validate-search-params.md +++ b/docs/router/how-to/validate-search-params.md @@ -12,14 +12,15 @@ Add robust validation with custom error messages, complex types, and production- ```tsx import { createFileRoute, useRouter } from '@tanstack/react-router' +import { zodValidator, fallback } from '@tanstack/zod-adapter' import { z } from 'zod' const productSearchSchema = z.object({ query: z.string().min(1, 'Search query required'), category: z.enum(['electronics', 'clothing', 'books', 'home']).optional(), - minPrice: z.number().min(0, 'Price cannot be negative').default(0), - maxPrice: z.number().min(0, 'Price cannot be negative').default(1000), - inStock: z.boolean().default(true), + minPrice: fallback(z.number().min(0, 'Price cannot be negative'), 0), + maxPrice: fallback(z.number().min(0, 'Price cannot be negative'), 1000), + inStock: fallback(z.boolean(), true), tags: z.array(z.string()).optional(), dateRange: z .object({ @@ -30,13 +31,13 @@ const productSearchSchema = z.object({ }) export const Route = createFileRoute('/products')({ - validateSearch: productSearchSchema, + validateSearch: zodValidator(productSearchSchema), errorComponent: ({ error }) => { const router = useRouter() return (

Invalid Search Parameters

-

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

+

{error.message}

diff --git a/docs/router/installation/manual.md b/docs/router/installation/manual.md index ab89060ef1..76d1f1fe6a 100644 --- a/docs/router/installation/manual.md +++ b/docs/router/installation/manual.md @@ -232,7 +232,7 @@ render(() => , rootElement) Regardless of whether you are using the `@tanstack/router-plugin` package and running the `npm run dev`/`npm run build` scripts, or manually running the `tsr watch`/`tsr generate` commands from your package scripts, the route tree file will be generated at `src/routeTree.gen.ts`. -If you are working with this pattern, you should change the `id` of the root `
` on your `index.html` file to `
` +If you are working with this pattern you should change the `id` of the root `
` on your `index.html` file to `
` ## Using Code-Based Route Configuration diff --git a/docs/router/installation/with-esbuild.md b/docs/router/installation/with-esbuild.md index 8ecd9b8d0a..b5cad0622c 100644 --- a/docs/router/installation/with-esbuild.md +++ b/docs/router/installation/with-esbuild.md @@ -25,6 +25,7 @@ export default { plugins: [ tanstackRouter({ target: 'react', + autoCodeSplitting: true, }), ], } @@ -49,7 +50,10 @@ const ctx = await esbuild.context({ format: 'esm', target: ['esnext'], sourcemap: true, - plugins: [solidPlugin(), tanstackRouter({ target: 'solid' })], + plugins: [ + solidPlugin(), + tanstackRouter({ target: 'solid', autoCodeSplitting: true }), + ], }) if (isDev) { @@ -68,9 +72,6 @@ Or, you can clone our [Quickstart Esbuild example](https://github.com/TanStack/r Now that you've added the plugin to your Esbuild configuration, you're all set to start using file-based routing with TanStack Router. -> [!NOTE] -> Automatic code splitting is not available with Esbuild: the plugin throws an error when `autoCodeSplitting` is `true`. Route generation works as usual. To split routes, use [manual code splitting](../guide/code-splitting.md) or another bundler. - ## Ignoring the generated route tree file If your project is configured to use a linter and/or formatter, you may want to ignore the generated route tree file. This file is managed by TanStack Router and therefore shouldn't be changed by your linter or formatter. diff --git a/docs/router/integrations/query.md b/docs/router/integrations/query.md index 707f90900c..22fbb927c8 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 @@ -64,61 +64,6 @@ export function getRouter() { By default, the integration wraps your router with a `QueryClientProvider`. If you already provide your own provider, pass `wrapQueryClient: false` and keep your custom wrapper. -You can also pass `dehydrateOptions` and `hydrateOptions` to customize how TanStack Query serializes SSR payloads and restores them on the client. - -```tsx -setupRouterSsrQueryIntegration({ - router, - queryClient, - dehydrateOptions: { - shouldDehydrateQuery: (query) => query.meta?.ssr !== false, - }, - hydrateOptions: { - defaultOptions: { - queries: { - gcTime: 60_000, - }, - }, - }, -}) -``` - -Common uses for these options: - -- Set `hydrateOptions.defaultOptions.queries.gcTime` to control how long hydrated SSR queries stay in the client cache before garbage collection. -- Set `dehydrateOptions.shouldDehydrateQuery` to exclude queries you do not want serialized into the HTML payload. -- Set `dehydrateOptions.serializeData` and `hydrateOptions.defaultOptions.deserializeData` when your SSR payload needs custom serialization. - -```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() - - const router = createRouter({ - routeTree, - context: { queryClient }, - }) - - setupRouterSsrQueryIntegration({ - router, - queryClient, - hydrateOptions: { - defaultOptions: { - queries: { - gcTime: 5 * 60 * 1000, - }, - }, - }, - }) - - return router -} -``` - ## SSR behavior and streaming - During server render, the integration dehydrates initial queries and streams any subsequent queries that resolve while rendering. @@ -132,6 +77,14 @@ export function getRouter() { - `useSuspenseQuery`: runs on the server during SSR when its data is required and will be streamed to the client as it resolves. - `useQuery`: does not execute on the server; it will fetch on the client after hydration. Use this for data that is not required for SSR. +```tsx +// Suspense: executes on server and streams +const { data } = useSuspenseQuery(postsQuery) + +// Non-suspense: executes only on client +const { data, isLoading } = useQuery(postsQuery) +``` + # React @@ -152,7 +105,7 @@ Preload critical data in the route `loader` to avoid waterfalls and loading flas -# Blocking `query` in loader +# React ```tsx title="src/routes/posts.tsx" import { queryOptions, useSuspenseQuery, useQuery } from '@tanstack/react-query' @@ -165,12 +118,7 @@ const postsQuery = queryOptions({ export const Route = createFileRoute('/posts')({ // Ensure the data is in the cache before render - loader: ({ context }) => - context.queryClient.query({ - ...postsQuery, - // returns data from cache immediately, otherwise executes a fetch - staleTime: 'static', - }), + loader: ({ context }) => context.queryClient.ensureQueryData(postsQuery), component: PostsPage, }) @@ -185,15 +133,15 @@ function PostsPage() { ### Prefetching and streaming -You can also prefetch with `query` in a loader without consuming the data in a component. If you return the promise directly from the loader, it will be awaited and thus block the SSR request until the query finishes. If you don't await the promise nor return it, the query will be started on the server and will be streamed to the client without blocking the SSR request. +You can also prefetch with `fetchQuery` or `ensureQueryData` in a loader without consuming the data in a component. If you return the promise directly from the loader, it will be awaited and thus block the SSR request until the query finishes. If you don't await the promise nor return it, the query will be started on the server and will be streamed to the client without blocking the SSR request. -# Non-blocking `query` in loader +# React ```tsx title="src/routes/users.$id.tsx" import { createFileRoute } from '@tanstack/react-router' -import { noop, queryOptions, useQuery } from '@tanstack/react-query' +import { queryOptions, useQuery } from '@tanstack/react-query' const userQuery = (id: string) => queryOptions({ @@ -202,18 +150,15 @@ const userQuery = (id: string) => }) export const Route = createFileRoute('/user/$id')({ - loader: ({ context, params }) => { - // Do not await this nor return the promise, just kick off the query to stream it to the client - void context.queryClient.query(userQuery(params.id)).catch(noop) + loader: ({ params }) => { + // do not await this nor return the promise, just kick off the query to stream it to the client + context.queryClient.fetchQuery(userQuery(params.id)) }, }) ``` -> [!NOTE] -> Previous versions of this guide used `queryClient.ensureQueryData` and `queryClient.prefetchQuery`. These methods are now deprecated in TanStack Query in favor of `queryClient.query`. See the TanStack Query [v5 migration guide](https://tanstack.com/query/latest/docs/framework/react/guides/migrating-to-v5#imperative-queryclient-methods) for more details. - ## Redirect handling If a query or mutation throws a `redirect(...)`, the integration intercepts it on the client and performs a router navigation. diff --git a/docs/router/llm-support.md b/docs/router/llm-support.md new file mode 100644 index 0000000000..0af9c58770 --- /dev/null +++ b/docs/router/llm-support.md @@ -0,0 +1,32 @@ +--- +id: llm-assistance +title: LLM Assistance Support +--- + +TanStack Router's documentation is integrated into its NPM module, making it available to install as LLM assistance rules. These rules can be integrated into various editors to provide context-aware help using [`vibe-rules`](https://www.npmjs.com/package/vibe-rules). + +## Installation + +To use `vibe-rules`, install it globally using your package manager of choice. For example, with `pnpm`: + +```bash +pnpm add -g vibe-rules +``` + +Once installed, you can then run it in the editor of your choice. For example, to integrate with Cursor: + +```bash +vibe-rules install cursor +``` + +## Supported Editors + +`vibe-rules` supports a variety of editors, including `windsurf`, `claude-code`, and more. For more information on supported editors and how to set them up, refer to the [`vibe-rules` documentation](https://github.com/FutureExcited/vibe-rules). + +> [!IMPORTANT] +> If you're using [Yarn Workspaces](https://yarnpkg.com/features/workspaces), you will need to add the following configuration to your `.yarnrc.yaml` file of your application that uses TanStack Router: + +> ```yaml +> pnpFallbackMode: all +> pnpMode: loose +> ``` diff --git a/docs/router/quick-start.md b/docs/router/quick-start.md index a3571756df..69ec50c538 100644 --- a/docs/router/quick-start.md +++ b/docs/router/quick-start.md @@ -9,8 +9,8 @@ The fastest way to get started with TanStack Router is to scaffold a new project -react: @tanstack/cli create --router-only -solid: @tanstack/cli create --router-only --framework solid +react: create-tsrouter-app@latest +solid: create-tsrouter-app@latest --framework solid @@ -25,7 +25,7 @@ The CLI will guide you through a short series of prompts to customize your setup Once complete, a new project will be generated with TanStack Router installed and ready to use. > [!TIP] -> For full details on available options and templates, visit the [`@tanstack/cli` documentation](https://github.com/TanStack/cli). +> For full details on available options and templates, visit the [`create-tsrouter-app` documentation](https://github.com/TanStack/create-tsrouter-app/tree/main/cli/create-tsrouter-app). ## Routing Options @@ -35,37 +35,23 @@ TanStack Router supports both file-based and code-based route configurations. Yo The file-based approach is the recommended option for most projects. It automatically creates routes based on your file structure, giving you the best mix of performance, simplicity, and developer experience. -For more details, see the [file-based routing documentation](./routing/file-based-routing.md) or + - +react: create-tsrouter-app@latest my-app --template file-router +solid: create-tsrouter-app@latest my-app --framework solid --template file-router -# React - -[explore the live example](https://tanstack.com/router/latest/docs/framework/react/examples/basic-file-based) - -# Solid - -[explore the live example](https://tanstack.com/router/latest/docs/framework/solid/examples/basic-file-based) - - + ### Code-Based Route Configuration If you prefer to define routes programmatically, you can use the code-based route configuration. This approach gives you full control over routing logic. -For more details, see the [code-based routing documentation](./routing/code-based-routing.md) or + - +react: create-tsrouter-app@latest my-app +solid: create-tsrouter-app@latest my-app --framework solid -# React - -[explore the live example](https://tanstack.com/router/latest/docs/framework/react/examples/basic) - -# Solid - -[explore the live example](https://tanstack.com/router/latest/docs/framework/solid/examples/basic) - - + With either approach, navigate to your project directory and start the development server. diff --git a/docs/router/routing/code-based-routing.md b/docs/router/routing/code-based-routing.md index b1457c6fbe..d3102cafd6 100644 --- a/docs/router/routing/code-based-routing.md +++ b/docs/router/routing/code-based-routing.md @@ -14,7 +14,7 @@ title: Code-Based Routing Code-based routing is no different from file-based routing in that it uses the same route tree concept to organize, match and compose matching routes into a component tree. The only difference is that instead of using the filesystem to organize your routes, you use code. -Let's consider the same route tree from the [Route Trees](./route-trees.md#route-trees) guide, and convert it to code-based routing: +Let's consider the same route tree from the [Route Trees & Nesting](./route-trees.md#route-trees) guide, and convert it to code-based routing: Here is the file-based version: diff --git a/docs/router/routing/file-based-routing.md b/docs/router/routing/file-based-routing.md index 2eea38bba2..6be11e55d6 100644 --- a/docs/router/routing/file-based-routing.md +++ b/docs/router/routing/file-based-routing.md @@ -12,7 +12,7 @@ File-based routing is a way to configure your routes using the filesystem. Inste - **Organization**: Routes are organized in a way that mirrors the URL structure of your application. - **Scalability**: As your application grows, file-based routing makes it easy to add new routes and maintain existing ones. - **Code-Splitting**: File-based routing allows TanStack Router to automatically code-split your routes for better performance. -- **Type-Safety**: File-based routing raises the ceiling on type-safety by generating and managing type linkages for your routes, which can otherwise be a tedious process via code-based routing. +- **Type-Safety**: File-based routing raises the ceiling on type-safety by generating managing type linkages for your routes, which can otherwise be a tedious process via code-based routing. - **Consistency**: File-based routing enforces a consistent structure for your routes, making it easier to maintain and update your application and move from one project to another. ## `/`s or `.`s? @@ -80,7 +80,7 @@ See the example below: ## Mixed Flat and Directory Routes -It's extremely likely that a 100% directory or flat route structure won't be the best fit for your project, which is why TanStack Router allows you to mix both flat and directory routes together to create a route tree that uses the best of both worlds where it makes sense. +It's extremely likely that a 100% directory or flat route structure won't be the best fit for your project, which is why TanStack Router allows you to mix both flat and directory routes together to create a route tree that uses the best of both worlds where it makes sense: See the example below: diff --git a/docs/router/routing/file-naming-conventions.md b/docs/router/routing/file-naming-conventions.md index 896e7d3d9b..115310f5b3 100644 --- a/docs/router/routing/file-naming-conventions.md +++ b/docs/router/routing/file-naming-conventions.md @@ -2,7 +2,7 @@ title: File Naming Conventions --- -File-based routing requires that you follow a few simple file naming conventions to ensure that your routes are generated correctly. The concepts these conventions enable are covered in detail in the [Route Trees](./route-trees.md) guide. +File-based routing requires that you follow a few simple file naming conventions to ensure that your routes are generated correctly. The concepts these conventions enable are covered in detail in the [Route Trees & Nesting](./route-trees.md) guide. | Feature | Description | | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -40,4 +40,4 @@ Pathless routes wrap child routes with either logic or a component without requi | ʦ `_app.a.tsx` | /a | `
` | | ʦ `_app.b.tsx` | /b | `` | -To learn more about pathless routes, see the [Routing Concepts - Pathless Layout Routes](./routing-concepts.md#pathless-layout-routes) guide. +To learn more about pathless routes, see the [Routing Concepts - Pathless Routes](./routing-concepts.md#pathless-layout-routes) guide. diff --git a/docs/router/routing/routing-concepts.md b/docs/router/routing/routing-concepts.md index 11674e69c2..bcd507a45f 100644 --- a/docs/router/routing/routing-concepts.md +++ b/docs/router/routing/routing-concepts.md @@ -193,7 +193,7 @@ These params are then usable in your route's configuration and components! Let's # React -```tsx title="src/routes/posts/$postId.tsx" +```tsx title="src/routes/posts.tsx" import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/posts/$postId')({ @@ -564,7 +564,7 @@ routes/ │ ├── ... ``` -We can import from the excluded files into our posts route: +We can import from the excluded files into our posts route diff --git a/docs/router/routing/virtual-file-routes.md b/docs/router/routing/virtual-file-routes.md index 2de0ded5df..79754685e1 100644 --- a/docs/router/routing/virtual-file-routes.md +++ b/docs/router/routing/virtual-file-routes.md @@ -187,8 +187,6 @@ export const routes = rootRoute('root.tsx', [ ]) ``` -Because `route` receives an explicit URL path, leading and trailing underscores are treated literally. Use `layout` to create pathless layout routes. - You can also define a virtual route without a file name. This allows to set a common path prefix for its children: ```tsx diff --git a/docs/start/config.json b/docs/start/config.json index 36af0e6e0d..f54ea4c78d 100644 --- a/docs/start/config.json +++ b/docs/start/config.json @@ -21,6 +21,10 @@ "label": "Getting Started", "to": "framework/react/getting-started" }, + { + "label": "Quick Start", + "to": "framework/react/quick-start" + }, { "label": "Build from Scratch", "to": "framework/react/build-from-scratch" @@ -36,10 +40,6 @@ { "label": "Migrate from Next.js", "to": "framework/react/migrate-from-next-js" - }, - { - "label": "Migrate from the Release Candidate", - "to": "framework/react/migrate-from-release-candidate" } ] }, @@ -55,21 +55,20 @@ "to": "framework/solid/getting-started" }, { - "label": "Build from Scratch", - "to": "framework/solid/build-from-scratch" + "label": "Quick Start", + "to": "framework/solid/quick-start" }, { - "label": "Migrate from the Release Candidate", - "to": "framework/solid/migrate-from-release-candidate" + "label": "Build from Scratch", + "to": "framework/solid/build-from-scratch" } ] } ] }, { - "label": "Server & Execution", + "label": "Guides", "children": [], - "collapsible": true, "frameworks": [ { "label": "react", @@ -90,10 +89,6 @@ "label": "Import Protection", "to": "framework/react/guide/import-protection" }, - { - "label": "Path Aliases", - "to": "framework/react/guide/path-aliases" - }, { "label": "Environment Variables", "to": "framework/react/guide/environment-variables" @@ -102,14 +97,6 @@ "label": "Server Functions", "to": "framework/react/guide/server-functions" }, - { - "label": "Streaming Data from Server Functions", - "to": "framework/react/guide/streaming-data-from-server-functions" - }, - { - "label": "Server Components", - "to": "framework/react/guide/server-components" - }, { "label": "Static Server Functions", "to": "framework/react/guide/static-server-functions" @@ -129,6 +116,78 @@ { "label": "Server Routes", "to": "framework/react/guide/server-routes" + }, + { + "label": "Hydration Errors", + "to": "framework/react/guide/hydration-errors" + }, + { + "label": "Selective SSR", + "to": "framework/react/guide/selective-ssr" + }, + { + "label": "SPA Mode", + "to": "framework/react/guide/spa-mode" + }, + { + "label": "Static Prerendering", + "to": "framework/react/guide/static-prerendering" + }, + { + "label": "Incremental Static Regeneration (ISR)", + "to": "framework/react/guide/isr" + }, + { + "label": "Server Entry Point", + "to": "framework/react/guide/server-entry-point" + }, + { + "label": "CDN Asset URLs", + "to": "framework/react/guide/cdn-asset-urls" + }, + { + "label": "Client Entry Point", + "to": "framework/react/guide/client-entry-point" + }, + { + "label": "Hosting", + "to": "framework/react/guide/hosting" + }, + { + "label": "Authentication Overview", + "to": "framework/react/guide/authentication-overview" + }, + { + "label": "Authentication", + "to": "framework/react/guide/authentication" + }, + { + "label": "Databases", + "to": "framework/react/guide/databases" + }, + { + "label": "Observability", + "to": "framework/react/guide/observability" + }, + { + "label": "Path Aliases", + "to": "framework/react/guide/path-aliases" + }, + { + "label": "Tailwind CSS Integration", + "to": "framework/react/guide/tailwind-integration" + }, + { + "label": "Rendering Markdown", + "to": "framework/react/guide/rendering-markdown" + }, + { + "label": "SEO", + "to": "framework/react/guide/seo" + }, + { + "label": "LLM Optimization (LLMO)", + "to": "framework/react/guide/llmo" } ] }, @@ -151,10 +210,6 @@ "label": "Import Protection", "to": "framework/solid/guide/import-protection" }, - { - "label": "Path Aliases", - "to": "framework/solid/guide/path-aliases" - }, { "label": "Environment Variables", "to": "framework/solid/guide/environment-variables" @@ -182,72 +237,11 @@ { "label": "Server Routes", "to": "framework/solid/guide/server-routes" - } - ] - } - ] - }, - { - "label": "Rendering", - "children": [], - "collapsible": true, - "frameworks": [ - { - "label": "react", - "children": [ - { - "label": "Hydration Errors", - "to": "framework/react/guide/hydration-errors" }, - { - "label": "Deferred Hydration", - "to": "framework/react/guide/deferred-hydration" - }, - { - "label": "Selective SSR", - "to": "framework/react/guide/selective-ssr" - }, - { - "label": "SPA Mode", - "to": "framework/react/guide/spa-mode" - }, - { - "label": "Static Prerendering", - "to": "framework/react/guide/static-prerendering" - }, - { - "label": "Incremental Static Regeneration (ISR)", - "to": "framework/react/guide/isr" - }, - { - "label": "Server Entry Point", - "to": "framework/react/guide/server-entry-point" - }, - { - "label": "Client Entry Point", - "to": "framework/react/guide/client-entry-point" - }, - { - "label": "Early Hints", - "to": "framework/react/guide/early-hints" - }, - { - "label": "CDN Asset URLs", - "to": "framework/react/guide/cdn-asset-urls" - } - ] - }, - { - "label": "solid", - "children": [ { "label": "Hydration Errors", "to": "framework/solid/guide/hydration-errors" }, - { - "label": "Deferred Hydration", - "to": "framework/solid/guide/deferred-hydration" - }, { "label": "Selective SSR", "to": "framework/solid/guide/selective-ssr" @@ -268,140 +262,29 @@ "label": "Client Entry Point", "to": "framework/solid/guide/client-entry-point" }, - { - "label": "Early Hints", - "to": "framework/solid/guide/early-hints" - } - ] - } - ] - }, - { - "label": "Deployment & Operations", - "children": [], - "collapsible": true, - "frameworks": [ - { - "label": "react", - "children": [ - { - "label": "Production Checklist", - "to": "framework/react/guide/production-checklist" - }, - { - "label": "Hosting", - "to": "framework/react/guide/hosting" - }, - { - "label": "Observability", - "to": "framework/react/guide/observability" - } - ] - }, - { - "label": "solid", - "children": [ { "label": "Hosting", "to": "framework/solid/guide/hosting" }, { - "label": "Observability", - "to": "framework/solid/guide/observability" - } - ] - } - ] - }, - { - "label": "Authentication & Data", - "children": [], - "collapsible": true, - "frameworks": [ - { - "label": "react", - "children": [ - { - "label": "Choose Authentication", - "to": "framework/react/guide/authentication-overview" - }, - { - "label": "Authentication Server Primitives", - "to": "framework/react/guide/authentication-server-primitives" - }, - { - "label": "Implement Authentication", - "to": "framework/react/guide/authentication" - }, - { - "label": "Databases", - "to": "framework/react/guide/databases" - }, - { - "label": "TanStack Query", - "to": "framework/react/guide/tanstack-query" - } - ] - }, - { - "label": "solid", - "children": [ - { - "label": "Choose Authentication", + "label": "Authentication Overview", "to": "framework/solid/guide/authentication-overview" }, { - "label": "Authentication Server Primitives", - "to": "framework/solid/guide/authentication-server-primitives" - }, - { - "label": "Implement Authentication", + "label": "Authentication", "to": "framework/solid/guide/authentication" }, { "label": "Databases", "to": "framework/solid/guide/databases" - } - ] - } - ] - }, - { - "label": "Styling & Metadata", - "children": [], - "collapsible": true, - "frameworks": [ - { - "label": "react", - "children": [ - { - "label": "CSS Styling", - "to": "framework/react/guide/css-styling" }, { - "label": "Tailwind CSS Integration", - "to": "framework/react/guide/tailwind-integration" + "label": "Observability", + "to": "framework/solid/guide/observability" }, { - "label": "Rendering Markdown", - "to": "framework/react/guide/rendering-markdown" - }, - { - "label": "SEO", - "to": "framework/react/guide/seo" - }, - { - "label": "Generative Engine Optimization (GEO)", - "to": "framework/react/guide/geo" - } - ] - }, - { - "label": "solid", - "children": [ - { - "label": "CSS Styling", - "to": "framework/solid/guide/css-styling" + "label": "Path Aliases", + "to": "framework/solid/guide/path-aliases" }, { "label": "Tailwind CSS Integration", @@ -412,112 +295,8 @@ "to": "framework/solid/guide/seo" }, { - "label": "Generative Engine Optimization (GEO)", - "to": "framework/solid/guide/geo" - } - ] - } - ] - }, - { - "label": "Examples", - "children": [], - "frameworks": [ - { - "label": "react", - "children": [ - { - "label": "Basic", - "to": "framework/react/examples/start-basic" - }, - { - "label": "Basic + React Query", - "to": "framework/react/examples/start-basic-react-query" - }, - { - "label": "Basic + Clerk Auth", - "to": "framework/react/examples/start-clerk-basic" - }, - { - "label": "Basic + DIY Auth", - "to": "framework/react/examples/start-basic-auth" - }, - { - "label": "Basic + Supabase Auth", - "to": "framework/react/examples/start-supabase-basic" - }, - { - "label": "Trellaux + Convex", - "to": "framework/react/examples/start-convex-trellaux" - }, - { - "label": "Trellaux", - "to": "framework/react/examples/start-trellaux" - }, - { - "label": "WorkOS", - "to": "framework/react/examples/start-workos" - }, - { - "label": "Material UI", - "to": "framework/react/examples/start-material-ui" - }, - { - "label": "Basic + Auth.js", - "to": "framework/react/examples/start-basic-authjs" - }, - { - "label": "Basic + Static rendering", - "to": "framework/react/examples/start-basic-static" - }, - { - "label": "Cloudflare Vite Plugin", - "to": "framework/react/examples/start-basic-cloudflare" - } - ] - }, - { - "label": "solid", - "children": [ - { - "label": "Basic", - "to": "framework/solid/examples/start-basic" - }, - { - "label": "Basic + Solid Query", - "to": "framework/solid/examples/start-basic-solid-query" - }, - { - "label": "Basic + DIY Auth", - "to": "framework/solid/examples/start-basic-auth" - }, - { - "label": "Basic + Supabase Auth", - "to": "framework/solid/examples/start-supabase-basic" - }, - { - "label": "Basic + Convex + Better Auth", - "to": "framework/solid/examples/start-convex-better-auth" - }, - { - "label": "Basic + Auth.js", - "to": "framework/solid/examples/start-basic-authjs" - }, - { - "label": "Basic + Static rendering", - "to": "framework/solid/examples/start-basic-static" - }, - { - "label": "Cloudflare Vite Plugin", - "to": "framework/solid/examples/start-basic-cloudflare" - }, - { - "label": "Netlify Vite Plugin", - "to": "framework/solid/examples/start-basic-netlify" - }, - { - "label": "Nitro Vite Plugin", - "to": "framework/solid/examples/start-basic-nitro" + "label": "LLM Optimization (LLMO)", + "to": "framework/solid/guide/llmo" } ] } @@ -539,19 +318,6 @@ "to": "framework/react/tutorial/fetching-external-api" } ] - }, - { - "label": "solid", - "children": [ - { - "label": "Reading and Writing a File", - "to": "framework/solid/tutorial/reading-writing-file" - }, - { - "label": "Fetching Data from External API", - "to": "framework/solid/tutorial/fetching-external-api" - } - ] } ] } diff --git a/docs/start/eslint/eslint-plugin-start.md b/docs/start/eslint/eslint-plugin-start.md deleted file mode 100644 index 1b143e74a4..0000000000 --- a/docs/start/eslint/eslint-plugin-start.md +++ /dev/null @@ -1,107 +0,0 @@ ---- -id: eslint-plugin-start -title: ESLint Plugin Start ---- - -TanStack Start comes with its own ESLint plugin. This plugin is used to enforce best practices and help you avoid common mistakes when working with Server Components and server/client boundaries. - -## Installation - -The plugin is a separate package that you need to install: - -```sh -npm install -D @tanstack/eslint-plugin-start -``` - -or - -```sh -pnpm add -D @tanstack/eslint-plugin-start -``` - -or - -```sh -yarn add -D @tanstack/eslint-plugin-start -``` - -or - -```sh -bun add -D @tanstack/eslint-plugin-start -``` - -## Flat Config (`eslint.config.js`) - -The release of ESLint 9.0 introduced a new way to configure ESLint using a flat config format. The TanStack Start ESLint Plugin supports this format and provides a recommended config you can use to enable all recommended rules. - -### Recommended Flat Config setup - -To enable all recommended rules: - -```js -// eslint.config.js -import pluginStart from '@tanstack/eslint-plugin-start' - -export default [ - pluginStart.configs['flat/recommended'], - // Any other config... -] -``` - -### Custom Flat Config setup - -Alternatively, load the plugin and configure only the rules you want: - -```js -// eslint.config.js -import pluginStart from '@tanstack/eslint-plugin-start' - -export default [ - { - plugins: { - '@tanstack/start': pluginStart, - }, - rules: { - '@tanstack/start/no-client-code-in-server-component': 'error', - '@tanstack/start/no-async-client-component': 'error', - }, - }, - // Any other config... -] -``` - -## Legacy Config (`.eslintrc`) - -Prior to ESLint 9.0, the most common way to configure ESLint was using a `.eslintrc` file. The TanStack Start ESLint plugin still supports this configuration method. - -### Recommended Legacy Config setup - -To enable all recommended rules, add `plugin:@tanstack/eslint-plugin-start/recommended` in `extends`: - -```json -{ - "extends": ["plugin:@tanstack/eslint-plugin-start/recommended"] -} -``` - -### Custom Legacy Config setup - -Alternatively, add `@tanstack/eslint-plugin-start` to `plugins` and configure the rules you want: - -```json -{ - "plugins": ["@tanstack/eslint-plugin-start"], - "rules": { - "@tanstack/start/no-client-code-in-server-component": "error", - "@tanstack/start/no-async-client-component": "error" - } -} -``` - -## Rules - -The following rules are available in the TanStack Start ESLint plugin: - -- [@tanstack/start/no-client-code-in-server-component](./no-client-code-in-server-component.md) -- [@tanstack/start/no-async-client-component](./no-async-client-component.md) diff --git a/docs/start/eslint/no-async-client-component.md b/docs/start/eslint/no-async-client-component.md deleted file mode 100644 index b2007d31e8..0000000000 --- a/docs/start/eslint/no-async-client-component.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -id: no-async-client-component -title: Disallow async components in client context ---- - -Async React components are only valid within React Server Components. - -In TanStack Start, that means async components must only be used in server-component context, for example: - -- rendered by `renderServerComponent()` -- rendered inside a `createCompositeComponent((props) => )` callback - -This rule helps you catch async components that have become "client" (directly or transitively), which would otherwise crash at runtime. - -## Rule Details - -Examples of **incorrect** code for this rule: - -```tsx -/* eslint "@tanstack/start/no-async-client-component": "error" */ - -import { createFileRoute } from '@tanstack/react-router' - -export async function Page() { - return
-} - -export const Route = createFileRoute(undefined)({ - component: Page, -}) -``` - -Examples of **correct** code for this rule: - -```tsx -/* eslint "@tanstack/start/no-async-client-component": "error" */ - -import { createFileRoute } from '@tanstack/react-router' - -export function Page() { - return
-} - -export const Route = createFileRoute(undefined)({ - component: Page, -}) -``` - -```tsx -/* eslint "@tanstack/start/no-async-client-component": "error" */ - -import { createCompositeComponent } from '@tanstack/react-start/rsc' - -export const ServerPage = createCompositeComponent(async () => { - const message = await Promise.resolve('hello') - return
{message}
-}) -``` - -## Reporting location - -This rule can report in two ways: - -- **Usage-site**: if a component becomes client due to being referenced by route options, the error should be reported at the route option usage. -- **Definition-site**: if a component is client due to `'use client'` or being rendered by a client component, the error is reported at the component definition. - -## Attributes - -- [x] ✅ Recommended diff --git a/docs/start/eslint/no-client-code-in-server-component.md b/docs/start/eslint/no-client-code-in-server-component.md deleted file mode 100644 index 8f93590cc9..0000000000 --- a/docs/start/eslint/no-client-code-in-server-component.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -id: no-client-code-in-server-component -title: Disallow client-only code in server components ---- - -TanStack Start defines React Server Component boundaries via RSC helpers like `renderServerComponent()` and `createCompositeComponent()`. - -- `renderServerComponent()` is a server boundary around the element. -- `createCompositeComponent((props) => )` is a server boundary around the callback. - -Inside these boundaries (and anything rendered from them, unless it crosses a `'use client'` boundary) you must not use client-only code. - -This rule detects common client-only patterns in server components: - -- React client hooks (eg `useState`, `useEffect`) -- browser-only globals (eg `window`, `document`) -- React event handlers (`onClick`, etc.) -- function props (non-serializable across the server/client boundary) -- class components - -## Rule Details - -Examples of **incorrect** code for this rule: - -```tsx -/* eslint "@tanstack/start/no-client-code-in-server-component": "error" */ - -import { createCompositeComponent } from '@tanstack/react-start/rsc' -import { useState } from 'react' - -export const Server = createCompositeComponent(() => { - const [count] = useState(0) - return
{count}
-}) -``` - -```tsx -/* eslint "@tanstack/start/no-client-code-in-server-component": "error" */ - -import { createCompositeComponent } from '@tanstack/react-start/rsc' - -export const Server = createCompositeComponent(() => { - return
{window.location.href}
-}) -``` - -Examples of **correct** code for this rule: - -```tsx -/* eslint "@tanstack/start/no-client-code-in-server-component": "error" */ - -import { renderServerComponent } from '@tanstack/react-start/rsc' - -export const Server = renderServerComponent( - (async () => { - const msg = await Promise.resolve('ok') - return
{msg}
- })(), -) -``` - -## Attributes - -- [x] ✅ Recommended diff --git a/docs/start/framework/react/build-from-scratch.md b/docs/start/framework/react/build-from-scratch.md index a0a04f06d4..00f5e4ddfe 100644 --- a/docs/start/framework/react/build-from-scratch.md +++ b/docs/start/framework/react/build-from-scratch.md @@ -4,7 +4,7 @@ title: Build a Project from Scratch --- > [!NOTE] -> If you already created a project with the CLI or by cloning an example from the [Getting Started](./getting-started) guide, you can skip this guide and move on to the [Routing](./guide/routing) guide. +> If you chose to quick start with an example or cloned project, you can skip this guide and move on to the [Routing](./guide/routing) guide. _So you want to build a TanStack Start project from scratch?_ @@ -14,7 +14,7 @@ This guide will help you build a **very** basic TanStack Start web application. - Display a counter - Increment the counter on the server and client -[Here is what that will look like](https://stackblitz.com/github/tanstack/router/tree/main/examples/react/start-counter) +[If you want a generated starting point instead, use TanStack Builder](https://tanstack.com/builder) Let's create a new project directory and initialize it. @@ -49,53 +49,43 @@ We highly recommend using TypeScript with TanStack Start. Create a `tsconfig.jso ## Install Dependencies -TanStack Start is powered by [TanStack Router](https://tanstack.com/router) and supports [Vite](https://vite.dev/) or [Rsbuild](https://rsbuild.dev/) as the build tool. +TanStack Start is powered by [Vite](https://vite.dev/) and [TanStack Router](https://tanstack.com/router) and requires them as dependencies. -To install Start and Router, run: +To install them, run: ```shell npm i @tanstack/react-start @tanstack/react-router ``` +We also need vite as a devDependency: + +```shell +npm i -D vite +``` + You'll also need React: ```shell npm i react react-dom ``` -Install the build tool and React integration you want to use: - - - -# Vite +As well as React's Vite plugin: ```shell -npm i -D vite @vitejs/plugin-react +npm i -D @vitejs/plugin-react ``` -# Rsbuild - -```shell -npm i -D @rsbuild/core @rsbuild/plugin-react -``` - - - -If you use Vite, you can also use `@vitejs/plugin-react-swc` instead of `@vitejs/plugin-react`. +Alternatively, you can also use `@vitejs/plugin-react-oxc` or `@vitejs/plugin-react-swc`. and some TypeScript: ```shell -npm i -D typescript @types/react @types/react-dom @types/node +npm i -D typescript @types/react @types/react-dom @types/node vite-tsconfig-paths ``` ## Update Configuration Files -We'll then update our `package.json` to use your build tool's CLI and set `"type": "module"`: - - - -# Vite +We'll then update our `package.json` to use Vite's CLI and set `"type": "module"`: ```json { @@ -108,29 +98,12 @@ We'll then update our `package.json` to use your build tool's CLI and set `"type } ``` -# Rsbuild +Then configure TanStack Start's Vite plugin in `vite.config.ts`: -```json -{ - // ... - "type": "module", - "scripts": { - "dev": "rsbuild dev", - "build": "rsbuild build" - } -} -``` - - - -Then configure TanStack Start's build tool plugin: - - - -# Vite - -```ts title="vite.config.ts" +```ts +// vite.config.ts import { defineConfig } from 'vite' +import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import viteReact from '@vitejs/plugin-react' @@ -138,10 +111,8 @@ export default defineConfig({ server: { port: 3000, }, - resolve: { - tsconfigPaths: true, - }, plugins: [ + tsConfigPaths(), tanstackStart(), // react's vite plugin must come after start's vite plugin viteReact(), @@ -149,23 +120,6 @@ export default defineConfig({ }) ``` -# 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()], -}) -``` - - - ## Add the Basic Templating There are 2 required files for TanStack Start usage: @@ -182,7 +136,7 @@ Once configuration is done, we'll have a file tree that looks like the following │ │ └── `__root.tsx` │ ├── `router.tsx` │ ├── `routeTree.gen.ts` -├── `vite.config.ts` or `rsbuild.config.ts` +├── `vite.config.ts` ├── `package.json` └── `tsconfig.json` ``` @@ -216,6 +170,7 @@ Finally, we need to create the root of our application. This is the entry point ```tsx // src/routes/__root.tsx +/// import type { ReactNode } from 'react' import { Outlet, @@ -290,7 +245,7 @@ const getCount = createServerFn({ }) const updateCount = createServerFn({ method: 'POST' }) - .validator((d: number) => d) + .inputValidator((d: number) => d) .handler(async ({ data }) => { const count = await readCount() await fs.promises.writeFile(filePath, `${count + data}`) diff --git a/docs/start/framework/react/comparison.md b/docs/start/framework/react/comparison.md index b72e286a76..953224d3a4 100644 --- a/docs/start/framework/react/comparison.md +++ b/docs/start/framework/react/comparison.md @@ -1,61 +1,337 @@ --- title: Comparison | TanStack Start vs Next.js vs React Router -description: Compare rendering, server APIs, caching, forms, and deployment in TanStack Start, Next.js App Router, and React Router Framework Mode. toc: false --- -This matrix compares full-stack framework capabilities. For the choice between Start and Next.js, read [TanStack Start vs Next.js](./start-vs-nextjs). For navigation and URL-state APIs, see the [TanStack Router comparison](/router/latest/docs/comparison). +Choosing a full-stack React framework? This comparison focuses on the **full-stack framework features** that distinguish TanStack Start from Next.js and React Router (v7 Framework Mode). -Checked September 11, 2026 against the linked documentation: TanStack Start's current guides, Next.js 16.3 App Router, and React Router 8.3 Framework Mode. +> **🚨 IMPORTANT: Looking for routing features?** +> +> TanStack Start is built on **TanStack Router**, which provides industry-leading type-safe routing capabilities. For a comprehensive comparison of routing features (nested routes, search params, type safety, loaders, etc.), please see: +> +> ### [📖 TanStack Router Comparison vs React Router / Next.js →](/router/latest/docs/framework/react/comparison) +> +> That comparison covers all the routing features in detail. This page focuses specifically on **full-stack framework capabilities** like SSR, server functions, middleware, deployment, and more. -## Rendering and data +While we aim to provide an accurate and fair comparison, please note that this table may not capture every nuance or recent update of each framework. We recommend reviewing the official documentation and trying out each solution to make the most informed decision for your specific use case. -| Capability | TanStack Start | Next.js App Router | React Router Framework Mode | -| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | -| Server rendering | [SSR with hydration by default](./overview) | [Server and Client Components contribute to initial HTML](https://nextjs.org/docs/app/getting-started/server-and-client-components) | [Server rendering is configurable](https://reactrouter.com/start/framework/rendering) | -| Rendering control | [Per-route full, data-only, or disabled SSR](./guide/selective-ssr) | [Server/Client Component boundaries](https://nextjs.org/docs/app/getting-started/server-and-client-components); `use client` does not disable initial SSR | [Global SSR setting and route-level client loaders](https://reactrouter.com/start/framework/rendering) | -| SPA applications | [Dedicated SPA mode](./guide/spa-mode) | [Documented SPA patterns](https://nextjs.org/docs/app/guides/single-page-applications) | [`ssr: false`](https://reactrouter.com/start/framework/rendering) | -| Static output | [Prerendering configuration](./guide/static-prerendering) | [Static export](https://nextjs.org/docs/app/guides/static-exports), with server-feature limitations | [Prerender selected URLs](https://reactrouter.com/start/framework/rendering) | -| React Server Components | [Experimental, opt-in](./guide/server-components) | [Core App Router component model](https://nextjs.org/docs/app/getting-started/server-and-client-components) | [Unstable RSC integration](https://reactrouter.com/how-to/react-server-components) | -| Client data reuse | [Router loader caching](/router/latest/docs/guide/data-loading), plus [Query integration](/router/latest/docs/integrations/query) | [Navigation caching and server cache APIs](https://nextjs.org/docs/app/getting-started/caching); a query library can manage additional client data | [Loader/action revalidation](https://reactrouter.com/start/framework/actions); separate client-data tools can be added | -| Revalidation after deployment | [HTTP caching and provider-specific ISR configuration](./guide/isr) | [ISR and cache coordination](https://nextjs.org/docs/app/guides/self-hosting) | [HTTP response headers](https://reactrouter.com/how-to/headers) and deployment infrastructure | +If you find any discrepancies or have suggestions for improvement, please don't hesitate to contribute via the "Edit this page on GitHub" link at the bottom of this page or open an issue in the [TanStack Router GitHub repository](https://github.com/TanStack/router). -A client loader cache, a cached server result, and a cached HTML response are different things. Compare invalidation behavior, persistence, and multi-instance coordination for the layer your application needs. A CDN honoring `stale-while-revalidate` is not proof of identical ISR behavior across providers. +Feature/Capability Key: -## Server APIs and forms +- ✅ 1st-class, built-in, and ready to use with no added configuration or code +- 🟡 Partial Support (rated 1-5 where noted) +- 🟠 Supported via addon/community package +- 🔶 Possible, but requires custom code/implementation/casting +- 🛑 Not officially supported -| Capability | TanStack Start | Next.js App Router | React Router Framework Mode | -| -------------------------- | -------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | -| Server calls and mutations | [Typed server functions with GET or POST](./guide/server-functions) | [Server Actions](https://nextjs.org/docs/app/guides/forms) | [Route actions and fetchers](https://reactrouter.com/start/framework/actions) | -| Input validation | [Validator API with inferred types](./guide/server-functions) | [Validate action input with application code or a schema](https://nextjs.org/docs/app/guides/forms) | [Validate action input with application code](https://reactrouter.com/how-to/form-validation) | -| Middleware | [Request middleware and client/server function middleware](./guide/middleware) | [Request interception with Proxy](https://nextjs.org/docs/app/getting-started/proxy); action authorization belongs in server code | [Server and client route middleware](https://reactrouter.com/how-to/middleware) | -| Form handling | [Server functions](./guide/server-functions) can be called from event handlers; use a form library when needed | [Built-in `next/form`](https://nextjs.org/docs/app/api-reference/components/form), plus [Server Action forms](https://nextjs.org/docs/app/guides/forms) | [`Form`, actions, and fetchers](https://reactrouter.com/start/framework/actions) | -| Server endpoints | [Server routes](./guide/server-routes) | [Route Handlers](https://nextjs.org/docs/app/getting-started/route-handlers) | [Resource routes](https://reactrouter.com/how-to/resource-routes) | +| | TanStack Start | Next.js [_(Website)_][nextjs] | React Router [_(Website)_][react-router] | +| ----------------------------------------------------------------- | ------------------------------------------------ | --------------------------------------------- | ------------------------------------------ | +| Github Repo / Stars | [![][stars-tanstack-router]][gh-tanstack-router] | [![][stars-nextjs]][gh-nextjs] | [![][stars-react-router]][gh-react-router] | +| Bundle Size | [![][bp-tanstack-router]][bpl-tanstack-router] | ❓ | ❓ | +| -- | -- | -- | -- | +| **Routing Features** [_(See Full Comparison)_][router-comparison] | ✅ Built on TanStack Router | ✅ File-based App Router | ✅ File-based Nested Routes | +| -- | -- | -- | -- | +| **Full-Stack Features** | -- | -- | -- | +| SSR | ✅ | ✅ | ✅ | +| Streaming SSR | ✅ | ✅ | ✅ | +| Selective SSR (per-route) | ✅ | 🔶 | 🔶 | +| SPA Mode | ✅ | 🔶 (via "use client") | ✅ | +| Built-in Client-Side SWR Caching | ✅ (via TanStack Router) | 🔶 (fetch cache only) | 🛑 | +| Data Fetching Library Integration | ✅ (Official TanStack Query, Apollo, etc.) | 🔶 (manual integration) | 🔶 (manual integration) | +| Static Prerendering (SSG) | ✅ | ✅ | ✅ | +| Incremental Static Regeneration (ISR) | ✅ (via Cache-Control headers) | ✅ (Proprietary) | ✅ (via Cache-Control headers) | +| React Server Components | 🛑 (In active development) | ✅ | 🟡 (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) | 🛑 (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 | ✅ (Any Vite-compatible host) | 🟡 (Optimized for Vercel, possible elsewhere) | ✅ (Multiple adapters) | +| Edge Runtime Support | ✅ | ✅ | ✅ | +| Serverless Support | ✅ | ✅ | ✅ | +| Node.js Support | ✅ | ✅ | ✅ | +| Docker Support | ✅ | ✅ | ✅ | +| Static Export | ✅ | ✅ | ✅ | +| Official Cloudflare Support | ✅ | 🟡 | ✅ | +| Official Netlify Support | ✅ | 🟡 | ✅ | +| Official Vercel Support | ✅ (via Nitro) | ✅ | ✅ | -Type inference helps callers write valid code. It does not validate an incoming HTTP request or authorize access to a record. All three frameworks need runtime validation and server-side authorization for private operations. For Start, see [Authentication Server Primitives](./guide/authentication-server-primitives). +--- -## Tooling and deployment +> **⚠️ Remember:** For detailed comparisons of **routing features** (type safety, search params, loaders, navigation, etc.), see the [**TanStack Router Comparison**][router-comparison]. This page focuses on full-stack framework capabilities. -| Capability | TanStack Start | Next.js App Router | React Router Framework Mode | -| ----------------------- | ------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | -| Build integration | [Vite or Rsbuild](./build-from-scratch) | [Turbopack](https://nextjs.org/docs/app/api-reference/turbopack) | [Framework tooling](https://reactrouter.com/start/framework/installation) | -| Type support | [Router inference](/router/latest/docs/guide/type-safety) and [server function inference](./guide/server-functions) | [Stable opt-in typed links](https://nextjs.org/docs/app/api-reference/config/next-config-js/typedRoutes) and TypeScript APIs | [Generated route-module types](https://reactrouter.com/how-to/route-module-type-safety) | -| Metadata | [Route head management and SEO guide](./guide/seo) | [Metadata API and file conventions](https://nextjs.org/docs/app/getting-started/metadata-and-og-images) | [Route-module metadata](https://reactrouter.com/start/framework/route-module) | -| Image and font handling | Choose CSS, an image service, or an integration for your deployment | Built-in [`next/image`](https://nextjs.org/docs/app/api-reference/components/image) and [`next/font`](https://nextjs.org/docs/app/api-reference/components/font) | Choose CSS, an image service, or an integration for your deployment | -| Hosting | [Provider and runtime guides](./guide/hosting) | [Self-hosting](https://nextjs.org/docs/app/guides/self-hosting) or a deployment provider | [Deployment templates and hosting options](https://reactrouter.com/start/framework/deploying) | +--- -Deployment support depends on the adapter, runtime, and features you use. Check streaming, image processing, filesystem access, background work, and shared-cache behavior on your chosen target. Next.js self-hosting includes image optimization and ISR configuration; those features should not be labeled Vercel-only. +## Key Philosophical Differences -## Performance Considerations +### TanStack Start -This page does not establish a performance winner. Startup time, HMR, memory use, JavaScript shipped, and response latency require separate measurements. Comparing a router package's bundle size with an entire framework is not a valid application benchmark. +**Philosophy**: Maximum developer freedom with best-in-class type safety. -For a useful comparison, build the same representative application with recommended patterns in each framework. Record package versions, hardware, dependencies, route count, rendering and caching settings, deployment target, warm and cold runs, and the raw results. +- **Router-First**: Built on TanStack Router (see [full routing comparison][router-comparison]) +- **Deployment Agnostic**: Built on Vite, deploy anywhere without vendor lock-in +- **Composable Middleware**: Middleware system works at both the request level AND individual server function level (both client & server) +- **Selective SSR**: Fine-grained control over SSR behavior per route (full SSR, data-only, or client-only) +- **Developer Control**: Explicit, composable patterns over convention-based magic +- **Type Safety First**: End-to-end compile-time safety for server functions, loaders, and routing + +### Next.js + +**Philosophy**: Production-ready with optimal defaults, best with Vercel. + +- **RSC-First**: Deep integration with React Server Components as the primary paradigm +- **Vercel-Optimized**: Best performance and DX on Vercel's infrastructure +- **Convention over Configuration**: Opinionated structure with file-system routing conventions +- **Automatic Optimizations**: Many performance optimizations happen automatically +- **Production Grade**: Battle-tested at massive scale + +### React Router (v7 Framework Mode) + +**Philosophy**: Web fundamentals with progressive enhancement. + +- **Web Standards**: Embraces web platform primitives (fetch, FormData, Headers) +- **Progressive Enhancement**: Works without JavaScript by default +- **Nested Routes**: First-class support for nested routing and data loading +- **Action-Based**: Form submissions via actions follow web standards +- **Framework Evolution**: Successor to Remix, with Vite-based architecture ## When to Choose Each Framework -- **TanStack Start:** you want typed route context and URL state, explicit loaders and server functions, and control over per-route rendering. -- **Next.js:** you want its Server Component model and integrated image, font, metadata, and form facilities. Existing team experience and integrations can also make staying with Next.js the better choice. -- **React Router Framework Mode:** you want route loaders and actions, fetchers, and form-driven workflows. Read its [progressive enhancement guide](https://reactrouter.com/explanation/progressive-enhancement) if operation before JavaScript loads matters to your application. +### Choose TanStack Start if you: -Check Start's [overview](./overview) and [Server Components guide](./guide/server-components) for current release and experimental-feature status before adopting those features. To try Start, use [Getting Started](./getting-started) or [Migrate from Next.js](./migrate-from-next-js). +- Want the absolute best type safety for routing (see [Router Comparison][router-comparison]) +- Need deployment flexibility without vendor lock-in (works with any Vite-compatible host) +- 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' }) + .inputValidator(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 +- 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 middleware.ts file that runs on the Edge Runtime for all requests. It cannot access server-only resources like databases and has limitations compared to the Node.js runtime. + +### Deployment Flexibility + +**TanStack Start** leverages Vite's ecosystem: + +- 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**: Supported +- **React Router**: Experimental support available + +RSC is still evolving across the ecosystem. TanStack Start treats RSC as a composable primitive alongside Router and server functions. + +## Performance Considerations + +### Production Performance + +All three frameworks are capable of achieving excellent production performance and top Lighthouse scores. The differences come down to optimization strategies: + +- **TanStack Start**: Vite's optimized builds, SWR caching reduces server load, lightweight runtime +- **Next.js**: Automatic code splitting, image optimization, and built-in performance features +- **React Router**: Web standards-based caching and optimization + +### Development Performance + +This is where the frameworks differ significantly: + +**TanStack Start & React Router:** + +- ⚡ **Instant dev server startup** - Vite starts in milliseconds +- ⚡ **Lightning-fast HMR** - Changes reflect instantly without page refresh +- ⚡ **Fast dev navigation** - Full-speed routing during development +- ⚡ **Lightweight resource usage** - Minimal CPU and RAM consumption +- ⚡ **High dev throughput** - Handle many concurrent requests efficiently + +**Next.js:** + +- 🐌 **Slow dev server startup** - Can take many seconds to start, especially on larger projects +- 🐌 **Slow HMR** - Hot reloading is noticeably sluggish even with Turbopack +- 🐌 **Throttled dev navigation** - Navigation is artificially slowed during development +- 🐌 **Heavy resource usage** - Significant CPU and RAM consumption during development + +**Why This Matters:** + +Development performance directly impacts developer productivity. Faster feedback loops mean: + +- More iterations per hour +- Better flow state and focus +- Lower machine requirements +- Reduced frustration during development +- Faster CI/CD pipelines for development builds + +While Next.js's production performance is excellent, the development experience can be notably slower, especially on larger codebases or less powerful machines. + +## Community and Ecosystem + +- **Next.js**: Largest community, most third-party integrations, extensive learning resources +- **React Router**: One of the oldest and most widely used React libraries, strong community, excellent documentation +- **TanStack Start**: Growing community, part of TanStack ecosystem, excellent Discord support + +## Maturity + +- **Next.js**: Production-ready, used by thousands of companies, proven at scale +- **React Router**: Production-ready, powers millions of apps, v7 Framework Mode is the evolution of Remix +- **TanStack Start**: Release Candidate stage, feature-complete, rapidly stabilizing toward v1 + +[bp-tanstack-router]: https://badgen.net/bundlephobia/minzip/@tanstack/react-router +[bpl-tanstack-router]: https://bundlephobia.com/result?p=@tanstack/react-router +[gh-tanstack-router]: https://github.com/tanstack/router +[stars-tanstack-router]: https://img.shields.io/github/stars/tanstack/router?label=%F0%9F%8C%9F +[router-comparison]: /router/latest/docs/framework/react/comparison +[_]: _ +[nextjs]: https://nextjs.org/ +[gh-nextjs]: https://github.com/vercel/next.js +[stars-nextjs]: https://img.shields.io/github/stars/vercel/next.js?label=%F0%9F%8C%9F +[_]: _ +[react-router]: https://reactrouter.com/ +[gh-react-router]: https://github.com/remix-run/react-router +[stars-react-router]: https://img.shields.io/github/stars/remix-run/react-router?label=%F0%9F%8C%9F diff --git a/docs/start/framework/react/getting-started.md b/docs/start/framework/react/getting-started.md index 6e5bcd8841..4c6f928cdf 100644 --- a/docs/start/framework/react/getting-started.md +++ b/docs/start/framework/react/getting-started.md @@ -1,97 +1,24 @@ --- 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 - -### Use TanStack Builder - -The best way to get started with TanStack Start is [TanStack Builder](https://tanstack.com/builder). It's the AI-first setup flow and the easiest way to get to a working project fast. - -### Use the CLI - -If you'd rather scaffold locally or want a backup path, use the TanStack CLI: - -```bash -npx @tanstack/cli@latest create -``` - -You'll be prompted to choose your package manager and optional add-ons like Tailwind CSS and ESLint. - -### Start from an example - -If you'd rather begin from a working codebase, clone one of the official examples. - -To start with the [Basic](https://github.com/TanStack/router/tree/main/examples/react/start-basic) example: - -```bash -npx gitpick TanStack/router/tree/main/examples/react/start-basic start-basic -cd start-basic -npm install -npm run dev -``` - -To use a different example, replace `start-basic` with one of the slugs below. - -#### Examples - -- [Basic](https://github.com/TanStack/router/tree/main/examples/react/start-basic) (`start-basic`) -- [Basic + Rsbuild](https://github.com/TanStack/router/tree/main/examples/react/start-basic-rsbuild) (`start-basic-rsbuild`) -- [Basic + Auth](https://github.com/TanStack/router/tree/main/examples/react/start-basic-auth) (`start-basic-auth`) -- [Counter](https://github.com/TanStack/router/tree/main/examples/react/start-counter) (`start-counter`) -- [Basic + React Query](https://github.com/TanStack/router/tree/main/examples/react/start-basic-react-query) (`start-basic-react-query`) -- [Clerk Auth](https://github.com/TanStack/router/tree/main/examples/react/start-clerk-basic) (`start-clerk-basic`) -- [Convex + Trellaux](https://github.com/TanStack/router/tree/main/examples/react/start-convex-trellaux) (`start-convex-trellaux`) -- [Supabase](https://github.com/TanStack/router/tree/main/examples/react/start-supabase-basic) (`start-supabase-basic`) -- [Trellaux](https://github.com/TanStack/router/tree/main/examples/react/start-trellaux) (`start-trellaux`) -- [WorkOS](https://github.com/TanStack/router/tree/main/examples/react/start-workos) (`start-workos`) -- [Material UI](https://github.com/TanStack/router/tree/main/examples/react/start-material-ui) (`start-material-ui`) - -Each example page also includes a StackBlitz preview so you can inspect it before cloning. - -To clone a different example manually, replace `EXAMPLE_SLUG` below with the slug you want to use: - -```bash -npx gitpick TanStack/router/tree/main/examples/react/EXAMPLE_SLUG my-new-project -cd my-new-project -npm install -npm run dev -``` - -If you want to clone and deploy quickly, use the **Deploy to Netlify** button on an example's page. - -### Build from scratch - -If you want to wire everything up by hand, follow [Build a project from scratch](./build-from-scratch). - ## Migrate an existing project from another framework -- If you want to learn Start from a clean slate first, use one of the new-project options above. +- [Start a new project from scratch](#start-a-new-project-from-scratch) to quickly learn how Start works (see below) - Refer to a migration guide for your specific framework: - [Next.js](./migrate-from-next-js) - Remix 2 / React Router 7 "Framework Mode" (coming soon!) +## Start a new project from scratch + +Choose one of the following options to start building a _new_ TanStack Start project: + +- [TanStack Start CLI](./quick-start) - Just run `npx @tanstack/cli create`. Local, fast, and optionally customizable +- [TanStack Builder](https://tanstack.com/builder) - A visual interface to configure new TanStack projects with a few clicks +- [Issue repro baseline](https://github.com/TanStack/router/tree/main/examples/react/start-basic) - A minimal starter we keep stable for bug reports and reproductions +- [Build a project from scratch](./build-from-scratch) - A guide to building a TanStack Start project line-by-line, file-by-file. + ## Next Steps -Once you've created, cloned, or deployed a project, continue to the [Routing](./guide/routing) guide. - -## Other Router Examples - -If you want Router-focused examples that are not Start-specific, these are useful references: - -- [Quickstart (file-based)](https://github.com/TanStack/router/tree/main/examples/react/quickstart-file-based) -- [Basic (file-based)](https://github.com/TanStack/router/tree/main/examples/react/basic-file-based) -- [Kitchen Sink (file-based)](https://github.com/TanStack/router/tree/main/examples/react/kitchen-sink-file-based) -- [Kitchen Sink + React Query (file-based)](https://github.com/TanStack/router/tree/main/examples/react/kitchen-sink-react-query-file-based) -- [Location Masking](https://github.com/TanStack/router/tree/main/examples/react/location-masking) -- [Authenticated Routes](https://github.com/TanStack/router/tree/main/examples/react/authenticated-routes) -- [Scroll Restoration](https://github.com/TanStack/router/tree/main/examples/react/scroll-restoration) -- [Deferred Data](https://github.com/TanStack/router/tree/main/examples/react/deferred-data) -- [Navigation Blocking](https://github.com/TanStack/router/tree/main/examples/react/navigation-blocking) -- [View Transitions](https://github.com/TanStack/router/tree/main/examples/react/view-transitions) -- [With tRPC](https://github.com/TanStack/router/tree/main/examples/react/with-trpc) -- [With tRPC + React Query](https://github.com/TanStack/router/tree/main/examples/react/with-trpc-react-query) +Unless you chose to build a project from scratch, you can now move on to the [Routing](./guide/routing) guide to learn how to use TanStack Start! diff --git a/docs/start/framework/react/guide/authentication-overview.md b/docs/start/framework/react/guide/authentication-overview.md index e80ba97f8c..bce3337b3b 100644 --- a/docs/start/framework/react/guide/authentication-overview.md +++ b/docs/start/framework/react/guide/authentication-overview.md @@ -1,11 +1,8 @@ --- id: authentication-overview -title: Choose Authentication for React Apps -description: Compare hosted services, auth libraries, and custom authentication for React apps built with TanStack Start. Choose an approach before implementing sessions and authorization. +title: Authentication --- -Choose how your React app will handle identity, sessions, and permissions. This page compares approaches and providers. Once you have chosen an approach, use [Implement Authentication in React](./authentication.md) for the application workflow. - ## Authentication vs Authorization - **Authentication**: Who is this user? (Login/logout, identity verification) @@ -75,11 +72,11 @@ Choose how your React app will handle identity, sessions, and permissions. This - Good for mixed public/private content on same route - Requires careful handling to prevent layout shifts -**Data/API Protection (Security Boundary)** +**Server Function Guards** -- Authorize every server function, server route, or API endpoint that reads or writes private data -- Reject unauthorized requests even if no protected route was loaded first -- Treat route guards as UX and navigation control, not as the data boundary +- Server-side validation before executing sensitive operations +- Works alongside route-level protection +- Essential for API security regardless of client-side protection ### State Management Patterns @@ -112,11 +109,11 @@ Choose how your React app will handle identity, sessions, and permissions. This ### 🛠️ DIY Authentication -Build your own authentication system using TanStack Start's server functions and session management. Start with the [Authentication Server Primitives](./authentication-server-primitives.md) guide — it covers session cookies (`HttpOnly`/`Secure`/`SameSite`/`__Host-`), session lookup as middleware, OAuth `state` + PKCE, password-reset enumeration defense, CSRF, rate limiting, and session rotation, with the WRONG/CORRECT patterns that catch the common mistakes. +Build your own authentication system using TanStack Start's server functions and session management: - **Full Control**: Complete customization over authentication flow -- **Server Primitives**: Sessions, OAuth, CSRF, rate limiting — see [Authentication Server Primitives](./authentication-server-primitives.md) -- **Session Management**: HTTP-only cookies written with `setCookie`, read with `getCookie` +- **Server Functions**: Secure authentication logic on the server +- **Session Management**: Built-in session handling with HTTP-only cookies - **Type Safety**: End-to-end type safety for authentication state ### 🌐 Other Excellent Options @@ -149,7 +146,7 @@ Build your own authentication system using TanStack Start's server functions and - **Multi-factor Authentication** - Enterprise-grade security options - **Compliance Ready** - SOC 2, GDPR, and CCPA compliant -[Visit WorkOS →](https://workos.com/) | [View example →](https://github.com/TanStack/router/tree/main/examples/react/start-workos) +[Visit WorkOS →](https://workos.com/) | [Get started in Builder →](https://tanstack.com/builder) ### Clerk - Complete Authentication Platform @@ -166,21 +163,21 @@ Build your own authentication system using TanStack Start's server functions and - **Multi-factor Authentication** - SMS, TOTP, and backup codes - **Organizations & Teams** - Built-in support for team-based applications -[Visit Clerk →](https://go.clerk.com/wOwHtuJ) | [Sign up free →](https://go.clerk.com/PrSDXti) | [View example →](https://github.com/TanStack/router/tree/main/examples/react/start-clerk-basic) +[Visit Clerk →](https://go.clerk.com/wOwHtuJ) | [Sign up free →](https://go.clerk.com/PrSDXti) | [Get started in Builder →](https://tanstack.com/builder) -## Examples +## Starter Paths **Partner Solutions:** -- [Clerk Integration](https://github.com/TanStack/router/tree/main/examples/react/start-clerk-basic) -- [WorkOS Integration](https://github.com/TanStack/router/tree/main/examples/react/start-workos) +- [Clerk Integration](https://tanstack.com/builder) +- [WorkOS Integration](https://tanstack.com/builder) **DIY Implementations:** -- [Basic Auth with Prisma](https://github.com/TanStack/router/tree/main/examples/react/start-basic-auth) -- [Supabase Auth](https://github.com/TanStack/router/tree/main/examples/react/start-supabase-basic) +- [Build with server sessions and middleware](./authentication) +- [Database setup patterns](./databases) -**Client-Side Examples:** +**Client-Side Patterns:** - [Basic Authentication](https://github.com/TanStack/router/tree/main/examples/react/authenticated-routes) - [Firebase Auth](https://github.com/TanStack/router/tree/main/examples/react/authenticated-routes-firebase) @@ -210,31 +207,27 @@ Build your own authentication system using TanStack Start's server functions and - Specific business logic needs - Full ownership of authentication data -### Production Auth Checklist +### Security Considerations -- Use HTTPS in production and set a strong session secret. -- Store sessions in `HttpOnly`, `Secure`, `SameSite` cookies. Do not store session tokens in `localStorage` or `sessionStorage`. -- Enforce auth in every server function, server route, or API endpoint that reads or writes private user, tenant, or account data. Use `beforeLoad` for page UX, not as the data boundary. -- Use `.validator()` on every server function that accepts input. -- Hash passwords with bcrypt, scrypt, or Argon2. For missing users, verify against a dummy hash and return the same login/reset message. -- Rate limit login, registration, and password-reset endpoints. -- Use CSRF or same-origin protections for non-GET server functions and server routes. -- Log authentication events and monitor failures. -- Test direct unauthenticated calls to protected server functions; they should reject before returning data. +- Use HTTPS in production +- Use HTTP-only cookies when possible +- Validate all inputs on the server +- Keep secrets in server-only functions +- Implement rate limiting for auth endpoints +- Use CSRF protection for form submissions ## Next Steps - **Partner solutions** → [Clerk](https://go.clerk.com/wOwHtuJ) or [WorkOS](https://workos.com/) - **DIY implementation** → [Authentication Guide](./authentication.md) -- **Examples** → [Working implementations](https://github.com/TanStack/router/tree/main/examples/react) +- **Templates & integrations** → [TanStack Builder](https://tanstack.com/builder) ## Resources **Implementation Guides:** -- [Authentication Server Primitives](./authentication-server-primitives.md) — sessions, cookies, OAuth, CSRF, rate limiting (the server half) - [Authentication Patterns](./authentication.md) -- [Router Authentication Guide](/router/latest/docs/framework/react/guide/authenticated-routes) +- [Router Authentication Guide](/router/latest/docs/framework/react/guide/authenticated-routes.md) **Foundation Concepts:** diff --git a/docs/start/framework/react/guide/authentication-server-primitives.md b/docs/start/framework/react/guide/authentication-server-primitives.md deleted file mode 100644 index 103e9c4455..0000000000 --- a/docs/start/framework/react/guide/authentication-server-primitives.md +++ /dev/null @@ -1,351 +0,0 @@ ---- -id: authentication-server-primitives -title: Authentication Server Primitives ---- - -This guide covers the **server-side primitives** for building authentication in TanStack Start: session cookies, session lookup, OAuth, password-reset hardening, CSRF, and rate limiting. It pairs with the [routing-side guide](/router/latest/docs/framework/react/guide/authenticated-routes) (`_authenticated` layout, `beforeLoad`, redirects, RBAC). - -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. - -## Protect Data First - -Authentication has a data/API boundary and a route/UI layer. The data boundary is the security boundary: every server function, server route, or API endpoint that reads or writes private data must authorize the request before returning data or mutating state. - -- **Data/API boundary** (this guide): issue and verify session cookies, exchange OAuth codes, hash and verify passwords, rate-limit credential endpoints, defeat user enumeration, and authorize private data access. -- **Route/UI layer** (`router-core/auth-and-guards`): redirect unauthenticated users away from screens they cannot use, gate UI on roles/permissions, surface a login form, and avoid triggering requests that would fail anyway. - -> **A route guard is not a data authorization boundary.** Server functions and server routes are API endpoints; they are reachable independently of the route that calls them. Auth must be enforced in the handler or middleware for the endpoint that touches private data. `beforeLoad` is for route UX. - -## Session Cookies - -The default session storage is an HTTP-only cookie. The cookie can hold: - -- An **opaque session ID** that the server looks up in a database (recommended — easy to revoke). -- A **signed/encrypted token** that carries the session payload itself (stateless, but revocation is harder). - -Whichever you choose, the cookie flags matter: - -```ts -// src/server/session.ts -import { - 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) { - setCookie(SESSION_COOKIE, token, { - ...sessionCookieOptions, - maxAge: ONE_DAY, - }) -} - -export function clearSessionCookie() { - deleteCookie(SESSION_COOKIE, sessionCookieOptions) -} - -export function readSessionToken(): string | 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. | -| `Secure` | HTTPS only. Required when using the `__Host-` prefix. | -| `SameSite=Lax` | Sent on top-level navigations; blocks most cross-site CSRF on POST. Use `Strict` for higher-risk apps where loss of cross-site GET navigation is acceptable. | -| `__Host-` prefix | Binds the cookie to the exact origin. No `Domain` attribute, `Path=/`, `Secure` required. Defeats subdomain-takeover session fixation. | -| `Path=/` | Required by `__Host-`. | -| `Max-Age` | Bounded lifetime. Pair with server-side rotation. | - -## Session Lookup as Middleware - -Centralize session loading in middleware so every protected handler sees a typed session: - -```ts -// src/server/auth-middleware.ts -import { createMiddleware } from '@tanstack/react-start' -import { readSessionToken } from './session' - -export const authMiddleware = createMiddleware({ type: 'function' }).server( - async ({ next }) => { - const token = readSessionToken() - const session = token ? await db.sessions.findValid(token) : null - if (!session) throw new Error('Unauthorized') - return next({ context: { session } }) - }, -) -``` - -Attach to every protected server function: - -```ts -import { createServerFn } from '@tanstack/react-start' -import { authMiddleware } from '~/server/auth-middleware' - -export const getMyOrders = createServerFn({ method: 'GET' }) - .middleware([authMiddleware]) - .handler(async ({ context }) => { - return db.orders.findMany({ where: { userId: context.session.userId } }) - }) -``` - -## Login - -```ts -// src/server/login.functions.ts -import { createServerFn } from '@tanstack/react-start' -import { z } from 'zod' -import { setSessionCookie } from './session' - -export const login = createServerFn({ method: 'POST' }) - .validator(z.object({ email: z.string().email(), password: z.string() })) - .handler(async ({ data }) => { - const user = await db.users.findByEmail(data.email) - // Always run verifyPasswordHash — even when the user doesn't exist — - // so the user-not-found branch takes the same time as wrong-password. - // DUMMY_PASSWORD_HASH is a hash of any throwaway password computed once - // at startup with the same algorithm/cost as real password hashes. - const hashToCheck = user?.passwordHash ?? DUMMY_PASSWORD_HASH - const passwordMatches = await verifyPasswordHash(hashToCheck, data.password) - const ok = user != null && passwordMatches - if (!ok) throw new Error('Invalid email or password') - - // Rotate: destroy any existing session, then issue fresh. - await db.sessions.revokeAllForUser(user.id) - const token = await db.sessions.create({ userId: user.id }) - setSessionCookie(token) - return { ok: true } - }) -``` - -The `Invalid email or password` message is identical for "user not found" and "wrong password". The dummy-hash technique above also makes the timing identical: without it, the no-user branch returns instantly while the wrong-password branch spends ~100ms on the hash compare, leaking account existence over the wire. - -## Logout - -```ts -import { createServerFn } from '@tanstack/react-start' -import { authMiddleware } from '~/server/auth-middleware' -import { clearSessionCookie } from '~/server/session' - -export const logout = createServerFn({ method: 'POST' }) - .middleware([authMiddleware]) - .handler(async ({ context }) => { - await db.sessions.revoke(context.session.id) - clearSessionCookie() - return { ok: true } - }) -``` - -## OAuth: state + PKCE - -For OAuth authorization-code flow: - -- Generate a one-time random `state` parameter — prevents CSRF on the callback. -- Generate a PKCE `code_verifier`/`code_challenge` pair — defends against authorization-code interception. -- Store both in a short-lived signed cookie keyed to this exact attempt. - -```ts -// src/server/oauth.functions.ts -import { createServerFn } from '@tanstack/react-start' -import { redirect } from '@tanstack/react-router' -import { setCookie } from '@tanstack/react-start/server' -import crypto from 'node:crypto' - -const OAUTH_STATE_COOKIE = '__Host-oauth' - -function base64url(buf: Buffer) { - return buf - .toString('base64') - .replace(/=/g, '') - .replace(/\+/g, '-') - .replace(/\//g, '_') -} - -export const startOAuth = createServerFn({ method: 'GET' }).handler( - async () => { - const state = base64url(crypto.randomBytes(32)) - const verifier = base64url(crypto.randomBytes(32)) - const challenge = base64url( - crypto.createHash('sha256').update(verifier).digest(), - ) - - setCookie(OAUTH_STATE_COOKIE, signed({ state, verifier }), { - httpOnly: true, - secure: true, - sameSite: 'lax', - path: '/', - maxAge: 600, - }) - - throw redirect({ - href: - `https://provider.example/authorize` + - `?response_type=code` + - `&client_id=${process.env.OAUTH_CLIENT_ID}` + - `&redirect_uri=${encodeURIComponent(process.env.OAUTH_REDIRECT_URI!)}` + - `&state=${state}` + - `&code_challenge=${challenge}` + - `&code_challenge_method=S256`, - }) - }, -) -``` - -In the callback handler: - -1. Read the cookie, verify its signature, and extract `state` + `verifier`. -2. Compare cookie-state to the `state` query param. If they don't match, abort. -3. Exchange the authorization code for an access token, sending `code_verifier` along with it. -4. Fetch the user profile, find/create the local user record, issue a session. -5. Clear the OAuth cookie. - -If any of those checks fail, the request did not originate from your `startOAuth` and must be rejected. - -## Password Reset: defeat user enumeration - -The reset endpoint must NOT tell the caller whether a given email is registered. Returning 200 vs 404 — or even different copy — leaks user existence to anyone who can hit the endpoint. - -```ts -import { createServerFn } from '@tanstack/react-start' -import { z } from 'zod' - -export const requestPasswordReset = createServerFn({ method: 'POST' }) - .validator(z.object({ email: z.string().email() })) - .handler(async ({ data }) => { - const user = await db.users.findByEmail(data.email) - if (user) { - const token = await db.passwordResets.issue(user.id) - await sendResetEmail(user.email, token) - } - // Same response, same body, regardless of existence. - return { ok: true } - }) -``` - -Do NOT: - -- Return 200 if exists, 404 if not. -- Vary the message ("we sent you a link" vs "no account found"). -- Skip the work when the user doesn't exist (timing leak — measurable from the wire). - -## CSRF for non-GET RPCs - -`SameSite=Lax` on the session cookie blocks most cross-site CSRF for POST/PUT/DELETE. Two cases need explicit defense: - -1. **GET-that-mutates** — never. Use POST/PUT/DELETE for any mutation. -2. **POST from a sibling subdomain** — `SameSite=Lax` does not block this; verify the `Origin` header matches your app. - -```ts -import { createMiddleware } from '@tanstack/react-start' -import { getRequest } from '@tanstack/react-start/server' - -export const csrfMiddleware = createMiddleware().server(async ({ next }) => { - const request = getRequest() - if (request.method !== 'GET' && request.method !== 'HEAD') { - const origin = request.headers.get('origin') - // Compare the FULL origin (scheme + host + port) — host alone lets - // http://example.com pass a check meant for https://example.com. - if (!origin || new URL(origin).origin !== process.env.APP_ORIGIN) { - throw new Error('Origin check failed') - } - } - return next() -}) -``` - -Attach this in `src/start.ts` global `requestMiddleware` so it runs on every non-GET request, including server routes and SSR. - -## Rate Limiting Auth Endpoints - -A login endpoint without rate limiting is a credential-stuffing target. Limit per IP (and per-account if you can identify the user) with a sliding window or token bucket. - -```ts -import { createMiddleware } from '@tanstack/react-start' -import { getRequest } from '@tanstack/react-start/server' - -function rateLimitMiddleware(opts: { - key: string - max: number - windowMs: number -}) { - return createMiddleware().server(async ({ next }) => { - const request = getRequest() - const ip = - request.headers.get('cf-connecting-ip') ?? - request.headers.get('x-forwarded-for')?.split(',')[0] ?? - 'unknown' - const allowed = await rateLimiter.consume( - `rl:${opts.key}:${ip}`, - opts.max, - opts.windowMs, - ) - if (!allowed) throw new Error('Too many requests') - return next() - }) -} - -export const login = createServerFn({ method: 'POST' }).middleware([ - rateLimitMiddleware({ key: 'login', max: 5, windowMs: 60_000 }), -]) -// ... -``` - -## Session Rotation - -Whenever the user's privileges change — login, logout, password change, role grant — destroy the old session and issue a new one. This neutralizes session-fixation attacks where an attacker plants their own session ID in the victim's browser before the privilege change. - -```ts -// On login: revoke any pre-login session, create fresh. -await db.sessions.revokeAllForUser(user.id) -const token = await db.sessions.create({ userId: user.id }) -setSessionCookie(token) - -// On password change / role grant: -await db.sessions.revokeAllForUser(user.id) -const token = await db.sessions.create({ userId: user.id }) -setSessionCookie(token) -``` - -## Read Cookies and Env Per Request, Not at Module Scope - -Module-scope reads are wrong on two axes: - -- **Security:** they can be inlined into the client bundle. -- **Correctness on edge runtimes:** Cloudflare Workers (and others) inject env at request time. Module-level reads run before any request exists and evaluate to `undefined` even on the server. - -```ts -// ❌ Wrong -const SESSION_SECRET = process.env.SESSION_SECRET -export function signSession(payload) { - return sign(payload, SESSION_SECRET) -} - -// ✅ Right -export function signSession(payload) { - return sign(payload, process.env.SESSION_SECRET) -} -``` - -See [Execution Model: Module-Level `process.env` Reads](./execution-model.md#module-level-processenv-reads) for the full rule. - -## See Also - -- [Authentication Overview](./authentication-overview.md) — choosing between partner solutions, OSS libraries, and DIY. -- [Authenticated Routes (Router)](/router/latest/docs/framework/react/guide/authenticated-routes) — the routing-side guide. -- [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). -- [MDN — Set-Cookie](https://developer.mozilla.org/docs/Web/HTTP/Headers/Set-Cookie). diff --git a/docs/start/framework/react/guide/authentication.md b/docs/start/framework/react/guide/authentication.md index c77c681ee0..50982206a7 100644 --- a/docs/start/framework/react/guide/authentication.md +++ b/docs/start/framework/react/guide/authentication.md @@ -1,12 +1,11 @@ --- id: authentication -title: Implement Authentication in React -description: Implement sessions, sign-in, sign-out, protected routes, and server-side authorization in a TanStack Start React app. +title: Authentication --- -Implement the authentication workflow in your React app, from sessions and sign-in to protected routes and authorization. +This guide covers authentication patterns and shows how to implement your own authentication system with TanStack Start. -To compare libraries and hosted services, read [Choose Authentication for React Apps](./authentication-overview.md). +> **📋 Before You Start:** Check our [Authentication Overview](./authentication-overview.md) for all available options including partner solutions and hosted services. ## Authentication Approaches @@ -35,9 +34,7 @@ Authentication involves many considerations including password security, session - **Authentication**: Who is this user? (Login/logout) - **Authorization**: What can this user do? (Permissions/roles) -TanStack Start provides server functions, request and cookie utilities, and route protection. Session storage and authentication come from your application or a library you choose. - -> 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. +TanStack Start provides the tools for both through server functions, sessions, and route protection. ## Essential Building Blocks @@ -48,11 +45,10 @@ 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' }) - .validator((data: { email: string; password: string }) => data) + .inputValidator((data: { email: string; password: string }) => data) .handler(async ({ data }) => { // Verify credentials (replace with your auth logic) const user = await authenticateUser(data.email, data.password) @@ -62,9 +58,11 @@ export const loginFn = createServerFn({ method: 'POST' }) } // Create session - const session = await getAppSession() - session.userId = user.id - await session.save() + const session = await useAppSession() + await session.update({ + userId: user.id, + email: user.email, + }) // Redirect to protected area throw redirect({ to: '/dashboard' }) @@ -72,131 +70,98 @@ export const loginFn = createServerFn({ method: 'POST' }) // Logout server function export const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await getAppSession() - session.destroy() + const session = await useAppSession() + await session.clear() throw redirect({ to: '/' }) }) // Get current user export const getCurrentUserFn = createServerFn({ method: 'GET' }).handler( async () => { - const session = await getAppSession() - const userId = session.userId + const session = await useAppSession() + const userId = session.data.userId if (!userId) { return null } - const user = await getUserById(userId) - return user ? { id: user.id, email: user.email, role: user.role } : null + return await getUserById(userId) }, ) ``` ### 2. Session Management -Start does not provide a session API. This guide uses iron-session for encrypted cookie sessions. Start's cookie helpers connect it to server functions, server routes, and request middleware. - -For encrypted cookie sessions, install [iron-session](https://github.com/vvo/iron-session): - -```sh -pnpm add iron-session -``` - -This example uses iron-session 9's cookie adapter. Its Node runtime requires Node 22.13 or newer; check the library's runtime requirements for other deployment targets. +TanStack Start provides secure HTTP-only cookie sessions: ```tsx -// utils/session.ts — import only from server code -import { getIronSession } from 'iron-session' -import { getCookie, setCookie } from '@tanstack/react-start/server' +// utils/session.ts +import { useSession } from '@tanstack/react-start/server' type SessionData = { - userId: string - oauthState: string + userId?: string + email?: string + role?: string } -export function getAppSession(ttl = 7 * 24 * 60 * 60) { - const password = process.env.SESSION_SECRET - if (!password || password.length < 32) { - throw new Error('SESSION_SECRET must be at least 32 characters') - } - - return getIronSession( - { read: getCookie, write: setCookie }, - { - cookieName: 'app-session', - password, - ttl, - cookieOptions: { - secure: process.env.NODE_ENV === 'production', - sameSite: 'lax', - httpOnly: true, - path: '/', - }, +export function useAppSession() { + return useSession({ + // Session configuration + name: 'app-session', + password: process.env.SESSION_SECRET!, // At least 32 characters + // Optional: customize cookie settings + cookie: { + secure: process.env.NODE_ENV === 'production', + sameSite: 'lax', + httpOnly: true, }, - ) + }) } ``` -Read fields directly from the returned session, change them, then `await session.save()` before returning or redirecting. Missing or expired sessions have no user ID. `session.destroy()` removes the browser cookie. Keep one session object for the operation; another call to `getAppSession()` reads the incoming request again. For middleware, pass that object through request context when downstream code needs the same mutations. - -The `getAppSession` helper belongs to your application. Start does not cache sessions, choose expiration rules, or synchronize concurrent writes. Keep secrets and session objects in server code, and read request-specific configuration inside the active request. - ### 3. Authentication Context -Load the current user in your root route's `beforeLoad` so the initial server render and child routes receive the same authentication state. `useServerFn` returns a callable function, not an object with `data`, `isLoading`, or `refetch`. You can call a server function directly from `beforeLoad`. - -Merge this pattern into your existing root route, keeping its metadata and document shell: +Share authentication state across your application: ```tsx -// routes/__root.tsx -import { - createRootRoute, - HeadContent, - Outlet, - Scripts, -} from '@tanstack/react-router' -import type { ReactNode } from 'react' +// contexts/auth.tsx +import { createContext, useContext, ReactNode } from 'react' +import { useServerFn } from '@tanstack/react-start' import { getCurrentUserFn } from '../server/auth' -export const Route = createRootRoute({ - headers: () => ({ 'Cache-Control': 'private, no-store' }), - beforeLoad: async () => ({ user: await getCurrentUserFn() }), - component: Outlet, - shellComponent: RootDocument, -}) +type User = { + id: string + email: string + role: string +} + +type AuthContextType = { + user: User | null + isLoading: boolean + refetch: () => void +} + +const AuthContext = createContext(undefined) + +export function AuthProvider({ children }: { children: ReactNode }) { + const { data: user, isLoading, refetch } = useServerFn(getCurrentUserFn) -function RootDocument({ children }: { children: ReactNode }) { return ( - - - - - - {children} - - - + + {children} + ) } -``` -The root includes session-specific data, so its responses use `Cache-Control: private, no-store`. Keep that policy on child routes that render this data, and do not override it with public caching at your CDN. - -Read that state from a descendant component: - -```tsx -// components/AuthStatus.tsx -import { Route } from '../routes/__root' - -export function AuthStatus() { - const { user } = Route.useRouteContext() - return {user ? user.email : 'Signed out'} +export function useAuth() { + const context = useContext(AuthContext) + if (!context) { + throw new Error('useAuth must be used within AuthProvider') + } + return context } ``` -After login or logout changes the session, call `await router.invalidate()` to reload the current user and rerun route guards. Keep private-data authorization in the server function itself, even when a route already checks the user. - ### 4. Route Protection Protect routes using `beforeLoad`: @@ -254,7 +219,9 @@ import { createServerFn } from '@tanstack/react-start' // User registration export const registerFn = createServerFn({ method: 'POST' }) - .validator((data: { email: string; password: string; name: string }) => data) + .inputValidator( + (data: { email: string; password: string; name: string }) => data, + ) .handler(async ({ data }) => { // Check if user exists const existingUser = await getUserByEmail(data.email) @@ -273,9 +240,8 @@ export const registerFn = createServerFn({ method: 'POST' }) }) // Create session - const session = await getAppSession() - session.userId = user.id - await session.save() + const session = await useAppSession() + await session.update({ userId: user.id }) return { success: true, user: { id: user.id, email: user.email } } }) @@ -337,15 +303,14 @@ export const authProviders = { } export const initiateOAuthFn = createServerFn({ method: 'POST' }) - .validator((data: { provider: 'google' | 'github' }) => data) + .inputValidator((data: { provider: 'google' | 'github' }) => data) .handler(async ({ data }) => { const provider = authProviders[data.provider] const state = generateRandomState() // Store state in session for CSRF protection - const session = await getAppSession() - session.oauthState = state - await session.save() + const session = await useAppSession() + await session.update({ oauthState: state }) // Generate OAuth URL const authUrl = generateOAuthUrl(provider, state) @@ -359,7 +324,7 @@ export const initiateOAuthFn = createServerFn({ method: 'POST' }) ```tsx // Password reset request export const requestPasswordResetFn = createServerFn({ method: 'POST' }) - .validator((data: { email: string }) => data) + .inputValidator((data: { email: string }) => data) .handler(async ({ data }) => { const user = await getUserByEmail(data.email) if (!user) { @@ -378,7 +343,7 @@ export const requestPasswordResetFn = createServerFn({ method: 'POST' }) // Password reset confirmation export const resetPasswordFn = createServerFn({ method: 'POST' }) - .validator((data: { token: string; newPassword: string }) => data) + .inputValidator((data: { token: string; newPassword: string }) => data) .handler(async ({ data }) => { const resetToken = await getPasswordResetToken(data.token) @@ -408,9 +373,21 @@ const hashedPassword = await bcrypt.hash(password, saltRounds) ### 2. Session Security -Set the library's server-validated expiration as well as appropriate cookie attributes. In the iron-session example, `ttl` limits a sealed credential's lifetime from its latest save; saving again renews it. A numeric `cookieOptions.maxAge` controls browser retention. In iron-session 9, explicitly setting `maxAge: undefined` also disables seal expiry; omit the property to use the configured `ttl`. Use an application-validated timestamp or a server-side record if you also need an absolute lifetime that writes cannot extend. - -Use `httpOnly`, `sameSite`, and `path` deliberately, and require `secure: true` on HTTPS deployments. These cookie attributes complement server-side authorization and CSRF protections. Keep only the minimum session data and load current account permissions from their authoritative store. Logout removes a stateless cookie from the current browser; it cannot revoke a copy without server-side state. +```tsx +// Use secure session configuration +export function useAppSession() { + return useSession({ + name: 'app-session', + password: process.env.SESSION_SECRET!, // 32+ characters + cookie: { + secure: process.env.NODE_ENV === 'production', // HTTPS only in production + sameSite: 'lax', // CSRF protection + httpOnly: true, // XSS protection + maxAge: 7 * 24 * 60 * 60, // 7 days + }, + }) +} +``` ### 3. Rate Limiting @@ -447,7 +424,7 @@ const loginSchema = z.object({ }) export const loginFn = createServerFn({ method: 'POST' }) - .validator((data) => loginSchema.parse(data)) + .inputValidator((data) => loginSchema.parse(data)) .handler(async ({ data }) => { // data is now validated }) @@ -512,69 +489,28 @@ describe('Authentication Flow', () => { ### Loading States -Call the function returned by `useServerFn` with `{ data }`. Track pending state in the component, handle invalid credentials, and refresh route context after a successful login. This form uses the `loginFn` from the server-functions example above. It requires JavaScript, so the fields stay disabled until hydration; `method="post"` also prevents credentials appearing in a native GET submission. - ```tsx -// components/LoginForm.tsx -import { useState } from 'react' -import type { FormEvent } from 'react' -import { useHydrated, useRouter } from '@tanstack/react-router' -import { useServerFn } from '@tanstack/react-start' -import { loginFn } from '../server/auth' - -export function LoginForm() { - const hydrated = useHydrated() +function LoginForm() { const [isLoading, setIsLoading] = useState(false) - const [error, setError] = useState('') - const login = useServerFn(loginFn) - const router = useRouter() - - const handleSubmit = async (event: FormEvent) => { - event.preventDefault() - const formData = new FormData(event.currentTarget) - const email = formData.get('email') - const password = formData.get('password') - if (typeof email !== 'string' || typeof password !== 'string') { - return - } + const loginMutation = useServerFn(loginFn) + const handleSubmit = async (data: LoginData) => { setIsLoading(true) - setError('') try { - const result = await login({ data: { email, password } }) - if (result?.error) { - setError(result.error) - return - } - await router.invalidate() - } catch { - setError('Login failed. Please try again.') + await loginMutation.mutate(data) + } catch (error) { + // Handle error } finally { setIsLoading(false) } } return ( - -
- - - -
-

{error}

+ + {/* Form fields */} + ) } @@ -584,31 +520,33 @@ export function LoginForm() { ```tsx export const loginFn = createServerFn({ method: 'POST' }) - .validator( + .inputValidator( (data: { email: string; password: string; rememberMe?: boolean }) => data, ) .handler(async ({ data }) => { const user = await authenticateUser(data.email, data.password) - if (!user) { - return { error: 'Invalid credentials' } - } + if (!user) return { error: 'Invalid credentials' } - const ttl = data.rememberMe ? 30 * 24 * 60 * 60 : 8 * 60 * 60 - const session = await getAppSession(ttl) - session.userId = user.id - await session.save() + const session = await useAppSession() + await session.update( + { userId: user.id }, + { + // Extend session if remember me is checked + maxAge: data.rememberMe ? 30 * 24 * 60 * 60 : undefined, // 30 days vs session + }, + ) return { success: true } }) ``` -## Working Examples +## Starter Paths -Study these implementations to understand different authentication patterns: +Use these paths depending on what you need: -- **[Basic Auth with Prisma](https://github.com/TanStack/router/tree/main/examples/react/start-basic-auth)** - Complete DIY implementation with database and sessions -- **[Supabase Integration](https://github.com/TanStack/router/tree/main/examples/react/start-supabase-basic)** - Third-party service integration example -- **[Client-side Context Auth](https://github.com/TanStack/router/tree/main/examples/react/authenticated-routes)** - Client-only authentication patterns +- **[TanStack Builder](https://tanstack.com/builder)** - Generate projects with hosted auth providers and deployment options +- **[Authentication Overview](./authentication-overview)** - Compare hosted, OSS, and DIY approaches +- **[Client-side Context Auth](/router/latest/docs/framework/react/guide/authenticated-routes)** - Client-only authentication patterns ## Migration from Other Solutions @@ -624,6 +562,7 @@ If you're migrating from client-side authentication (localStorage, context only) ### From Other Frameworks - **Next.js**: Replace API routes with server functions, migrate NextAuth sessions +- **Remix**: Convert loaders/actions to server functions, adapt session patterns - **SvelteKit**: Move form actions to server functions, update route protection ## Production Considerations @@ -668,4 +607,4 @@ When implementing authentication, consider: - **Monitoring**: Add logging and monitoring for authentication events - **Compliance**: Ensure compliance with relevant regulations if storing personal data -For other authentication approaches, check the [Authentication Overview](./authentication-overview.md). For specific integration help, explore our [working examples](https://github.com/TanStack/router/tree/main/examples/react). +For other authentication approaches, check the [Authentication Overview](./authentication-overview.md). For specific integration help, use [TanStack Builder](https://tanstack.com/builder) and the auth guides linked above. diff --git a/docs/start/framework/react/guide/cdn-asset-urls.md b/docs/start/framework/react/guide/cdn-asset-urls.md index ac5f3e7b57..977c030c68 100644 --- a/docs/start/framework/react/guide/cdn-asset-urls.md +++ b/docs/start/framework/react/guide/cdn-asset-urls.md @@ -3,26 +3,25 @@ id: cdn-asset-urls title: CDN Asset URLs --- -> **Experimental:** `transformAssets` is experimental and subject to change. +# CDN Asset URLs -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. +> **Experimental:** `transformAssetUrls` is experimental and subject to change. -This guide is about asset URL rewriting. For choosing CSS import patterns and configuring CSS inlining, see the [CSS Styling guide](./css-styling). +When deploying to production, you may want to serve your static assets (JavaScript, CSS) from a CDN. The `transformAssetUrls` option on `createStartHandler` lets you rewrite asset URLs at runtime — for example, prepending a CDN origin that is only known when the server starts. -## What `transformAssets` Rewrites +## Why Runtime URL Rewriting? -The `transformAssets` option on `createStartHandler` rewrites URLs that Start manages in its SSR manifest: +Vite's `base` config is evaluated at build time. If your CDN URL is determined at deploy time (via environment variables, dynamic configuration, etc.), you need a way to rewrite URLs at runtime. `transformAssetUrls` solves this for the URLs that TanStack Start manages in its manifest: -- JavaScript preload links (`` for module output, or `` for IIFE output) -- `` tags for manifest-managed CSS -- The client entry script URL -- `url(...)` and `@import` URLs inside [inlined CSS](./css-styling#inline-route-css-in-production) when CSS URL templates are enabled +- `` tags (JS preloads) +- `` tags (CSS) +- The client entry ` - - - diff --git a/e2e/react-router/issue-4759/package.json b/e2e/react-router/issue-4759/package.json deleted file mode 100644 index ee6a105ad5..0000000000 --- a/e2e/react-router/issue-4759/package.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "name": "tanstack-router-e2e-react-issue-4759", - "private": true, - "type": "module", - "scripts": { - "build": "vite build && tsc --noEmit", - "dev": "vite --port 3000", - "dev:e2e": "vite", - "preview": "vite preview", - "start": "vite", - "test:e2e": "playwright test --project=chromium" - }, - "dependencies": { - "@tanstack/react-router": "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-router/issue-4759/playwright.config.ts b/e2e/react-router/issue-4759/playwright.config.ts deleted file mode 100644 index a301f62881..0000000000 --- a/e2e/react-router/issue-4759/playwright.config.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' - -const PORT = Number(process.env.E2E_APP_PORT ?? 0) -const baseURL = `http://localhost:${PORT}` - -export default defineConfig({ - testDir: './tests', - workers: 1, - reporter: [['line']], - 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-router/issue-4759/src/main.tsx b/e2e/react-router/issue-4759/src/main.tsx deleted file mode 100644 index e251178045..0000000000 --- a/e2e/react-router/issue-4759/src/main.tsx +++ /dev/null @@ -1,74 +0,0 @@ -import { StrictMode } from 'react' -import { createRoot } from 'react-dom/client' -import { - Outlet, - RouterProvider, - createRootRoute, - createRoute, - createRouter, -} from '@tanstack/react-router' - -const rootRoute = createRootRoute({ - context: () => ({ locale: 'en' }), - component: RootComponent, -}) -function RootComponent() { - const { locale } = rootRoute.useRouteContext() - return ( -
- -
- ) -} -const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - loader: () => new Promise((resolve) => setTimeout(resolve, 1_000)), - component: () =>
loaded
, -}) -const routePendingRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/route-pending', - pendingMs: 0, - pendingMinMs: 0, - 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( - -
- -
-
, -) diff --git a/e2e/react-router/issue-4759/tests/issue-4759.spec.ts b/e2e/react-router/issue-4759/tests/issue-4759.spec.ts deleted file mode 100644 index 95689010c8..0000000000 --- a/e2e/react-router/issue-4759/tests/issue-4759.spec.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { expect, test } from '@playwright/test' -import type { Page } from '@playwright/test' - -async function expectNoBlankFrame( - page: Page, - pendingSource: 'default' | 'route', -) { - 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( - () => - (globalThis as typeof globalThis & { __paintStates: Array }) - .__paintStates, - ) - - expect(paintStates).toContain('pending') - expect(paintStates).not.toContain('shell') - expect(paintStates).not.toContain('empty') - await expect(page.locator('[data-state="loaded"]')).toBeVisible() -} - -test('#4759: the initial default pending component has no blank frame before it', async ({ - page, -}) => { - await page.goto('/') - await expectNoBlankFrame(page, 'default') -}) - -test('an initial route pending component has no blank frame before it', async ({ - page, -}) => { - await page.goto('/route-pending') - await expectNoBlankFrame(page, 'route') -}) diff --git a/e2e/react-router/issue-4759/tsconfig.json b/e2e/react-router/issue-4759/tsconfig.json deleted file mode 100644 index e4ba4788a3..0000000000 --- a/e2e/react-router/issue-4759/tsconfig.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "compilerOptions": { - "strict": true, - "jsx": "react-jsx", - "target": "ESNext", - "moduleResolution": "Bundler", - "module": "ESNext", - "resolveJsonModule": true, - "skipLibCheck": true, - "types": ["vite/client"] - }, - "exclude": ["node_modules", "dist"] -} diff --git a/e2e/react-router/issue-4759/vite.config.ts b/e2e/react-router/issue-4759/vite.config.ts deleted file mode 100644 index 9ffcc67574..0000000000 --- a/e2e/react-router/issue-4759/vite.config.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { defineConfig } from 'vite' -import react from '@vitejs/plugin-react' - -export default defineConfig({ - plugins: [react()], -}) diff --git a/e2e/react-router/issue-7120/index.html b/e2e/react-router/issue-7120/index.html deleted file mode 100644 index 04a3530c9d..0000000000 --- a/e2e/react-router/issue-7120/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - Issues 7120 and 7367 - - - - diff --git a/e2e/react-router/issue-7120/package.json b/e2e/react-router/issue-7120/package.json deleted file mode 100644 index 979b32556c..0000000000 --- a/e2e/react-router/issue-7120/package.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "tanstack-router-e2e-react-issue-7120", - "private": true, - "type": "module", - "scripts": { - "dev": "vite --port 3000", - "dev:e2e": "vite", - "build": "vite build && tsc --noEmit", - "preview": "vite preview", - "start": "vite", - "test:e2e": "playwright test --project=chromium" - }, - "dependencies": { - "@tanstack/react-router": "workspace:^", - "@tanstack/router-plugin": "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-router/issue-7120/playwright.config.ts b/e2e/react-router/issue-7120/playwright.config.ts deleted file mode 100644 index a8ba116fb4..0000000000 --- a/e2e/react-router/issue-7120/playwright.config.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' - -const PORT = Number(process.env.E2E_APP_PORT ?? 0) -const baseURL = `http://localhost:${PORT}` - -export default defineConfig({ - testDir: './tests', - workers: 1, - reporter: [['line']], - use: { baseURL }, - webServer: { - command: `VITE_NODE_ENV="test" 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-router/issue-7120/src/main.tsx b/e2e/react-router/issue-7120/src/main.tsx deleted file mode 100644 index 0c983251af..0000000000 --- a/e2e/react-router/issue-7120/src/main.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import { StrictMode } from 'react' -import { createRoot } from 'react-dom/client' -import { RouterProvider, createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -const router = createRouter({ - routeTree, - defaultViewTransition: true, -}) - -declare module '@tanstack/react-router' { - interface Register { - router: typeof router - } -} - -createRoot(document.getElementById('root')!).render( - - - , -) diff --git a/e2e/react-router/issue-7120/src/redirectGate.ts b/e2e/react-router/issue-7120/src/redirectGate.ts deleted file mode 100644 index 399d303aac..0000000000 --- a/e2e/react-router/issue-7120/src/redirectGate.ts +++ /dev/null @@ -1,35 +0,0 @@ -type RedirectGate = { - waiting: boolean - released: boolean - release: () => void -} - -declare global { - interface Window { - redirectGate: RedirectGate - } -} - -let releasePromise!: () => void -const promise = new Promise((resolve) => { - releasePromise = resolve -}) - -const redirectGate: RedirectGate = { - waiting: false, - released: false, - release: () => { - if (!redirectGate.released) { - redirectGate.released = true - releasePromise() - } - }, -} - -window.redirectGate = redirectGate - -export async function waitForRedirectGate() { - redirectGate.waiting = true - await promise - redirectGate.waiting = false -} diff --git a/e2e/react-router/issue-7120/src/routeTree.gen.ts b/e2e/react-router/issue-7120/src/routeTree.gen.ts deleted file mode 100644 index e8c6d92110..0000000000 --- a/e2e/react-router/issue-7120/src/routeTree.gen.ts +++ /dev/null @@ -1,77 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as PostsRouteImport } from './routes/posts' - -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 - '/posts': typeof PostsRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/posts': typeof PostsRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/posts': typeof PostsRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/posts' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/posts' - id: '__root__' | '/' | '/posts' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - PostsRoute: typeof PostsRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - PostsRoute: PostsRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/e2e/react-router/issue-7120/src/routes/__root.tsx b/e2e/react-router/issue-7120/src/routes/__root.tsx deleted file mode 100644 index 2f01516a55..0000000000 --- a/e2e/react-router/issue-7120/src/routes/__root.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import { Outlet, createRootRoute, redirect } from '@tanstack/react-router' -import { waitForRedirectGate } from '../redirectGate' - -let shouldRedirect = true - -export const Route = createRootRoute({ - pendingMs: 0, - pendingMinMs: 500, - pendingComponent: RootPendingComponent, - beforeLoad: async ({ location }) => { - if (location.pathname !== '/' || !shouldRedirect) { - return - } - - await waitForRedirectGate() - - if (!shouldRedirect) { - return - } - - shouldRedirect = false - throw redirect({ to: '/posts', replace: true }) - }, - component: () => , -}) - -function RootPendingComponent() { - return ( -
- Loading route -
- ) -} diff --git a/e2e/react-router/issue-7120/src/routes/index.tsx b/e2e/react-router/issue-7120/src/routes/index.tsx deleted file mode 100644 index 1626ce706b..0000000000 --- a/e2e/react-router/issue-7120/src/routes/index.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: () =>
Home
, -}) diff --git a/e2e/react-router/issue-7120/src/routes/posts.lazy.tsx b/e2e/react-router/issue-7120/src/routes/posts.lazy.tsx deleted file mode 100644 index dc0b0cfd7f..0000000000 --- a/e2e/react-router/issue-7120/src/routes/posts.lazy.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createLazyFileRoute } from '@tanstack/react-router' - -export const Route = createLazyFileRoute('/posts')({ - component: PostsComponent, -}) - -function PostsComponent() { - return ( -
-

Posts loaded

-

The redirected lazy route rendered.

-
- ) -} diff --git a/e2e/react-router/issue-7120/src/routes/posts.tsx b/e2e/react-router/issue-7120/src/routes/posts.tsx deleted file mode 100644 index cc0519b74e..0000000000 --- a/e2e/react-router/issue-7120/src/routes/posts.tsx +++ /dev/null @@ -1,3 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/posts')({}) diff --git a/e2e/react-router/issue-7120/src/vite-env.d.ts b/e2e/react-router/issue-7120/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/react-router/issue-7120/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/react-router/issue-7120/tests/issue-7120.repro.spec.ts b/e2e/react-router/issue-7120/tests/issue-7120.repro.spec.ts deleted file mode 100644 index 081ae73691..0000000000 --- a/e2e/react-router/issue-7120/tests/issue-7120.repro.spec.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { expect, test } from '@playwright/test' - -test('#7120 / #7367: a root redirect cannot commit a stale match during a view transition', async ({ - page, -}) => { - const pageErrors: Array = [] - const consoleErrors: Array = [] - - page.on('pageerror', (error) => { - pageErrors.push(error.message || String(error)) - }) - page.on('console', (message) => { - if (message.type() === 'error') { - consoleErrors.push(message.text()) - } - }) - - await page.goto('/') - - const pending = page.getByTestId('root-pending') - await expect(pending).toBeVisible() - expect(await page.evaluate(() => window.redirectGate.waiting)).toBe(true) - - await page.evaluate(() => window.redirectGate.release()) - - await expect(page).toHaveURL(/\/posts$/) - await expect( - page.getByRole('heading', { name: 'Posts loaded' }), - ).toBeVisible() - await expect(pending).not.toBeVisible() - expect(pageErrors).toEqual([]) - expect(consoleErrors).toEqual([]) -}) diff --git a/e2e/react-router/issue-7120/tsconfig.json b/e2e/react-router/issue-7120/tsconfig.json deleted file mode 100644 index 4f6089bc08..0000000000 --- a/e2e/react-router/issue-7120/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "react-jsx", - "target": "ESNext", - "moduleResolution": "Bundler", - "module": "ESNext", - "resolveJsonModule": true, - "allowJs": true, - "skipLibCheck": true, - "types": ["vite/client"] - }, - "exclude": ["node_modules", "dist"] -} diff --git a/e2e/react-router/issue-7120/vite.config.ts b/e2e/react-router/issue-7120/vite.config.ts deleted file mode 100644 index 5b1c613906..0000000000 --- a/e2e/react-router/issue-7120/vite.config.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { defineConfig } from 'vite' -import react from '@vitejs/plugin-react' -import { tanstackRouter } from '@tanstack/router-plugin/vite' - -export default defineConfig({ - plugins: [tanstackRouter({ target: 'react' }), react()], -}) diff --git a/e2e/react-router/issue-7457/index.html b/e2e/react-router/issue-7457/index.html deleted file mode 100644 index 76369b5957..0000000000 --- a/e2e/react-router/issue-7457/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - Issue 7457 - - - - diff --git a/e2e/react-router/issue-7457/package.json b/e2e/react-router/issue-7457/package.json deleted file mode 100644 index 838f5173e2..0000000000 --- a/e2e/react-router/issue-7457/package.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "tanstack-router-e2e-react-issue-7457", - "private": true, - "type": "module", - "scripts": { - "dev": "vite --port 3000", - "dev:e2e": "vite", - "build": "vite build && tsc --noEmit", - "preview": "vite preview", - "start": "vite", - "test:e2e": "playwright test --project=chromium" - }, - "dependencies": { - "@tanstack/react-query": "^5.99.0", - "@tanstack/react-router": "workspace:^", - "@tanstack/router-plugin": "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-router/issue-7457/playwright.config.ts b/e2e/react-router/issue-7457/playwright.config.ts deleted file mode 100644 index a8ba116fb4..0000000000 --- a/e2e/react-router/issue-7457/playwright.config.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' - -const PORT = Number(process.env.E2E_APP_PORT ?? 0) -const baseURL = `http://localhost:${PORT}` - -export default defineConfig({ - testDir: './tests', - workers: 1, - reporter: [['line']], - use: { baseURL }, - webServer: { - command: `VITE_NODE_ENV="test" 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-router/issue-7457/src/main.tsx b/e2e/react-router/issue-7457/src/main.tsx deleted file mode 100644 index 1b6805edc0..0000000000 --- a/e2e/react-router/issue-7457/src/main.tsx +++ /dev/null @@ -1,32 +0,0 @@ -import { StrictMode, useEffect } from 'react' -import { createRoot } from 'react-dom/client' -import { QueryClient } from '@tanstack/react-query' -import { RouterProvider, createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -const queryClient = new QueryClient() -const router = createRouter({ - routeTree, - context: { queryClient }, - defaultPendingComponent: DefaultPendingComponent, - defaultPreloadStaleTime: 0, -}) - -declare module '@tanstack/react-router' { - interface Register { - router: typeof router - } -} - -function DefaultPendingComponent() { - useEffect(() => { - ;(globalThis as any).__pendingSeen = true - }, []) - return
loading
-} - -createRoot(document.body).render( - - - , -) diff --git a/e2e/react-router/issue-7457/src/routeTree.gen.ts b/e2e/react-router/issue-7457/src/routeTree.gen.ts deleted file mode 100644 index 04a2c94ce8..0000000000 --- a/e2e/react-router/issue-7457/src/routeTree.gen.ts +++ /dev/null @@ -1,77 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as AnotherRouteImport } from './routes/another' - -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 - '/another': typeof AnotherRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/another': typeof AnotherRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/another': typeof AnotherRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/another' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/another' - id: '__root__' | '/' | '/another' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - AnotherRoute: typeof AnotherRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/another': { - id: '/another' - path: '/another' - fullPath: '/another' - preLoaderRoute: typeof AnotherRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - AnotherRoute: AnotherRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() diff --git a/e2e/react-router/issue-7457/src/routes/__root.tsx b/e2e/react-router/issue-7457/src/routes/__root.tsx deleted file mode 100644 index 988ba76263..0000000000 --- a/e2e/react-router/issue-7457/src/routes/__root.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { Outlet, createRootRouteWithContext } from '@tanstack/react-router' -import type { QueryClient } from '@tanstack/react-query' - -export const Route = createRootRouteWithContext<{ - queryClient: QueryClient -}>()({ - beforeLoad: async ({ context }) => { - await context.queryClient.ensureQueryData({ - queryKey: ['issue-7457-root'], - queryFn: async () => { - await new Promise((resolve) => setTimeout(resolve, 1_500)) - return true - }, - }) - }, - component: RootComponent, -}) - -function RootComponent() { - return ( -
- -
- ) -} diff --git a/e2e/react-router/issue-7457/src/routes/another.tsx b/e2e/react-router/issue-7457/src/routes/another.tsx deleted file mode 100644 index 6b6caa55b3..0000000000 --- a/e2e/react-router/issue-7457/src/routes/another.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/another')({ - component: () =>
Hello "/another"!
, -}) diff --git a/e2e/react-router/issue-7457/src/routes/index.tsx b/e2e/react-router/issue-7457/src/routes/index.tsx deleted file mode 100644 index daaae2aeed..0000000000 --- a/e2e/react-router/issue-7457/src/routes/index.tsx +++ /dev/null @@ -1,8 +0,0 @@ -import { createFileRoute, redirect } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - beforeLoad: () => { - throw redirect({ to: '/another', replace: true }) - }, - component: () =>
You should never see this!
, -}) diff --git a/e2e/react-router/issue-7457/src/vite-env.d.ts b/e2e/react-router/issue-7457/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/react-router/issue-7457/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/react-router/issue-7457/tests/issue-7457.repro.spec.ts b/e2e/react-router/issue-7457/tests/issue-7457.repro.spec.ts deleted file mode 100644 index 8b20fac1eb..0000000000 --- a/e2e/react-router/issue-7457/tests/issue-7457.repro.spec.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { expect, test } from '@playwright/test' - -test('#7457: initial child redirect after async root beforeLoad does not blank', async ({ - page, -}) => { - const pageErrors: Array = [] - const consoleErrors: Array = [] - page.on('pageerror', (error) => - pageErrors.push(error.message || String(error)), - ) - page.on('console', (message) => { - if (message.type() === 'error') { - consoleErrors.push(message.text()) - } - }) - - await page.goto('/') - - await expect(page).toHaveURL(/\/another$/) - const target = page.getByText('Hello "/another"!') - await expect - .poll(async () => ({ - targetCount: await target.count(), - pageErrors: [...pageErrors], - consoleErrors: [...consoleErrors], - })) - .toEqual({ targetCount: 1, pageErrors: [], consoleErrors: [] }) - await expect(target).toBeVisible() - await expect - .poll(() => page.evaluate(() => (globalThis as any).__pendingSeen)) - .toBe(true) - await expect(page.getByTestId('app-pending')).not.toBeVisible() - expect(pageErrors).toEqual([]) - expect(consoleErrors).toEqual([]) -}) diff --git a/e2e/react-router/issue-7457/tsconfig.json b/e2e/react-router/issue-7457/tsconfig.json deleted file mode 100644 index 4f6089bc08..0000000000 --- a/e2e/react-router/issue-7457/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "react-jsx", - "target": "ESNext", - "moduleResolution": "Bundler", - "module": "ESNext", - "resolveJsonModule": true, - "allowJs": true, - "skipLibCheck": true, - "types": ["vite/client"] - }, - "exclude": ["node_modules", "dist"] -} diff --git a/e2e/react-router/issue-7457/vite.config.js b/e2e/react-router/issue-7457/vite.config.js deleted file mode 100644 index 9e39ea83d9..0000000000 --- a/e2e/react-router/issue-7457/vite.config.js +++ /dev/null @@ -1,10 +0,0 @@ -import { defineConfig } from 'vite' -import react from '@vitejs/plugin-react' -import { tanstackRouter } from '@tanstack/router-plugin/vite' - -export default defineConfig({ - plugins: [ - tanstackRouter({ target: 'react', autoCodeSplitting: true }), - react(), - ], -}) diff --git a/e2e/react-router/js-only-file-based/.devcontainer/devcontainer.json b/e2e/react-router/js-only-file-based/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/react-router/js-only-file-based/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/react-router/js-only-file-based/package.json b/e2e/react-router/js-only-file-based/package.json index 39742d9c84..808741fcf0 100644 --- a/e2e/react-router/js-only-file-based/package.json +++ b/e2e/react-router/js-only-file-based/package.json @@ -8,24 +8,24 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", + "@tailwindcss/vite": "^4.1.18", "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "catalog:", - "tailwindcss": "^4.2.2" + "redaxios": "^0.5.1", + "tailwindcss": "^4.1.18" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", "@tanstack/router-plugin": "workspace:^", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.3.4", + "vite": "^7.3.1" } } diff --git a/e2e/react-router/js-only-file-based/playwright.config.ts b/e2e/react-router/js-only-file-based/playwright.config.ts index 0925936d55..4f93bc1413 100644 --- a/e2e/react-router/js-only-file-based/playwright.config.ts +++ b/e2e/react-router/js-only-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,15 +18,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/js-only-file-based/src/posts.js b/e2e/react-router/js-only-file-based/src/posts.js index 36c1c281f6..979e5e381c 100644 --- a/e2e/react-router/js-only-file-based/src/posts.js +++ b/e2e/react-router/js-only-file-based/src/posts.js @@ -2,7 +2,11 @@ import axios from 'redaxios' export class NotFoundError extends Error {} -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/react-router/js-only-file-based/src/routeTree.gen.js b/e2e/react-router/js-only-file-based/src/routeTree.gen.js index 80683abb30..f2d42e5a6c 100644 --- a/e2e/react-router/js-only-file-based/src/routeTree.gen.js +++ b/e2e/react-router/js-only-file-based/src/routeTree.gen.js @@ -9,20 +9,15 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as PostsRouteRouteImport } from './routes/posts.route' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' +import { Route as IndexRouteImport } from './routes/index' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -}) const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, @@ -32,11 +27,11 @@ const PostsRouteRoute = PostsRouteRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, }) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, - }) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +}) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -47,11 +42,10 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRouteRoute, }) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, }) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ @@ -59,6 +53,12 @@ const PathlessLayoutNestedLayoutRouteBRoute = path: '/route-b', getParentRoute: () => PathlessLayoutNestedLayoutRoute, }) +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + }) const PostsRouteRouteChildren = { PostsPostIdRoute: PostsPostIdRoute, diff --git a/e2e/react-router/js-only-file-based/src/vite-env.d.ts b/e2e/react-router/js-only-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/react-router/js-only-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/react-router/js-only-file-based/tests/app.spec.ts b/e2e/react-router/js-only-file-based/tests/app.spec.ts index ced5ac9310..5a83a314f2 100644 --- a/e2e/react-router/js-only-file-based/tests/app.spec.ts +++ b/e2e/react-router/js-only-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/js-only-file-based/tests/setup/global.setup.ts b/e2e/react-router/js-only-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/js-only-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-router/js-only-file-based/tests/setup/global.teardown.ts b/e2e/react-router/js-only-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/js-only-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-router/match-params/.gitignore b/e2e/react-router/match-params/.gitignore deleted file mode 100644 index 4d2da67b50..0000000000 --- a/e2e/react-router/match-params/.gitignore +++ /dev/null @@ -1,11 +0,0 @@ -node_modules -.DS_Store -dist -dist-hash -dist-ssr -*.local - -/test-results/ -/playwright-report/ -/blob-report/ -/playwright/.cache/ diff --git a/e2e/react-router/match-params/index.html b/e2e/react-router/match-params/index.html deleted file mode 100644 index cee534dbdb..0000000000 --- a/e2e/react-router/match-params/index.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - Match Params - - -
- - - diff --git a/e2e/react-router/match-params/package.json b/e2e/react-router/match-params/package.json deleted file mode 100644 index 908be67a9d..0000000000 --- a/e2e/react-router/match-params/package.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "tanstack-router-e2e-react-match-params", - "private": true, - "type": "module", - "scripts": { - "dev": "vite --port 3000", - "build": "vite build && tsc --noEmit", - "preview": "vite preview", - "test:e2e": "playwright test --project=chromium" - }, - "dependencies": { - "@tanstack/react-router": "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", - "vite": "^8.0.14" - } -} diff --git a/e2e/react-router/match-params/playwright.config.ts b/e2e/react-router/match-params/playwright.config.ts deleted file mode 100644 index 9e8c1fab2b..0000000000 --- a/e2e/react-router/match-params/playwright.config.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' - -const PORT = Number(process.env.E2E_APP_PORT ?? 0) -const baseURL = `http://localhost:${PORT}` - -export default defineConfig({ - testDir: './tests', - workers: 1, - reporter: [['line']], - use: { - baseURL, - }, - webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, - stdout: 'pipe', - }, - projects: [ - { - name: 'chromium', - use: { ...devices['Desktop Chrome'] }, - }, - ], -}) diff --git a/e2e/react-router/match-params/src/main.tsx b/e2e/react-router/match-params/src/main.tsx deleted file mode 100644 index 33709cfcc2..0000000000 --- a/e2e/react-router/match-params/src/main.tsx +++ /dev/null @@ -1,229 +0,0 @@ -import ReactDOM from 'react-dom/client' -import { - Link, - Outlet, - RouterProvider, - createRootRoute, - createRoute, - createRouter, -} from '@tanstack/react-router' - -const rootRoute = createRootRoute({ - component: RootComponent, - notFoundComponent: () =>

Root not found

, -}) - -function RootComponent() { - return ( - <> - - - - ) -} - -const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () =>

Match params e2e

, -}) - -const matchLanguageRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/match/{$language}', - params: { - parse: ({ language }) => { - if (language === 'en') return { language: 'en-US' as const } - if (language === 'pl') return { language: 'pl-PL' as const } - return false - }, - stringify: ({ language }) => { - if (language === 'en-US') return { language: 'en' } - if (language === 'pl-PL') return { language: 'pl' } - return { language } - }, - }, - component: MatchLanguageComponent, -}) - -function MatchLanguageComponent() { - const params = matchLanguageRoute.useParams() - return

Match language {params.language}

-} - -const usersRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/users', -}) - -const numericUserRoute = createRoute({ - getParentRoute: () => usersRoute, - path: '$userId', - params: { - parse: ({ userId }) => { - const parsed = Number(userId) - if (!Number.isInteger(parsed)) return false - return { userId: parsed } - }, - stringify: ({ userId }) => ({ userId: String(userId) }), - }, - component: NumericUserComponent, -}) - -function NumericUserComponent() { - const params = numericUserRoute.useParams() - return

Numeric user {params.userId}

-} - -const usernameRoute = createRoute({ - getParentRoute: () => usersRoute, - path: '$username', - component: UsernameComponent, -}) - -function UsernameComponent() { - const params = usernameRoute.useParams() - return

Username {params.username}

-} - -const numericOrgRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/orgs/$orgId', - params: { - parse: ({ orgId }) => { - const parsed = Number(orgId) - if (!Number.isInteger(parsed)) return false - return { orgId: parsed } - }, - stringify: ({ orgId }) => ({ orgId: String(orgId) }), - }, -}) - -const orgSettingsRoute = createRoute({ - getParentRoute: () => numericOrgRoute, - path: 'settings', - component: OrgSettingsComponent, -}) - -function OrgSettingsComponent() { - const params = orgSettingsRoute.useParams() - return

Org settings {params.orgId}

-} - -const orgAboutRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/orgs/$slug/about', - component: OrgAboutComponent, -}) - -function OrgAboutComponent() { - const params = orgAboutRoute.useParams() - return

Org about {params.slug}

-} - -const ambiguousRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/ambiguous', -}) - -const ambiguousDollarRoute = createRoute({ - getParentRoute: () => ambiguousRoute, - path: '$value', - params: { - parse: ({ value }) => { - if (!value.startsWith('dollar-')) return false - return { value: value.slice(7) } - }, - stringify: ({ value }) => ({ value: `dollar-${value}` }), - }, - component: AmbiguousDollarComponent, -}) - -function AmbiguousDollarComponent() { - const params = ambiguousDollarRoute.useParams() - return

Dollar {params.value}

-} - -const ambiguousCurlyRoute = createRoute({ - getParentRoute: () => ambiguousRoute, - path: '{$value}', - params: { - parse: ({ value }) => { - if (!value.startsWith('curly-')) return false - return { value: value.slice(6) } - }, - stringify: ({ value }) => ({ value: `curly-${value}` }), - }, - component: AmbiguousCurlyComponent, -}) - -function AmbiguousCurlyComponent() { - const params = ambiguousCurlyRoute.useParams() - return

Curly {params.value}

-} - -const routeTree = rootRoute.addChildren([ - indexRoute, - matchLanguageRoute, - usersRoute.addChildren([numericUserRoute, usernameRoute]), - numericOrgRoute.addChildren([orgSettingsRoute]), - orgAboutRoute, - ambiguousRoute.addChildren([ambiguousDollarRoute, ambiguousCurlyRoute]), -]) - -const router = createRouter({ routeTree }) - -declare module '@tanstack/react-router' { - interface Register { - router: typeof router - } -} - -const rootElement = document.getElementById('app')! - -if (!rootElement.innerHTML) { - ReactDOM.createRoot(rootElement).render() -} diff --git a/e2e/react-router/match-params/tests/match-params.spec.ts b/e2e/react-router/match-params/tests/match-params.spec.ts deleted file mode 100644 index 9b57061911..0000000000 --- a/e2e/react-router/match-params/tests/match-params.spec.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { expect, test } from '@playwright/test' - -test.beforeEach(async ({ page }) => { - await page.goto('/') -}) - -test('params.parse stringifies links and parses concrete params', async ({ - page, -}) => { - await expect(page.getByTestId('match-en-link')).toHaveAttribute( - 'href', - '/match/en', - ) - - await page.getByTestId('match-en-link').click() - await expect(page.getByTestId('match-language')).toHaveText( - 'Match language en-US', - ) - - await page.goto('/match/pl') - await expect(page.getByTestId('match-language')).toHaveText( - 'Match language pl-PL', - ) - - await page.goto('/match/en-US') - await expect(page.getByTestId('not-found')).toHaveText('Root not found') -}) - -test('params.parse can fall through to sibling dynamic routes', async ({ - page, -}) => { - await expect(page.getByTestId('numeric-user-link')).toHaveAttribute( - 'href', - '/users/456', - ) - await expect(page.getByTestId('username-link')).toHaveAttribute( - 'href', - '/users/alice', - ) - - await page.goto('/users/123') - await expect(page.getByTestId('numeric-user')).toHaveText('Numeric user 123') - - await page.goto('/users/alice') - await expect(page.getByTestId('username')).toHaveText('Username alice') -}) - -test('params.parse can gate child routes', async ({ page }) => { - await expect(page.getByTestId('org-settings-link')).toHaveAttribute( - 'href', - '/orgs/42/settings', - ) - - await page.goto('/orgs/42/settings') - await expect(page.getByTestId('org-settings')).toHaveText('Org settings 42') - - await page.goto('/orgs/acme/about') - await expect(page.getByTestId('org-about')).toHaveText('Org about acme') - - await page.goto('/orgs/acme/settings') - await expect(page.getByTestId('not-found')).toHaveText('Root not found') -}) - -test('buildLocation uses exact route templates before matching paths', async ({ - page, -}) => { - await expect(page.getByTestId('ambiguous-dollar-link')).toHaveAttribute( - 'href', - '/ambiguous/dollar-alpha', - ) - await expect(page.getByTestId('ambiguous-curly-link')).toHaveAttribute( - 'href', - '/ambiguous/curly-alpha', - ) - - await page.getByTestId('ambiguous-dollar-link').click() - await expect(page.getByTestId('ambiguous-dollar')).toHaveText('Dollar alpha') - - await page.getByTestId('ambiguous-curly-link').click() - await expect(page.getByTestId('ambiguous-curly')).toHaveText('Curly alpha') -}) diff --git a/e2e/react-router/match-params/tsconfig.json b/e2e/react-router/match-params/tsconfig.json deleted file mode 100644 index 4f6089bc08..0000000000 --- a/e2e/react-router/match-params/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "react-jsx", - "target": "ESNext", - "moduleResolution": "Bundler", - "module": "ESNext", - "resolveJsonModule": true, - "allowJs": true, - "skipLibCheck": true, - "types": ["vite/client"] - }, - "exclude": ["node_modules", "dist"] -} diff --git a/e2e/react-router/match-params/vite.config.js b/e2e/react-router/match-params/vite.config.js deleted file mode 100644 index 4f1b25a0c3..0000000000 --- a/e2e/react-router/match-params/vite.config.js +++ /dev/null @@ -1,3 +0,0 @@ -import { defineConfig } from 'vite' - -export default defineConfig({}) diff --git a/e2e/react-router/react-compiler/index.html b/e2e/react-router/react-compiler/index.html deleted file mode 100644 index 0c5b6b471c..0000000000 --- a/e2e/react-router/react-compiler/index.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - React Compiler useMatchRoute test - - -
- - - diff --git a/e2e/react-router/react-compiler/package.json b/e2e/react-router/react-compiler/package.json deleted file mode 100644 index 82e6fbf86b..0000000000 --- a/e2e/react-router/react-compiler/package.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "tanstack-router-e2e-react-compiler", - "private": true, - "type": "module", - "scripts": { - "dev": "vite --port 3000", - "dev:e2e": "vite", - "build": "vite build && tsc --noEmit", - "preview": "vite preview", - "start": "vite", - "test:e2e": "playwright test --project=chromium" - }, - "dependencies": { - "@tanstack/react-router": "workspace:^", - "react": "^19.0.0", - "react-dom": "^19.0.0" - }, - "devDependencies": { - "@babel/core": "^7.29.0", - "@playwright/test": "^1.61.0", - "@rolldown/plugin-babel": "^0.2.0", - "@tanstack/router-e2e-utils": "workspace:^", - "@types/react": "^19.0.8", - "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "babel-plugin-react-compiler": "^1.0.0", - "vite": "^8.0.14" - } -} diff --git a/e2e/react-router/react-compiler/playwright.config.ts b/e2e/react-router/react-compiler/playwright.config.ts deleted file mode 100644 index a8ba116fb4..0000000000 --- a/e2e/react-router/react-compiler/playwright.config.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' - -const PORT = Number(process.env.E2E_APP_PORT ?? 0) -const baseURL = `http://localhost:${PORT}` - -export default defineConfig({ - testDir: './tests', - workers: 1, - reporter: [['line']], - use: { baseURL }, - webServer: { - command: `VITE_NODE_ENV="test" 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-router/react-compiler/src/main.tsx b/e2e/react-router/react-compiler/src/main.tsx deleted file mode 100644 index e6e549da83..0000000000 --- a/e2e/react-router/react-compiler/src/main.tsx +++ /dev/null @@ -1,73 +0,0 @@ -import { StrictMode } from 'react' -import { createRoot } from 'react-dom/client' -import { - Link, - Outlet, - RouterProvider, - createRootRoute, - createRoute, - createRouter, - linkOptions, - useMatchRoute, -} from '@tanstack/react-router' - -const links = linkOptions([ - { to: '/home', label: 'Home' }, - { to: '/about', label: 'About' }, -]) - -function useRouteName() { - const matchRoute = useMatchRoute() - - return links.find((link) => matchRoute(link))?.label ?? 'Unknown' -} - -function RootComponent() { - const matchedRoute = useRouteName() - - return ( - <> - -

- Matched route: {matchedRoute} -

- - - ) -} - -const rootRoute = createRootRoute({ component: RootComponent }) -const homeRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/home', -}) -const aboutRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/about', -}) -const router = createRouter({ - routeTree: rootRoute.addChildren([homeRoute, aboutRoute]), -}) - -declare module '@tanstack/react-router' { - interface Register { - router: typeof router - } -} - -const rootElement = document.getElementById('app') -if (!rootElement) { - throw new Error('Root element not found') -} - -createRoot(rootElement).render( - - - , -) diff --git a/e2e/react-router/react-compiler/tests/use-match-route.spec.ts b/e2e/react-router/react-compiler/tests/use-match-route.spec.ts deleted file mode 100644 index b800e3c908..0000000000 --- a/e2e/react-router/react-compiler/tests/use-match-route.spec.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { expect, test } from '@playwright/test' - -test('useMatchRoute updates after navigation with React Compiler', async ({ - page, -}) => { - await page.goto('/home') - await expect(page.getByTestId('matched-route')).toHaveText('Home') - - await page.getByRole('link', { name: 'About' }).click() - await expect(page).toHaveURL(/\/about$/) - await expect(page.getByTestId('matched-route')).toHaveText('About') - - await page.getByRole('link', { name: 'Home' }).click() - await expect(page).toHaveURL(/\/home$/) - await expect(page.getByTestId('matched-route')).toHaveText('Home') -}) diff --git a/e2e/react-router/react-compiler/tsconfig.json b/e2e/react-router/react-compiler/tsconfig.json deleted file mode 100644 index 4f6089bc08..0000000000 --- a/e2e/react-router/react-compiler/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "react-jsx", - "target": "ESNext", - "moduleResolution": "Bundler", - "module": "ESNext", - "resolveJsonModule": true, - "allowJs": true, - "skipLibCheck": true, - "types": ["vite/client"] - }, - "exclude": ["node_modules", "dist"] -} diff --git a/e2e/react-router/react-compiler/vite.config.js b/e2e/react-router/react-compiler/vite.config.js deleted file mode 100644 index b4478aced4..0000000000 --- a/e2e/react-router/react-compiler/vite.config.js +++ /dev/null @@ -1,7 +0,0 @@ -import { defineConfig } from 'vite' -import react, { reactCompilerPreset } from '@vitejs/plugin-react' -import babel from '@rolldown/plugin-babel' - -export default defineConfig({ - plugins: [react(), babel({ presets: [reactCompilerPreset()] })], -}) diff --git a/e2e/react-router/rspack-basic-file-based/.devcontainer/devcontainer.json b/e2e/react-router/rspack-basic-file-based/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/react-router/rspack-basic-file-based/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/react-router/rspack-basic-file-based/package.json b/e2e/react-router/rspack-basic-file-based/package.json index 5ec9ed9862..4d28e5d27c 100644 --- a/e2e/react-router/rspack-basic-file-based/package.json +++ b/e2e/react-router/rspack-basic-file-based/package.json @@ -7,27 +7,26 @@ "build": "rsbuild build && tsc --noEmit", "preview": "rsbuild preview", "start": "rsbuild preview", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "catalog:" + "redaxios": "^0.5.1" }, "devDependencies": { - "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", - "@rsbuild/plugin-react": "^2.0.0", - "@tailwindcss/postcss": "^4.2.2", + "@playwright/test": "^1.50.1", + "@rsbuild/core": "^1.2.4", + "@rsbuild/plugin-react": "^1.1.0", + "@tailwindcss/postcss": "^4.1.18", "@tanstack/router-e2e-utils": "workspace:^", "@tanstack/router-plugin": "workspace:^", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "postcss": "^8.5.1", - "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2" + "tailwindcss": "^4.1.18", + "typescript": "^5.7.2" } } diff --git a/e2e/react-router/rspack-basic-file-based/playwright.config.ts b/e2e/react-router/rspack-basic-file-based/playwright.config.ts index 4eead86444..decceaef2f 100644 --- a/e2e/react-router/rspack-basic-file-based/playwright.config.ts +++ b/e2e/react-router/rspack-basic-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `PUBLIC_NODE_ENV="test" PUBLIC_EXTERNAL_PORT=${EXTERNAL_PORT} PUBLIC_SERVER_PORT=${PORT} pnpm build && PUBLIC_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/rspack-basic-file-based/src/posts.tsx b/e2e/react-router/rspack-basic-file-based/src/posts.tsx index 97c96d77eb..a1225b7fe7 100644 --- a/e2e/react-router/rspack-basic-file-based/src/posts.tsx +++ b/e2e/react-router/rspack-basic-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.PUBLIC_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.PUBLIC_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/react-router/rspack-basic-file-based/src/vite-env.d.ts b/e2e/react-router/rspack-basic-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/react-router/rspack-basic-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/react-router/rspack-basic-file-based/tests/app.spec.ts b/e2e/react-router/rspack-basic-file-based/tests/app.spec.ts index d230263bfe..10beff655f 100644 --- a/e2e/react-router/rspack-basic-file-based/tests/app.spec.ts +++ b/e2e/react-router/rspack-basic-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/rspack-basic-file-based/tests/setup/global.setup.ts b/e2e/react-router/rspack-basic-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/rspack-basic-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-router/rspack-basic-file-based/tests/setup/global.teardown.ts b/e2e/react-router/rspack-basic-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/rspack-basic-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-router/rspack-basic-file-based/tsconfig.json b/e2e/react-router/rspack-basic-file-based/tsconfig.json index 2f5f67eac7..76f578eb54 100644 --- a/e2e/react-router/rspack-basic-file-based/tsconfig.json +++ b/e2e/react-router/rspack-basic-file-based/tsconfig.json @@ -12,6 +12,6 @@ "useDefineForClassFields": true, "allowJs": true }, - "include": ["src", "tests"], + "include": ["src", "playwright.config.ts", "tests"], "exclude": ["node_modules", "dist"] } diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/.devcontainer/devcontainer.json b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/package.json b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/package.json index 30c62d0af1..841d7b802d 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,28 +7,27 @@ "build": "rsbuild build && tsc --noEmit", "preview": "rsbuild preview", "start": "rsbuild preview", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "catalog:" + "redaxios": "^0.5.1" }, "devDependencies": { - "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", - "@rsbuild/plugin-react": "^2.0.0", - "@tailwindcss/postcss": "^4.2.2", + "@playwright/test": "^1.50.1", + "@rsbuild/core": "^1.2.4", + "@rsbuild/plugin-react": "^1.1.0", + "@tailwindcss/postcss": "^4.1.18", "@tanstack/router-e2e-utils": "workspace:^", "@tanstack/router-plugin": "workspace:^", "@tanstack/virtual-file-routes": "workspace:^", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "postcss": "^8.5.1", - "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2" + "tailwindcss": "^4.1.18", + "typescript": "^5.7.2" } } diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts index 1c1d021f2f..bf3adc082c 100644 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm start --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `PUBLIC_NODE_ENV="test" PUBLIC_EXTERNAL_PORT=${EXTERNAL_PORT} PUBLIC_SERVER_PORT=${PORT} pnpm build && PUBLIC_SERVER_PORT=${PORT} pnpm start --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx index cc3cb0f9c8..b196982420 100644 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.PUBLIC_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.PUBLIC_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/vite-env.d.ts b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts index 8b808782f6..a689f459e3 100644 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tsconfig.json b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tsconfig.json index a32f07a8ef..7dc6d51cf9 100644 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tsconfig.json +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tsconfig.json @@ -12,6 +12,6 @@ "useDefineForClassFields": true, "allowJs": true }, - "include": ["src", "tests", "./routes.ts"], + "include": ["src", "playwright.config.ts", "tests", "./routes.ts"], "exclude": ["node_modules", "dist"] } diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/.devcontainer/devcontainer.json b/e2e/react-router/scroll-restoration-sandbox-vite/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/react-router/scroll-restoration-sandbox-vite/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/package.json b/e2e/react-router/scroll-restoration-sandbox-vite/package.json index 51e9e70cc5..df3ee62b00 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/package.json +++ b/e2e/react-router/scroll-restoration-sandbox-vite/package.json @@ -11,35 +11,26 @@ "start": "vite", "test:e2e:browser": "VITE_APP_HISTORY=browser playwright test --config=playwright.browser.config.ts --project=chromium", "test:e2e:hash": "VITE_APP_HISTORY=hash playwright test --config=playwright.hash.config.ts --project=chromium", - "test:e2e": "pnpm run test:e2e:browser && pnpm run test:e2e:hash" + "test:e2e": "rm -rf port*.txt; pnpm run test:e2e:browser && pnpm run test:e2e:hash" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", + "@tailwindcss/vite": "^4.1.18", "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", "@tanstack/router-plugin": "workspace:^", + "@tanstack/zod-adapter": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "catalog:", - "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "redaxios": "^0.5.1", + "tailwindcss": "^4.1.18", + "zod": "^3.24.2" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@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" - }, - "nx": { - "targets": { - "test:e2e": { - "outputs": [ - "...", - "{projectRoot}/dist-hash" - ] - } - } + "@vitejs/plugin-react": "^4.3.4", + "vite": "^7.3.1" } } diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts b/e2e/react-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts index eb31d94080..972124647c 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts +++ b/e2e/react-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts @@ -1,7 +1,15 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, + resolveRuntimeSuffix, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort( + packageJson.name + `-${resolveRuntimeSuffix('browser')}`, +) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,15 +21,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_APP_HISTORY=browser pnpm build && VITE_APP_HISTORY=browser pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=browser pnpm build && VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=browser pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts b/e2e/react-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts index 6b160e3908..a6fa77afbf 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts +++ b/e2e/react-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts @@ -1,7 +1,15 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, + resolveRuntimeSuffix, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort( + packageJson.name + `-${resolveRuntimeSuffix('hash')}`, +) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,15 +21,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_APP_HISTORY=hash vite build --outDir dist-hash && VITE_APP_HISTORY=hash pnpm preview --port ${PORT} --outDir dist-hash`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=hash vite build --outDir dist-hash && VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=hash pnpm preview --port ${PORT} --outDir dist-hash`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/src/posts.tsx b/e2e/react-router/scroll-restoration-sandbox-vite/src/posts.tsx index c4a2d0dcca..e45ef52969 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/src/posts.tsx +++ b/e2e/react-router/scroll-restoration-sandbox-vite/src/posts.tsx @@ -10,7 +10,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export class PostNotFoundError extends Error {} diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts b/e2e/react-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts index 0c6823c368..6664a9ddf7 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts +++ b/e2e/react-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts @@ -12,12 +12,10 @@ import { createFileRoute } from '@tanstack/react-router' import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as testsIssue7040SourceRouteImport } from './routes/(tests)/issue-7040-source' -import { Route as testsIssue7040TargetRouteImport } from './routes/(tests)/issue-7040-target' -import { Route as testsLazyPageRouteImport } from './routes/(tests)/lazy-page' -import { Route as testsLazyWithLoaderPageRouteImport } from './routes/(tests)/lazy-with-loader-page' -import { Route as testsNormalPageRouteImport } from './routes/(tests)/normal-page' import { Route as testsPageWithSearchRouteImport } from './routes/(tests)/page-with-search' +import { Route as testsNormalPageRouteImport } from './routes/(tests)/normal-page' +import { Route as testsLazyWithLoaderPageRouteImport } from './routes/(tests)/lazy-with-loader-page' +import { Route as testsLazyPageRouteImport } from './routes/(tests)/lazy-page' const testsVirtualPageLazyRouteImport = createFileRoute( '/(tests)/virtual-page', @@ -28,23 +26,23 @@ const IndexRoute = IndexRouteImport.update({ path: '/', getParentRoute: () => rootRouteImport, } as any) -const testsIssue7040SourceRoute = testsIssue7040SourceRouteImport.update({ - id: '/(tests)/issue-7040-source', - path: '/issue-7040-source', - getParentRoute: () => rootRouteImport, -} as any) -const testsIssue7040TargetRoute = testsIssue7040TargetRouteImport.update({ - id: '/(tests)/issue-7040-target', - path: '/issue-7040-target', - getParentRoute: () => rootRouteImport, -} as any) -const testsLazyPageRoute = testsLazyPageRouteImport +const testsVirtualPageLazyRoute = testsVirtualPageLazyRouteImport .update({ - id: '/(tests)/lazy-page', - path: '/lazy-page', + id: '/(tests)/virtual-page', + path: '/virtual-page', getParentRoute: () => rootRouteImport, } as any) - .lazy(() => import('./routes/(tests)/lazy-page.lazy').then((d) => d.Route)) + .lazy(() => import('./routes/(tests)/virtual-page.lazy').then((d) => d.Route)) +const testsPageWithSearchRoute = testsPageWithSearchRouteImport.update({ + id: '/(tests)/page-with-search', + path: '/page-with-search', + getParentRoute: () => rootRouteImport, +} as any) +const testsNormalPageRoute = testsNormalPageRouteImport.update({ + id: '/(tests)/normal-page', + path: '/normal-page', + getParentRoute: () => rootRouteImport, +} as any) const testsLazyWithLoaderPageRoute = testsLazyWithLoaderPageRouteImport .update({ id: '/(tests)/lazy-with-loader-page', @@ -54,28 +52,16 @@ const testsLazyWithLoaderPageRoute = testsLazyWithLoaderPageRouteImport .lazy(() => import('./routes/(tests)/lazy-with-loader-page.lazy').then((d) => d.Route), ) -const testsNormalPageRoute = testsNormalPageRouteImport.update({ - id: '/(tests)/normal-page', - path: '/normal-page', - getParentRoute: () => rootRouteImport, -} as any) -const testsPageWithSearchRoute = testsPageWithSearchRouteImport.update({ - id: '/(tests)/page-with-search', - path: '/page-with-search', - getParentRoute: () => rootRouteImport, -} as any) -const testsVirtualPageLazyRoute = testsVirtualPageLazyRouteImport +const testsLazyPageRoute = testsLazyPageRouteImport .update({ - id: '/(tests)/virtual-page', - path: '/virtual-page', + id: '/(tests)/lazy-page', + path: '/lazy-page', getParentRoute: () => rootRouteImport, } as any) - .lazy(() => import('./routes/(tests)/virtual-page.lazy').then((d) => d.Route)) + .lazy(() => import('./routes/(tests)/lazy-page.lazy').then((d) => d.Route)) export interface FileRoutesByFullPath { '/': typeof IndexRoute - '/issue-7040-source': typeof testsIssue7040SourceRoute - '/issue-7040-target': typeof testsIssue7040TargetRoute '/lazy-page': typeof testsLazyPageRoute '/lazy-with-loader-page': typeof testsLazyWithLoaderPageRoute '/normal-page': typeof testsNormalPageRoute @@ -84,8 +70,6 @@ export interface FileRoutesByFullPath { } export interface FileRoutesByTo { '/': typeof IndexRoute - '/issue-7040-source': typeof testsIssue7040SourceRoute - '/issue-7040-target': typeof testsIssue7040TargetRoute '/lazy-page': typeof testsLazyPageRoute '/lazy-with-loader-page': typeof testsLazyWithLoaderPageRoute '/normal-page': typeof testsNormalPageRoute @@ -95,8 +79,6 @@ export interface FileRoutesByTo { export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute - '/(tests)/issue-7040-source': typeof testsIssue7040SourceRoute - '/(tests)/issue-7040-target': typeof testsIssue7040TargetRoute '/(tests)/lazy-page': typeof testsLazyPageRoute '/(tests)/lazy-with-loader-page': typeof testsLazyWithLoaderPageRoute '/(tests)/normal-page': typeof testsNormalPageRoute @@ -107,8 +89,6 @@ export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath fullPaths: | '/' - | '/issue-7040-source' - | '/issue-7040-target' | '/lazy-page' | '/lazy-with-loader-page' | '/normal-page' @@ -117,8 +97,6 @@ export interface FileRouteTypes { fileRoutesByTo: FileRoutesByTo to: | '/' - | '/issue-7040-source' - | '/issue-7040-target' | '/lazy-page' | '/lazy-with-loader-page' | '/normal-page' @@ -127,8 +105,6 @@ export interface FileRouteTypes { id: | '__root__' | '/' - | '/(tests)/issue-7040-source' - | '/(tests)/issue-7040-target' | '/(tests)/lazy-page' | '/(tests)/lazy-with-loader-page' | '/(tests)/normal-page' @@ -138,8 +114,6 @@ export interface FileRouteTypes { } export interface RootRouteChildren { IndexRoute: typeof IndexRoute - testsIssue7040SourceRoute: typeof testsIssue7040SourceRoute - testsIssue7040TargetRoute: typeof testsIssue7040TargetRoute testsLazyPageRoute: typeof testsLazyPageRoute testsLazyWithLoaderPageRoute: typeof testsLazyWithLoaderPageRoute testsNormalPageRoute: typeof testsNormalPageRoute @@ -156,39 +130,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/(tests)/issue-7040-source': { - id: '/(tests)/issue-7040-source' - path: '/issue-7040-source' - fullPath: '/issue-7040-source' - preLoaderRoute: typeof testsIssue7040SourceRouteImport - parentRoute: typeof rootRouteImport - } - '/(tests)/issue-7040-target': { - id: '/(tests)/issue-7040-target' - path: '/issue-7040-target' - fullPath: '/issue-7040-target' - preLoaderRoute: typeof testsIssue7040TargetRouteImport - parentRoute: typeof rootRouteImport - } - '/(tests)/lazy-page': { - id: '/(tests)/lazy-page' - path: '/lazy-page' - fullPath: '/lazy-page' - preLoaderRoute: typeof testsLazyPageRouteImport - parentRoute: typeof rootRouteImport - } - '/(tests)/lazy-with-loader-page': { - id: '/(tests)/lazy-with-loader-page' - path: '/lazy-with-loader-page' - fullPath: '/lazy-with-loader-page' - preLoaderRoute: typeof testsLazyWithLoaderPageRouteImport - parentRoute: typeof rootRouteImport - } - '/(tests)/normal-page': { - id: '/(tests)/normal-page' - path: '/normal-page' - fullPath: '/normal-page' - preLoaderRoute: typeof testsNormalPageRouteImport + '/(tests)/virtual-page': { + id: '/(tests)/virtual-page' + path: '/virtual-page' + fullPath: '/virtual-page' + preLoaderRoute: typeof testsVirtualPageLazyRouteImport parentRoute: typeof rootRouteImport } '/(tests)/page-with-search': { @@ -198,11 +144,25 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof testsPageWithSearchRouteImport parentRoute: typeof rootRouteImport } - '/(tests)/virtual-page': { - id: '/(tests)/virtual-page' - path: '/virtual-page' - fullPath: '/virtual-page' - preLoaderRoute: typeof testsVirtualPageLazyRouteImport + '/(tests)/normal-page': { + id: '/(tests)/normal-page' + path: '/normal-page' + fullPath: '/normal-page' + preLoaderRoute: typeof testsNormalPageRouteImport + parentRoute: typeof rootRouteImport + } + '/(tests)/lazy-with-loader-page': { + id: '/(tests)/lazy-with-loader-page' + path: '/lazy-with-loader-page' + fullPath: '/lazy-with-loader-page' + preLoaderRoute: typeof testsLazyWithLoaderPageRouteImport + parentRoute: typeof rootRouteImport + } + '/(tests)/lazy-page': { + id: '/(tests)/lazy-page' + path: '/lazy-page' + fullPath: '/lazy-page' + preLoaderRoute: typeof testsLazyPageRouteImport parentRoute: typeof rootRouteImport } } @@ -210,8 +170,6 @@ declare module '@tanstack/react-router' { const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, - testsIssue7040SourceRoute: testsIssue7040SourceRoute, - testsIssue7040TargetRoute: testsIssue7040TargetRoute, testsLazyPageRoute: testsLazyPageRoute, testsLazyWithLoaderPageRoute: testsLazyWithLoaderPageRoute, testsNormalPageRoute: testsNormalPageRoute, diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/(tests)/issue-7040-source.tsx b/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/(tests)/issue-7040-source.tsx deleted file mode 100644 index 3c1702a942..0000000000 --- a/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/(tests)/issue-7040-source.tsx +++ /dev/null @@ -1,49 +0,0 @@ -import * as React from 'react' -import { Link, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/(tests)/issue-7040-source')({ - component: Component, -}) - -const sectionCount = 180 - -function Component() { - return ( -
-
-

issue-7040-source

-

- Tall page for reproducing the scroll restoration race. -

-
- - - Go to issue-7040-target - - -
- {Array.from({ length: sectionCount }).map((_, index) => ( -
-

Section {index + 1}

-

- This section adds vertical space so the page can be scrolled far - enough to reproduce issue #7040. -

-
- ))} -
- -
- Bottom of issue-7040-source -
-
- ) -} diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/(tests)/issue-7040-target.tsx b/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/(tests)/issue-7040-target.tsx deleted file mode 100644 index df541c6dbb..0000000000 --- a/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/(tests)/issue-7040-target.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import * as React from 'react' -import { createFileRoute } from '@tanstack/react-router' -import { sleep } from '../../posts' - -export const Route = createFileRoute('/(tests)/issue-7040-target')({ - loader: async () => { - await sleep(250) - return null - }, - component: Component, -}) - -function Component() { - return ( -
-
-

issue-7040-target

-

- Short page that should reset to top on navigation. -

-
- -
- {Array.from({ length: 18 }).map((_, index) => ( -
-

Target section {index + 1}

-

This page is intentionally much shorter than the source page.

-
- ))} -
- -
- Bottom of issue-7040-target -
-
- ) -} diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/(tests)/page-with-search.tsx b/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/(tests)/page-with-search.tsx index 427b6f12b0..d9591671f5 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/(tests)/page-with-search.tsx +++ b/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/(tests)/page-with-search.tsx @@ -1,9 +1,10 @@ import { createFileRoute } from '@tanstack/react-router' import { z } from 'zod' +import { zodValidator } from '@tanstack/zod-adapter' import { ScrollBlock } from '../-components/scroll-block' export const Route = createFileRoute('/(tests)/page-with-search')({ - validateSearch: z.object({ where: z.string() }), + validateSearch: zodValidator(z.object({ where: z.string() })), component: Component, }) diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/__root.tsx b/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/__root.tsx index ed80300a68..18726e1168 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/__root.tsx +++ b/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/__root.tsx @@ -45,8 +45,6 @@ function Nav({ type }: { type: 'header' | 'footer' }) { linkOptions({ to: '/virtual-page' }), linkOptions({ to: '/lazy-with-loader-page' }), linkOptions({ to: '/page-with-search', search: { where: type } }), - linkOptions({ to: '/issue-7040-source' }), - linkOptions({ to: '/issue-7040-target' }), ] as const ).map((options, i) => ( {( [ - linkOptions({ to: '/issue-7040-source' }), - linkOptions({ to: '/issue-7040-target' }), linkOptions({ to: '/normal-page' }), linkOptions({ to: '/lazy-page' }), linkOptions({ to: '/virtual-page' }), diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/src/vite-env.d.ts b/e2e/react-router/scroll-restoration-sandbox-vite/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/react-router/scroll-restoration-sandbox-vite/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/tests/app.spec.ts b/e2e/react-router/scroll-restoration-sandbox-vite/tests/app.spec.ts index e396c28686..6b59842625 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,23 +1,7 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import { linkOptions } from '@tanstack/react-router' import { toRuntimePath } from '@tanstack/router-e2e-utils' -type ScrollPaintTestState = { - sourceFrameScrollYs: Array - sourceWasReset: boolean - destinationMounted: boolean - destinationCommitScrollY: number | null - destinationFrameScrollYs: Array - cleanup: () => void -} - -declare global { - interface Window { - __scrollPaintTestState?: ScrollPaintTestState - } -} - test('Smoke - Renders home', async ({ page }) => { await page.goto(toRuntimePath('/')) await expect( @@ -25,236 +9,6 @@ test('Smoke - Renders home', async ({ page }) => { ).toBeVisible() }) -test('PUSH resets scroll before the destination can render a frame (#7815)', async ({ - page, -}) => { - await page.goto(toRuntimePath('/issue-7040-source')) - await expect(page.getByTestId('issue-7040-source-top')).toBeVisible() - - const sourceScrollY = await page.evaluate(async () => { - window.scrollTo(0, 500) - await new Promise((resolve) => requestAnimationFrame(() => resolve())) - return window.scrollY - }) - - expect(sourceScrollY).toBeGreaterThan(0) - - await page.evaluate((expectedSourceScrollY) => { - const root = document.querySelector('#app') - if (!root) { - throw new Error('App root not found') - } - - const geometry = document.createElement('div') - geometry.setAttribute('aria-hidden', 'true') - geometry.style.height = `${window.innerHeight + expectedSourceScrollY + 100}px` - geometry.style.pointerEvents = 'none' - geometry.style.width = '1px' - document.body.append(geometry) - - const state: ScrollPaintTestState = { - sourceFrameScrollYs: [], - sourceWasReset: false, - destinationMounted: false, - destinationCommitScrollY: null, - destinationFrameScrollYs: [], - cleanup: () => {}, - } - - const getDestinationHeading = () => - Array.from(document.querySelectorAll('h3')).find( - (heading) => heading.textContent === 'normal-page', - ) - - const commitObserver = new MutationObserver(() => { - const destinationHeading = getDestinationHeading() - - if (!destinationHeading) { - return - } - - commitObserver.disconnect() - state.destinationMounted = true - state.destinationCommitScrollY = window.scrollY - }) - - commitObserver.observe(root, { childList: true, subtree: true }) - - const handleScroll = () => { - if ( - document.querySelector('[data-testid="issue-7040-source-top"]') && - Math.abs(window.scrollY - expectedSourceScrollY) > 1 - ) { - state.sourceWasReset = true - } - } - window.addEventListener('scroll', handleScroll, { passive: true }) - - const originalScrollTo = window.scrollTo - window.scrollTo = ((...args: Array) => { - const requestedTop = - typeof args[0] === 'number' - ? args[1] - : typeof args[0] === 'object' && args[0] !== null - ? (args[0] as ScrollToOptions).top - : undefined - if ( - typeof requestedTop === 'number' && - Math.abs(requestedTop - expectedSourceScrollY) > 1 && - document.querySelector('[data-testid="issue-7040-source-top"]') - ) { - state.sourceWasReset = true - } - Reflect.apply(originalScrollTo, window, args) - }) as typeof window.scrollTo - - let animationFrameId = 0 - const recordFrame = () => { - if (getDestinationHeading()) { - state.destinationFrameScrollYs.push(window.scrollY) - } else if ( - document.querySelector('[data-testid="issue-7040-source-top"]') - ) { - state.sourceFrameScrollYs.push(window.scrollY) - } - animationFrameId = requestAnimationFrame(recordFrame) - } - animationFrameId = requestAnimationFrame(recordFrame) - - state.cleanup = () => { - commitObserver.disconnect() - cancelAnimationFrame(animationFrameId) - window.removeEventListener('scroll', handleScroll) - window.scrollTo = originalScrollTo - geometry.remove() - delete window.__scrollPaintTestState - } - window.__scrollPaintTestState = state - }, sourceScrollY) - - await page.evaluate( - () => - new Promise((resolve) => { - requestAnimationFrame(() => resolve()) - }), - ) - expect(await page.evaluate(() => window.scrollY)).toBe(sourceScrollY) - - await page - .getByRole('link', { name: 'Head-/normal-page' }) - .dispatchEvent('click') - - await page.waitForFunction(() => { - const state = window.__scrollPaintTestState - if (!state?.destinationMounted) { - return false - } - - const lastFrames = state.destinationFrameScrollYs.slice(-2) - return ( - lastFrames.length === 2 && - lastFrames.every((scrollY) => Math.abs(scrollY) <= 1) - ) - }) - - const observation = await page.evaluate(() => { - const state = window.__scrollPaintTestState - if (!state) { - throw new Error('Scroll paint observer not found') - } - - return { - sourceFrameScrollYs: state.sourceFrameScrollYs, - sourceWasReset: state.sourceWasReset, - destinationCommitScrollY: state.destinationCommitScrollY, - destinationFrameScrollYs: state.destinationFrameScrollYs, - destinationMaxScrollY: - document.documentElement.scrollHeight - window.innerHeight, - finalScrollY: window.scrollY, - } - }) - - expect(observation.sourceFrameScrollYs.length).toBeGreaterThan(0) - expect( - observation.sourceFrameScrollYs.every( - (scrollY) => Math.abs(scrollY - sourceScrollY) <= 1, - ), - ).toBe(true) - expect(observation.sourceWasReset).toBe(false) - expect(observation.destinationMaxScrollY).toBeGreaterThanOrEqual( - sourceScrollY, - ) - expect(observation.finalScrollY).toBe(0) - expect(observation.destinationFrameScrollYs.length).toBeGreaterThanOrEqual(2) - expect( - observation.destinationFrameScrollYs.every( - (scrollY) => Math.abs(scrollY) <= 1, - ), - `Destination paint opportunities: ${observation.destinationFrameScrollYs.join(', ')}, commit: ${observation.destinationCommitScrollY}, final: ${observation.finalScrollY}`, - ).toBe(true) -}) - -test('restores the prior scroll position after browser back then forward', async ({ - page, -}) => { - await page.goto(toRuntimePath('/')) - await page.getByRole('link', { name: 'Head-/normal-page' }).click() - await page.waitForURL('**/normal-page') - await expect(page.getByTestId('at-the-top')).toBeInViewport() - - const scrollY = await page.evaluate(async () => { - window.scrollTo(0, document.documentElement.scrollHeight) - await new Promise((resolve) => requestAnimationFrame(() => resolve(null))) - return window.scrollY - }) - - expect(scrollY).toBeGreaterThan(0) - await expect(page.getByTestId('at-the-bottom')).toBeInViewport() - - await page.goBack() - await expect( - page.getByRole('heading', { name: 'Welcome Home!' }), - ).toBeVisible() - - await page.goForward() - await page.waitForURL('**/normal-page') - await page.waitForFunction( - (expectedScrollY) => Math.abs(window.scrollY - expectedScrollY) <= 2, - scrollY, - ) - await expect(page.getByTestId('at-the-bottom')).toBeInViewport() -}) - -test('restores the prior scroll position after browser back navigation', async ({ - page, -}) => { - await page.goto(toRuntimePath('/normal-page')) - await expect(page.getByTestId('at-the-top')).toBeInViewport() - - const scrollY = await page.evaluate(async () => { - window.scrollTo(0, document.documentElement.scrollHeight) - await new Promise((resolve) => requestAnimationFrame(() => resolve(null))) - return window.scrollY - }) - - expect(scrollY).toBeGreaterThan(0) - await expect(page.getByTestId('at-the-bottom')).toBeInViewport() - - await page.getByRole('link', { name: 'Foot-/', exact: true }).click() - await page.waitForURL('**/') - await expect( - page.getByRole('heading', { name: 'Welcome Home!' }), - ).toBeVisible() - - await page.goBack() - await page.waitForURL('**/normal-page') - await page.waitForFunction( - (expectedScrollY) => Math.abs(window.scrollY - expectedScrollY) <= 2, - scrollY, - ) - await expect(page.getByTestId('at-the-bottom')).toBeInViewport() -}) - const pages = [ linkOptions({ to: '/normal-page' }), linkOptions({ to: '/lazy-page' }), 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 deleted file mode 100644 index 2db25517c8..0000000000 --- a/e2e/react-router/scroll-restoration-sandbox-vite/tests/issue-7040.repro.spec.ts +++ /dev/null @@ -1,152 +0,0 @@ -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' - -const attemptCount = 3 -const sourceScrollTargetY = 6000 -const fastScrollStepPx = 220 -const fastScrollDelayMs = 3 -const maxFastScrollSteps = 80 -const preClickReverseScrollPx = 60 - -type ReproAttempt = { - attempt: number - before: { - sourceKey: string - sourceScrollY: number - sourceHeight: number - } - after: { - destinationKey: string - destinationScrollY: number - destinationHeight: number - destinationMaxScrollY: number - } -} - -async function openFreshSourcePage(page: Page) { - await page.goto(toRuntimePath('/issue-7040-source')) - await expect(page.getByTestId('issue-7040-source-top')).toBeVisible() - - await page.evaluate(() => { - sessionStorage.clear() - window.scrollTo(0, 0) - }) - - await page.reload() - await expect(page.getByTestId('issue-7040-source-top')).toBeVisible() -} - -async function fastScrollSourcePage(page: Page) { - await page.evaluate( - async ({ targetScrollY, stepPx, stepDelayMs, maxSteps }) => { - const sleep = (ms: number) => - new Promise((resolve) => setTimeout(resolve, ms)) - - window.scrollTo(0, 0) - - let steps = 0 - - while (window.scrollY < targetScrollY && steps < maxSteps) { - window.scrollBy(0, stepPx) - steps += 1 - await sleep(stepDelayMs) - } - - if (window.scrollY < targetScrollY) { - throw new Error( - `Could not reach source scroll target ${targetScrollY}; got ${window.scrollY}`, - ) - } - }, - { - targetScrollY: sourceScrollTargetY, - stepPx: fastScrollStepPx, - stepDelayMs: fastScrollDelayMs, - maxSteps: maxFastScrollSteps, - }, - ) -} - -async function clickTargetLinkImmediatelyAfterScroll(page: Page) { - await page.evaluate( - ({ reverseScrollPx }) => { - const link = document.querySelector( - '[data-testid="issue-7040-target-link"]', - ) - - if (!(link instanceof HTMLAnchorElement)) { - throw new Error('issue-7040 target link not found') - } - - // Trigger one more browser scroll update immediately before navigation - // so the test stays focused on the stale-scroll race. - window.scrollBy(0, -reverseScrollPx) - link.dispatchEvent( - new MouseEvent('click', { - bubbles: true, - cancelable: true, - view: window, - }), - ) - }, - { reverseScrollPx: preClickReverseScrollPx }, - ) -} - -async function waitForTargetPageToSettle(page: Page) { - await page.waitForURL('**/issue-7040-target') - await expect(page.getByTestId('issue-7040-target-top')).toBeVisible() - await page.waitForFunction(() => window.scrollY === 0) -} - -test('Issue #7040 repro: fast scroll then click can restore target below top', async ({ - page, -}) => { - const attempts: Array = [] - - for (let attempt = 0; attempt < attemptCount; attempt++) { - await openFreshSourcePage(page) - await fastScrollSourcePage(page) - - const before = await page.evaluate(() => { - return { - sourceKey: window.history.state.__TSR_key, - sourceScrollY: window.scrollY, - sourceHeight: document.documentElement.scrollHeight, - } - }) - - await clickTargetLinkImmediatelyAfterScroll(page) - await waitForTargetPageToSettle(page) - - const after = await page.evaluate(() => { - return { - destinationKey: window.history.state.__TSR_key, - destinationScrollY: window.scrollY, - destinationHeight: document.documentElement.scrollHeight, - destinationMaxScrollY: - document.documentElement.scrollHeight - window.innerHeight, - } - }) - - attempts.push({ attempt, before, after }) - } - - for (const attempt of attempts) { - expect(attempt.before.sourceHeight).toBeGreaterThan(15000) - expect(attempt.before.sourceScrollY).toBeGreaterThan(sourceScrollTargetY) - expect(attempt.before.sourceKey).not.toBe(attempt.after.destinationKey) - expect(attempt.before.sourceScrollY).toBeGreaterThan( - attempt.after.destinationMaxScrollY, - ) - expect(attempt.after.destinationHeight).toBeLessThan( - attempt.before.sourceHeight, - ) - expect(attempt.after.destinationScrollY).toBe(0) - expect(attempt.after.destinationScrollY).toBeLessThanOrEqual( - attempt.after.destinationMaxScrollY, - ) - } -}) diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts b/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts b/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/tsconfig.json b/e2e/react-router/scroll-restoration-sandbox-vite/tsconfig.json index 5d58406b2e..f33b5a7aa3 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/tsconfig.json +++ b/e2e/react-router/scroll-restoration-sandbox-vite/tsconfig.json @@ -11,5 +11,5 @@ "allowJs": true, "types": ["vite/client", "node"] }, - "exclude": ["node_modules", "dist", "dist-hash"] + "exclude": ["node_modules", "dist"] } diff --git a/e2e/react-router/sentry-integration/.devcontainer/devcontainer.json b/e2e/react-router/sentry-integration/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/react-router/sentry-integration/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/react-router/sentry-integration/package.json b/e2e/react-router/sentry-integration/package.json index 5ebbdf31d9..5679752b9d 100644 --- a/e2e/react-router/sentry-integration/package.json +++ b/e2e/react-router/sentry-integration/package.json @@ -8,26 +8,26 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@sentry/react": "^10.32.0", "@sentry/tracing": "^7.120.4", "@sentry/vite-plugin": "^4.6.1", - "@tailwindcss/vite": "^4.2.2", + "@tailwindcss/vite": "^4.1.18", "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "catalog:", - "tailwindcss": "^4.2.2" + "redaxios": "^0.5.1", + "tailwindcss": "^4.1.18" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@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" + "@vitejs/plugin-react": "^4.3.4", + "vite": "^7.3.1" } } diff --git a/e2e/react-router/sentry-integration/playwright.config.ts b/e2e/react-router/sentry-integration/playwright.config.ts index 6a684ac89e..0c5cee43e4 100644 --- a/e2e/react-router/sentry-integration/playwright.config.ts +++ b/e2e/react-router/sentry-integration/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/sentry-integration/src/vite-env.d.ts b/e2e/react-router/sentry-integration/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/react-router/sentry-integration/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/react-router/view-transitions/.devcontainer/devcontainer.json b/e2e/react-router/view-transitions/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/react-router/view-transitions/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/react-router/view-transitions/package.json b/e2e/react-router/view-transitions/package.json index e2d7a181e1..81c5eefa38 100644 --- a/e2e/react-router/view-transitions/package.json +++ b/e2e/react-router/view-transitions/package.json @@ -8,27 +8,26 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", + "@tailwindcss/vite": "^4.1.18", "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", "@tanstack/router-plugin": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "catalog:", - "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "redaxios": "^0.5.1", + "tailwindcss": "^4.1.18", + "zod": "^3.24.2" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1" } } diff --git a/e2e/react-router/view-transitions/playwright.config.ts b/e2e/react-router/view-transitions/playwright.config.ts index 4eead86444..c5de6b5611 100644 --- a/e2e/react-router/view-transitions/playwright.config.ts +++ b/e2e/react-router/view-transitions/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,10 +22,13 @@ export default defineConfig({ baseURL, }, + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/view-transitions/src/routeTree.gen.ts b/e2e/react-router/view-transitions/src/routeTree.gen.ts index 8982fca68f..20ee76a1a5 100644 --- a/e2e/react-router/view-transitions/src/routeTree.gen.ts +++ b/e2e/react-router/view-transitions/src/routeTree.gen.ts @@ -9,16 +9,16 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as ExploreRouteImport } from './routes/explore' import { Route as HowItWorksRouteImport } from './routes/how-it-works' +import { Route as ExploreRouteImport } from './routes/explore' import { Route as PostsRouteRouteImport } from './routes/posts.route' +import { Route as IndexRouteImport } from './routes/index' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const HowItWorksRoute = HowItWorksRouteImport.update({ + id: '/how-it-works', + path: '/how-it-works', getParentRoute: () => rootRouteImport, } as any) const ExploreRoute = ExploreRouteImport.update({ @@ -26,16 +26,16 @@ const ExploreRoute = ExploreRouteImport.update({ path: '/explore', getParentRoute: () => rootRouteImport, } as any) -const HowItWorksRoute = HowItWorksRouteImport.update({ - id: '/how-it-works', - path: '/how-it-works', - getParentRoute: () => rootRouteImport, -} as any) const PostsRouteRoute = PostsRouteRouteImport.update({ id: '/posts', path: '/posts', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -101,11 +101,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/how-it-works': { + id: '/how-it-works' + path: '/how-it-works' + fullPath: '/how-it-works' + preLoaderRoute: typeof HowItWorksRouteImport parentRoute: typeof rootRouteImport } '/explore': { @@ -115,13 +115,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ExploreRouteImport parentRoute: typeof rootRouteImport } - '/how-it-works': { - id: '/how-it-works' - path: '/how-it-works' - fullPath: '/how-it-works' - preLoaderRoute: typeof HowItWorksRouteImport - parentRoute: typeof rootRouteImport - } '/posts': { id: '/posts' path: '/posts' @@ -129,6 +122,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/posts/': { id: '/posts/' path: '/' diff --git a/e2e/react-router/view-transitions/src/vite-env.d.ts b/e2e/react-router/view-transitions/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/react-router/view-transitions/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/react-router/view-transitions/tests/app.spec.ts b/e2e/react-router/view-transitions/tests/app.spec.ts index 6c1ccf1a6e..472bd6ed0b 100644 --- a/e2e/react-router/view-transitions/tests/app.spec.ts +++ b/e2e/react-router/view-transitions/tests/app.spec.ts @@ -1,4 +1,4 @@ -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/view-transitions/tests/setup/global.setup.ts b/e2e/react-router/view-transitions/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/view-transitions/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-router/view-transitions/tests/setup/global.teardown.ts b/e2e/react-router/view-transitions/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/view-transitions/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-start/basic-auth/.devcontainer/devcontainer.json b/e2e/react-start/basic-auth/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/react-start/basic-auth/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/react-start/basic-auth/package.json b/e2e/react-start/basic-auth/package.json index f7ff609e76..afc6ced31e 100644 --- a/e2e/react-start/basic-auth/package.json +++ b/e2e/react-start/basic-auth/package.json @@ -10,7 +10,7 @@ "preview": "vite preview", "start": "node .output/server/index.mjs", "prisma-generate": "prisma generate", - "test:e2e": "exit 0; pnpm run prisma-generate && playwright test --project=chromium" + "test:e2e": "exit 0; rm -rf port*.txt; pnpm run prisma-generate && playwright test --project=chromium" }, "dependencies": { "@libsql/client": "^0.15.15", @@ -19,25 +19,24 @@ "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", "@tanstack/react-start": "workspace:^", - "iron-session": "^9.0.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "catalog:", - "tailwind-merge": "^3.6.0" + "redaxios": "^0.5.1", + "tailwind-merge": "^2.6.0", + "vite": "^7.3.1" }, "devDependencies": { - "@playwright/test": "^1.61.0", - "@tailwindcss/vite": "^4.2.2", + "@playwright/test": "^1.50.1", + "@tailwindcss/vite": "^4.1.18", "@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", + "@vitejs/plugin-react": "^4.3.4", "dotenv": "^17.2.3", "prisma": "^7.0.0", - "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "tailwindcss": "^4.1.18", + "typescript": "^5.7.2", + "vite-tsconfig-paths": "^5.1.4" } } diff --git a/e2e/react-start/basic-auth/playwright.config.ts b/e2e/react-start/basic-auth/playwright.config.ts index 82678ac00b..18b8905468 100644 --- a/e2e/react-start/basic-auth/playwright.config.ts +++ b/e2e/react-start/basic-auth/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/basic-auth/src/components/DefaultCatchBoundary.tsx b/e2e/react-start/basic-auth/src/components/DefaultCatchBoundary.tsx index 405fb5f4a7..ef2daa1ea1 100644 --- a/e2e/react-start/basic-auth/src/components/DefaultCatchBoundary.tsx +++ b/e2e/react-start/basic-auth/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/react-router' import type { ErrorComponentProps } from '@tanstack/react-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) console.error(error) diff --git a/e2e/react-start/basic-auth/src/routeTree.gen.ts b/e2e/react-start/basic-auth/src/routeTree.gen.ts index 998d34a709..9e96fafa6a 100644 --- a/e2e/react-start/basic-auth/src/routeTree.gen.ts +++ b/e2e/react-start/basic-auth/src/routeTree.gen.ts @@ -9,27 +9,18 @@ // 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 AuthedRouteImport } from './routes/_authed' -import { Route as LoginRouteImport } from './routes/login' -import { Route as LogoutRouteImport } from './routes/logout' import { Route as SignupRouteImport } from './routes/signup' +import { Route as LogoutRouteImport } from './routes/logout' +import { Route as LoginRouteImport } from './routes/login' +import { Route as AuthedRouteImport } from './routes/_authed' +import { Route as IndexRouteImport } from './routes/index' import { Route as AuthedPostsRouteImport } from './routes/_authed/posts' import { Route as AuthedPostsIndexRouteImport } from './routes/_authed/posts.index' import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AuthedRoute = AuthedRouteImport.update({ - id: '/_authed', - getParentRoute: () => rootRouteImport, -} as any) -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', +const SignupRoute = SignupRouteImport.update({ + id: '/signup', + path: '/signup', getParentRoute: () => rootRouteImport, } as any) const LogoutRoute = LogoutRouteImport.update({ @@ -37,9 +28,18 @@ const LogoutRoute = LogoutRouteImport.update({ path: '/logout', getParentRoute: () => rootRouteImport, } as any) -const SignupRoute = SignupRouteImport.update({ - id: '/signup', - path: '/signup', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', + getParentRoute: () => rootRouteImport, +} as any) +const AuthedRoute = AuthedRouteImport.update({ + id: '/_authed', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AuthedPostsRoute = AuthedPostsRouteImport.update({ @@ -120,25 +120,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_authed': { - id: '/_authed' - path: '' - fullPath: '/' - preLoaderRoute: typeof AuthedRouteImport - parentRoute: typeof rootRouteImport - } - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport + '/signup': { + id: '/signup' + path: '/signup' + fullPath: '/signup' + preLoaderRoute: typeof SignupRouteImport parentRoute: typeof rootRouteImport } '/logout': { @@ -148,11 +134,25 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LogoutRouteImport parentRoute: typeof rootRouteImport } - '/signup': { - id: '/signup' - path: '/signup' - fullPath: '/signup' - preLoaderRoute: typeof SignupRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport + parentRoute: typeof rootRouteImport + } + '/_authed': { + id: '/_authed' + path: '' + fullPath: '' + preLoaderRoute: typeof AuthedRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_authed/posts': { diff --git a/e2e/react-start/basic-auth/src/routes/__root.tsx b/e2e/react-start/basic-auth/src/routes/__root.tsx index fb7868435d..76e5f8b1d6 100644 --- a/e2e/react-start/basic-auth/src/routes/__root.tsx +++ b/e2e/react-start/basic-auth/src/routes/__root.tsx @@ -14,18 +14,18 @@ import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary.js' import { NotFound } from '~/components/NotFound.js' import appCss from '~/styles/app.css?url' import { seo } from '~/utils/seo.js' -import { getAppSession } from '~/utils/session.js' +import { useAppSession } from '~/utils/session.js' const fetchUser = createServerFn({ method: 'GET' }).handler(async () => { // We need to auth on the server so we have access to secure cookies - const session = await getAppSession() + const session = await useAppSession() - if (!session.userEmail) { + if (!session.data.userEmail) { return null } return { - email: session.userEmail, + email: session.data.userEmail, } }) diff --git a/e2e/react-start/basic-auth/src/routes/_authed.tsx b/e2e/react-start/basic-auth/src/routes/_authed.tsx index fe73185136..221627851a 100644 --- a/e2e/react-start/basic-auth/src/routes/_authed.tsx +++ b/e2e/react-start/basic-auth/src/routes/_authed.tsx @@ -3,12 +3,12 @@ import { createServerFn } from '@tanstack/react-start' import { hashPassword, prismaClient } from '~/utils/prisma' import { Login } from '~/components/Login' -import { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' export const loginFn = createServerFn({ method: 'POST', }) - .validator((payload: { email: string; password: string }) => payload) + .inputValidator((payload: { email: string; password: string }) => payload) .handler(async ({ data }) => { // Find the user const user = await prismaClient.user.findUnique({ @@ -37,11 +37,12 @@ export const loginFn = createServerFn({ } // Create a session - const session = await getAppSession() + const session = await useAppSession() // Store the user's email in the session - session.userEmail = user.email - await session.save() + await session.update({ + userEmail: user.email, + }) }) export const Route = createFileRoute('/_authed')({ @@ -51,7 +52,7 @@ export const Route = createFileRoute('/_authed')({ } }, errorComponent: ({ error }) => { - if (error instanceof Error && error.message === 'Not authenticated') { + if (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 0f86b0d4e3..a08f9c737e 100644 --- a/e2e/react-start/basic-auth/src/routes/logout.tsx +++ b/e2e/react-start/basic-auth/src/routes/logout.tsx @@ -1,12 +1,12 @@ import { redirect, createFileRoute } from '@tanstack/react-router' import { createServerFn } from '@tanstack/react-start' -import { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await getAppSession() + const session = await useAppSession() - session.destroy() + session.clear() throw redirect({ href: '/', diff --git a/e2e/react-start/basic-auth/src/routes/signup.tsx b/e2e/react-start/basic-auth/src/routes/signup.tsx index d7d5d40129..d6ef153786 100644 --- a/e2e/react-start/basic-auth/src/routes/signup.tsx +++ b/e2e/react-start/basic-auth/src/routes/signup.tsx @@ -4,12 +4,12 @@ import { createServerFn, useServerFn } from '@tanstack/react-start' import { hashPassword, prismaClient } from '~/utils/prisma' import { useMutation } from '~/hooks/useMutation' import { Auth } from '~/components/Auth' -import { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' export const signupFn = createServerFn({ method: 'POST', }) - .validator( + .inputValidator( (data: { email: string; password: string; redirectUrl?: string }) => data, ) .handler(async ({ data: payload }) => { @@ -24,7 +24,7 @@ export const signupFn = createServerFn({ const password = await hashPassword(payload.password) // Create a session - const session = await getAppSession() + const session = await useAppSession() if (found) { if (found.password !== password) { @@ -36,8 +36,9 @@ export const signupFn = createServerFn({ } // Store the user's email in the session - session.userEmail = found.email - await session.save() + await session.update({ + userEmail: found.email, + }) // Redirect to the prev page stored in the "redirect" search param throw redirect({ @@ -54,8 +55,9 @@ export const signupFn = createServerFn({ }) // Store the user's email in the session - session.userEmail = user.email - await session.save() + await session.update({ + userEmail: user.email, + }) // Redirect to the prev page stored in the "redirect" search param throw redirect({ diff --git a/e2e/react-start/basic-auth/src/utils/posts.ts b/e2e/react-start/basic-auth/src/utils/posts.ts index 532e883ac0..b30810a5a3 100644 --- a/e2e/react-start/basic-auth/src/utils/posts.ts +++ b/e2e/react-start/basic-auth/src/utils/posts.ts @@ -9,7 +9,7 @@ export type PostType = { } export const fetchPost = createServerFn({ method: 'GET' }) - .validator((postId: string) => postId) + .inputValidator((postId: string) => postId) .handler(async ({ data: postId }) => { console.info(`Fetching post with id ${postId}...`) const post = await axios diff --git a/e2e/react-start/basic-auth/src/utils/session.ts b/e2e/react-start/basic-auth/src/utils/session.ts index f1deacf85b..c38bac1e48 100644 --- a/e2e/react-start/basic-auth/src/utils/session.ts +++ b/e2e/react-start/basic-auth/src/utils/session.ts @@ -1,25 +1,13 @@ -import { getIronSession } from 'iron-session' -import { getCookie, setCookie } from '@tanstack/react-start/server' +// src/services/session.server.ts +import { useSession } from '@tanstack/react-start/server' import type { User } from '@prisma/client' type SessionUser = { userEmail: User['email'] } -export function getAppSession() { - return getIronSession( - { read: getCookie, write: setCookie }, - { - cookieName: 'test-auth-session', - // This fixture only runs locally with test credentials. - password: 'local-e2e-only-session-password-at-least-32-characters', - ttl: 60 * 60, - cookieOptions: { - httpOnly: true, - secure: false, - sameSite: 'lax', - path: '/', - }, - }, - ) +export function useAppSession() { + return useSession({ + password: 'ChangeThisBeforeShippingToProdOrYouWillBeFired', + }) } diff --git a/e2e/react-start/basic-auth/tsconfig.json b/e2e/react-start/basic-auth/tsconfig.json index cef9369516..3a9fb7cd71 100644 --- a/e2e/react-start/basic-auth/tsconfig.json +++ b/e2e/react-start/basic-auth/tsconfig.json @@ -13,6 +13,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/react-start/basic-auth/vite.config.ts b/e2e/react-start/basic-auth/vite.config.ts index 6c9a4c347a..3e946e6645 100644 --- a/e2e/react-start/basic-auth/vite.config.ts +++ b/e2e/react-start/basic-auth/vite.config.ts @@ -1,9 +1,16 @@ import { defineConfig } from 'vite' +import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import viteReact from '@vitejs/plugin-react' import tailwindcss from '@tailwindcss/vite' export default defineConfig({ - resolve: { tsconfigPaths: true }, - plugins: [tailwindcss(), tanstackStart(), viteReact()], + plugins: [ + tailwindcss(), + tsConfigPaths({ + projects: ['./tsconfig.json'], + }), + tanstackStart(), + viteReact(), + ], }) diff --git a/e2e/react-start/basic-cloudflare/.devcontainer/devcontainer.json b/e2e/react-start/basic-cloudflare/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/react-start/basic-cloudflare/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/react-start/basic-cloudflare/package.json b/e2e/react-start/basic-cloudflare/package.json index b9b8031ac4..6af4ba848e 100644 --- a/e2e/react-start/basic-cloudflare/package.json +++ b/e2e/react-start/basic-cloudflare/package.json @@ -9,8 +9,8 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "cf-typegen": "wrangler types", - "postinstall": "WRANGLER_LOG=warn npm run --silent cf-typegen", - "test:e2e": "playwright test --project=chromium" + "postinstall": "npm run cf-typegen", + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -20,28 +20,18 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@cloudflare/vite-plugin": "^1.29.0", - "@playwright/test": "^1.61.0", - "@tailwindcss/vite": "^4.2.2", + "@cloudflare/vite-plugin": "^1.15.1", + "@playwright/test": "^1.50.1", + "@tailwindcss/vite": "^4.1.18", "@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", - "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "wrangler": "^4.74.0" - }, - "nx": { - "targets": { - "test:e2e": { - "outputs": [ - "...", - "{projectRoot}/.wrangler/deploy" - ] - } - } + "@vitejs/plugin-react": "^4.3.4", + "tailwindcss": "^4.1.18", + "typescript": "^5.7.2", + "vite": "^7.3.1", + "vite-tsconfig-paths": "^5.1.4", + "wrangler": "^4.49.1" } } diff --git a/e2e/react-start/basic-cloudflare/playwright.config.ts b/e2e/react-start/basic-cloudflare/playwright.config.ts index 0925936d55..a545dff891 100644 --- a/e2e/react-start/basic-cloudflare/playwright.config.ts +++ b/e2e/react-start/basic-cloudflare/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,6 +14,9 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, @@ -20,8 +24,8 @@ export default defineConfig({ webServer: { command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx b/e2e/react-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx index 405fb5f4a7..ef2daa1ea1 100644 --- a/e2e/react-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx +++ b/e2e/react-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/react-router' import type { ErrorComponentProps } from '@tanstack/react-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) console.error(error) diff --git a/e2e/react-start/basic-cloudflare/src/routeTree.gen.ts b/e2e/react-start/basic-cloudflare/src/routeTree.gen.ts index b29f0d8d68..4219501f5e 100644 --- a/e2e/react-start/basic-cloudflare/src/routeTree.gen.ts +++ b/e2e/react-start/basic-cloudflare/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 IndexRouteImport } from './routes/index' import { Route as StaticRouteImport } from './routes/static' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const StaticRoute = StaticRouteImport.update({ id: '/static', path: '/static', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/static': { id: '/static' path: '/static' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof StaticRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/e2e/react-start/basic-cloudflare/tests/app.spec.ts b/e2e/react-start/basic-cloudflare/tests/app.spec.ts index c9497070dd..add28cb73e 100644 --- a/e2e/react-start/basic-cloudflare/tests/app.spec.ts +++ b/e2e/react-start/basic-cloudflare/tests/app.spec.ts @@ -1,5 +1,3 @@ -import { execFileSync } from 'node:child_process' -import { fileURLToPath } from 'node:url' import { existsSync } from 'node:fs' import { join } from 'node:path' import { expect } from '@playwright/test' @@ -31,19 +29,3 @@ test('prerender with Cloudflare Workers runtime', async ({ page }) => { 'The value is Hello from Cloudflare', ) }) - -test('the built Cloudflare app passes a deployment dry run', () => { - const wrangler = fileURLToPath( - new URL('../node_modules/wrangler/bin/wrangler.js', import.meta.url), - ) - const output = execFileSync( - process.execPath, - [wrangler, 'deploy', '--dry-run'], - { - encoding: 'utf8', - env: { ...process.env, WRANGLER_SEND_METRICS: 'false' }, - }, - ) - expect(output).toContain('dist/server/wrangler.json') - expect(output).toContain('--dry-run: exiting now.') -}) diff --git a/e2e/react-start/basic-cloudflare/tests/setup/global.setup.ts b/e2e/react-start/basic-cloudflare/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-start/basic-cloudflare/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-start/basic-cloudflare/tests/setup/global.teardown.ts b/e2e/react-start/basic-cloudflare/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-start/basic-cloudflare/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-start/basic-cloudflare/tsconfig.json b/e2e/react-start/basic-cloudflare/tsconfig.json index cef9369516..3a9fb7cd71 100644 --- a/e2e/react-start/basic-cloudflare/tsconfig.json +++ b/e2e/react-start/basic-cloudflare/tsconfig.json @@ -13,6 +13,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/react-start/basic-cloudflare/vite.config.ts b/e2e/react-start/basic-cloudflare/vite.config.ts index d19ab50ea5..06543fc07c 100644 --- a/e2e/react-start/basic-cloudflare/vite.config.ts +++ b/e2e/react-start/basic-cloudflare/vite.config.ts @@ -1,13 +1,16 @@ import { defineConfig } from 'vite' +import tsConfigPaths from 'vite-tsconfig-paths' import { cloudflare } from '@cloudflare/vite-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import viteReact from '@vitejs/plugin-react' import tailwindcss from '@tailwindcss/vite' export default defineConfig({ - resolve: { tsconfigPaths: true }, plugins: [ tailwindcss(), + tsConfigPaths({ + projects: ['./tsconfig.json'], + }), cloudflare({ viteEnvironment: { name: 'ssr' }, inspectorPort: false }), tanstackStart({ prerender: { diff --git a/e2e/react-start/basic-cloudflare/worker-configuration.d.ts b/e2e/react-start/basic-cloudflare/worker-configuration.d.ts index f7a8f16397..bdfccc2017 100644 --- a/e2e/react-start/basic-cloudflare/worker-configuration.d.ts +++ b/e2e/react-start/basic-cloudflare/worker-configuration.d.ts @@ -1,6 +1,6 @@ /* eslint-disable */ // Generated by Wrangler by running `wrangler types` (hash: b11df627d8b3c51b1bf3230a546b0f20) -// Runtime types generated with workerd@1.20260317.1 2025-09-24 nodejs_compat +// Runtime types generated with workerd@1.20251118.0 2025-09-24 nodejs_compat declare namespace Cloudflare { interface Env { MY_VAR: "Hello from Cloudflare"; @@ -436,22 +436,22 @@ interface ExecutionContext { passThroughOnException(): void; readonly props: Props; } -type ExportedHandlerFetchHandler = (request: Request>, env: Env, ctx: ExecutionContext) => Response | Promise; -type ExportedHandlerTailHandler = (events: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTraceHandler = (traces: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTailStreamHandler = (event: TailStream.TailEvent, env: Env, ctx: ExecutionContext) => TailStream.TailEventHandlerType | Promise; -type ExportedHandlerScheduledHandler = (controller: ScheduledController, env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerQueueHandler = (batch: MessageBatch, env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTestHandler = (controller: TestController, env: Env, ctx: ExecutionContext) => void | Promise; -interface ExportedHandler { - fetch?: ExportedHandlerFetchHandler; - tail?: ExportedHandlerTailHandler; - trace?: ExportedHandlerTraceHandler; - tailStream?: ExportedHandlerTailStreamHandler; - scheduled?: ExportedHandlerScheduledHandler; - test?: ExportedHandlerTestHandler; - email?: EmailExportedHandler; - queue?: ExportedHandlerQueueHandler; +type ExportedHandlerFetchHandler = (request: Request>, env: Env, ctx: ExecutionContext) => Response | Promise; +type ExportedHandlerTailHandler = (events: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerTraceHandler = (traces: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerTailStreamHandler = (event: TailStream.TailEvent, env: Env, ctx: ExecutionContext) => TailStream.TailEventHandlerType | Promise; +type ExportedHandlerScheduledHandler = (controller: ScheduledController, env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerQueueHandler = (batch: MessageBatch, env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerTestHandler = (controller: TestController, env: Env, ctx: ExecutionContext) => void | Promise; +interface ExportedHandler { + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + tailStream?: ExportedHandlerTailStreamHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; } interface StructuredSerializeOptions { transfer?: any[]; @@ -499,10 +499,8 @@ interface DurableObjectNamespaceNewUniqueIdOptions { jurisdiction?: DurableObjectJurisdiction; } type DurableObjectLocationHint = "wnam" | "enam" | "sam" | "weur" | "eeur" | "apac" | "oc" | "afr" | "me"; -type DurableObjectRoutingMode = "primary-only"; interface DurableObjectNamespaceGetDurableObjectOptions { locationHint?: DurableObjectLocationHint; - routingMode?: DurableObjectRoutingMode; } interface DurableObjectClass<_T extends Rpc.DurableObjectBranded | undefined = undefined> { } @@ -1389,12 +1387,6 @@ declare abstract class PromiseRejectionEvent extends Event { */ declare class FormData { constructor(); - /** - * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) - */ - append(name: string, value: string | Blob): void; /** * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. * @@ -1431,12 +1423,6 @@ declare class FormData { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has) */ has(name: string): boolean; - /** - * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) - */ - set(name: string, value: string | Blob): void; /** * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. * @@ -1763,7 +1749,7 @@ interface Request> e * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) */ signal: AbortSignal; - cf?: Cf; + cf: Cf | undefined; /** * The **`integrity`** read-only property of the Request interface contains the subresource integrity value of the request. * @@ -2098,8 +2084,6 @@ interface Transformer { expectedLength?: number; } interface StreamPipeOptions { - preventAbort?: boolean; - preventCancel?: boolean; /** * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. * @@ -2118,6 +2102,8 @@ interface StreamPipeOptions { * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. */ preventClose?: boolean; + preventAbort?: boolean; + preventCancel?: boolean; signal?: AbortSignal; } type ReadableStreamReadResult = { @@ -2392,13 +2378,13 @@ declare abstract class TransformStreamDefaultController { terminate(): void; } interface ReadableWritablePair { - readable: ReadableStream; /** * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use. * * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. */ writable: WritableStream; + readable: ReadableStream; } /** * The **`WritableStream`** interface of the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. @@ -3046,7 +3032,7 @@ declare var WebSocket: { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) */ interface WebSocket extends EventTarget { - accept(options?: WebSocketAcceptOptions): void; + accept(): void; /** * The **`WebSocket.send()`** method enqueues the specified data to be transmitted to the server over the WebSocket connection, increasing the value of `bufferedAmount` by the number of bytes needed to contain the data. * @@ -3085,22 +3071,6 @@ interface WebSocket extends EventTarget { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) */ extensions: string | null; - /** - * The **`WebSocket.binaryType`** property controls the type of binary data being received over the WebSocket connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/binaryType) - */ - binaryType: "blob" | "arraybuffer"; -} -interface WebSocketAcceptOptions { - /** - * When set to `true`, receiving a server-initiated WebSocket Close frame will not - * automatically send a reciprocal Close frame, leaving the connection in a half-open - * state. This is useful for proxying scenarios where you need to coordinate closing - * both sides independently. Defaults to `false` when the - * `no_web_socket_half_open_by_default` compatibility flag is enabled. - */ - allowHalfOpen?: boolean; } declare const WebSocketPair: { new (): { @@ -3219,8 +3189,6 @@ interface Container { signal(signo: number): void; getTcpPort(port: number): Fetcher; setInactivityTimeout(durationMs: number | bigint): Promise; - interceptOutboundHttp(addr: string, binding: Fetcher): Promise; - interceptAllOutboundHttp(binding: Fetcher): Promise; } interface ContainerStartupOptions { entrypoint?: string[]; @@ -3313,8 +3281,7 @@ interface WorkerStubEntrypointOptions { props?: any; } interface WorkerLoader { - get(name: string | null, getCode: () => WorkerLoaderWorkerCode | Promise): WorkerStub; - load(code: WorkerLoaderWorkerCode): WorkerStub; + get(name: string, getCode: () => WorkerLoaderWorkerCode | Promise): WorkerStub; } interface WorkerLoaderModule { js?: string; @@ -3347,181 +3314,6 @@ declare abstract class Performance { get timeOrigin(): number; /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */ now(): number; - /** - * The **`toJSON()`** method of the Performance interface is a Serialization; it returns a JSON representation of the Performance object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/toJSON) - */ - toJSON(): object; -} -// AI Search V2 API Error Interfaces -interface AiSearchInternalError extends Error { -} -interface AiSearchNotFoundError extends Error { -} -interface AiSearchNameNotSetError extends Error { -} -// AI Search V2 Request Types -type AiSearchSearchRequest = { - messages: Array<{ - role: 'system' | 'developer' | 'user' | 'assistant' | 'tool'; - content: string | null; - }>; - ai_search_options?: { - retrieval?: { - retrieval_type?: 'vector' | 'keyword' | 'hybrid'; - /** Match threshold (0-1, default 0.4) */ - match_threshold?: number; - /** Maximum number of results (1-50, default 10) */ - max_num_results?: number; - filters?: VectorizeVectorMetadataFilter; - /** Context expansion (0-3, default 0) */ - context_expansion?: number; - [key: string]: unknown; - }; - query_rewrite?: { - enabled?: boolean; - model?: string; - rewrite_prompt?: string; - [key: string]: unknown; - }; - reranking?: { - /** Enable reranking (default false) */ - enabled?: boolean; - model?: '@cf/baai/bge-reranker-base' | ''; - /** Match threshold (0-1, default 0.4) */ - match_threshold?: number; - [key: string]: unknown; - }; - [key: string]: unknown; - }; -}; -type AiSearchChatCompletionsRequest = { - messages: Array<{ - role: 'system' | 'developer' | 'user' | 'assistant' | 'tool'; - content: string | null; - }>; - model?: string; - stream?: boolean; - ai_search_options?: { - retrieval?: { - retrieval_type?: 'vector' | 'keyword' | 'hybrid'; - match_threshold?: number; - max_num_results?: number; - filters?: VectorizeVectorMetadataFilter; - context_expansion?: number; - [key: string]: unknown; - }; - query_rewrite?: { - enabled?: boolean; - model?: string; - rewrite_prompt?: string; - [key: string]: unknown; - }; - reranking?: { - enabled?: boolean; - model?: '@cf/baai/bge-reranker-base' | ''; - match_threshold?: number; - [key: string]: unknown; - }; - [key: string]: unknown; - }; - [key: string]: unknown; -}; -// AI Search V2 Response Types -type AiSearchSearchResponse = { - search_query: string; - chunks: Array<{ - id: string; - type: string; - /** Match score (0-1) */ - score: number; - text: string; - item: { - timestamp?: number; - key: string; - metadata?: Record; - }; - scoring_details?: { - /** Keyword match score (0-1) */ - keyword_score?: number; - /** Vector similarity score (0-1) */ - vector_score?: number; - }; - }>; -}; -type AiSearchListResponse = Array<{ - id: string; - internal_id?: string; - account_id?: string; - account_tag?: string; - /** Whether the instance is enabled (default true) */ - enable?: boolean; - type?: 'r2' | 'web-crawler'; - source?: string; - [key: string]: unknown; -}>; -type AiSearchConfig = { - /** Instance ID (1-32 chars, pattern: ^[a-z0-9_]+(?:-[a-z0-9_]+)*$) */ - id: string; - type: 'r2' | 'web-crawler'; - source: string; - source_params?: object; - /** Token ID (UUID format) */ - token_id?: string; - ai_gateway_id?: string; - /** Enable query rewriting (default false) */ - rewrite_query?: boolean; - /** Enable reranking (default false) */ - reranking?: boolean; - embedding_model?: string; - ai_search_model?: string; -}; -type AiSearchInstance = { - id: string; - enable?: boolean; - type?: 'r2' | 'web-crawler'; - source?: string; - [key: string]: unknown; -}; -// AI Search Instance Service - Instance-level operations -declare abstract class AiSearchInstanceService { - /** - * Search the AI Search instance for relevant chunks. - * @param params Search request with messages and AI search options - * @returns Search response with matching chunks - */ - search(params: AiSearchSearchRequest): Promise; - /** - * Generate chat completions with AI Search context. - * @param params Chat completions request with optional streaming - * @returns Response object (if streaming) or chat completion result - */ - chatCompletions(params: AiSearchChatCompletionsRequest): Promise; - /** - * Delete this AI Search instance. - */ - delete(): Promise; -} -// AI Search Account Service - Account-level operations -declare abstract class AiSearchAccountService { - /** - * List all AI Search instances in the account. - * @returns Array of AI Search instances - */ - list(): Promise; - /** - * Get an AI Search instance by ID. - * @param name Instance ID - * @returns Instance service for performing operations - */ - get(name: string): AiSearchInstanceService; - /** - * Create a new AI Search instance. - * @param config Instance configuration - * @returns Instance service for performing operations - */ - create(config: AiSearchConfig): Promise; } type AiImageClassificationInput = { image: number[]; @@ -3786,363 +3578,6 @@ declare abstract class BaseAiTranslation { inputs: AiTranslationInput; postProcessedOutputs: AiTranslationOutput; } -/** - * Workers AI support for OpenAI's Responses API - * Reference: https://github.com/openai/openai-node/blob/master/src/resources/responses/responses.ts - * - * It's a stripped down version from its source. - * It currently supports basic function calling, json mode and accepts images as input. - * - * It does not include types for WebSearch, CodeInterpreter, FileInputs, MCP, CustomTools. - * We plan to add those incrementally as model + platform capabilities evolve. - */ -type ResponsesInput = { - background?: boolean | null; - conversation?: string | ResponseConversationParam | null; - include?: Array | null; - input?: string | ResponseInput; - instructions?: string | null; - max_output_tokens?: number | null; - parallel_tool_calls?: boolean | null; - previous_response_id?: string | null; - prompt_cache_key?: string; - reasoning?: Reasoning | null; - safety_identifier?: string; - service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; - stream?: boolean | null; - stream_options?: StreamOptions | null; - temperature?: number | null; - text?: ResponseTextConfig; - tool_choice?: ToolChoiceOptions | ToolChoiceFunction; - tools?: Array; - top_p?: number | null; - truncation?: "auto" | "disabled" | null; -}; -type ResponsesOutput = { - id?: string; - created_at?: number; - output_text?: string; - error?: ResponseError | null; - incomplete_details?: ResponseIncompleteDetails | null; - instructions?: string | Array | null; - object?: "response"; - output?: Array; - parallel_tool_calls?: boolean; - temperature?: number | null; - tool_choice?: ToolChoiceOptions | ToolChoiceFunction; - tools?: Array; - top_p?: number | null; - max_output_tokens?: number | null; - previous_response_id?: string | null; - prompt?: ResponsePrompt | null; - reasoning?: Reasoning | null; - safety_identifier?: string; - service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; - status?: ResponseStatus; - text?: ResponseTextConfig; - truncation?: "auto" | "disabled" | null; - usage?: ResponseUsage; -}; -type EasyInputMessage = { - content: string | ResponseInputMessageContentList; - role: "user" | "assistant" | "system" | "developer"; - type?: "message"; -}; -type ResponsesFunctionTool = { - name: string; - parameters: { - [key: string]: unknown; - } | null; - strict: boolean | null; - type: "function"; - description?: string | null; -}; -type ResponseIncompleteDetails = { - reason?: "max_output_tokens" | "content_filter"; -}; -type ResponsePrompt = { - id: string; - variables?: { - [key: string]: string | ResponseInputText | ResponseInputImage; - } | null; - version?: string | null; -}; -type Reasoning = { - effort?: ReasoningEffort | null; - generate_summary?: "auto" | "concise" | "detailed" | null; - summary?: "auto" | "concise" | "detailed" | null; -}; -type ResponseContent = ResponseInputText | ResponseInputImage | ResponseOutputText | ResponseOutputRefusal | ResponseContentReasoningText; -type ResponseContentReasoningText = { - text: string; - type: "reasoning_text"; -}; -type ResponseConversationParam = { - id: string; -}; -type ResponseCreatedEvent = { - response: Response; - sequence_number: number; - type: "response.created"; -}; -type ResponseCustomToolCallOutput = { - call_id: string; - output: string | Array; - type: "custom_tool_call_output"; - id?: string; -}; -type ResponseError = { - code: "server_error" | "rate_limit_exceeded" | "invalid_prompt" | "vector_store_timeout" | "invalid_image" | "invalid_image_format" | "invalid_base64_image" | "invalid_image_url" | "image_too_large" | "image_too_small" | "image_parse_error" | "image_content_policy_violation" | "invalid_image_mode" | "image_file_too_large" | "unsupported_image_media_type" | "empty_image_file" | "failed_to_download_image" | "image_file_not_found"; - message: string; -}; -type ResponseErrorEvent = { - code: string | null; - message: string; - param: string | null; - sequence_number: number; - type: "error"; -}; -type ResponseFailedEvent = { - response: Response; - sequence_number: number; - type: "response.failed"; -}; -type ResponseFormatText = { - type: "text"; -}; -type ResponseFormatJSONObject = { - type: "json_object"; -}; -type ResponseFormatTextConfig = ResponseFormatText | ResponseFormatTextJSONSchemaConfig | ResponseFormatJSONObject; -type ResponseFormatTextJSONSchemaConfig = { - name: string; - schema: { - [key: string]: unknown; - }; - type: "json_schema"; - description?: string; - strict?: boolean | null; -}; -type ResponseFunctionCallArgumentsDeltaEvent = { - delta: string; - item_id: string; - output_index: number; - sequence_number: number; - type: "response.function_call_arguments.delta"; -}; -type ResponseFunctionCallArgumentsDoneEvent = { - arguments: string; - item_id: string; - name: string; - output_index: number; - sequence_number: number; - type: "response.function_call_arguments.done"; -}; -type ResponseFunctionCallOutputItem = ResponseInputTextContent | ResponseInputImageContent; -type ResponseFunctionCallOutputItemList = Array; -type ResponseFunctionToolCall = { - arguments: string; - call_id: string; - name: string; - type: "function_call"; - id?: string; - status?: "in_progress" | "completed" | "incomplete"; -}; -interface ResponseFunctionToolCallItem extends ResponseFunctionToolCall { - id: string; -} -type ResponseFunctionToolCallOutputItem = { - id: string; - call_id: string; - output: string | Array; - type: "function_call_output"; - status?: "in_progress" | "completed" | "incomplete"; -}; -type ResponseIncludable = "message.input_image.image_url" | "message.output_text.logprobs"; -type ResponseIncompleteEvent = { - response: Response; - sequence_number: number; - type: "response.incomplete"; -}; -type ResponseInput = Array; -type ResponseInputContent = ResponseInputText | ResponseInputImage; -type ResponseInputImage = { - detail: "low" | "high" | "auto"; - type: "input_image"; - /** - * Base64 encoded image - */ - image_url?: string | null; -}; -type ResponseInputImageContent = { - type: "input_image"; - detail?: "low" | "high" | "auto" | null; - /** - * Base64 encoded image - */ - image_url?: string | null; -}; -type ResponseInputItem = EasyInputMessage | ResponseInputItemMessage | ResponseOutputMessage | ResponseFunctionToolCall | ResponseInputItemFunctionCallOutput | ResponseReasoningItem; -type ResponseInputItemFunctionCallOutput = { - call_id: string; - output: string | ResponseFunctionCallOutputItemList; - type: "function_call_output"; - id?: string | null; - status?: "in_progress" | "completed" | "incomplete" | null; -}; -type ResponseInputItemMessage = { - content: ResponseInputMessageContentList; - role: "user" | "system" | "developer"; - status?: "in_progress" | "completed" | "incomplete"; - type?: "message"; -}; -type ResponseInputMessageContentList = Array; -type ResponseInputMessageItem = { - id: string; - content: ResponseInputMessageContentList; - role: "user" | "system" | "developer"; - status?: "in_progress" | "completed" | "incomplete"; - type?: "message"; -}; -type ResponseInputText = { - text: string; - type: "input_text"; -}; -type ResponseInputTextContent = { - text: string; - type: "input_text"; -}; -type ResponseItem = ResponseInputMessageItem | ResponseOutputMessage | ResponseFunctionToolCallItem | ResponseFunctionToolCallOutputItem; -type ResponseOutputItem = ResponseOutputMessage | ResponseFunctionToolCall | ResponseReasoningItem; -type ResponseOutputItemAddedEvent = { - item: ResponseOutputItem; - output_index: number; - sequence_number: number; - type: "response.output_item.added"; -}; -type ResponseOutputItemDoneEvent = { - item: ResponseOutputItem; - output_index: number; - sequence_number: number; - type: "response.output_item.done"; -}; -type ResponseOutputMessage = { - id: string; - content: Array; - role: "assistant"; - status: "in_progress" | "completed" | "incomplete"; - type: "message"; -}; -type ResponseOutputRefusal = { - refusal: string; - type: "refusal"; -}; -type ResponseOutputText = { - text: string; - type: "output_text"; - logprobs?: Array; -}; -type ResponseReasoningItem = { - id: string; - summary: Array; - type: "reasoning"; - content?: Array; - encrypted_content?: string | null; - status?: "in_progress" | "completed" | "incomplete"; -}; -type ResponseReasoningSummaryItem = { - text: string; - type: "summary_text"; -}; -type ResponseReasoningContentItem = { - text: string; - type: "reasoning_text"; -}; -type ResponseReasoningTextDeltaEvent = { - content_index: number; - delta: string; - item_id: string; - output_index: number; - sequence_number: number; - type: "response.reasoning_text.delta"; -}; -type ResponseReasoningTextDoneEvent = { - content_index: number; - item_id: string; - output_index: number; - sequence_number: number; - text: string; - type: "response.reasoning_text.done"; -}; -type ResponseRefusalDeltaEvent = { - content_index: number; - delta: string; - item_id: string; - output_index: number; - sequence_number: number; - type: "response.refusal.delta"; -}; -type ResponseRefusalDoneEvent = { - content_index: number; - item_id: string; - output_index: number; - refusal: string; - sequence_number: number; - type: "response.refusal.done"; -}; -type ResponseStatus = "completed" | "failed" | "in_progress" | "cancelled" | "queued" | "incomplete"; -type ResponseStreamEvent = ResponseCompletedEvent | ResponseCreatedEvent | ResponseErrorEvent | ResponseFunctionCallArgumentsDeltaEvent | ResponseFunctionCallArgumentsDoneEvent | ResponseFailedEvent | ResponseIncompleteEvent | ResponseOutputItemAddedEvent | ResponseOutputItemDoneEvent | ResponseReasoningTextDeltaEvent | ResponseReasoningTextDoneEvent | ResponseRefusalDeltaEvent | ResponseRefusalDoneEvent | ResponseTextDeltaEvent | ResponseTextDoneEvent; -type ResponseCompletedEvent = { - response: Response; - sequence_number: number; - type: "response.completed"; -}; -type ResponseTextConfig = { - format?: ResponseFormatTextConfig; - verbosity?: "low" | "medium" | "high" | null; -}; -type ResponseTextDeltaEvent = { - content_index: number; - delta: string; - item_id: string; - logprobs: Array; - output_index: number; - sequence_number: number; - type: "response.output_text.delta"; -}; -type ResponseTextDoneEvent = { - content_index: number; - item_id: string; - logprobs: Array; - output_index: number; - sequence_number: number; - text: string; - type: "response.output_text.done"; -}; -type Logprob = { - token: string; - logprob: number; - top_logprobs?: Array; -}; -type TopLogprob = { - token?: string; - logprob?: number; -}; -type ResponseUsage = { - input_tokens: number; - output_tokens: number; - total_tokens: number; -}; -type Tool = ResponsesFunctionTool; -type ToolChoiceFunction = { - name: string; - type: "function"; -}; -type ToolChoiceOptions = "none"; -type ReasoningEffort = "minimal" | "low" | "medium" | "high" | null; -type StreamOptions = { - include_obfuscation?: boolean; -}; type Ai_Cf_Baai_Bge_Base_En_V1_5_Input = { text: string | string[]; /** @@ -4171,8 +3606,8 @@ type Ai_Cf_Baai_Bge_Base_En_V1_5_Output = { * The pooling method used in the embedding process. */ pooling?: "mean" | "cls"; -} | Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse; -interface Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse { +} | AsyncResponse; +interface AsyncResponse { /** * The async request id that can be used to obtain the results. */ @@ -4248,13 +3683,7 @@ type Ai_Cf_Meta_M2M100_1_2B_Output = { * The translated text in the target language */ translated_text?: string; -} | Ai_Cf_Meta_M2M100_1_2B_AsyncResponse; -interface Ai_Cf_Meta_M2M100_1_2B_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} +} | AsyncResponse; declare abstract class Base_Ai_Cf_Meta_M2M100_1_2B { inputs: Ai_Cf_Meta_M2M100_1_2B_Input; postProcessedOutputs: Ai_Cf_Meta_M2M100_1_2B_Output; @@ -4287,13 +3716,7 @@ type Ai_Cf_Baai_Bge_Small_En_V1_5_Output = { * The pooling method used in the embedding process. */ pooling?: "mean" | "cls"; -} | Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse; -interface Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} +} | AsyncResponse; declare abstract class Base_Ai_Cf_Baai_Bge_Small_En_V1_5 { inputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Input; postProcessedOutputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Output; @@ -4326,13 +3749,7 @@ type Ai_Cf_Baai_Bge_Large_En_V1_5_Output = { * The pooling method used in the embedding process. */ pooling?: "mean" | "cls"; -} | Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse; -interface Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} +} | AsyncResponse; declare abstract class Base_Ai_Cf_Baai_Bge_Large_En_V1_5 { inputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Input; postProcessedOutputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Output; @@ -4518,13 +3935,13 @@ declare abstract class Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo { inputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input; postProcessedOutputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output; } -type Ai_Cf_Baai_Bge_M3_Input = Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts | Ai_Cf_Baai_Bge_M3_Input_Embedding | { +type Ai_Cf_Baai_Bge_M3_Input = BGEM3InputQueryAndContexts | BGEM3InputEmbedding | { /** * Batch of the embeddings requests to run using async-queue */ - requests: (Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 | Ai_Cf_Baai_Bge_M3_Input_Embedding_1)[]; + requests: (BGEM3InputQueryAndContexts1 | BGEM3InputEmbedding1)[]; }; -interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts { +interface BGEM3InputQueryAndContexts { /** * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts */ @@ -4543,14 +3960,14 @@ interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts { */ truncate_inputs?: boolean; } -interface Ai_Cf_Baai_Bge_M3_Input_Embedding { +interface BGEM3InputEmbedding { text: string | string[]; /** * When provided with too long context should the model error out or truncate the context to fit? */ truncate_inputs?: boolean; } -interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 { +interface BGEM3InputQueryAndContexts1 { /** * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts */ @@ -4569,15 +3986,15 @@ interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 { */ truncate_inputs?: boolean; } -interface Ai_Cf_Baai_Bge_M3_Input_Embedding_1 { +interface BGEM3InputEmbedding1 { text: string | string[]; /** * When provided with too long context should the model error out or truncate the context to fit? */ truncate_inputs?: boolean; } -type Ai_Cf_Baai_Bge_M3_Output = Ai_Cf_Baai_Bge_M3_Ouput_Query | Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts | Ai_Cf_Baai_Bge_M3_Ouput_Embedding | Ai_Cf_Baai_Bge_M3_AsyncResponse; -interface Ai_Cf_Baai_Bge_M3_Ouput_Query { +type Ai_Cf_Baai_Bge_M3_Output = BGEM3OuputQuery | BGEM3OutputEmbeddingForContexts | BGEM3OuputEmbedding | AsyncResponse; +interface BGEM3OuputQuery { response?: { /** * Index of the context in the request @@ -4589,7 +4006,7 @@ interface Ai_Cf_Baai_Bge_M3_Ouput_Query { score?: number; }[]; } -interface Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts { +interface BGEM3OutputEmbeddingForContexts { response?: number[][]; shape?: number[]; /** @@ -4597,7 +4014,7 @@ interface Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts { */ pooling?: "mean" | "cls"; } -interface Ai_Cf_Baai_Bge_M3_Ouput_Embedding { +interface BGEM3OuputEmbedding { shape?: number[]; /** * Embeddings of the requested text values @@ -4608,12 +4025,6 @@ interface Ai_Cf_Baai_Bge_M3_Ouput_Embedding { */ pooling?: "mean" | "cls"; } -interface Ai_Cf_Baai_Bge_M3_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} declare abstract class Base_Ai_Cf_Baai_Bge_M3 { inputs: Ai_Cf_Baai_Bge_M3_Input; postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output; @@ -4638,8 +4049,8 @@ declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell { inputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input; postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output; } -type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt | Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages; -interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt { +type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = Prompt | Messages; +interface Prompt { /** * The input text prompt for the model to generate a response. */ @@ -4690,7 +4101,7 @@ interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt { */ lora?: string; } -interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages { +interface Messages { /** * An array of message objects representing the conversation history. */ @@ -4881,8 +4292,8 @@ declare abstract class Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct { inputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input; postProcessedOutputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output; } -type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch; -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { +type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt | Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages | AsyncBatch; +interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { /** * The input text prompt for the model to generate a response. */ @@ -4891,7 +4302,7 @@ interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. */ lora?: string; - response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode; + response_format?: JSONMode; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -4933,11 +4344,11 @@ interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { */ presence_penalty?: number; } -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode { +interface JSONMode { type?: "json_object" | "json_schema"; json_schema?: unknown; } -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { +interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { /** * An array of message objects representing the conversation history. */ @@ -5042,7 +4453,7 @@ interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { }; }; })[]; - response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1; + response_format?: JSONMode; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -5084,11 +4495,7 @@ interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { */ presence_penalty?: number; } -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch { +interface AsyncBatch { requests?: { /** * User-supplied reference. This field will be present in the response as well it can be used to reference the request and response. It's NOT validated to be unique. @@ -5130,13 +4537,9 @@ interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch { * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number; - response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2; + response_format?: JSONMode; }[]; } -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = { /** * The generated text response from the model @@ -5172,13 +4575,7 @@ type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = { */ name?: string; }[]; -} | string | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse; -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} +} | string | AsyncResponse; declare abstract class Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast { inputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input; postProcessedOutputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output; @@ -5282,8 +4679,8 @@ declare abstract class Base_Ai_Cf_Baai_Bge_Reranker_Base { inputs: Ai_Cf_Baai_Bge_Reranker_Base_Input; postProcessedOutputs: Ai_Cf_Baai_Bge_Reranker_Base_Output; } -type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt | Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages; -interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt { +type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = Qwen2_5_Coder_32B_Instruct_Prompt | Qwen2_5_Coder_32B_Instruct_Messages; +interface Qwen2_5_Coder_32B_Instruct_Prompt { /** * The input text prompt for the model to generate a response. */ @@ -5292,7 +4689,7 @@ interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt { * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. */ lora?: string; - response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode; + response_format?: JSONMode; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -5334,11 +4731,7 @@ interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt { */ presence_penalty?: number; } -interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages { +interface Qwen2_5_Coder_32B_Instruct_Messages { /** * An array of message objects representing the conversation history. */ @@ -5443,7 +4836,7 @@ interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages { }; }; })[]; - response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1; + response_format?: JSONMode; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -5485,10 +4878,6 @@ interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages { */ presence_penalty?: number; } -interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = { /** * The generated text response from the model @@ -5529,8 +4918,8 @@ declare abstract class Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct { inputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input; postProcessedOutputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output; } -type Ai_Cf_Qwen_Qwq_32B_Input = Ai_Cf_Qwen_Qwq_32B_Prompt | Ai_Cf_Qwen_Qwq_32B_Messages; -interface Ai_Cf_Qwen_Qwq_32B_Prompt { +type Ai_Cf_Qwen_Qwq_32B_Input = Qwen_Qwq_32B_Prompt | Qwen_Qwq_32B_Messages; +interface Qwen_Qwq_32B_Prompt { /** * The input text prompt for the model to generate a response. */ @@ -5580,7 +4969,7 @@ interface Ai_Cf_Qwen_Qwq_32B_Prompt { */ presence_penalty?: number; } -interface Ai_Cf_Qwen_Qwq_32B_Messages { +interface Qwen_Qwq_32B_Messages { /** * An array of message objects representing the conversation history. */ @@ -5711,7 +5100,7 @@ interface Ai_Cf_Qwen_Qwq_32B_Messages { }; })[]; /** - * JSON schema that should be fulfilled for the response. + * JSON schema that should be fufilled for the response. */ guided_json?: object; /** @@ -5795,8 +5184,8 @@ declare abstract class Base_Ai_Cf_Qwen_Qwq_32B { inputs: Ai_Cf_Qwen_Qwq_32B_Input; postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output; } -type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt | Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages; -interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt { +type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = Mistral_Small_3_1_24B_Instruct_Prompt | Mistral_Small_3_1_24B_Instruct_Messages; +interface Mistral_Small_3_1_24B_Instruct_Prompt { /** * The input text prompt for the model to generate a response. */ @@ -5846,7 +5235,7 @@ interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt { */ presence_penalty?: number; } -interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages { +interface Mistral_Small_3_1_24B_Instruct_Messages { /** * An array of message objects representing the conversation history. */ @@ -5977,7 +5366,7 @@ interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages { }; })[]; /** - * JSON schema that should be fulfilled for the response. + * JSON schema that should be fufilled for the response. */ guided_json?: object; /** @@ -6061,14 +5450,14 @@ declare abstract class Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct { inputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input; postProcessedOutputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output; } -type Ai_Cf_Google_Gemma_3_12B_It_Input = Ai_Cf_Google_Gemma_3_12B_It_Prompt | Ai_Cf_Google_Gemma_3_12B_It_Messages; -interface Ai_Cf_Google_Gemma_3_12B_It_Prompt { +type Ai_Cf_Google_Gemma_3_12B_It_Input = Google_Gemma_3_12B_It_Prompt | Google_Gemma_3_12B_It_Messages; +interface Google_Gemma_3_12B_It_Prompt { /** * The input text prompt for the model to generate a response. */ prompt: string; /** - * JSON schema that should be fulfilled for the response. + * JSON schema that should be fufilled for the response. */ guided_json?: object; /** @@ -6112,7 +5501,7 @@ interface Ai_Cf_Google_Gemma_3_12B_It_Prompt { */ presence_penalty?: number; } -interface Ai_Cf_Google_Gemma_3_12B_It_Messages { +interface Google_Gemma_3_12B_It_Messages { /** * An array of message objects representing the conversation history. */ @@ -6133,7 +5522,19 @@ interface Ai_Cf_Google_Gemma_3_12B_It_Messages { */ url?: string; }; - }[]; + }[] | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; }[]; functions?: { name: string; @@ -6227,7 +5628,7 @@ interface Ai_Cf_Google_Gemma_3_12B_It_Messages { }; })[]; /** - * JSON schema that should be fulfilled for the response. + * JSON schema that should be fufilled for the response. */ guided_json?: object; /** @@ -6311,8 +5712,8 @@ declare abstract class Base_Ai_Cf_Google_Gemma_3_12B_It { inputs: Ai_Cf_Google_Gemma_3_12B_It_Input; postProcessedOutputs: Ai_Cf_Google_Gemma_3_12B_It_Output; } -type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch; -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt { +type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = Ai_Cf_Meta_Llama_4_Prompt | Ai_Cf_Meta_Llama_4_Messages | Ai_Cf_Meta_Llama_4_Async_Batch; +interface Ai_Cf_Meta_Llama_4_Prompt { /** * The input text prompt for the model to generate a response. */ @@ -6321,7 +5722,7 @@ interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt { * JSON schema that should be fulfilled for the response. */ guided_json?: object; - response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; + response_format?: JSONMode; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -6363,11 +5764,7 @@ interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt { */ presence_penalty?: number; } -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages { +interface Ai_Cf_Meta_Llama_4_Messages { /** * An array of message objects representing the conversation history. */ @@ -6497,9 +5894,9 @@ interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages { }; }; })[]; - response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; + response_format?: JSONMode; /** - * JSON schema that should be fulfilled for the response. + * JSON schema that should be fufilled for the response. */ guided_json?: object; /** @@ -6543,10 +5940,10 @@ interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages { */ presence_penalty?: number; } -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch { - requests: (Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner)[]; +interface Ai_Cf_Meta_Llama_4_Async_Batch { + requests: (Ai_Cf_Meta_Llama_4_Prompt_Inner | Ai_Cf_Meta_Llama_4_Messages_Inner)[]; } -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner { +interface Ai_Cf_Meta_Llama_4_Prompt_Inner { /** * The input text prompt for the model to generate a response. */ @@ -6555,7 +5952,7 @@ interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner { * JSON schema that should be fulfilled for the response. */ guided_json?: object; - response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; + response_format?: JSONMode; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -6597,7 +5994,7 @@ interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner { */ presence_penalty?: number; } -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner { +interface Ai_Cf_Meta_Llama_4_Messages_Inner { /** * An array of message objects representing the conversation history. */ @@ -6727,9 +6124,9 @@ interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner { }; }; })[]; - response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; + response_format?: JSONMode; /** - * JSON schema that should be fulfilled for the response. + * JSON schema that should be fufilled for the response. */ guided_json?: object; /** @@ -6826,597 +6223,6 @@ declare abstract class Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct { inputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input; postProcessedOutputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output; } -type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input = Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch; -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - /** - * The content of the message as a string. - */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch { - requests: (Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1)[]; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1 { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - /** - * The content of the message as a string. - */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output = Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response | string | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse; -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response { - /** - * Unique identifier for the completion - */ - id?: string; - /** - * Object type identifier - */ - object?: "chat.completion"; - /** - * Unix timestamp of when the completion was created - */ - created?: number; - /** - * Model used for the completion - */ - model?: string; - /** - * List of completion choices - */ - choices?: { - /** - * Index of the choice in the list - */ - index?: number; - /** - * The message generated by the model - */ - message?: { - /** - * Role of the message author - */ - role: string; - /** - * The content of the message - */ - content: string; - /** - * Internal reasoning content (if available) - */ - reasoning_content?: string; - /** - * Tool calls made by the assistant - */ - tool_calls?: { - /** - * Unique identifier for the tool call - */ - id: string; - /** - * Type of tool call - */ - type: "function"; - function: { - /** - * Name of the function to call - */ - name: string; - /** - * JSON string of arguments for the function - */ - arguments: string; - }; - }[]; - }; - /** - * Reason why the model stopped generating - */ - finish_reason?: string; - /** - * Stop reason (may be null) - */ - stop_reason?: string | null; - /** - * Log probabilities (if requested) - */ - logprobs?: {} | null; - }[]; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * Log probabilities for the prompt (if requested) - */ - prompt_logprobs?: {} | null; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response { - /** - * Unique identifier for the completion - */ - id?: string; - /** - * Object type identifier - */ - object?: "text_completion"; - /** - * Unix timestamp of when the completion was created - */ - created?: number; - /** - * Model used for the completion - */ - model?: string; - /** - * List of completion choices - */ - choices?: { - /** - * Index of the choice in the list - */ - index: number; - /** - * The generated text completion - */ - text: string; - /** - * Reason why the model stopped generating - */ - finish_reason: string; - /** - * Stop reason (may be null) - */ - stop_reason?: string | null; - /** - * Log probabilities (if requested) - */ - logprobs?: {} | null; - /** - * Log probabilities for the prompt (if requested) - */ - prompt_logprobs?: {} | null; - }[]; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8 { - inputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input; - postProcessedOutputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output; -} interface Ai_Cf_Deepgram_Nova_3_Input { audio: { body: object; @@ -7600,23 +6406,6 @@ declare abstract class Base_Ai_Cf_Deepgram_Nova_3 { inputs: Ai_Cf_Deepgram_Nova_3_Input; postProcessedOutputs: Ai_Cf_Deepgram_Nova_3_Output; } -interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input { - queries?: string | string[]; - /** - * Optional instruction for the task - */ - instruction?: string; - documents?: string | string[]; - text?: string | string[]; -} -interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output { - data?: number[][]; - shape?: number[]; -} -declare abstract class Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B { - inputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input; - postProcessedOutputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output; -} type Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input = { /** * readable stream with audio data and content-type specified for that data @@ -7653,13 +6442,85 @@ declare abstract class Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2 { inputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input; postProcessedOutputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output; } -declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_120B { - inputs: ResponsesInput; - postProcessedOutputs: ResponsesOutput; +type Ai_Cf_Openai_Gpt_Oss_120B_Input = GPT_OSS_120B_Responses | GPT_OSS_120B_Responses_Async; +interface GPT_OSS_120B_Responses { + /** + * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types + */ + input: string | unknown[]; + reasoning?: { + /** + * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. + */ + effort?: "low" | "medium" | "high"; + /** + * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. + */ + summary?: "auto" | "concise" | "detailed"; + }; } +interface GPT_OSS_120B_Responses_Async { + requests: { + /** + * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types + */ + input: string | unknown[]; + reasoning?: { + /** + * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. + */ + effort?: "low" | "medium" | "high"; + /** + * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. + */ + summary?: "auto" | "concise" | "detailed"; + }; + }[]; +} +type Ai_Cf_Openai_Gpt_Oss_120B_Output = {} | (string & NonNullable); +declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_120B { + inputs: Ai_Cf_Openai_Gpt_Oss_120B_Input; + postProcessedOutputs: Ai_Cf_Openai_Gpt_Oss_120B_Output; +} +type Ai_Cf_Openai_Gpt_Oss_20B_Input = GPT_OSS_20B_Responses | GPT_OSS_20B_Responses_Async; +interface GPT_OSS_20B_Responses { + /** + * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types + */ + input: string | unknown[]; + reasoning?: { + /** + * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. + */ + effort?: "low" | "medium" | "high"; + /** + * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. + */ + summary?: "auto" | "concise" | "detailed"; + }; +} +interface GPT_OSS_20B_Responses_Async { + requests: { + /** + * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types + */ + input: string | unknown[]; + reasoning?: { + /** + * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. + */ + effort?: "low" | "medium" | "high"; + /** + * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. + */ + summary?: "auto" | "concise" | "detailed"; + }; + }[]; +} +type Ai_Cf_Openai_Gpt_Oss_20B_Output = {} | (string & NonNullable); declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_20B { - inputs: ResponsesInput; - postProcessedOutputs: ResponsesOutput; + inputs: Ai_Cf_Openai_Gpt_Oss_20B_Input; + postProcessedOutputs: Ai_Cf_Openai_Gpt_Oss_20B_Output; } interface Ai_Cf_Leonardo_Phoenix_1_0_Input { /** @@ -7773,799 +6634,6 @@ declare abstract class Base_Ai_Cf_Deepgram_Aura_1 { inputs: Ai_Cf_Deepgram_Aura_1_Input; postProcessedOutputs: Ai_Cf_Deepgram_Aura_1_Output; } -interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input { - /** - * Input text to translate. Can be a single string or a list of strings. - */ - text: string | string[]; - /** - * Target language to translate to - */ - target_language: "asm_Beng" | "awa_Deva" | "ben_Beng" | "bho_Deva" | "brx_Deva" | "doi_Deva" | "eng_Latn" | "gom_Deva" | "gon_Deva" | "guj_Gujr" | "hin_Deva" | "hne_Deva" | "kan_Knda" | "kas_Arab" | "kas_Deva" | "kha_Latn" | "lus_Latn" | "mag_Deva" | "mai_Deva" | "mal_Mlym" | "mar_Deva" | "mni_Beng" | "mni_Mtei" | "npi_Deva" | "ory_Orya" | "pan_Guru" | "san_Deva" | "sat_Olck" | "snd_Arab" | "snd_Deva" | "tam_Taml" | "tel_Telu" | "urd_Arab" | "unr_Deva"; -} -interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output { - /** - * Translated texts - */ - translations: string[]; -} -declare abstract class Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B { - inputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input; - postProcessedOutputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output; -} -type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input = Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch; -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - /** - * The content of the message as a string. - */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch { - requests: (Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1)[]; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1 { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - /** - * The content of the message as a string. - */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output = Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response | string | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse; -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response { - /** - * Unique identifier for the completion - */ - id?: string; - /** - * Object type identifier - */ - object?: "chat.completion"; - /** - * Unix timestamp of when the completion was created - */ - created?: number; - /** - * Model used for the completion - */ - model?: string; - /** - * List of completion choices - */ - choices?: { - /** - * Index of the choice in the list - */ - index?: number; - /** - * The message generated by the model - */ - message?: { - /** - * Role of the message author - */ - role: string; - /** - * The content of the message - */ - content: string; - /** - * Internal reasoning content (if available) - */ - reasoning_content?: string; - /** - * Tool calls made by the assistant - */ - tool_calls?: { - /** - * Unique identifier for the tool call - */ - id: string; - /** - * Type of tool call - */ - type: "function"; - function: { - /** - * Name of the function to call - */ - name: string; - /** - * JSON string of arguments for the function - */ - arguments: string; - }; - }[]; - }; - /** - * Reason why the model stopped generating - */ - finish_reason?: string; - /** - * Stop reason (may be null) - */ - stop_reason?: string | null; - /** - * Log probabilities (if requested) - */ - logprobs?: {} | null; - }[]; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * Log probabilities for the prompt (if requested) - */ - prompt_logprobs?: {} | null; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response { - /** - * Unique identifier for the completion - */ - id?: string; - /** - * Object type identifier - */ - object?: "text_completion"; - /** - * Unix timestamp of when the completion was created - */ - created?: number; - /** - * Model used for the completion - */ - model?: string; - /** - * List of completion choices - */ - choices?: { - /** - * Index of the choice in the list - */ - index: number; - /** - * The generated text completion - */ - text: string; - /** - * Reason why the model stopped generating - */ - finish_reason: string; - /** - * Stop reason (may be null) - */ - stop_reason?: string | null; - /** - * Log probabilities (if requested) - */ - logprobs?: {} | null; - /** - * Log probabilities for the prompt (if requested) - */ - prompt_logprobs?: {} | null; - }[]; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It { - inputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input; - postProcessedOutputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output; -} -interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Input { - /** - * Input text to embed. Can be a single string or a list of strings. - */ - text: string | string[]; -} -interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Output { - /** - * Embedding vectors, where each vector is a list of floats. - */ - data: number[][]; - /** - * Shape of the embedding data as [number_of_embeddings, embedding_dimension]. - * - * @minItems 2 - * @maxItems 2 - */ - shape: [ - number, - number - ]; -} -declare abstract class Base_Ai_Cf_Pfnet_Plamo_Embedding_1B { - inputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Input; - postProcessedOutputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Output; -} -interface Ai_Cf_Deepgram_Flux_Input { - /** - * Encoding of the audio stream. Currently only supports raw signed little-endian 16-bit PCM. - */ - encoding: "linear16"; - /** - * Sample rate of the audio stream in Hz. - */ - sample_rate: string; - /** - * End-of-turn confidence required to fire an eager end-of-turn event. When set, enables EagerEndOfTurn and TurnResumed events. Valid Values 0.3 - 0.9. - */ - eager_eot_threshold?: string; - /** - * End-of-turn confidence required to finish a turn. Valid Values 0.5 - 0.9. - */ - eot_threshold?: string; - /** - * A turn will be finished when this much time has passed after speech, regardless of EOT confidence. - */ - eot_timeout_ms?: string; - /** - * Keyterm prompting can improve recognition of specialized terminology. Pass multiple keyterm query parameters to boost multiple keyterms. - */ - keyterm?: string; - /** - * Opts out requests from the Deepgram Model Improvement Program. Refer to Deepgram Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip - */ - mip_opt_out?: "true" | "false"; - /** - * Label your requests for the purpose of identification during usage reporting - */ - tag?: string; -} -/** - * Output will be returned as websocket messages. - */ -interface Ai_Cf_Deepgram_Flux_Output { - /** - * The unique identifier of the request (uuid) - */ - request_id?: string; - /** - * Starts at 0 and increments for each message the server sends to the client. - */ - sequence_id?: number; - /** - * The type of event being reported. - */ - event?: "Update" | "StartOfTurn" | "EagerEndOfTurn" | "TurnResumed" | "EndOfTurn"; - /** - * The index of the current turn - */ - turn_index?: number; - /** - * Start time in seconds of the audio range that was transcribed - */ - audio_window_start?: number; - /** - * End time in seconds of the audio range that was transcribed - */ - audio_window_end?: number; - /** - * Text that was said over the course of the current turn - */ - transcript?: string; - /** - * The words in the transcript - */ - words?: { - /** - * The individual punctuated, properly-cased word from the transcript - */ - word: string; - /** - * Confidence that this word was transcribed correctly - */ - confidence: number; - }[]; - /** - * Confidence that no more speech is coming in this turn - */ - end_of_turn_confidence?: number; -} -declare abstract class Base_Ai_Cf_Deepgram_Flux { - inputs: Ai_Cf_Deepgram_Flux_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Flux_Output; -} -interface Ai_Cf_Deepgram_Aura_2_En_Input { - /** - * Speaker used to produce the audio. - */ - speaker?: "amalthea" | "andromeda" | "apollo" | "arcas" | "aries" | "asteria" | "athena" | "atlas" | "aurora" | "callista" | "cora" | "cordelia" | "delia" | "draco" | "electra" | "harmonia" | "helena" | "hera" | "hermes" | "hyperion" | "iris" | "janus" | "juno" | "jupiter" | "luna" | "mars" | "minerva" | "neptune" | "odysseus" | "ophelia" | "orion" | "orpheus" | "pandora" | "phoebe" | "pluto" | "saturn" | "thalia" | "theia" | "vesta" | "zeus"; - /** - * Encoding of the output audio. - */ - encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; - /** - * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. - */ - container?: "none" | "wav" | "ogg"; - /** - * The text content to be converted to speech - */ - text: string; - /** - * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable - */ - sample_rate?: number; - /** - * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. - */ - bit_rate?: number; -} -/** - * The generated audio in MP3 format - */ -type Ai_Cf_Deepgram_Aura_2_En_Output = string; -declare abstract class Base_Ai_Cf_Deepgram_Aura_2_En { - inputs: Ai_Cf_Deepgram_Aura_2_En_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_En_Output; -} -interface Ai_Cf_Deepgram_Aura_2_Es_Input { - /** - * Speaker used to produce the audio. - */ - speaker?: "sirio" | "nestor" | "carina" | "celeste" | "alvaro" | "diana" | "aquila" | "selena" | "estrella" | "javier"; - /** - * Encoding of the output audio. - */ - encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; - /** - * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. - */ - container?: "none" | "wav" | "ogg"; - /** - * The text content to be converted to speech - */ - text: string; - /** - * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable - */ - sample_rate?: number; - /** - * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. - */ - bit_rate?: number; -} -/** - * The generated audio in MP3 format - */ -type Ai_Cf_Deepgram_Aura_2_Es_Output = string; -declare abstract class Base_Ai_Cf_Deepgram_Aura_2_Es { - inputs: Ai_Cf_Deepgram_Aura_2_Es_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_Es_Output; -} interface AiModels { "@cf/huggingface/distilbert-sst-2-int8": BaseAiTextClassification; "@cf/stabilityai/stable-diffusion-xl-base-1.0": BaseAiTextToImage; @@ -8609,12 +6677,12 @@ interface AiModels { "@cf/meta/llama-3-8b-instruct": BaseAiTextGeneration; "@cf/fblgit/una-cybertron-7b-v2-bf16": BaseAiTextGeneration; "@cf/meta/llama-3-8b-instruct-awq": BaseAiTextGeneration; + "@hf/meta-llama/meta-llama-3-8b-instruct": BaseAiTextGeneration; "@cf/meta/llama-3.1-8b-instruct-fp8": BaseAiTextGeneration; "@cf/meta/llama-3.1-8b-instruct-awq": BaseAiTextGeneration; "@cf/meta/llama-3.2-3b-instruct": BaseAiTextGeneration; "@cf/meta/llama-3.2-1b-instruct": BaseAiTextGeneration; "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b": BaseAiTextGeneration; - "@cf/ibm-granite/granite-4.0-h-micro": BaseAiTextGeneration; "@cf/facebook/bart-large-cnn": BaseAiSummarization; "@cf/llava-hf/llava-1.5-7b-hf": BaseAiImageToText; "@cf/baai/bge-base-en-v1.5": Base_Ai_Cf_Baai_Bge_Base_En_V1_5; @@ -8636,21 +6704,13 @@ interface AiModels { "@cf/mistralai/mistral-small-3.1-24b-instruct": Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct; "@cf/google/gemma-3-12b-it": Base_Ai_Cf_Google_Gemma_3_12B_It; "@cf/meta/llama-4-scout-17b-16e-instruct": Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct; - "@cf/qwen/qwen3-30b-a3b-fp8": Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8; "@cf/deepgram/nova-3": Base_Ai_Cf_Deepgram_Nova_3; - "@cf/qwen/qwen3-embedding-0.6b": Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B; "@cf/pipecat-ai/smart-turn-v2": Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2; "@cf/openai/gpt-oss-120b": Base_Ai_Cf_Openai_Gpt_Oss_120B; "@cf/openai/gpt-oss-20b": Base_Ai_Cf_Openai_Gpt_Oss_20B; "@cf/leonardo/phoenix-1.0": Base_Ai_Cf_Leonardo_Phoenix_1_0; "@cf/leonardo/lucid-origin": Base_Ai_Cf_Leonardo_Lucid_Origin; "@cf/deepgram/aura-1": Base_Ai_Cf_Deepgram_Aura_1; - "@cf/ai4bharat/indictrans2-en-indic-1B": Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B; - "@cf/aisingapore/gemma-sea-lion-v4-27b-it": Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It; - "@cf/pfnet/plamo-embedding-1b": Base_Ai_Cf_Pfnet_Plamo_Embedding_1B; - "@cf/deepgram/flux": Base_Ai_Cf_Deepgram_Flux; - "@cf/deepgram/aura-2-en": Base_Ai_Cf_Deepgram_Aura_2_En; - "@cf/deepgram/aura-2-es": Base_Ai_Cf_Deepgram_Aura_2_Es; } type AiOptions = { /** @@ -8662,16 +6722,6 @@ type AiOptions = { * Establish websocket connections, only works for supported models */ websocket?: boolean; - /** - * Tag your requests to group and view them in Cloudflare dashboard. - * - * Rules: - * Tags must only contain letters, numbers, and the symbols: : - . / @ - * Each tag can have maximum 50 characters. - * Maximum 5 tags are allowed each request. - * Duplicate tags will removed. - */ - tags?: string[]; gateway?: GatewayOptions; returnRawResponse?: boolean; prefix?: string; @@ -8710,48 +6760,6 @@ type AiModelListType = Record; declare abstract class Ai { aiGatewayLogId: string | null; gateway(gatewayId: string): AiGateway; - /** - * Access the AI Search API for managing AI-powered search instances. - * - * This is the new API that replaces AutoRAG with better namespace separation: - * - Account-level operations: `list()`, `create()` - * - Instance-level operations: `get(id).search()`, `get(id).chatCompletions()`, `get(id).delete()` - * - * @example - * ```typescript - * // List all AI Search instances - * const instances = await env.AI.aiSearch.list(); - * - * // Search an instance - * const results = await env.AI.aiSearch.get('my-search').search({ - * messages: [{ role: 'user', content: 'What is the policy?' }], - * ai_search_options: { - * retrieval: { max_num_results: 10 } - * } - * }); - * - * // Generate chat completions with AI Search context - * const response = await env.AI.aiSearch.get('my-search').chatCompletions({ - * messages: [{ role: 'user', content: 'What is the policy?' }], - * model: '@cf/meta/llama-3.3-70b-instruct-fp8-fast' - * }); - * ``` - */ - aiSearch(): AiSearchAccountService; - /** - * @deprecated AutoRAG has been replaced by AI Search. - * Use `env.AI.aiSearch` instead for better API design and new features. - * - * Migration guide: - * - `env.AI.autorag().list()` → `env.AI.aiSearch.list()` - * - `env.AI.autorag('id').search({ query: '...' })` → `env.AI.aiSearch.get('id').search({ messages: [{ role: 'user', content: '...' }] })` - * - `env.AI.autorag('id').aiSearch(...)` → `env.AI.aiSearch.get('id').chatCompletions(...)` - * - * Note: The old API continues to work for backwards compatibility, but new projects should use AI Search. - * - * @see AiSearchAccountService - * @param autoragId Optional instance ID (omit for account-level operations) - */ autorag(autoragId: string): AutoRAG; run(model: Name, inputs: InputOptions, options?: Options): Promise; getUrl(provider?: AIGatewayProviders | string): Promise; // eslint-disable-line } -/** - * @deprecated AutoRAG has been replaced by AI Search. Use AiSearchInternalError instead. - * @see AiSearchInternalError - */ interface AutoRAGInternalError extends Error { } -/** - * @deprecated AutoRAG has been replaced by AI Search. Use AiSearchNotFoundError instead. - * @see AiSearchNotFoundError - */ interface AutoRAGNotFoundError extends Error { } -/** - * @deprecated This error type is no longer used in the AI Search API. - */ interface AutoRAGUnauthorizedError extends Error { } -/** - * @deprecated AutoRAG has been replaced by AI Search. Use AiSearchNameNotSetError instead. - * @see AiSearchNameNotSetError - */ interface AutoRAGNameNotSetError extends Error { } type ComparisonFilter = { @@ -8892,11 +6885,6 @@ type CompoundFilter = { type: 'and' | 'or'; filters: ComparisonFilter[]; }; -/** - * @deprecated AutoRAG has been replaced by AI Search. - * Use AiSearchSearchRequest with the new API instead. - * @see AiSearchSearchRequest - */ type AutoRagSearchRequest = { query: string; filters?: CompoundFilter | ComparisonFilter; @@ -8911,28 +6899,13 @@ type AutoRagSearchRequest = { }; rewrite_query?: boolean; }; -/** - * @deprecated AutoRAG has been replaced by AI Search. - * Use AiSearchChatCompletionsRequest with the new API instead. - * @see AiSearchChatCompletionsRequest - */ type AutoRagAiSearchRequest = AutoRagSearchRequest & { stream?: boolean; system_prompt?: string; }; -/** - * @deprecated AutoRAG has been replaced by AI Search. - * Use AiSearchChatCompletionsRequest with stream: true instead. - * @see AiSearchChatCompletionsRequest - */ type AutoRagAiSearchRequestStreaming = Omit & { stream: true; }; -/** - * @deprecated AutoRAG has been replaced by AI Search. - * Use AiSearchSearchResponse with the new API instead. - * @see AiSearchSearchResponse - */ type AutoRagSearchResponse = { object: 'vector_store.search_results.page'; search_query: string; @@ -8949,11 +6922,6 @@ type AutoRagSearchResponse = { has_more: boolean; next_page: string | null; }; -/** - * @deprecated AutoRAG has been replaced by AI Search. - * Use AiSearchListResponse with the new API instead. - * @see AiSearchListResponse - */ type AutoRagListResponse = { id: string; enable: boolean; @@ -8963,51 +6931,14 @@ type AutoRagListResponse = { paused: boolean; status: string; }[]; -/** - * @deprecated AutoRAG has been replaced by AI Search. - * The new API returns different response formats for chat completions. - */ type AutoRagAiSearchResponse = AutoRagSearchResponse & { response: string; }; -/** - * @deprecated AutoRAG has been replaced by AI Search. - * Use the new AI Search API instead: `env.AI.aiSearch` - * - * Migration guide: - * - `env.AI.autorag().list()` → `env.AI.aiSearch.list()` - * - `env.AI.autorag('id').search(...)` → `env.AI.aiSearch.get('id').search(...)` - * - `env.AI.autorag('id').aiSearch(...)` → `env.AI.aiSearch.get('id').chatCompletions(...)` - * - * @see AiSearchAccountService - * @see AiSearchInstanceService - */ declare abstract class AutoRAG { - /** - * @deprecated Use `env.AI.aiSearch.list()` instead. - * @see AiSearchAccountService.list - */ list(): Promise; - /** - * @deprecated Use `env.AI.aiSearch.get(id).search(...)` instead. - * Note: The new API uses a messages array instead of a query string. - * @see AiSearchInstanceService.search - */ search(params: AutoRagSearchRequest): Promise; - /** - * @deprecated Use `env.AI.aiSearch.get(id).chatCompletions(...)` instead. - * @see AiSearchInstanceService.chatCompletions - */ aiSearch(params: AutoRagAiSearchRequestStreaming): Promise; - /** - * @deprecated Use `env.AI.aiSearch.get(id).chatCompletions(...)` instead. - * @see AiSearchInstanceService.chatCompletions - */ aiSearch(params: AutoRagAiSearchRequest): Promise; - /** - * @deprecated Use `env.AI.aiSearch.get(id).chatCompletions(...)` instead. - * @see AiSearchInstanceService.chatCompletions - */ aiSearch(params: AutoRagAiSearchRequest): Promise; } interface BasicImageTransformations { @@ -9758,10 +7689,6 @@ interface D1Meta { * The region of the database instance that executed the query. */ served_by_region?: string; - /** - * The three letters airport code of the colo that executed the query. - */ - served_by_colo?: string; /** * True if-and-only-if the database instance that executed the query was the primary. */ @@ -9850,15 +7777,6 @@ declare abstract class D1PreparedStatement { // ignored when `Disposable` is included in the standard lib. interface Disposable { } -/** - * The returned data after sending an email - */ -interface EmailSendResult { - /** - * The Email Message ID - */ - messageId: string; -} /** * An email message that can be sent from a Worker. */ @@ -9900,55 +7818,24 @@ interface ForwardableEmailMessage extends EmailMessage { * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). * @returns A promise that resolves when the email message is forwarded. */ - forward(rcptTo: string, headers?: Headers): Promise; + forward(rcptTo: string, headers?: Headers): Promise; /** * Reply to the sender of this email message with a new EmailMessage object. * @param message The reply message. * @returns A promise that resolves when the email message is replied. */ - reply(message: EmailMessage): Promise; -} -/** A file attachment for an email message */ -type EmailAttachment = { - disposition: 'inline'; - contentId: string; - filename: string; - type: string; - content: string | ArrayBuffer | ArrayBufferView; -} | { - disposition: 'attachment'; - contentId?: undefined; - filename: string; - type: string; - content: string | ArrayBuffer | ArrayBufferView; -}; -/** An Email Address */ -interface EmailAddress { - name: string; - email: string; + reply(message: EmailMessage): Promise; } /** * A binding that allows a Worker to send email messages. */ interface SendEmail { - send(message: EmailMessage): Promise; - send(builder: { - from: string | EmailAddress; - to: string | string[]; - subject: string; - replyTo?: string | EmailAddress; - cc?: string | string[]; - bcc?: string | string[]; - headers?: Record; - text?: string; - html?: string; - attachments?: EmailAttachment[]; - }): Promise; + send(message: EmailMessage): Promise; } declare abstract class EmailEvent extends ExtendableEvent { readonly message: ForwardableEmailMessage; } -declare type EmailExportedHandler = (message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext) => void | Promise; +declare type EmailExportedHandler = (message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext) => void | Promise; declare module "cloudflare:email" { let _EmailMessage: { prototype: EmailMessage; @@ -9976,7 +7863,7 @@ interface Hyperdrive { /** * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. * - * Calling this method returns an identical socket to if you call + * Calling this method returns an idential socket to if you call * `connect("host:port")` using the `host` and `port` fields from this object. * Pick whichever approach works better with your preferred DB client library. * @@ -10089,83 +7976,6 @@ type ImageOutputOptions = { background?: string; anim?: boolean; }; -interface ImageMetadata { - id: string; - filename?: string; - uploaded?: string; - requireSignedURLs: boolean; - meta?: Record; - variants: string[]; - draft?: boolean; - creator?: string; -} -interface ImageUploadOptions { - id?: string; - filename?: string; - requireSignedURLs?: boolean; - metadata?: Record; - creator?: string; - encoding?: 'base64'; -} -interface ImageUpdateOptions { - requireSignedURLs?: boolean; - metadata?: Record; - creator?: string; -} -interface ImageListOptions { - limit?: number; - cursor?: string; - sortOrder?: 'asc' | 'desc'; - creator?: string; -} -interface ImageList { - images: ImageMetadata[]; - cursor?: string; - listComplete: boolean; -} -interface HostedImagesBinding { - /** - * Get detailed metadata for a hosted image - * @param imageId The ID of the image (UUID or custom ID) - * @returns Image metadata, or null if not found - */ - details(imageId: string): Promise; - /** - * Get the raw image data for a hosted image - * @param imageId The ID of the image (UUID or custom ID) - * @returns ReadableStream of image bytes, or null if not found - */ - image(imageId: string): Promise | null>; - /** - * Upload a new hosted image - * @param image The image file to upload - * @param options Upload configuration - * @returns Metadata for the uploaded image - * @throws {@link ImagesError} if upload fails - */ - upload(image: ReadableStream | ArrayBuffer, options?: ImageUploadOptions): Promise; - /** - * Update hosted image metadata - * @param imageId The ID of the image - * @param options Properties to update - * @returns Updated image metadata - * @throws {@link ImagesError} if update fails - */ - update(imageId: string, options: ImageUpdateOptions): Promise; - /** - * Delete a hosted image - * @param imageId The ID of the image - * @returns True if deleted, false if not found - */ - delete(imageId: string): Promise; - /** - * List hosted images with pagination - * @param options List configuration - * @returns List of images with pagination info - * @throws {@link ImagesError} if list fails - */ - list(options?: ImageListOptions): Promise; -} interface ImagesBinding { /** * Get image metadata (type, width and height) @@ -10179,10 +7989,6 @@ interface ImagesBinding { * @returns A transform handle */ input(stream: ReadableStream, options?: ImageInputOptions): ImageTransformer; - /** - * Access hosted images CRUD operations - */ - readonly hosted: HostedImagesBinding; } interface ImageTransformer { /** @@ -10249,13 +8055,7 @@ interface MediaTransformer { * @param transform - Configuration for how the media should be transformed * @returns A generator for producing the transformed media output */ - transform(transform?: MediaTransformationInputOptions): MediaTransformationGenerator; - /** - * Generates the final media output with specified options. - * @param output - Configuration for the output format and parameters - * @returns The final transformation result containing the transformed media - */ - output(output?: MediaTransformationOutputOptions): MediaTransformationResult; + transform(transform: MediaTransformationInputOptions): MediaTransformationGenerator; } /** * Generator for producing media transformation results. @@ -10267,7 +8067,7 @@ interface MediaTransformationGenerator { * @param output - Configuration for the output format and parameters * @returns The final transformation result containing the transformed media */ - output(output?: MediaTransformationOutputOptions): MediaTransformationResult; + output(output: MediaTransformationOutputOptions): MediaTransformationResult; } /** * Result of a media transformation operation. @@ -10276,19 +8076,19 @@ interface MediaTransformationGenerator { interface MediaTransformationResult { /** * Returns the transformed media as a readable stream of bytes. - * @returns A promise containing a readable stream with the transformed media + * @returns A stream containing the transformed media data */ - media(): Promise>; + media(): ReadableStream; /** * Returns the transformed media as an HTTP response object. - * @returns The transformed media as a Promise, ready to store in cache or return to users + * @returns The transformed media as a Response, ready to store in cache or return to users */ - response(): Promise; + response(): Response; /** * Returns the MIME type of the transformed media. - * @returns A promise containing the content type string (e.g., 'image/jpeg', 'video/mp4') + * @returns The content type string (e.g., 'image/jpeg', 'video/mp4') */ - contentType(): Promise; + contentType(): string; } /** * Configuration options for transforming media input. @@ -10396,7 +8196,7 @@ declare module "cloudflare:pipelines" { protected ctx: ExecutionContext; constructor(ctx: ExecutionContext, env: Env); /** - * run receives an array of PipelineRecord which can be + * run recieves an array of PipelineRecord which can be * transformed and returned to the pipeline * @param records Incoming records from the pipeline to be transformed * @param metadata Information about the specific pipeline calling the transformation entrypoint @@ -10562,9 +8362,9 @@ declare namespace Rpc { // Base type for all other types providing RPC-like interfaces. // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. - export type Provider = MaybeCallableProvider & Pick<{ - [K in keyof T]: MethodOrProperty; - }, Exclude>>; + export type Provider = MaybeCallableProvider & { + [K in Exclude>]: MethodOrProperty; + }; } declare namespace Cloudflare { // Type of `env`. @@ -10667,12 +8467,9 @@ declare namespace CloudflareWorkersModule { timestamp: Date; type: string; }; - export type WorkflowStepContext = { - attempt: number; - }; export abstract class WorkflowStep { - do>(name: string, callback: (ctx: WorkflowStepContext) => Promise): Promise; - do>(name: string, config: WorkflowStepConfig, callback: (ctx: WorkflowStepContext) => Promise): Promise; + do>(name: string, callback: () => Promise): Promise; + do>(name: string, config: WorkflowStepConfig, callback: () => Promise): Promise; sleep: (name: string, duration: WorkflowSleepDuration) => Promise; sleepUntil: (name: string, timestamp: Date | number) => Promise; waitForEvent>(name: string, options: { @@ -10680,7 +8477,6 @@ declare namespace CloudflareWorkersModule { timeout?: WorkflowTimeoutDuration | number; }): Promise>; } - export type WorkflowInstanceStatus = 'queued' | 'running' | 'paused' | 'errored' | 'terminated' | 'complete' | 'waiting' | 'waitingForPause' | 'unknown'; export abstract class WorkflowEntrypoint | unknown = unknown> implements Rpc.WorkflowEntrypointBranded { [Rpc.__WORKFLOW_ENTRYPOINT_BRAND]: never; protected ctx: ExecutionContext; @@ -10689,11 +8485,7 @@ declare namespace CloudflareWorkersModule { run(event: Readonly>, step: WorkflowStep): Promise; } export function waitUntil(promise: Promise): void; - export function withEnv(newEnv: unknown, fn: () => unknown): unknown; - export function withExports(newExports: unknown, fn: () => unknown): unknown; - export function withEnvAndExports(newEnv: unknown, newExports: unknown, fn: () => unknown): unknown; export const env: Cloudflare.Env; - export const exports: Cloudflare.Exports; } declare module 'cloudflare:workers' { export = CloudflareWorkersModule; @@ -10709,765 +8501,17 @@ declare module "cloudflare:sockets" { function _connect(address: string | SocketAddress, options?: SocketOptions): Socket; export { _connect as connect }; } -/** - * Binding entrypoint for Cloudflare Stream. - * - * Usage: - * - Binding-level operations: - * `await env.STREAM.videos.upload` - * `await env.STREAM.videos.createDirectUpload` - * `await env.STREAM.videos.*` - * `await env.STREAM.watermarks.*` - * - Per-video operations: - * `await env.STREAM.video(id).downloads.*` - * `await env.STREAM.video(id).captions.*` - * - * Example usage: - * ```ts - * await env.STREAM.video(id).downloads.generate(); - * - * const video = env.STREAM.video(id) - * const captions = video.captions.list(); - * const videoDetails = video.details() - * ``` - */ -interface StreamBinding { - /** - * Returns a handle scoped to a single video for per-video operations. - * @param id The unique identifier for the video. - * @returns A handle for per-video operations. - */ - video(id: string): StreamVideoHandle; - /** - * Uploads a new video from a File. - * @param file The video file to upload. - * @returns The uploaded video details. - * @throws {BadRequestError} if the upload parameter is invalid - * @throws {QuotaReachedError} if the account storage capacity is exceeded - * @throws {MaxFileSizeError} if the file size is too large - * @throws {RateLimitedError} if the server received too many requests - * @throws {InternalError} if an unexpected error occurs - */ - upload(file: File): Promise; - /** - * Uploads a new video from a provided URL. - * @param url The URL to upload from. - * @param params Optional upload parameters. - * @returns The uploaded video details. - * @throws {BadRequestError} if the upload parameter is invalid or the URL is invalid - * @throws {QuotaReachedError} if the account storage capacity is exceeded - * @throws {MaxFileSizeError} if the file size is too large - * @throws {RateLimitedError} if the server received too many requests - * @throws {AlreadyUploadedError} if a video was already uploaded to this URL - * @throws {InternalError} if an unexpected error occurs - */ - upload(url: string, params?: StreamUrlUploadParams): Promise; - /** - * Creates a direct upload that allows video uploads without an API key. - * @param params Parameters for the direct upload - * @returns The direct upload details. - * @throws {BadRequestError} if the parameters are invalid - * @throws {RateLimitedError} if the server received too many requests - * @throws {InternalError} if an unexpected error occurs - */ - createDirectUpload(params: StreamDirectUploadCreateParams): Promise; - videos: StreamVideos; - watermarks: StreamWatermarks; -} -/** - * Handle for operations scoped to a single Stream video. - */ -interface StreamVideoHandle { - /** - * The unique identifier for the video. - */ - id: string; - /** - * Get a full videos details - * @returns The full video details. - * @throws {NotFoundError} if the video is not found - * @throws {InternalError} if an unexpected error occurs - */ - details(): Promise; - /** - * Update details for a single video. - * @param params The fields to update for the video. - * @returns The updated video details. - * @throws {NotFoundError} if the video is not found - * @throws {BadRequestError} if the parameters are invalid - * @throws {InternalError} if an unexpected error occurs - */ - update(params: StreamUpdateVideoParams): Promise; - /** - * Deletes a video and its copies from Cloudflare Stream. - * @returns A promise that resolves when deletion completes. - * @throws {NotFoundError} if the video is not found - * @throws {InternalError} if an unexpected error occurs - */ - delete(): Promise; - /** - * Creates a signed URL token for a video. - * @returns The signed token that was created. - * @throws {InternalError} if the signing key cannot be retrieved or the token cannot be signed - */ - generateToken(): Promise; - downloads: StreamScopedDownloads; - captions: StreamScopedCaptions; -} -interface StreamVideo { - /** - * The unique identifier for the video. - */ - id: string; - /** - * A user-defined identifier for the media creator. - */ - creator: string | null; - /** - * The thumbnail URL for the video. - */ - thumbnail: string; - /** - * The thumbnail timestamp percentage. - */ - thumbnailTimestampPct: number; - /** - * Indicates whether the video is ready to stream. - */ - readyToStream: boolean; - /** - * The date and time the video became ready to stream. - */ - readyToStreamAt: string | null; - /** - * Processing status information. - */ - status: StreamVideoStatus; - /** - * A user modifiable key-value store. - */ - meta: Record; - /** - * The date and time the video was created. - */ - created: string; - /** - * The date and time the video was last modified. - */ - modified: string; - /** - * The date and time at which the video will be deleted. - */ - scheduledDeletion: string | null; - /** - * The size of the video in bytes. - */ - size: number; - /** - * The preview URL for the video. - */ - preview?: string; - /** - * Origins allowed to display the video. - */ - allowedOrigins: Array; - /** - * Indicates whether signed URLs are required. - */ - requireSignedURLs: boolean | null; - /** - * The date and time the video was uploaded. - */ - uploaded: string | null; - /** - * The date and time when the upload URL expires. - */ - uploadExpiry: string | null; - /** - * The maximum size in bytes for direct uploads. - */ - maxSizeBytes: number | null; - /** - * The maximum duration in seconds for direct uploads. - */ - maxDurationSeconds: number | null; - /** - * The video duration in seconds. -1 indicates unknown. - */ - duration: number; - /** - * Input metadata for the original upload. - */ - input: StreamVideoInput; - /** - * Playback URLs for the video. - */ - hlsPlaybackUrl: string; - dashPlaybackUrl: string; - /** - * The watermark applied to the video, if any. - */ - watermark: StreamWatermark | null; - /** - * The live input id associated with the video, if any. - */ - liveInputId?: string | null; - /** - * The source video id if this is a clip. - */ - clippedFromId: string | null; - /** - * Public details associated with the video. - */ - publicDetails: StreamPublicDetails | null; -} -type StreamVideoStatus = { - /** - * The current processing state. - */ - state: string; - /** - * The current processing step. - */ - step?: string; - /** - * The percent complete as a string. - */ - pctComplete?: string; - /** - * An error reason code, if applicable. - */ - errorReasonCode: string; - /** - * An error reason text, if applicable. - */ - errorReasonText: string; -}; -type StreamVideoInput = { - /** - * The input width in pixels. - */ - width: number; - /** - * The input height in pixels. - */ - height: number; -}; -type StreamPublicDetails = { - /** - * The public title for the video. - */ - title: string | null; - /** - * The public share link. - */ - share_link: string | null; - /** - * The public channel link. - */ - channel_link: string | null; - /** - * The public logo URL. - */ - logo: string | null; -}; -type StreamDirectUpload = { - /** - * The URL an unauthenticated upload can use for a single multipart request. - */ - uploadURL: string; - /** - * A Cloudflare-generated unique identifier for a media item. - */ - id: string; - /** - * The watermark profile applied to the upload. - */ - watermark: StreamWatermark | null; - /** - * The scheduled deletion time, if any. - */ - scheduledDeletion: string | null; -}; -type StreamDirectUploadCreateParams = { - /** - * The maximum duration in seconds for a video upload. - */ - maxDurationSeconds: number; - /** - * The date and time after upload when videos will not be accepted. - */ - expiry?: string; - /** - * A user-defined identifier for the media creator. - */ - creator?: string; - /** - * A user modifiable key-value store used to reference other systems of record for - * managing videos. - */ - meta?: Record; - /** - * Lists the origins allowed to display the video. - */ - allowedOrigins?: Array; - /** - * Indicates whether the video can be accessed using the id. When set to `true`, - * a signed token must be generated with a signing key to view the video. - */ - requireSignedURLs?: boolean; - /** - * The thumbnail timestamp percentage. - */ - thumbnailTimestampPct?: number; - /** - * The date and time at which the video will be deleted. Include `null` to remove - * a scheduled deletion. - */ - scheduledDeletion?: string | null; - /** - * The watermark profile to apply. - */ - watermark?: StreamDirectUploadWatermark; -}; -type StreamDirectUploadWatermark = { - /** - * The unique identifier for the watermark profile. - */ - id: string; -}; -type StreamUrlUploadParams = { - /** - * Lists the origins allowed to display the video. Enter allowed origin - * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the - * video to be viewed on any origin. - */ - allowedOrigins?: Array; - /** - * A user-defined identifier for the media creator. - */ - creator?: string; - /** - * A user modifiable key-value store used to reference other systems of - * record for managing videos. - */ - meta?: Record; - /** - * Indicates whether the video can be a accessed using the id. When - * set to `true`, a signed token must be generated with a signing key to view the - * video. - */ - requireSignedURLs?: boolean; - /** - * Indicates the date and time at which the video will be deleted. Omit - * the field to indicate no change, or include with a `null` value to remove an - * existing scheduled deletion. If specified, must be at least 30 days from upload - * time. - */ - scheduledDeletion?: string | null; - /** - * The timestamp for a thumbnail image calculated as a percentage value - * of the video's duration. To convert from a second-wise timestamp to a - * percentage, divide the desired timestamp by the total duration of the video. If - * this value is not set, the default thumbnail image is taken from 0s of the - * video. - */ - thumbnailTimestampPct?: number; - /** - * The identifier for the watermark profile - */ - watermarkId?: string; -}; -interface StreamScopedCaptions { - /** - * Uploads the caption or subtitle file to the endpoint for a specific BCP47 language. - * One caption or subtitle file per language is allowed. - * @param language The BCP 47 language tag for the caption or subtitle. - * @param file The caption or subtitle file to upload. - * @returns The created caption entry. - * @throws {NotFoundError} if the video is not found - * @throws {BadRequestError} if the language or file is invalid - * @throws {MaxFileSizeError} if the file size is too large - * @throws {InternalError} if an unexpected error occurs - */ - upload(language: string, file: File): Promise; - /** - * Generate captions or subtitles for the provided language via AI. - * @param language The BCP 47 language tag to generate. - * @returns The generated caption entry. - * @throws {NotFoundError} if the video is not found - * @throws {BadRequestError} if the language is invalid - * @throws {StreamError} if a generated caption already exists - * @throws {StreamError} if the video duration is too long - * @throws {StreamError} if the video is missing audio - * @throws {StreamError} if the requested language is not supported - * @throws {InternalError} if an unexpected error occurs - */ - generate(language: string): Promise; - /** - * Lists the captions or subtitles. - * Use the language parameter to filter by a specific language. - * @param language The optional BCP 47 language tag to filter by. - * @returns The list of captions or subtitles. - * @throws {NotFoundError} if the video or caption is not found - * @throws {InternalError} if an unexpected error occurs - */ - list(language?: string): Promise; - /** - * Removes the captions or subtitles from a video. - * @param language The BCP 47 language tag to remove. - * @returns A promise that resolves when deletion completes. - * @throws {NotFoundError} if the video or caption is not found - * @throws {InternalError} if an unexpected error occurs - */ - delete(language: string): Promise; -} -interface StreamScopedDownloads { - /** - * Generates a download for a video when a video is ready to view. Available - * types are `default` and `audio`. Defaults to `default` when omitted. - * @param downloadType The download type to create. - * @returns The current downloads for the video. - * @throws {NotFoundError} if the video is not found - * @throws {BadRequestError} if the download type is invalid - * @throws {StreamError} if the video duration is too long to generate a download - * @throws {StreamError} if the video is not ready to stream - * @throws {InternalError} if an unexpected error occurs - */ - generate(downloadType?: StreamDownloadType): Promise; - /** - * Lists the downloads created for a video. - * @returns The current downloads for the video. - * @throws {NotFoundError} if the video or downloads are not found - * @throws {InternalError} if an unexpected error occurs - */ - get(): Promise; - /** - * Delete the downloads for a video. Available types are `default` and `audio`. - * Defaults to `default` when omitted. - * @param downloadType The download type to delete. - * @returns A promise that resolves when deletion completes. - * @throws {NotFoundError} if the video or downloads are not found - * @throws {InternalError} if an unexpected error occurs - */ - delete(downloadType?: StreamDownloadType): Promise; -} -interface StreamVideos { - /** - * Lists all videos in a users account. - * @returns The list of videos. - * @throws {BadRequestError} if the parameters are invalid - * @throws {InternalError} if an unexpected error occurs - */ - list(params?: StreamVideosListParams): Promise; -} -interface StreamWatermarks { - /** - * Generate a new watermark profile - * @param file The image file to upload - * @param params The watermark creation parameters. - * @returns The created watermark profile. - * @throws {BadRequestError} if the parameters are invalid - * @throws {InvalidURLError} if the URL is invalid - * @throws {MaxFileSizeError} if the file size is too large - * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached - * @throws {InternalError} if an unexpected error occurs - */ - generate(file: File, params: StreamWatermarkCreateParams): Promise; - /** - * Generate a new watermark profile - * @param url The image url to upload - * @param params The watermark creation parameters. - * @returns The created watermark profile. - * @throws {BadRequestError} if the parameters are invalid - * @throws {InvalidURLError} if the URL is invalid - * @throws {MaxFileSizeError} if the file size is too large - * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached - * @throws {InternalError} if an unexpected error occurs - */ - generate(url: string, params: StreamWatermarkCreateParams): Promise; - /** - * Lists all watermark profiles for an account. - * @returns The list of watermark profiles. - * @throws {InternalError} if an unexpected error occurs - */ - list(): Promise; - /** - * Retrieves details for a single watermark profile. - * @param watermarkId The watermark profile identifier. - * @returns The watermark profile details. - * @throws {NotFoundError} if the watermark is not found - * @throws {InternalError} if an unexpected error occurs - */ - get(watermarkId: string): Promise; - /** - * Deletes a watermark profile. - * @param watermarkId The watermark profile identifier. - * @returns A promise that resolves when deletion completes. - * @throws {NotFoundError} if the watermark is not found - * @throws {InternalError} if an unexpected error occurs - */ - delete(watermarkId: string): Promise; -} -type StreamUpdateVideoParams = { - /** - * Lists the origins allowed to display the video. Enter allowed origin - * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the - * video to be viewed on any origin. - */ - allowedOrigins?: Array; - /** - * A user-defined identifier for the media creator. - */ - creator?: string; - /** - * The maximum duration in seconds for a video upload. Can be set for a - * video that is not yet uploaded to limit its duration. Uploads that exceed the - * specified duration will fail during processing. A value of `-1` means the value - * is unknown. - */ - maxDurationSeconds?: number; - /** - * A user modifiable key-value store used to reference other systems of - * record for managing videos. - */ - meta?: Record; - /** - * Indicates whether the video can be a accessed using the id. When - * set to `true`, a signed token must be generated with a signing key to view the - * video. - */ - requireSignedURLs?: boolean; - /** - * Indicates the date and time at which the video will be deleted. Omit - * the field to indicate no change, or include with a `null` value to remove an - * existing scheduled deletion. If specified, must be at least 30 days from upload - * time. - */ - scheduledDeletion?: string | null; - /** - * The timestamp for a thumbnail image calculated as a percentage value - * of the video's duration. To convert from a second-wise timestamp to a - * percentage, divide the desired timestamp by the total duration of the video. If - * this value is not set, the default thumbnail image is taken from 0s of the - * video. - */ - thumbnailTimestampPct?: number; -}; -type StreamCaption = { - /** - * Whether the caption was generated via AI. - */ - generated?: boolean; - /** - * The language label displayed in the native language to users. - */ - label: string; - /** - * The language tag in BCP 47 format. - */ - language: string; - /** - * The status of a generated caption. - */ - status?: 'ready' | 'inprogress' | 'error'; -}; -type StreamDownloadStatus = 'ready' | 'inprogress' | 'error'; -type StreamDownloadType = 'default' | 'audio'; -type StreamDownload = { - /** - * Indicates the progress as a percentage between 0 and 100. - */ - percentComplete: number; - /** - * The status of a generated download. - */ - status: StreamDownloadStatus; - /** - * The URL to access the generated download. - */ - url?: string; -}; -/** - * An object with download type keys. Each key is optional and only present if that - * download type has been created. - */ -type StreamDownloadGetResponse = { - /** - * The audio-only download. Only present if this download type has been created. - */ - audio?: StreamDownload; - /** - * The default video download. Only present if this download type has been created. - */ - default?: StreamDownload; -}; -type StreamWatermarkPosition = 'upperRight' | 'upperLeft' | 'lowerLeft' | 'lowerRight' | 'center'; -type StreamWatermark = { - /** - * The unique identifier for a watermark profile. - */ - id: string; - /** - * The size of the image in bytes. - */ - size: number; - /** - * The height of the image in pixels. - */ - height: number; - /** - * The width of the image in pixels. - */ - width: number; - /** - * The date and a time a watermark profile was created. - */ - created: string; - /** - * The source URL for a downloaded image. If the watermark profile was created via - * direct upload, this field is null. - */ - downloadedFrom: string | null; - /** - * A short description of the watermark profile. - */ - name: string; - /** - * The translucency of the image. A value of `0.0` makes the image completely - * transparent, and `1.0` makes the image completely opaque. Note that if the image - * is already semi-transparent, setting this to `1.0` will not make the image - * completely opaque. - */ - opacity: number; - /** - * The whitespace between the adjacent edges (determined by position) of the video - * and the image. `0.0` indicates no padding, and `1.0` indicates a fully padded - * video width or length, as determined by the algorithm. - */ - padding: number; - /** - * The size of the image relative to the overall size of the video. This parameter - * will adapt to horizontal and vertical videos automatically. `0.0` indicates no - * scaling (use the size of the image as-is), and `1.0 `fills the entire video. - */ - scale: number; - /** - * The location of the image. Valid positions are: `upperRight`, `upperLeft`, - * `lowerLeft`, `lowerRight`, and `center`. Note that `center` ignores the - * `padding` parameter. - */ - position: StreamWatermarkPosition; -}; -type StreamWatermarkCreateParams = { - /** - * A short description of the watermark profile. - */ - name?: string; - /** - * The translucency of the image. A value of `0.0` makes the image completely - * transparent, and `1.0` makes the image completely opaque. Note that if the - * image is already semi-transparent, setting this to `1.0` will not make the - * image completely opaque. - */ - opacity?: number; - /** - * The whitespace between the adjacent edges (determined by position) of the - * video and the image. `0.0` indicates no padding, and `1.0` indicates a fully - * padded video width or length, as determined by the algorithm. - */ - padding?: number; - /** - * The size of the image relative to the overall size of the video. This - * parameter will adapt to horizontal and vertical videos automatically. `0.0` - * indicates no scaling (use the size of the image as-is), and `1.0 `fills the - * entire video. - */ - scale?: number; - /** - * The location of the image. - */ - position?: StreamWatermarkPosition; -}; -type StreamVideosListParams = { - /** - * The maximum number of videos to return. - */ - limit?: number; - /** - * Return videos created before this timestamp. - * (RFC3339/RFC3339Nano) - */ - before?: string; - /** - * Comparison operator for the `before` field. - * @default 'lt' - */ - beforeComp?: StreamPaginationComparison; - /** - * Return videos created after this timestamp. - * (RFC3339/RFC3339Nano) - */ - after?: string; - /** - * Comparison operator for the `after` field. - * @default 'gte' - */ - afterComp?: StreamPaginationComparison; -}; -type StreamPaginationComparison = 'eq' | 'gt' | 'gte' | 'lt' | 'lte'; -/** - * Error object for Stream binding operations. - */ -interface StreamError extends Error { - readonly code: number; - readonly statusCode: number; - readonly message: string; - readonly stack?: string; -} -interface InternalError extends StreamError { - name: 'InternalError'; -} -interface BadRequestError extends StreamError { - name: 'BadRequestError'; -} -interface NotFoundError extends StreamError { - name: 'NotFoundError'; -} -interface ForbiddenError extends StreamError { - name: 'ForbiddenError'; -} -interface RateLimitedError extends StreamError { - name: 'RateLimitedError'; -} -interface QuotaReachedError extends StreamError { - name: 'QuotaReachedError'; -} -interface MaxFileSizeError extends StreamError { - name: 'MaxFileSizeError'; -} -interface InvalidURLError extends StreamError { - name: 'InvalidURLError'; -} -interface AlreadyUploadedError extends StreamError { - name: 'AlreadyUploadedError'; -} -interface TooManyWatermarksError extends StreamError { - name: 'TooManyWatermarksError'; -} type MarkdownDocument = { name: string; blob: Blob; }; type ConversionResponse = { - id: string; name: string; mimeType: string; format: 'markdown'; tokens: number; data: string; } | { - id: string; name: string; mimeType: string; format: 'error'; @@ -11485,8 +8529,6 @@ type ConversionOptions = { images?: EmbeddedImageConversionOptions & { convertOGImage?: boolean; }; - hostname?: string; - cssSelector?: string; }; docx?: { images?: EmbeddedImageConversionOptions; @@ -11624,15 +8666,6 @@ declare namespace TailStream { readonly level: "debug" | "error" | "info" | "log" | "warn"; readonly message: object; } - interface DroppedEventsDiagnostic { - readonly diagnosticsType: "droppedEvents"; - readonly count: number; - } - interface StreamDiagnostic { - readonly type: 'streamDiagnostic'; - // To add new diagnostic types, define a new interface and add it to this union type. - readonly diagnostic: DroppedEventsDiagnostic; - } // This marks the worker handler return information. // This is separate from Outcome because the worker invocation can live for a long time after // returning. For example - Websockets that return an http upgrade response but then continue @@ -11649,7 +8682,7 @@ declare namespace TailStream { readonly type: "attributes"; readonly info: Attribute[]; } - type EventType = Onset | Outcome | SpanOpen | SpanClose | DiagnosticChannelEvent | Exception | Log | StreamDiagnostic | Return | Attributes; + type EventType = Onset | Outcome | SpanOpen | SpanClose | DiagnosticChannelEvent | Exception | Log | Return | Attributes; // Context in which this trace event lives. interface SpanContext { // Single id for the entire top-level invocation @@ -11663,7 +8696,7 @@ declare namespace TailStream { // For Hibernate and Mark this would be the span under which they were emitted. // spanId is not set ONLY if: // 1. This is an Onset event - // 2. We are not inheriting any SpanContext. (e.g. this is a cross-account service binding or a new top-level invocation) + // 2. We are not inherting any SpanContext. (e.g. this is a cross-account service binding or a new top-level invocation) readonly spanId?: string; } interface TailEvent { @@ -12029,11 +9062,8 @@ type InstanceStatus = { | 'complete' | 'waiting' // instance is hibernating and waiting for sleep or event to finish | 'waitingForPause' // instance is finishing the current work to pause | 'unknown'; - error?: { - name: string; - message: string; - }; - output?: unknown; + error?: string; + output?: object; }; interface WorkflowError { code?: number; diff --git a/e2e/react-start/basic-react-query/.devcontainer/devcontainer.json b/e2e/react-start/basic-react-query/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/react-start/basic-react-query/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/react-start/basic-react-query/package.json b/e2e/react-start/basic-react-query/package.json index ee37b82ba6..2fce084cc9 100644 --- a/e2e/react-start/basic-react-query/package.json +++ b/e2e/react-start/basic-react-query/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-query": "^5.90.0", @@ -20,22 +20,22 @@ "@tanstack/react-start": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "catalog:", - "tailwind-merge": "^3.6.0", - "zod": "^4.4.3" + "redaxios": "^0.5.1", + "tailwind-merge": "^2.6.0", + "vite": "^7.3.1", + "zod": "^4.1.12" }, "devDependencies": { - "@playwright/test": "^1.61.0", - "@tailwindcss/vite": "^4.2.2", + "@playwright/test": "^1.50.1", + "@tailwindcss/vite": "^4.1.18", "@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", - "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.3.4", + "srvx": "^0.11.2", + "tailwindcss": "^4.1.18", + "typescript": "^5.7.2", + "vite-tsconfig-paths": "^5.1.4" } } diff --git a/e2e/react-start/basic-react-query/playwright.config.ts b/e2e/react-start/basic-react-query/playwright.config.ts index 216fade4d5..fd2150e435 100644 --- a/e2e/react-start/basic-react-query/playwright.config.ts +++ b/e2e/react-start/basic-react-query/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,19 +18,19 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', - env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, - }, }, projects: [ diff --git a/e2e/react-start/basic-react-query/src/components/DefaultCatchBoundary.tsx b/e2e/react-start/basic-react-query/src/components/DefaultCatchBoundary.tsx index 405fb5f4a7..ef2daa1ea1 100644 --- a/e2e/react-start/basic-react-query/src/components/DefaultCatchBoundary.tsx +++ b/e2e/react-start/basic-react-query/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/react-router' import type { ErrorComponentProps } from '@tanstack/react-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) console.error(error) diff --git a/e2e/react-start/basic-react-query/src/routeTree.gen.ts b/e2e/react-start/basic-react-query/src/routeTree.gen.ts index 72bd9579f6..c140825485 100644 --- a/e2e/react-start/basic-react-query/src/routeTree.gen.ts +++ b/e2e/react-start/basic-react-query/src/routeTree.gen.ts @@ -9,47 +9,28 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as LayoutRouteImport } from './routes/_layout' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as RedirectRouteImport } from './routes/redirect' -import { Route as SuspenseTransitionRouteImport } from './routes/suspense-transition' 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 PostsIndexRouteImport } from './routes/posts.index' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as SuspenseTransitionRouteImport } from './routes/suspense-transition' +import { Route as RedirectRouteImport } from './routes/redirect' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as IndexRouteImport } from './routes/index' import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' -import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as ApiUsersRouteImport } from './routes/api.users' +import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' import { Route as TransitionCountQueryRouteImport } from './routes/transition/count/query' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' +import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const SuspenseTransitionRoute = SuspenseTransitionRouteImport.update({ @@ -57,64 +38,83 @@ const SuspenseTransitionRoute = SuspenseTransitionRouteImport.update({ path: '/suspense-transition', getParentRoute: () => rootRouteImport, } as any) -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', getParentRoute: () => rootRouteImport, } as any) -const LayoutLayout2Route = LayoutLayout2RouteImport.update({ - id: '/_layout-2', - getParentRoute: () => LayoutRoute, -} as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => PostsRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, + getParentRoute: () => rootRouteImport, } as any) const UsersIndexRoute = UsersIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => UsersRoute, } as any) +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) const UsersUserIdRoute = UsersUserIdRouteImport.update({ id: '/$userId', path: '/$userId', getParentRoute: () => UsersRoute, } as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, } as any) -const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ - id: '/layout-b', - path: '/layout-b', - getParentRoute: () => LayoutLayout2Route, +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', + getParentRoute: () => rootRouteImport, } as any) -const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => ApiUsersRoute, +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, +} as any) +const TransitionCountQueryRoute = TransitionCountQueryRouteImport.update({ + id: '/transition/count/query', + path: '/transition/count/query', + getParentRoute: () => rootRouteImport, } as any) const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ id: '/posts_/$postId/deep', path: '/posts/$postId/deep', getParentRoute: () => rootRouteImport, } as any) -const TransitionCountQueryRoute = TransitionCountQueryRouteImport.update({ - id: '/transition/count/query', - path: '/transition/count/query', - getParentRoute: () => rootRouteImport, +const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => ApiUsersRoute, +} as any) +const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ + id: '/layout-b', + path: '/layout-b', + getParentRoute: () => LayoutLayout2Route, +} as any) +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, } as any) export interface FileRoutesByFullPath { @@ -244,39 +244,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout': { - id: '/_layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/suspense-transition': { @@ -286,40 +258,40 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof SuspenseTransitionRouteImport parentRoute: typeof rootRouteImport } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport parentRoute: typeof rootRouteImport } - '/_layout/_layout-2': { - id: '/_layout/_layout-2' + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout': { + id: '/_layout' path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute - } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + fullPath: '' + preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' + '/': { + id: '/' path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/users/': { id: '/users/' @@ -328,6 +300,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof UsersIndexRouteImport parentRoute: typeof UsersRoute } + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute + } '/users/$userId': { id: '/users/$userId' path: '/$userId' @@ -335,26 +314,33 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof UsersUserIdRouteImport parentRoute: typeof UsersRoute } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute } - '/_layout/_layout-2/layout-b': { - id: '/_layout/_layout-2/layout-b' - path: '/layout-b' - fullPath: '/layout-b' - preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport - parentRoute: typeof LayoutLayout2Route + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport + parentRoute: typeof rootRouteImport } - '/api/users/$id': { - id: '/api/users/$id' - path: '/$id' - fullPath: '/api/users/$id' - preLoaderRoute: typeof ApiUsersIdRouteImport - parentRoute: typeof ApiUsersRoute + '/_layout/_layout-2': { + id: '/_layout/_layout-2' + path: '' + fullPath: '' + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute + } + '/transition/count/query': { + id: '/transition/count/query' + path: '/transition/count/query' + fullPath: '/transition/count/query' + preLoaderRoute: typeof TransitionCountQueryRouteImport + parentRoute: typeof rootRouteImport } '/posts_/$postId/deep': { id: '/posts_/$postId/deep' @@ -363,12 +349,26 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsPostIdDeepRouteImport parentRoute: typeof rootRouteImport } - '/transition/count/query': { - id: '/transition/count/query' - path: '/transition/count/query' - fullPath: '/transition/count/query' - preLoaderRoute: typeof TransitionCountQueryRouteImport - parentRoute: typeof rootRouteImport + '/api/users/$id': { + id: '/api/users/$id' + path: '/$id' + fullPath: '/api/users/$id' + preLoaderRoute: typeof ApiUsersIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/_layout/_layout-2/layout-b': { + id: '/_layout/_layout-2/layout-b' + path: '/layout-b' + fullPath: '/layout-b' + preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport + parentRoute: typeof LayoutLayout2Route + } + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route } } } diff --git a/e2e/react-start/basic-react-query/src/routes/api.users.ts b/e2e/react-start/basic-react-query/src/routes/api.users.ts index 924c5b6860..bb37c6e68d 100644 --- a/e2e/react-start/basic-react-query/src/routes/api.users.ts +++ b/e2e/react-start/basic-react-query/src/routes/api.users.ts @@ -2,7 +2,11 @@ import { createFileRoute } from '@tanstack/react-router' import axios from 'redaxios' import type { User } from '../utils/users' -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const Route = createFileRoute('/api/users')({ server: { diff --git a/e2e/react-start/basic-react-query/src/routes/api/users.$id.ts b/e2e/react-start/basic-react-query/src/routes/api/users.$id.ts index febea309ea..e11e039652 100644 --- a/e2e/react-start/basic-react-query/src/routes/api/users.$id.ts +++ b/e2e/react-start/basic-react-query/src/routes/api/users.$id.ts @@ -2,7 +2,11 @@ import { createFileRoute } from '@tanstack/react-router' import axios from 'redaxios' import type { User } from '../../utils/users' -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const Route = createFileRoute('/api/users/$id')({ server: { diff --git a/e2e/react-start/basic-react-query/src/routes/deferred.tsx b/e2e/react-start/basic-react-query/src/routes/deferred.tsx index 11af82ed27..0380f79aca 100644 --- a/e2e/react-start/basic-react-query/src/routes/deferred.tsx +++ b/e2e/react-start/basic-react-query/src/routes/deferred.tsx @@ -1,5 +1,6 @@ import { createFileRoute } from '@tanstack/react-router' import { queryOptions, useSuspenseQuery } from '@tanstack/react-query' +import {} from '@tanstack/react-router' import { Suspense, useState } from 'react' const deferredQueryOptions = () => diff --git a/e2e/react-start/basic-react-query/src/utils/posts.tsx b/e2e/react-start/basic-react-query/src/utils/posts.tsx index abb6e95b92..2574bf10d1 100644 --- a/e2e/react-start/basic-react-query/src/utils/posts.tsx +++ b/e2e/react-start/basic-react-query/src/utils/posts.tsx @@ -9,7 +9,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPosts = createServerFn({ method: 'GET' }).handler( async () => { @@ -27,7 +31,7 @@ export const postsQueryOptions = () => }) export const fetchPost = createServerFn({ method: 'GET' }) - .validator((postId: string) => postId) + .inputValidator((postId: string) => postId) .handler(async ({ data: postId }) => { console.info(`Fetching post with id ${postId}...`) const post = await axios diff --git a/e2e/react-start/basic-react-query/src/utils/users.tsx b/e2e/react-start/basic-react-query/src/utils/users.tsx index 15216680e9..26b934fcb3 100644 --- a/e2e/react-start/basic-react-query/src/utils/users.tsx +++ b/e2e/react-start/basic-react-query/src/utils/users.tsx @@ -1,6 +1,4 @@ import { queryOptions } from '@tanstack/react-query' -import { createIsomorphicFn } from '@tanstack/react-start' -import { getRequestUrl } from '@tanstack/react-start/server' import axios from 'redaxios' export type User = { @@ -9,16 +7,17 @@ export type User = { email: string } -const getOrigin = createIsomorphicFn() - .server(() => getRequestUrl().origin) - .client(() => window.location.origin) +const PORT = + import.meta.env.VITE_SERVER_PORT || process.env.VITE_SERVER_PORT || 3000 + +export const DEPLOY_URL = `http://localhost:${PORT}` export const usersQueryOptions = () => queryOptions({ queryKey: ['users'], queryFn: () => axios - .get>(getOrigin() + '/api/users') + .get>(DEPLOY_URL + '/api/users') .then((r) => r.data) .catch(() => { throw new Error('Failed to fetch users') @@ -30,7 +29,7 @@ export const userQueryOptions = (id: string) => queryKey: ['users', id], queryFn: () => axios - .get(getOrigin() + '/api/users/' + id) + .get(DEPLOY_URL + '/api/users/' + id) .then((r) => r.data) .catch(() => { throw new Error('Failed to fetch user') diff --git a/e2e/react-start/basic-react-query/tests/setup/global.setup.ts b/e2e/react-start/basic-react-query/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-start/basic-react-query/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-start/basic-react-query/tests/setup/global.teardown.ts b/e2e/react-start/basic-react-query/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-start/basic-react-query/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-start/basic-react-query/tsconfig.json b/e2e/react-start/basic-react-query/tsconfig.json index c7a0597e4b..a07911fe5f 100644 --- a/e2e/react-start/basic-react-query/tsconfig.json +++ b/e2e/react-start/basic-react-query/tsconfig.json @@ -13,6 +13,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/react-start/basic-react-query/vite.config.ts b/e2e/react-start/basic-react-query/vite.config.ts index 6c9a4c347a..3e946e6645 100644 --- a/e2e/react-start/basic-react-query/vite.config.ts +++ b/e2e/react-start/basic-react-query/vite.config.ts @@ -1,9 +1,16 @@ import { defineConfig } from 'vite' +import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import viteReact from '@vitejs/plugin-react' import tailwindcss from '@tailwindcss/vite' export default defineConfig({ - resolve: { tsconfigPaths: true }, - plugins: [tailwindcss(), tanstackStart(), viteReact()], + plugins: [ + tailwindcss(), + tsConfigPaths({ + projects: ['./tsconfig.json'], + }), + tanstackStart(), + viteReact(), + ], }) diff --git a/examples/react/start-trellaux/.gitignore b/e2e/react-start/basic-rsc/.gitignore similarity index 100% rename from examples/react/start-trellaux/.gitignore rename to e2e/react-start/basic-rsc/.gitignore diff --git a/examples/react/start-basic-auth/.prettierignore b/e2e/react-start/basic-rsc/.prettierignore similarity index 100% rename from examples/react/start-basic-auth/.prettierignore rename to e2e/react-start/basic-rsc/.prettierignore diff --git a/e2e/react-start/basic-rsc/package.json b/e2e/react-start/basic-rsc/package.json new file mode 100644 index 0000000000..ab7e287ae5 --- /dev/null +++ b/e2e/react-start/basic-rsc/package.json @@ -0,0 +1,35 @@ +{ + "name": "tanstack-react-start-e2e-basic-rsc", + "private": true, + "sideEffects": false, + "type": "module", + "scripts": { + "dev": "vite dev", + "build": "exit 0; vite build", + "start": "node .output/server/index.mjs" + }, + "dependencies": { + "@babel/plugin-syntax-typescript": "^7.25.9", + "@tanstack/react-router": "workspace:^", + "@tanstack/react-router-devtools": "workspace:^", + "@tanstack/react-start": "workspace:^", + "react": "^19.0.0", + "react-dom": "^19.0.0", + "redaxios": "^0.5.1", + "tailwind-merge": "^2.6.0", + "vite": "^7.3.1" + }, + "devDependencies": { + "@tailwindcss/vite": "^4.1.18", + "@types/react": "^19.0.8", + "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^4.3.4", + "tailwindcss": "^4.1.18", + "typescript": "^5.7.2", + "vite-tsconfig-paths": "^5.1.4" + }, + "overrides": { + "react": "0.0.0-experimental-035a41c4e-20230704", + "react-dom": "0.0.0-experimental-035a41c4e-20230704" + } +} diff --git a/examples/react/start-basic-auth/public/android-chrome-192x192.png b/e2e/react-start/basic-rsc/public/android-chrome-192x192.png similarity index 100% rename from examples/react/start-basic-auth/public/android-chrome-192x192.png rename to e2e/react-start/basic-rsc/public/android-chrome-192x192.png diff --git a/examples/react/start-basic-auth/public/android-chrome-512x512.png b/e2e/react-start/basic-rsc/public/android-chrome-512x512.png similarity index 100% rename from examples/react/start-basic-auth/public/android-chrome-512x512.png rename to e2e/react-start/basic-rsc/public/android-chrome-512x512.png diff --git a/examples/react/start-basic-auth/public/apple-touch-icon.png b/e2e/react-start/basic-rsc/public/apple-touch-icon.png similarity index 100% rename from examples/react/start-basic-auth/public/apple-touch-icon.png rename to e2e/react-start/basic-rsc/public/apple-touch-icon.png diff --git a/examples/react/start-basic-auth/public/favicon-16x16.png b/e2e/react-start/basic-rsc/public/favicon-16x16.png similarity index 100% rename from examples/react/start-basic-auth/public/favicon-16x16.png rename to e2e/react-start/basic-rsc/public/favicon-16x16.png diff --git a/examples/react/start-basic-auth/public/favicon-32x32.png b/e2e/react-start/basic-rsc/public/favicon-32x32.png similarity index 100% rename from examples/react/start-basic-auth/public/favicon-32x32.png rename to e2e/react-start/basic-rsc/public/favicon-32x32.png diff --git a/examples/react/start-bare/public/favicon.ico b/e2e/react-start/basic-rsc/public/favicon.ico similarity index 100% rename from examples/react/start-bare/public/favicon.ico rename to e2e/react-start/basic-rsc/public/favicon.ico diff --git a/examples/react/start-basic-auth/public/favicon.png b/e2e/react-start/basic-rsc/public/favicon.png similarity index 100% rename from examples/react/start-basic-auth/public/favicon.png rename to e2e/react-start/basic-rsc/public/favicon.png diff --git a/examples/react/start-basic-auth/public/site.webmanifest b/e2e/react-start/basic-rsc/public/site.webmanifest similarity index 100% rename from examples/react/start-basic-auth/public/site.webmanifest rename to e2e/react-start/basic-rsc/public/site.webmanifest diff --git a/e2e/react-start/basic-rsc/src/components/DefaultCatchBoundary.tsx b/e2e/react-start/basic-rsc/src/components/DefaultCatchBoundary.tsx new file mode 100644 index 0000000000..ef2daa1ea1 --- /dev/null +++ b/e2e/react-start/basic-rsc/src/components/DefaultCatchBoundary.tsx @@ -0,0 +1,53 @@ +import { + ErrorComponent, + Link, + rootRouteId, + useMatch, + useRouter, +} from '@tanstack/react-router' +import type { ErrorComponentProps } from '@tanstack/react-router' + +export function DefaultCatchBoundary({ error }: ErrorComponentProps) { + const router = useRouter() + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, + }) + + console.error(error) + + return ( +
+ +
+ + {isRoot ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
+
+ ) +} diff --git a/examples/react/start-basic-auth/src/components/NotFound.tsx b/e2e/react-start/basic-rsc/src/components/NotFound.tsx similarity index 100% rename from examples/react/start-basic-auth/src/components/NotFound.tsx rename to e2e/react-start/basic-rsc/src/components/NotFound.tsx diff --git a/e2e/react-start/basic-rsc/src/routeTree.gen.ts b/e2e/react-start/basic-rsc/src/routeTree.gen.ts new file mode 100644 index 0000000000..500f71a9f7 --- /dev/null +++ b/e2e/react-start/basic-rsc/src/routeTree.gen.ts @@ -0,0 +1,254 @@ +/* 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 PostsRouteImport } from './routes/posts' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as IndexRouteImport } from './routes/index' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' + +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, +} as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ + id: '/layout-b', + path: '/layout-b', + getParentRoute: () => LayoutLayout2Route, +} as any) +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/posts': typeof PostsRouteWithChildren + '/posts/$postId': typeof PostsPostIdRoute + '/posts/': typeof PostsIndexRoute + '/layout-a': typeof LayoutLayout2LayoutARoute + '/layout-b': typeof LayoutLayout2LayoutBRoute + '/posts/$postId/deep': typeof PostsPostIdDeepRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/posts/$postId': typeof PostsPostIdRoute + '/posts': typeof PostsIndexRoute + '/layout-a': typeof LayoutLayout2LayoutARoute + '/layout-b': typeof LayoutLayout2LayoutBRoute + '/posts/$postId/deep': typeof PostsPostIdDeepRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/_layout': typeof LayoutRouteWithChildren + '/posts': typeof PostsRouteWithChildren + '/_layout/_layout-2': typeof LayoutLayout2RouteWithChildren + '/posts/$postId': typeof PostsPostIdRoute + '/posts/': typeof PostsIndexRoute + '/_layout/_layout-2/layout-a': typeof LayoutLayout2LayoutARoute + '/_layout/_layout-2/layout-b': typeof LayoutLayout2LayoutBRoute + '/posts_/$postId/deep': typeof PostsPostIdDeepRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/posts' + | '/posts/$postId' + | '/posts/' + | '/layout-a' + | '/layout-b' + | '/posts/$postId/deep' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/posts/$postId' + | '/posts' + | '/layout-a' + | '/layout-b' + | '/posts/$postId/deep' + id: + | '__root__' + | '/' + | '/_layout' + | '/posts' + | '/_layout/_layout-2' + | '/posts/$postId' + | '/posts/' + | '/_layout/_layout-2/layout-a' + | '/_layout/_layout-2/layout-b' + | '/posts_/$postId/deep' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + LayoutRoute: typeof LayoutRouteWithChildren + PostsRoute: typeof PostsRouteWithChildren + PostsPostIdDeepRoute: typeof PostsPostIdDeepRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout': { + id: '/_layout' + path: '' + fullPath: '' + preLoaderRoute: typeof LayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute + } + '/_layout/_layout-2': { + id: '/_layout/_layout-2' + path: '' + fullPath: '' + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute + } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout/_layout-2/layout-b': { + id: '/_layout/_layout-2/layout-b' + path: '/layout-b' + fullPath: '/layout-b' + preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport + parentRoute: typeof LayoutLayout2Route + } + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route + } + } +} + +interface LayoutLayout2RouteChildren { + LayoutLayout2LayoutARoute: typeof LayoutLayout2LayoutARoute + LayoutLayout2LayoutBRoute: typeof LayoutLayout2LayoutBRoute +} + +const LayoutLayout2RouteChildren: LayoutLayout2RouteChildren = { + LayoutLayout2LayoutARoute: LayoutLayout2LayoutARoute, + LayoutLayout2LayoutBRoute: LayoutLayout2LayoutBRoute, +} + +const LayoutLayout2RouteWithChildren = LayoutLayout2Route._addFileChildren( + LayoutLayout2RouteChildren, +) + +interface LayoutRouteChildren { + LayoutLayout2Route: typeof LayoutLayout2RouteWithChildren +} + +const LayoutRouteChildren: LayoutRouteChildren = { + LayoutLayout2Route: LayoutLayout2RouteWithChildren, +} + +const LayoutRouteWithChildren = + LayoutRoute._addFileChildren(LayoutRouteChildren) + +interface PostsRouteChildren { + PostsPostIdRoute: typeof PostsPostIdRoute + PostsIndexRoute: typeof PostsIndexRoute +} + +const PostsRouteChildren: PostsRouteChildren = { + PostsPostIdRoute: PostsPostIdRoute, + PostsIndexRoute: PostsIndexRoute, +} + +const PostsRouteWithChildren = PostsRoute._addFileChildren(PostsRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + LayoutRoute: LayoutRouteWithChildren, + PostsRoute: PostsRouteWithChildren, + PostsPostIdDeepRoute: PostsPostIdDeepRoute, +} +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 { + router: Awaited> + } +} diff --git a/e2e/react-start/basic-rsc/src/router.tsx b/e2e/react-start/basic-rsc/src/router.tsx new file mode 100644 index 0000000000..fef35c9e06 --- /dev/null +++ b/e2e/react-start/basic-rsc/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' +import { DefaultCatchBoundary } from './components/DefaultCatchBoundary' +import { NotFound } from './components/NotFound' + +export function getRouter() { + const router = createRouter({ + routeTree, + scrollRestoration: true, + defaultPreload: 'intent', + defaultErrorComponent: DefaultCatchBoundary, + defaultNotFoundComponent: () => , + }) + + return router +} diff --git a/e2e/react-start/basic-rsc/src/routes/__root.tsx b/e2e/react-start/basic-rsc/src/routes/__root.tsx new file mode 100644 index 0000000000..7e5ac89786 --- /dev/null +++ b/e2e/react-start/basic-rsc/src/routes/__root.tsx @@ -0,0 +1,125 @@ +/// +import { + HeadContent, + Link, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' +import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' +import * as React from 'react' +import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary' +import { NotFound } from '~/components/NotFound' +import appCss from '~/styles/app.css?url' +import { seo } from '~/utils/seo' + +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { + charSet: 'utf-8', + }, + { + name: 'viewport', + content: 'width=device-width, initial-scale=1', + }, + ...seo({ + title: + 'TanStack Start | Type-Safe, Client-First, Full-Stack React Framework', + description: `TanStack Start is a type-safe, client-first, full-stack React framework. `, + }), + ], + links: [ + { rel: 'stylesheet', href: appCss }, + { + rel: 'apple-touch-icon', + sizes: '180x180', + href: '/apple-touch-icon.png', + }, + { + rel: 'icon', + type: 'image/png', + sizes: '32x32', + href: '/favicon-32x32.png', + }, + { + rel: 'icon', + type: 'image/png', + sizes: '16x16', + href: '/favicon-16x16.png', + }, + { rel: 'manifest', href: '/site.webmanifest', color: '#fffff' }, + { rel: 'icon', href: '/favicon.ico' }, + ], + }), + errorComponent: (props) => { + return ( + + + + ) + }, + notFoundComponent: () => , + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + ) +} + +function RootDocument({ children }: { children: React.ReactNode }) { + return ( + + + + + +
+ + Home + {' '} + + Posts + + + Layout + + + This Route Does Not Exist + +
+
+ {/* {children} */} + {children} + + + + + ) +} diff --git a/e2e/react-start/basic-rsc/src/routes/_layout.tsx b/e2e/react-start/basic-rsc/src/routes/_layout.tsx new file mode 100644 index 0000000000..02ddbb1cd9 --- /dev/null +++ b/e2e/react-start/basic-rsc/src/routes/_layout.tsx @@ -0,0 +1,16 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/_layout')({ + component: LayoutComponent, +}) + +function LayoutComponent() { + return ( +
+
I'm a layout
+
+ +
+
+ ) +} diff --git a/e2e/react-start/basic-rsc/src/routes/_layout/_layout-2.tsx b/e2e/react-start/basic-rsc/src/routes/_layout/_layout-2.tsx new file mode 100644 index 0000000000..3b7dbf2903 --- /dev/null +++ b/e2e/react-start/basic-rsc/src/routes/_layout/_layout-2.tsx @@ -0,0 +1,34 @@ +import { Link, Outlet, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/_layout/_layout-2')({ + component: LayoutComponent, +}) + +function LayoutComponent() { + return ( +
+
I'm a nested layout
+
+ + Layout A + + + Layout B + +
+
+ +
+
+ ) +} diff --git a/e2e/react-start/basic-rsc/src/routes/_layout/_layout-2/layout-a.tsx b/e2e/react-start/basic-rsc/src/routes/_layout/_layout-2/layout-a.tsx new file mode 100644 index 0000000000..ed2dea8800 --- /dev/null +++ b/e2e/react-start/basic-rsc/src/routes/_layout/_layout-2/layout-a.tsx @@ -0,0 +1,8 @@ +import { createFileRoute } from '@tanstack/react-router' +export const Route = createFileRoute('/_layout/_layout-2/layout-a')({ + component: LayoutAComponent, +}) + +function LayoutAComponent() { + return
I'm layout A!
+} diff --git a/e2e/react-start/basic-rsc/src/routes/_layout/_layout-2/layout-b.tsx b/e2e/react-start/basic-rsc/src/routes/_layout/_layout-2/layout-b.tsx new file mode 100644 index 0000000000..4799d403e9 --- /dev/null +++ b/e2e/react-start/basic-rsc/src/routes/_layout/_layout-2/layout-b.tsx @@ -0,0 +1,8 @@ +import { createFileRoute } from '@tanstack/react-router' +export const Route = createFileRoute('/_layout/_layout-2/layout-b')({ + component: LayoutBComponent, +}) + +function LayoutBComponent() { + return
I'm layout B!
+} diff --git a/e2e/react-start/basic-rsc/src/routes/index.tsx b/e2e/react-start/basic-rsc/src/routes/index.tsx new file mode 100644 index 0000000000..d531858f8c --- /dev/null +++ b/e2e/react-start/basic-rsc/src/routes/index.tsx @@ -0,0 +1,12 @@ +import { createFileRoute } from '@tanstack/react-router' +export const Route = createFileRoute('/')({ + component: Home, +}) + +function Home() { + return ( +
+

Welcome Home!

+
+ ) +} diff --git a/e2e/react-start/basic-rsc/src/routes/posts.$postId.tsx b/e2e/react-start/basic-rsc/src/routes/posts.$postId.tsx new file mode 100644 index 0000000000..a7f2a551b2 --- /dev/null +++ b/e2e/react-start/basic-rsc/src/routes/posts.$postId.tsx @@ -0,0 +1,46 @@ +import { ErrorComponent, Link, createFileRoute } from '@tanstack/react-router' +import { createServerFn } from '@tanstack/react-start' +import type { ErrorComponentProps } from '@tanstack/react-router' + +import { fetchPost } from '~/utils/posts' +import { NotFound } from '~/components/NotFound' + +const renderPost = createServerFn({ method: 'GET' }) + .inputValidator((postId: string) => postId) + .handler(async ({ data: postId }) => { + const post = await fetchPost(postId) + + return ( +
+

{post.title}

+
{post.body}
+ + Deep View + +
+ ) + }) + +export const Route = createFileRoute('/posts/$postId')({ + loader: async ({ params: { postId } }) => renderPost({ data: postId }), + errorComponent: PostErrorComponent, + component: PostComponent, + notFoundComponent: () => { + return Post not found + }, +}) + +export function PostErrorComponent({ error }: ErrorComponentProps) { + return +} + +function PostComponent() { + return Route.useLoaderData() +} diff --git a/examples/react/start-basic-react-query/src/routes/posts.index.tsx b/e2e/react-start/basic-rsc/src/routes/posts.index.tsx similarity index 100% rename from examples/react/start-basic-react-query/src/routes/posts.index.tsx rename to e2e/react-start/basic-rsc/src/routes/posts.index.tsx diff --git a/e2e/react-start/basic-rsc/src/routes/posts.tsx b/e2e/react-start/basic-rsc/src/routes/posts.tsx new file mode 100644 index 0000000000..a3ef2a2e20 --- /dev/null +++ b/e2e/react-start/basic-rsc/src/routes/posts.tsx @@ -0,0 +1,16 @@ +import { createFileRoute } from '@tanstack/react-router' +import { createServerFn, renderRsc } from '@tanstack/react-start' +import { renderPosts } from '~/utils/renderPosts' + +export const serverRenderPosts = createServerFn({ method: 'GET' }).handler( + renderPosts, +) + +export const Route = createFileRoute('/posts')({ + loader: async () => serverRenderPosts(), + component: PostsComponent, +}) + +function PostsComponent() { + return renderRsc(Route.useLoaderData()) +} diff --git a/e2e/react-start/basic-rsc/src/routes/posts_.$postId.deep.tsx b/e2e/react-start/basic-rsc/src/routes/posts_.$postId.deep.tsx new file mode 100644 index 0000000000..13d368cf9c --- /dev/null +++ b/e2e/react-start/basic-rsc/src/routes/posts_.$postId.deep.tsx @@ -0,0 +1,26 @@ +import { Link, createFileRoute } from '@tanstack/react-router' +import { fetchPost } from '../utils/posts' +import { PostErrorComponent } from './posts.$postId' + +export const Route = createFileRoute('/posts_/$postId/deep')({ + loader: async ({ params: { postId } }) => fetchPost(postId), + errorComponent: PostErrorComponent, + component: PostDeepComponent, +}) + +function PostDeepComponent() { + const post = Route.useLoaderData() + + return ( +
+ + ← All Posts + +

{post.title}

+
{post.body}
+
+ ) +} diff --git a/e2e/react-start/custom-server-rsbuild/src/styles/app.css b/e2e/react-start/basic-rsc/src/styles/app.css similarity index 100% rename from e2e/react-start/custom-server-rsbuild/src/styles/app.css rename to e2e/react-start/basic-rsc/src/styles/app.css diff --git a/e2e/react-start/basic-rsc/src/utils/posts.tsx b/e2e/react-start/basic-rsc/src/utils/posts.tsx new file mode 100644 index 0000000000..16fc1744e6 --- /dev/null +++ b/e2e/react-start/basic-rsc/src/utils/posts.tsx @@ -0,0 +1,35 @@ +// import { notFound } from '@tanstack/react-router' +// import { createServerFn } from '@tanstack/react-start' +import axios from 'redaxios' + +export type PostType = { + id: string + title: string + body: string +} + +export const fetchPost = async (postId: string) => { + 'use server' + console.info(`Fetching post with id ${postId}...`) + await new Promise((r) => setTimeout(r, 500)) + const post = await axios + .get(`https://jsonplaceholder.typicode.com/posts/${postId}`) + .then((r) => r.data) + .catch((err) => { + if (err.status === 404) { + // throw notFound() + } + throw err + }) + + return post +} + +export const fetchPosts = async () => { + 'use server' + console.info('Fetching posts...') + await new Promise((r) => setTimeout(r, 500)) + return axios + .get>('https://jsonplaceholder.typicode.com/posts') + .then((r) => r.data.slice(0, 10)) +} diff --git a/e2e/react-start/basic-rsc/src/utils/renderPosts.tsx b/e2e/react-start/basic-rsc/src/utils/renderPosts.tsx new file mode 100644 index 0000000000..37c0661217 --- /dev/null +++ b/e2e/react-start/basic-rsc/src/utils/renderPosts.tsx @@ -0,0 +1,63 @@ +'use server' + +import React from 'react' +import { fetchPosts } from './posts' + +export async function renderPosts() { + const posts = await fetchPosts() + + posts.state = posts.state || { + status: 'pending', + promise: Promise.resolve(), + } + + return ( +
+
    + {[...posts, { id: 'i-do-not-exist', title: 'Non-existent Post' }]?.map( + (post) => { + return ( +
  • + {post.title.substring(0, 20)} + {/* +
    {post.title.substring(0, 20)}
    + */} +
  • + ) + }, + )} +
+
+ Loading...
}> + + +
+ ) +} + +function DelayedDateViaSuspense({ state }) { + // a component that will suspend for 1 second and then show the current date + if (state.status === 'pending') { + state.promise = new Promise((resolve) => { + setTimeout(() => { + state.status = 'success' + resolve() + }, 5000) + }) + throw state.promise + } + + return
{new Date().toISOString().replace('T', ' ').split('.')[0]}
+} + +// ...fetchPosts +// posts +// ...5000 +// timestamp diff --git a/examples/react/start-basic-auth/src/utils/seo.ts b/e2e/react-start/basic-rsc/src/utils/seo.ts similarity index 100% rename from examples/react/start-basic-auth/src/utils/seo.ts rename to e2e/react-start/basic-rsc/src/utils/seo.ts diff --git a/e2e/react-start/early-hints/tsconfig.json b/e2e/react-start/basic-rsc/tsconfig.json similarity index 100% rename from e2e/react-start/early-hints/tsconfig.json rename to e2e/react-start/basic-rsc/tsconfig.json diff --git a/e2e/react-start/basic-rsc/vite.config.ts b/e2e/react-start/basic-rsc/vite.config.ts new file mode 100644 index 0000000000..3e946e6645 --- /dev/null +++ b/e2e/react-start/basic-rsc/vite.config.ts @@ -0,0 +1,16 @@ +import { defineConfig } from 'vite' +import tsConfigPaths from 'vite-tsconfig-paths' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import viteReact from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' + +export default defineConfig({ + plugins: [ + tailwindcss(), + tsConfigPaths({ + projects: ['./tsconfig.json'], + }), + tanstackStart(), + viteReact(), + ], +}) diff --git a/e2e/react-start/basic-tsr-config/.devcontainer/devcontainer.json b/e2e/react-start/basic-tsr-config/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/react-start/basic-tsr-config/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/react-start/basic-tsr-config/package.json b/e2e/react-start/basic-tsr-config/package.json index 99e681ac9d..e175d6766c 100644 --- a/e2e/react-start/basic-tsr-config/package.json +++ b/e2e/react-start/basic-tsr-config/package.json @@ -8,23 +8,21 @@ "dev:e2e": "vite dev", "build": "rimraf ./count.txt && vite build && tsc --noEmit", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", "@tanstack/react-start": "workspace:^", "react": "^19.0.0", - "react-dom": "^19.0.0" + "react-dom": "^19.0.0", + "vite": "^7.3.1" }, "devDependencies": { "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "srvx": "^1.0.0", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "rimraf": "catalog:" + "srvx": "^0.11.2", + "typescript": "^5.7.2" } } diff --git a/e2e/react-start/basic-tsr-config/playwright.config.ts b/e2e/react-start/basic-tsr-config/playwright.config.ts index 82678ac00b..18b8905468 100644 --- a/e2e/react-start/basic-tsr-config/playwright.config.ts +++ b/e2e/react-start/basic-tsr-config/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/basic-tsr-config/src/routes/index.tsx b/e2e/react-start/basic-tsr-config/src/routes/index.tsx index aaa4bdfdb3..413617217d 100644 --- a/e2e/react-start/basic-tsr-config/src/routes/index.tsx +++ b/e2e/react-start/basic-tsr-config/src/routes/index.tsx @@ -12,7 +12,7 @@ const getCount = createServerFn({ }) const updateCount = createServerFn({ method: 'POST' }) - .validator((d: number) => d) + .inputValidator((d: number) => d) .handler(async ({ data }) => { const count = await getCount() await fs.promises.writeFile(filePath, `${count + data}`) diff --git a/e2e/react-start/basic-tsr-config/tsconfig.json b/e2e/react-start/basic-tsr-config/tsconfig.json index f3895f6eb1..3558337b0c 100644 --- a/e2e/react-start/basic-tsr-config/tsconfig.json +++ b/e2e/react-start/basic-tsr-config/tsconfig.json @@ -13,6 +13,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/app/*"] }, diff --git a/e2e/react-start/basic/.devcontainer/devcontainer.json b/e2e/react-start/basic/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/react-start/basic/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/react-start/basic/.gitignore b/e2e/react-start/basic/.gitignore index a5f07919aa..a79d5cf129 100644 --- a/e2e/react-start/basic/.gitignore +++ b/e2e/react-start/basic/.gitignore @@ -18,5 +18,3 @@ yarn.lock /playwright-report/ /blob-report/ /playwright/.cache/ -/dist-vite-*/ -/dist-rsbuild-*/ \ No newline at end of file diff --git a/e2e/react-start/basic/package.json b/e2e/react-start/basic/package.json index 3a1a4ea9c8..883627bb4f 100644 --- a/e2e/react-start/basic/package.json +++ b/e2e/react-start/basic/package.json @@ -4,129 +4,48 @@ "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", + "dev": "vite dev --port 3000", + "dev:e2e": "vite dev", + "build": "vite build && tsc --noEmit", + "build:spa": "MODE=spa vite build && tsc --noEmit", + "build:prerender": "MODE=prerender vite build && tsc --noEmit", "preview": "vite preview", - "preview:rsbuild": "rsbuild preview", "start": "node server.js", - "test:e2e:local": "playwright test --project=chromium" + "test:e2e:startDummyServer": "node -e 'import(\"./tests/setup/global.setup.ts\").then(m => m.default())' &", + "test:e2e:stopDummyServer": "node -e 'import(\"./tests/setup/global.teardown.ts\").then(m => m.default())'", + "test:e2e:spaMode": "rm -rf dist; rm -rf port*.txt; MODE=spa playwright test --project=chromium", + "test:e2e:ssrMode": "rm -rf dist; rm -rf port*.txt; playwright test --project=chromium", + "test:e2e:prerender": "rm -rf dist; rm -rf port*.txt; MODE=prerender playwright test --project=chromium", + "test:e2e:preview": "rm -rf dist; rm -rf port*.txt; MODE=preview playwright test --project=chromium", + "test:e2e": "pnpm run test:e2e:spaMode && pnpm run test:e2e:ssrMode && pnpm run test:e2e:prerender && pnpm run test:e2e:preview" }, "dependencies": { "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", "@tanstack/react-start": "workspace:^", - "express": "^5.2.1", + "express": "^5.1.0", "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": "catalog:", - "tailwind-merge": "^3.6.0" + "redaxios": "^0.5.1", + "tailwind-merge": "^2.6.0" }, "devDependencies": { - "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", - "@rsbuild/plugin-react": "^2.0.0", - "@tailwindcss/postcss": "^4.2.2", - "@tailwindcss/vite": "^4.2.2", + "@playwright/test": "^1.50.1", + "@tailwindcss/vite": "^4.1.18", "@tanstack/router-e2e-utils": "workspace:^", "@types/js-cookie": "^3.0.6", "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", + "@vitejs/plugin-react": "^4.3.4", "combinate": "^1.1.11", - "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", - "zod": "^4.4.3" - }, - "nx": { - "targets": { - "test:e2e--vite-spa--dev": { - "dependsOn": [ - "^build" - ] - }, - "test:e2e--rsbuild-spa--dev": { - "dependsOn": [ - "^build" - ] - } - }, - "metadata": { - "playwrightModes": [ - { - "toolchain": "vite", - "mode": "ssr" - }, - { - "toolchain": "vite", - "mode": "spa" - }, - { - "toolchain": "vite", - "mode": "spa", - "name": "dev", - "env": { - "E2E_DEV_SERVER": "true" - } - }, - { - "toolchain": "vite", - "mode": "prerender", - "env": { - "NODE_OPTIONS": "--import=@tanstack/router-e2e-utils/mock-api" - } - }, - { - "toolchain": "vite", - "mode": "preview" - }, - { - "toolchain": "rsbuild", - "mode": "ssr" - }, - { - "toolchain": "rsbuild", - "mode": "ssr", - "name": "iife", - "env": { - "TSS_RSB_CLIENT_OUTPUT": "iife" - } - }, - { - "toolchain": "rsbuild", - "mode": "spa" - }, - { - "toolchain": "rsbuild", - "mode": "spa", - "name": "dev", - "env": { - "E2E_DEV_SERVER": "true" - } - }, - { - "toolchain": "rsbuild", - "mode": "prerender", - "env": { - "NODE_OPTIONS": "--import=@tanstack/router-e2e-utils/mock-api" - } - }, - { - "toolchain": "rsbuild", - "mode": "preview" - } - ] - } + "srvx": "^0.11.2", + "tailwindcss": "^4.1.18", + "typescript": "^5.7.2", + "vite": "^7.3.1", + "vite-tsconfig-paths": "^5.1.4", + "zod": "^3.24.2" } } diff --git a/e2e/react-start/basic/playwright.config.ts b/e2e/react-start/basic/playwright.config.ts index bb4c2cb761..86c58bc1ce 100644 --- a/e2e/react-start/basic/playwright.config.ts +++ b/e2e/react-start/basic/playwright.config.ts @@ -1,62 +1,63 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import { isSpaMode } from './tests/utils/isSpaMode' +import { isPrerender } from './tests/utils/isPrerender' +import { isPreview } from './tests/utils/isPreview' +import packageJson from './package.json' with { type: 'json' } -const mode = process.env.MODE ?? 'ssr' -const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' - -const distDir = process.env.E2E_DIST_DIR ?? 'dist' -// The dev runs start the dev server and run only the SPA shell spec -const devServer = process.env.E2E_DEV_SERVER === 'true' - -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort( + `${packageJson.name}${isSpaMode ? '_spa' : ''}${isPreview ? '_preview' : ''}`, +) +const START_PORT = await getTestServerPort( + `${packageJson.name}${isSpaMode ? '_spa_start' : ''}`, +) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` -const previewCommand = - toolchain === 'rsbuild' - ? `pnpm preview:rsbuild --host 0.0.0.0 --port ${PORT}` - : `pnpm preview --host 0.0.0.0 --outDir ${distDir} --port ${PORT}` -const devCommand = - toolchain === 'rsbuild' - ? `pnpm dev:rsbuild --port ${PORT}` - : `pnpm dev:vite --port ${PORT}` -const commandByMode = devServer - ? devCommand - : mode === 'preview' - ? previewCommand - : 'pnpm start' +const spaModeCommand = `pnpm build:spa && pnpm start` +const ssrModeCommand = `pnpm build && pnpm start` +const prerenderModeCommand = `pnpm run test:e2e:startDummyServer && pnpm build:prerender && pnpm run test:e2e:stopDummyServer && pnpm start` +const previewModeCommand = `pnpm build && pnpm preview --port ${PORT}` + +const getCommand = () => { + if (isSpaMode) return spaModeCommand + if (isPrerender) return prerenderModeCommand + if (isPreview) return previewModeCommand + return ssrModeCommand +} +console.log('running in spa mode: ', isSpaMode.toString()) +console.log('running in prerender mode: ', isPrerender.toString()) +console.log('running in preview mode: ', isPreview.toString()) /** * 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']], + 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: commandByMode, - wait: appServerReady, - reuseExistingServer: false, + command: getCommand(), + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, - MODE: mode, - E2E_TOOLCHAIN: toolchain, - START_PORT: '0', + MODE: process.env.MODE || '', + VITE_NODE_ENV: 'test', + VITE_EXTERNAL_PORT: String(EXTERNAL_PORT), + VITE_SERVER_PORT: String(PORT), + START_PORT: String(START_PORT), PORT: String(PORT), - E2E_DIST_DIR: distDir, - ...(process.env.TSS_RSB_CLIENT_OUTPUT - ? { TSS_RSB_CLIENT_OUTPUT: process.env.TSS_RSB_CLIENT_OUTPUT } - : {}), }, }, diff --git a/e2e/react-start/basic/postcss.config.mjs b/e2e/react-start/basic/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/react-start/basic/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/react-start/basic/rsbuild.config.ts b/e2e/react-start/basic/rsbuild.config.ts deleted file mode 100644 index 23072b6c1b..0000000000 --- a/e2e/react-start/basic/rsbuild.config.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { defineConfig } from '@rsbuild/core' -import { pluginReact } from '@rsbuild/plugin-react' -import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' -import { getStartModeConfig } from './start-mode-config' - -const outDir = process.env.E2E_DIST_DIR ?? 'dist' -const startModeConfig = getStartModeConfig() - -export default defineConfig({ - 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 3e1ddab400..83f5ff0079 100644 --- a/e2e/react-start/basic/server.js +++ b/e2e/react-start/basic/server.js @@ -1,42 +1,24 @@ -import fs from 'node:fs' -import path from 'node:path' import { toNodeHandler } from 'srvx/node' +import path from 'node:path' import express from 'express' import { createProxyMiddleware } from 'http-proxy-middleware' -const port = Number(process.env.PORT ?? 3000) +const port = process.env.PORT || 3000 -const startPort = Number(process.env.START_PORT ?? 0) +const startPort = process.env.START_PORT || 3001 const isSpaMode = process.env.MODE === 'spa' const isPrerender = process.env.MODE === 'prerender' -const distDir = process.env.E2E_DIST_DIR || 'dist' -const distClientDir = path.resolve(distDir, 'client') - -function resolveDistServerEntryPath() { - const serverJsPath = path.resolve(distDir, 'server', 'server.js') - if (fs.existsSync(serverJsPath)) { - return serverJsPath - } - - const indexJsPath = path.resolve(distDir, 'server', 'index.js') - if (fs.existsSync(indexJsPath)) { - return indexJsPath - } - - return serverJsPath -} export async function createStartServer() { - const distServerEntryPath = resolveDistServerEntryPath() - const server = (await import(distServerEntryPath)).default + const server = (await import('./dist/server/server.js')).default const nodeHandler = toNodeHandler(server.fetch) const app = express() // to keep testing uniform stop express from redirecting /posts to /posts/ // when serving pre-rendered pages - app.use(express.static(distClientDir, { redirect: !isPrerender })) + app.use(express.static('./dist/client', { redirect: !isPrerender })) app.use(async (req, res, next) => { try { @@ -49,13 +31,13 @@ export async function createStartServer() { return { app } } -export async function createSpaServer(backendPort) { +export async function createSpaServer() { const app = express() app.use( '/api', createProxyMiddleware({ - target: `http://localhost:${backendPort}/api`, // Replace with your target server's URL + target: `http://localhost:${startPort}/api`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) @@ -63,36 +45,36 @@ export async function createSpaServer(backendPort) { app.use( '/_serverFn', createProxyMiddleware({ - target: `http://localhost:${backendPort}/_serverFn`, // Replace with your target server's URL + target: `http://localhost:${startPort}/_serverFn`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) - app.use(express.static(distClientDir)) + app.use(express.static('./dist/client')) app.get('/{*splat}', (req, res) => { - res.sendFile('index.html', { root: distClientDir }) + res.sendFile(path.resolve('./dist/client/index.html')) }) return { app } } -// Bind the backend first so the SPA proxy receives the port actually held by it. -const { app: startApp } = await createStartServer() -const backend = startApp.listen(isSpaMode ? startPort : port, async (error) => { - if (error) { - throw error - } - const backendPort = backend.address().port - if (isSpaMode) { - const { app } = await createSpaServer(backendPort) - const frontend = app.listen(port, (frontendError) => { - if (frontendError) { - throw frontendError - } - console.info(`E2E app: http://localhost:${frontend.address().port}`) - }) - } else { - console.info(`E2E app: http://localhost:${backendPort}`) - } -}) +if (isSpaMode) { + createSpaServer().then(async ({ app }) => + app.listen(port, () => { + console.info(`Client Server: http://localhost:${port}`) + }), + ) + + createStartServer().then(async ({ app }) => + app.listen(startPort, () => { + console.info(`Start Server: http://localhost:${startPort}`) + }), + ) +} else { + createStartServer().then(async ({ app }) => + app.listen(port, () => { + console.info(`Start Server: http://localhost:${port}`) + }), + ) +} diff --git a/e2e/react-start/basic/src/components/DefaultCatchBoundary.tsx b/e2e/react-start/basic/src/components/DefaultCatchBoundary.tsx index 405fb5f4a7..ef2daa1ea1 100644 --- a/e2e/react-start/basic/src/components/DefaultCatchBoundary.tsx +++ b/e2e/react-start/basic/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/react-router' import type { ErrorComponentProps } from '@tanstack/react-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) console.error(error) diff --git a/e2e/react-start/basic/src/components/throwRedirect.ts b/e2e/react-start/basic/src/components/throwRedirect.ts index 6a7a011912..0081a3c560 100644 --- a/e2e/react-start/basic/src/components/throwRedirect.ts +++ b/e2e/react-start/basic/src/components/throwRedirect.ts @@ -2,7 +2,7 @@ import { redirect } from '@tanstack/react-router' import { createServerFn } from '@tanstack/react-start' export const throwRedirect = createServerFn() - .validator( + .inputValidator( (opts: { target: 'internal' | 'external' reloadDocument?: boolean diff --git a/e2e/react-start/basic/src/raw-stream-fns.ts b/e2e/react-start/basic/src/raw-stream-fns.ts index 912837c218..b0a3b51ef8 100644 --- a/e2e/react-start/basic/src/raw-stream-fns.ts +++ b/e2e/react-start/basic/src/raw-stream-fns.ts @@ -364,93 +364,6 @@ export const errorStreamFn = createServerFn().handler(async () => { } }) -// ============================================================================ -// LATE RAWSTREAM TESTS - RawStream inside Promise (discovered after initial serialization) -// ============================================================================ - -// Expected data for late stream tests -export const LATE_STREAM_CHUNKS = [ - encode('late-1'), - encode('late-2'), - encode('late-3'), -] -export const LATE_STREAM_EXPECTED = concatBytes(LATE_STREAM_CHUNKS) - -export const LATE_STREAM_A_CHUNKS = [encode('lateA-1'), encode('lateA-2')] -export const LATE_STREAM_A_EXPECTED = concatBytes(LATE_STREAM_A_CHUNKS) - -export const LATE_STREAM_B_CHUNKS = [encode('lateB-1'), encode('lateB-2')] -export const LATE_STREAM_B_EXPECTED = concatBytes(LATE_STREAM_B_CHUNKS) - -export const IMMEDIATE_STREAM_CHUNKS = [ - encode('immediate-1'), - encode('immediate-2'), -] -export const IMMEDIATE_STREAM_EXPECTED = concatBytes(IMMEDIATE_STREAM_CHUNKS) - -// Test 17: Single late RawStream (Promise) -// The RawStream is wrapped in a Promise, so it's not discovered during initial serialization -export const lateRawStreamFn = createServerFn().handler(async () => { - // Promise that resolves to a RawStream after a delay - const lateStream = new Promise((resolve) => { - setTimeout(() => { - const stream = createDelayedStream(LATE_STREAM_CHUNKS, 30) - resolve(new RawStream(stream)) - }, 100) - }) - - return { - message: 'Late stream test', - lateData: lateStream, - } -}) - -// Test 18: Multiple late RawStreams with different delays -export const multipleLateStreamsFn = createServerFn().handler(async () => { - // Two Promises resolving to RawStreams at different times - const lateStreamA = new Promise((resolve) => { - setTimeout(() => { - const stream = createDelayedStream(LATE_STREAM_A_CHUNKS, 20) - resolve(new RawStream(stream)) - }, 50) - }) - - const lateStreamB = new Promise((resolve) => { - setTimeout(() => { - const stream = createDelayedStream(LATE_STREAM_B_CHUNKS, 20) - resolve(new RawStream(stream)) - }, 150) - }) - - return { - message: 'Multiple late streams test', - streamA: lateStreamA, - streamB: lateStreamB, - } -}) - -// Test 19: Mixed immediate and late RawStreams -// One RawStream is immediate (discovered during initial serialization) -// One is wrapped in Promise (discovered after initial serialization) -export const mixedImmediateLateFn = createServerFn().handler(async () => { - // Immediate RawStream - discovered during initial serialization - const immediateStream = createDelayedStream(IMMEDIATE_STREAM_CHUNKS, 30) - - // Late RawStream - wrapped in Promise, discovered after initial serialization - const lateStream = new Promise((resolve) => { - setTimeout(() => { - const stream = createDelayedStream(LATE_STREAM_CHUNKS, 30) - resolve(new RawStream(stream)) - }, 100) - }) - - return { - message: 'Mixed immediate and late test', - immediate: new RawStream(immediateStream), - late: lateStream, - } -}) - // Helpers for consuming streams (exported for use in components) // Note: RawStream is the marker class used in loaders/server functions, // but after SSR deserialization it becomes ReadableStream. diff --git a/e2e/react-start/basic/src/routeTree.gen.ts b/e2e/react-start/basic/src/routeTree.gen.ts index b6603dd01d..6efad91f8d 100644 --- a/e2e/react-start/basic/src/routeTree.gen.ts +++ b/e2e/react-start/basic/src/routeTree.gen.ts @@ -9,176 +9,69 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as LayoutRouteImport } from './routes/_layout' -import { Route as 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' -import { Route as PlainTsTypeAssertionRouteImport } from './routes/plain-ts-type-assertion' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as PrimitiveBeforeloadErrorRouteImport } from './routes/primitive-beforeload-error' -import { Route as RawStreamRouteImport } from './routes/raw-stream' -import { Route as ScriptsRouteImport } from './routes/scripts' -import { Route as SearchParamsRouteRouteImport } from './routes/search-params/route' -import { Route as SpecialCharsRouteRouteImport } from './routes/specialChars/route' -import { Route as StreamRouteImport } from './routes/stream' -import { Route as TypeOnlyReexportRouteImport } from './routes/type-only-reexport' 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' -import { Route as NotFoundIndexRouteImport } from './routes/not-found/index' -import { Route as NotFoundDeepRouteRouteImport } from './routes/not-found/deep/route' -import { Route as NotFoundParentBoundaryRouteRouteImport } from './routes/not-found/parent-boundary/route' -import { Route as NotFoundViaBeforeLoadRouteImport } from './routes/not-found/via-beforeLoad' -import { Route as NotFoundViaBeforeLoadTargetRootRouteImport } from './routes/not-found/via-beforeLoad-target-root' -import { Route as NotFoundViaLoaderRouteImport } from './routes/not-found/via-loader' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as RawStreamIndexRouteImport } from './routes/raw-stream/index' -import { Route as RawStreamClientCallRouteImport } from './routes/raw-stream/client-call' -import { Route as RawStreamSsrBinaryHintRouteImport } from './routes/raw-stream/ssr-binary-hint' -import { Route as RawStreamSsrMixedRouteImport } from './routes/raw-stream/ssr-mixed' -import { Route as RawStreamSsrMultipleRouteImport } from './routes/raw-stream/ssr-multiple' -import { Route as RawStreamSsrSingleRouteImport } from './routes/raw-stream/ssr-single' -import { Route as RawStreamSsrTextHintRouteImport } from './routes/raw-stream/ssr-text-hint' -import { Route as RedirectIndexRouteImport } from './routes/redirect/index' -import { Route as RedirectTargetRouteImport } from './routes/redirect/$target' -import { Route as SearchParamsIndexRouteImport } from './routes/search-params/index' -import { Route as SearchParamsDefaultRouteImport } from './routes/search-params/default' -import { Route as SearchParamsLoaderThrowsRedirectRouteImport } from './routes/search-params/loader-throws-redirect' -import { Route as SpecialCharsParamRouteImport } from './routes/specialChars/$param' -import { Route as SpecialCharsHashRouteImport } from './routes/specialChars/hash' -import { Route as SpecialCharsMalformedRouteRouteImport } from './routes/specialChars/malformed/route' -import { Route as SpecialCharsSearchRouteImport } from './routes/specialChars/search' -import { Route as SpecialCharsChar45824Char54620Char48124Char44397RouteImport } from './routes/specialChars/대한민국' +import { Route as TypeOnlyReexportRouteImport } from './routes/type-only-reexport' +import { Route as StreamRouteImport } from './routes/stream' +import { Route as ScriptsRouteImport } from './routes/scripts' +import { Route as RawStreamRouteImport } from './routes/raw-stream' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as LinksRouteImport } from './routes/links' +import { Route as InlineScriptsRouteImport } from './routes/inline-scripts' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as ClientOnlyRouteImport } from './routes/client-only' +import { Route as AsyncScriptsRouteImport } from './routes/async-scripts' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as SpecialCharsRouteRouteImport } from './routes/specialChars/route' +import { Route as SearchParamsRouteRouteImport } from './routes/search-params/route' +import { Route as NotFoundRouteRouteImport } from './routes/not-found/route' +import { Route as IndexRouteImport } from './routes/index' import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as SearchParamsIndexRouteImport } from './routes/search-params/index' +import { Route as RedirectIndexRouteImport } from './routes/redirect/index' +import { Route as RawStreamIndexRouteImport } from './routes/raw-stream/index' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as NotFoundIndexRouteImport } from './routes/not-found/index' +import { Route as MultiCookieRedirectIndexRouteImport } from './routes/multi-cookie-redirect/index' import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' -import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' -import { Route as Issue6221ArticleIdRouteImport } from './routes/issue-6221.article.$id' -import { Route as NotFoundDeepIndexRouteImport } from './routes/not-found/deep/index' -import { Route as NotFoundDeepBRouteRouteImport } from './routes/not-found/deep/b/route' -import { Route as NotFoundParentBoundaryIndexRouteImport } from './routes/not-found/parent-boundary/index' -import { Route as NotFoundParentBoundaryViaBeforeLoadRouteImport } from './routes/not-found/parent-boundary/via-beforeLoad' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' +import { Route as SpecialCharsChar45824Char54620Char48124Char44397RouteImport } from './routes/specialChars/대한민국' +import { Route as SpecialCharsSearchRouteImport } from './routes/specialChars/search' +import { Route as SpecialCharsHashRouteImport } from './routes/specialChars/hash' +import { Route as SpecialCharsParamRouteImport } from './routes/specialChars/$param' +import { Route as SearchParamsLoaderThrowsRedirectRouteImport } from './routes/search-params/loader-throws-redirect' +import { Route as SearchParamsDefaultRouteImport } from './routes/search-params/default' +import { Route as RedirectTargetRouteImport } from './routes/redirect/$target' +import { Route as RawStreamSsrTextHintRouteImport } from './routes/raw-stream/ssr-text-hint' +import { Route as RawStreamSsrSingleRouteImport } from './routes/raw-stream/ssr-single' +import { Route as RawStreamSsrMultipleRouteImport } from './routes/raw-stream/ssr-multiple' +import { Route as RawStreamSsrMixedRouteImport } from './routes/raw-stream/ssr-mixed' +import { Route as RawStreamSsrBinaryHintRouteImport } from './routes/raw-stream/ssr-binary-hint' +import { Route as RawStreamClientCallRouteImport } from './routes/raw-stream/client-call' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as NotFoundViaLoaderRouteImport } from './routes/not-found/via-loader' +import { Route as NotFoundViaBeforeLoadRouteImport } from './routes/not-found/via-beforeLoad' +import { Route as MultiCookieRedirectTargetRouteImport } from './routes/multi-cookie-redirect/target' +import { Route as ApiUsersRouteImport } from './routes/api.users' +import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' +import { Route as SpecialCharsMalformedRouteRouteImport } from './routes/specialChars/malformed/route' import { Route as RedirectTargetIndexRouteImport } from './routes/redirect/$target/index' -import { Route as RedirectTargetViaBeforeLoadRouteImport } from './routes/redirect/$target/via-beforeLoad' -import { Route as RedirectTargetViaLoaderRouteImport } from './routes/redirect/$target/via-loader' -import { Route as SpecialCharsMalformedParamRouteImport } from './routes/specialChars/malformed/$param' import { Route as SpecialCharsMalformedSearchRouteImport } from './routes/specialChars/malformed/search' -import { Route as FooBarQuxHereRouteImport } from './routes/foo/$bar/$qux/_here' -import { Route as NotFoundDeepBCRouteRouteImport } from './routes/not-found/deep/b/c/route' +import { Route as SpecialCharsMalformedParamRouteImport } from './routes/specialChars/malformed/$param' +import { Route as RedirectTargetViaLoaderRouteImport } from './routes/redirect/$target/via-loader' +import { Route as RedirectTargetViaBeforeLoadRouteImport } from './routes/redirect/$target/via-beforeLoad' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' +import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' import { Route as RedirectTargetServerFnIndexRouteImport } from './routes/redirect/$target/serverFn/index' -import { Route as RedirectTargetServerFnViaBeforeLoadRouteImport } from './routes/redirect/$target/serverFn/via-beforeLoad' -import { Route as RedirectTargetServerFnViaLoaderRouteImport } from './routes/redirect/$target/serverFn/via-loader' import { Route as RedirectTargetServerFnViaUseServerFnRouteImport } from './routes/redirect/$target/serverFn/via-useServerFn' +import { Route as RedirectTargetServerFnViaLoaderRouteImport } from './routes/redirect/$target/serverFn/via-loader' +import { Route as RedirectTargetServerFnViaBeforeLoadRouteImport } from './routes/redirect/$target/serverFn/via-beforeLoad' +import { Route as FooBarQuxHereRouteImport } from './routes/foo/$bar/$qux/_here' import { Route as FooBarQuxHereIndexRouteImport } from './routes/foo/$bar/$qux/_here/index' -import { Route as NotFoundDeepBCDRouteImport } from './routes/not-found/deep/b/c/d' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', - getParentRoute: () => rootRouteImport, -} as any) -const AsyncScriptsRoute = AsyncScriptsRouteImport.update({ - id: '/async-scripts', - 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', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - 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', - getParentRoute: () => rootRouteImport, -} as any) -const LinksRoute = LinksRouteImport.update({ - id: '/links', - path: '/links', - getParentRoute: () => rootRouteImport, -} as any) -const NotFoundRouteRoute = NotFoundRouteRouteImport.update({ - id: '/not-found', - path: '/not-found', - getParentRoute: () => rootRouteImport, -} as any) -const PlainTsTypeAssertionRoute = PlainTsTypeAssertionRouteImport.update({ - id: '/plain-ts-type-assertion', - path: '/plain-ts-type-assertion', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const PrimitiveBeforeloadErrorRoute = - PrimitiveBeforeloadErrorRouteImport.update({ - id: '/primitive-beforeload-error', - path: '/primitive-beforeload-error', - getParentRoute: () => rootRouteImport, - } as any) -const RawStreamRoute = RawStreamRouteImport.update({ - id: '/raw-stream', - path: '/raw-stream', - getParentRoute: () => rootRouteImport, -} as any) -const ScriptsRoute = ScriptsRouteImport.update({ - id: '/scripts', - path: '/scripts', - getParentRoute: () => rootRouteImport, -} as any) -const SearchParamsRouteRoute = SearchParamsRouteRouteImport.update({ - id: '/search-params', - path: '/search-params', - getParentRoute: () => rootRouteImport, -} as any) -const SpecialCharsRouteRoute = SpecialCharsRouteRouteImport.update({ - id: '/specialChars', - path: '/specialChars', - getParentRoute: () => rootRouteImport, -} as any) -const StreamRoute = StreamRouteImport.update({ - id: '/stream', - path: '/stream', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const TypeOnlyReexportRoute = TypeOnlyReexportRouteImport.update({ @@ -186,165 +79,115 @@ const TypeOnlyReexportRoute = TypeOnlyReexportRouteImport.update({ path: '/type-only-reexport', getParentRoute: () => rootRouteImport, } as any) -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const StreamRoute = StreamRouteImport.update({ + id: '/stream', + path: '/stream', getParentRoute: () => rootRouteImport, } as any) -const LayoutLayout2Route = LayoutLayout2RouteImport.update({ - id: '/_layout-2', - getParentRoute: () => LayoutRoute, -} as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const ScriptsRoute = ScriptsRouteImport.update({ + id: '/scripts', + path: '/scripts', 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', +const RawStreamRoute = RawStreamRouteImport.update({ + id: '/raw-stream', + path: '/raw-stream', getParentRoute: () => rootRouteImport, } as any) +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) +const LinksRoute = LinksRouteImport.update({ + id: '/links', + path: '/links', + getParentRoute: () => rootRouteImport, +} as any) +const InlineScriptsRoute = InlineScriptsRouteImport.update({ + id: '/inline-scripts', + path: '/inline-scripts', + getParentRoute: () => rootRouteImport, +} as any) +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', + getParentRoute: () => rootRouteImport, +} as any) +const ClientOnlyRoute = ClientOnlyRouteImport.update({ + id: '/client-only', + path: '/client-only', + getParentRoute: () => rootRouteImport, +} as any) +const AsyncScriptsRoute = AsyncScriptsRouteImport.update({ + id: '/async-scripts', + path: '/async-scripts', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', + getParentRoute: () => rootRouteImport, +} as any) +const SpecialCharsRouteRoute = SpecialCharsRouteRouteImport.update({ + id: '/specialChars', + path: '/specialChars', + getParentRoute: () => rootRouteImport, +} as any) +const SearchParamsRouteRoute = SearchParamsRouteRouteImport.update({ + id: '/search-params', + path: '/search-params', + getParentRoute: () => rootRouteImport, +} as any) +const NotFoundRouteRoute = NotFoundRouteRouteImport.update({ + id: '/not-found', + path: '/not-found', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, +} as any) +const SearchParamsIndexRoute = SearchParamsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SearchParamsRouteRoute, +} as any) +const RedirectIndexRoute = RedirectIndexRouteImport.update({ + id: '/redirect/', + path: '/redirect/', + getParentRoute: () => rootRouteImport, +} as any) +const RawStreamIndexRoute = RawStreamIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => RawStreamRoute, +} as any) +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) +const NotFoundIndexRoute = NotFoundIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => NotFoundRouteRoute, +} as any) const MultiCookieRedirectIndexRoute = MultiCookieRedirectIndexRouteImport.update({ id: '/multi-cookie-redirect/', path: '/multi-cookie-redirect/', getParentRoute: () => rootRouteImport, } as any) -const MultiCookieRedirectTargetRoute = - MultiCookieRedirectTargetRouteImport.update({ - id: '/multi-cookie-redirect/target', - path: '/multi-cookie-redirect/target', - getParentRoute: () => rootRouteImport, - } as any) -const NotFoundIndexRoute = NotFoundIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => NotFoundRouteRoute, -} as any) -const NotFoundDeepRouteRoute = NotFoundDeepRouteRouteImport.update({ - id: '/deep', - path: '/deep', - getParentRoute: () => NotFoundRouteRoute, -} as any) -const NotFoundParentBoundaryRouteRoute = - NotFoundParentBoundaryRouteRouteImport.update({ - id: '/parent-boundary', - path: '/parent-boundary', - getParentRoute: () => NotFoundRouteRoute, - } as any) -const NotFoundViaBeforeLoadRoute = NotFoundViaBeforeLoadRouteImport.update({ - id: '/via-beforeLoad', - path: '/via-beforeLoad', - getParentRoute: () => NotFoundRouteRoute, -} as any) -const NotFoundViaBeforeLoadTargetRootRoute = - NotFoundViaBeforeLoadTargetRootRouteImport.update({ - id: '/via-beforeLoad-target-root', - path: '/via-beforeLoad-target-root', - getParentRoute: () => NotFoundRouteRoute, - } as any) -const NotFoundViaLoaderRoute = NotFoundViaLoaderRouteImport.update({ - id: '/via-loader', - path: '/via-loader', - getParentRoute: () => NotFoundRouteRoute, -} as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const RawStreamIndexRoute = RawStreamIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => RawStreamRoute, -} as any) -const RawStreamClientCallRoute = RawStreamClientCallRouteImport.update({ - id: '/client-call', - path: '/client-call', - getParentRoute: () => RawStreamRoute, -} as any) -const RawStreamSsrBinaryHintRoute = RawStreamSsrBinaryHintRouteImport.update({ - id: '/ssr-binary-hint', - path: '/ssr-binary-hint', - getParentRoute: () => RawStreamRoute, -} as any) -const RawStreamSsrMixedRoute = RawStreamSsrMixedRouteImport.update({ - id: '/ssr-mixed', - path: '/ssr-mixed', - getParentRoute: () => RawStreamRoute, -} as any) -const RawStreamSsrMultipleRoute = RawStreamSsrMultipleRouteImport.update({ - id: '/ssr-multiple', - path: '/ssr-multiple', - getParentRoute: () => RawStreamRoute, -} as any) -const RawStreamSsrSingleRoute = RawStreamSsrSingleRouteImport.update({ - id: '/ssr-single', - path: '/ssr-single', - getParentRoute: () => RawStreamRoute, -} as any) -const RawStreamSsrTextHintRoute = RawStreamSsrTextHintRouteImport.update({ - id: '/ssr-text-hint', - path: '/ssr-text-hint', - getParentRoute: () => RawStreamRoute, -} as any) -const RedirectIndexRoute = RedirectIndexRouteImport.update({ - id: '/redirect/', - path: '/redirect/', - getParentRoute: () => rootRouteImport, -} as any) -const RedirectTargetRoute = RedirectTargetRouteImport.update({ - id: '/redirect/$target', - path: '/redirect/$target', - getParentRoute: () => rootRouteImport, -} as any) -const SearchParamsIndexRoute = SearchParamsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SearchParamsRouteRoute, -} as any) -const SearchParamsDefaultRoute = SearchParamsDefaultRouteImport.update({ - id: '/default', - path: '/default', - getParentRoute: () => SearchParamsRouteRoute, -} as any) -const SearchParamsLoaderThrowsRedirectRoute = - SearchParamsLoaderThrowsRedirectRouteImport.update({ - id: '/loader-throws-redirect', - path: '/loader-throws-redirect', - getParentRoute: () => SearchParamsRouteRoute, - } as any) -const SpecialCharsParamRoute = SpecialCharsParamRouteImport.update({ - id: '/$param', - path: '/$param', - getParentRoute: () => SpecialCharsRouteRoute, -} as any) -const SpecialCharsHashRoute = SpecialCharsHashRouteImport.update({ - id: '/hash', - path: '/hash', - getParentRoute: () => SpecialCharsRouteRoute, -} as any) -const SpecialCharsMalformedRouteRoute = - SpecialCharsMalformedRouteRouteImport.update({ - id: '/malformed', - path: '/malformed', - getParentRoute: () => SpecialCharsRouteRoute, - } as any) -const SpecialCharsSearchRoute = SpecialCharsSearchRouteImport.update({ - id: '/search', - path: '/search', - getParentRoute: () => SpecialCharsRouteRoute, +const UsersUserIdRoute = UsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => UsersRoute, } as any) const SpecialCharsChar45824Char54620Char48124Char44397Route = SpecialCharsChar45824Char54620Char48124Char44397RouteImport.update({ @@ -352,100 +195,150 @@ const SpecialCharsChar45824Char54620Char48124Char44397Route = path: '/대한민국', getParentRoute: () => SpecialCharsRouteRoute, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, +const SpecialCharsSearchRoute = SpecialCharsSearchRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => SpecialCharsRouteRoute, } as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, +const SpecialCharsHashRoute = SpecialCharsHashRouteImport.update({ + id: '/hash', + path: '/hash', + getParentRoute: () => SpecialCharsRouteRoute, } as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, +const SpecialCharsParamRoute = SpecialCharsParamRouteImport.update({ + id: '/$param', + path: '/$param', + getParentRoute: () => SpecialCharsRouteRoute, } as any) -const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ - id: '/layout-b', - path: '/layout-b', - getParentRoute: () => LayoutLayout2Route, +const SearchParamsLoaderThrowsRedirectRoute = + SearchParamsLoaderThrowsRedirectRouteImport.update({ + id: '/loader-throws-redirect', + path: '/loader-throws-redirect', + getParentRoute: () => SearchParamsRouteRoute, + } as any) +const SearchParamsDefaultRoute = SearchParamsDefaultRouteImport.update({ + id: '/default', + path: '/default', + getParentRoute: () => SearchParamsRouteRoute, } as any) -const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => ApiUsersRoute, -} as any) -const Issue6221ArticleIdRoute = Issue6221ArticleIdRouteImport.update({ - id: '/issue-6221/article/$id', - path: '/issue-6221/article/$id', +const RedirectTargetRoute = RedirectTargetRouteImport.update({ + id: '/redirect/$target', + path: '/redirect/$target', getParentRoute: () => rootRouteImport, } as any) -const NotFoundDeepIndexRoute = NotFoundDeepIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => NotFoundDeepRouteRoute, +const RawStreamSsrTextHintRoute = RawStreamSsrTextHintRouteImport.update({ + id: '/ssr-text-hint', + path: '/ssr-text-hint', + getParentRoute: () => RawStreamRoute, } as any) -const NotFoundDeepBRouteRoute = NotFoundDeepBRouteRouteImport.update({ - id: '/b', - path: '/b', - getParentRoute: () => NotFoundDeepRouteRoute, +const RawStreamSsrSingleRoute = RawStreamSsrSingleRouteImport.update({ + id: '/ssr-single', + path: '/ssr-single', + getParentRoute: () => RawStreamRoute, } as any) -const NotFoundParentBoundaryIndexRoute = - NotFoundParentBoundaryIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => NotFoundParentBoundaryRouteRoute, +const RawStreamSsrMultipleRoute = RawStreamSsrMultipleRouteImport.update({ + id: '/ssr-multiple', + path: '/ssr-multiple', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrMixedRoute = RawStreamSsrMixedRouteImport.update({ + id: '/ssr-mixed', + path: '/ssr-mixed', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrBinaryHintRoute = RawStreamSsrBinaryHintRouteImport.update({ + id: '/ssr-binary-hint', + path: '/ssr-binary-hint', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamClientCallRoute = RawStreamClientCallRouteImport.update({ + id: '/client-call', + path: '/client-call', + getParentRoute: () => RawStreamRoute, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const NotFoundViaLoaderRoute = NotFoundViaLoaderRouteImport.update({ + id: '/via-loader', + path: '/via-loader', + getParentRoute: () => NotFoundRouteRoute, +} as any) +const NotFoundViaBeforeLoadRoute = NotFoundViaBeforeLoadRouteImport.update({ + id: '/via-beforeLoad', + path: '/via-beforeLoad', + getParentRoute: () => NotFoundRouteRoute, +} as any) +const MultiCookieRedirectTargetRoute = + MultiCookieRedirectTargetRouteImport.update({ + id: '/multi-cookie-redirect/target', + path: '/multi-cookie-redirect/target', + getParentRoute: () => rootRouteImport, } as any) -const NotFoundParentBoundaryViaBeforeLoadRoute = - NotFoundParentBoundaryViaBeforeLoadRouteImport.update({ - id: '/via-beforeLoad', - path: '/via-beforeLoad', - getParentRoute: () => NotFoundParentBoundaryRouteRoute, - } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', getParentRoute: () => rootRouteImport, } as any) +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, +} as any) +const SpecialCharsMalformedRouteRoute = + SpecialCharsMalformedRouteRouteImport.update({ + id: '/malformed', + path: '/malformed', + getParentRoute: () => SpecialCharsRouteRoute, + } as any) const RedirectTargetIndexRoute = RedirectTargetIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => RedirectTargetRoute, } as any) +const SpecialCharsMalformedSearchRoute = + SpecialCharsMalformedSearchRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => SpecialCharsMalformedRouteRoute, + } as any) +const SpecialCharsMalformedParamRoute = + SpecialCharsMalformedParamRouteImport.update({ + id: '/$param', + path: '/$param', + getParentRoute: () => SpecialCharsMalformedRouteRoute, + } as any) +const RedirectTargetViaLoaderRoute = RedirectTargetViaLoaderRouteImport.update({ + id: '/via-loader', + path: '/via-loader', + getParentRoute: () => RedirectTargetRoute, +} as any) const RedirectTargetViaBeforeLoadRoute = RedirectTargetViaBeforeLoadRouteImport.update({ id: '/via-beforeLoad', path: '/via-beforeLoad', getParentRoute: () => RedirectTargetRoute, } as any) -const RedirectTargetViaLoaderRoute = RedirectTargetViaLoaderRouteImport.update({ - id: '/via-loader', - path: '/via-loader', - getParentRoute: () => RedirectTargetRoute, -} as any) -const SpecialCharsMalformedParamRoute = - SpecialCharsMalformedParamRouteImport.update({ - id: '/$param', - path: '/$param', - getParentRoute: () => SpecialCharsMalformedRouteRoute, - } as any) -const SpecialCharsMalformedSearchRoute = - SpecialCharsMalformedSearchRouteImport.update({ - id: '/search', - path: '/search', - getParentRoute: () => SpecialCharsMalformedRouteRoute, - } as any) -const FooBarQuxHereRoute = FooBarQuxHereRouteImport.update({ - id: '/foo/$bar/$qux/_here', - path: '/foo/$bar/$qux', +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', getParentRoute: () => rootRouteImport, } as any) -const NotFoundDeepBCRouteRoute = NotFoundDeepBCRouteRouteImport.update({ - id: '/c', - path: '/c', - getParentRoute: () => NotFoundDeepBRouteRoute, +const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => ApiUsersRoute, +} as any) +const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ + id: '/layout-b', + path: '/layout-b', + getParentRoute: () => LayoutLayout2Route, +} as any) +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, } as any) const RedirectTargetServerFnIndexRoute = RedirectTargetServerFnIndexRouteImport.update({ @@ -453,34 +346,34 @@ const RedirectTargetServerFnIndexRoute = path: '/serverFn/', getParentRoute: () => RedirectTargetRoute, } as any) -const RedirectTargetServerFnViaBeforeLoadRoute = - RedirectTargetServerFnViaBeforeLoadRouteImport.update({ - id: '/serverFn/via-beforeLoad', - path: '/serverFn/via-beforeLoad', - getParentRoute: () => RedirectTargetRoute, - } as any) -const RedirectTargetServerFnViaLoaderRoute = - RedirectTargetServerFnViaLoaderRouteImport.update({ - id: '/serverFn/via-loader', - path: '/serverFn/via-loader', - getParentRoute: () => RedirectTargetRoute, - } as any) const RedirectTargetServerFnViaUseServerFnRoute = RedirectTargetServerFnViaUseServerFnRouteImport.update({ id: '/serverFn/via-useServerFn', path: '/serverFn/via-useServerFn', getParentRoute: () => RedirectTargetRoute, } as any) +const RedirectTargetServerFnViaLoaderRoute = + RedirectTargetServerFnViaLoaderRouteImport.update({ + id: '/serverFn/via-loader', + path: '/serverFn/via-loader', + getParentRoute: () => RedirectTargetRoute, + } as any) +const RedirectTargetServerFnViaBeforeLoadRoute = + RedirectTargetServerFnViaBeforeLoadRouteImport.update({ + id: '/serverFn/via-beforeLoad', + path: '/serverFn/via-beforeLoad', + getParentRoute: () => RedirectTargetRoute, + } as any) +const FooBarQuxHereRoute = FooBarQuxHereRouteImport.update({ + id: '/foo/$bar/$qux/_here', + path: '/foo/$bar/$qux', + getParentRoute: () => rootRouteImport, +} as any) const FooBarQuxHereIndexRoute = FooBarQuxHereIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => FooBarQuxHereRoute, } as any) -const NotFoundDeepBCDRoute = NotFoundDeepBCDRouteImport.update({ - id: '/d', - path: '/d', - getParentRoute: () => NotFoundDeepBCRouteRoute, -} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -488,30 +381,20 @@ 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 '/posts': typeof PostsRouteWithChildren - '/primitive-beforeload-error': typeof PrimitiveBeforeloadErrorRoute '/raw-stream': typeof RawStreamRouteWithChildren '/scripts': typeof ScriptsRoute '/stream': typeof StreamRoute '/type-only-reexport': typeof TypeOnlyReexportRoute '/users': typeof UsersRouteWithChildren - '/not-found/deep': typeof NotFoundDeepRouteRouteWithChildren - '/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 - '/not-found/via-beforeLoad-target-root': typeof NotFoundViaBeforeLoadTargetRootRoute '/not-found/via-loader': typeof NotFoundViaLoaderRoute '/posts/$postId': typeof PostsPostIdRoute '/raw-stream/client-call': typeof RawStreamClientCallRoute @@ -535,52 +418,37 @@ export interface FileRoutesByFullPath { '/redirect/': typeof RedirectIndexRoute '/search-params/': typeof SearchParamsIndexRoute '/users/': typeof UsersIndexRoute - '/not-found/deep/b': typeof NotFoundDeepBRouteRouteWithChildren '/layout-a': typeof LayoutLayout2LayoutARoute '/layout-b': typeof LayoutLayout2LayoutBRoute '/api/users/$id': typeof ApiUsersIdRoute - '/issue-6221/article/$id': typeof Issue6221ArticleIdRoute - '/not-found/parent-boundary/via-beforeLoad': typeof NotFoundParentBoundaryViaBeforeLoadRoute '/posts/$postId/deep': typeof PostsPostIdDeepRoute '/redirect/$target/via-beforeLoad': typeof RedirectTargetViaBeforeLoadRoute '/redirect/$target/via-loader': typeof RedirectTargetViaLoaderRoute '/specialChars/malformed/$param': typeof SpecialCharsMalformedParamRoute '/specialChars/malformed/search': typeof SpecialCharsMalformedSearchRoute - '/not-found/deep/': typeof NotFoundDeepIndexRoute - '/not-found/parent-boundary/': typeof NotFoundParentBoundaryIndexRoute '/redirect/$target/': typeof RedirectTargetIndexRoute - '/not-found/deep/b/c': typeof NotFoundDeepBCRouteRouteWithChildren '/foo/$bar/$qux': typeof FooBarQuxHereRouteWithChildren '/redirect/$target/serverFn/via-beforeLoad': typeof RedirectTargetServerFnViaBeforeLoadRoute '/redirect/$target/serverFn/via-loader': typeof RedirectTargetServerFnViaLoaderRoute '/redirect/$target/serverFn/via-useServerFn': typeof RedirectTargetServerFnViaUseServerFnRoute '/redirect/$target/serverFn/': typeof RedirectTargetServerFnIndexRoute - '/not-found/deep/b/c/d': typeof NotFoundDeepBCDRoute '/foo/$bar/$qux/': typeof FooBarQuxHereIndexRoute } 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 - '/primitive-beforeload-error': typeof PrimitiveBeforeloadErrorRoute '/scripts': typeof ScriptsRoute '/stream': typeof StreamRoute '/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 - '/not-found/via-beforeLoad-target-root': typeof NotFoundViaBeforeLoadTargetRootRoute '/not-found/via-loader': typeof NotFoundViaLoaderRoute '/posts/$postId': typeof PostsPostIdRoute '/raw-stream/client-call': typeof RawStreamClientCallRoute @@ -603,26 +471,19 @@ export interface FileRoutesByTo { '/redirect': typeof RedirectIndexRoute '/search-params': typeof SearchParamsIndexRoute '/users': typeof UsersIndexRoute - '/not-found/deep/b': typeof NotFoundDeepBRouteRouteWithChildren '/layout-a': typeof LayoutLayout2LayoutARoute '/layout-b': typeof LayoutLayout2LayoutBRoute '/api/users/$id': typeof ApiUsersIdRoute - '/issue-6221/article/$id': typeof Issue6221ArticleIdRoute - '/not-found/parent-boundary/via-beforeLoad': typeof NotFoundParentBoundaryViaBeforeLoadRoute '/posts/$postId/deep': typeof PostsPostIdDeepRoute '/redirect/$target/via-beforeLoad': typeof RedirectTargetViaBeforeLoadRoute '/redirect/$target/via-loader': typeof RedirectTargetViaLoaderRoute '/specialChars/malformed/$param': typeof SpecialCharsMalformedParamRoute '/specialChars/malformed/search': typeof SpecialCharsMalformedSearchRoute - '/not-found/deep': typeof NotFoundDeepIndexRoute - '/not-found/parent-boundary': typeof NotFoundParentBoundaryIndexRoute '/redirect/$target': typeof RedirectTargetIndexRoute - '/not-found/deep/b/c': typeof NotFoundDeepBCRouteRouteWithChildren '/redirect/$target/serverFn/via-beforeLoad': typeof RedirectTargetServerFnViaBeforeLoadRoute '/redirect/$target/serverFn/via-loader': typeof RedirectTargetServerFnViaLoaderRoute '/redirect/$target/serverFn/via-useServerFn': typeof RedirectTargetServerFnViaUseServerFnRoute '/redirect/$target/serverFn': typeof RedirectTargetServerFnIndexRoute - '/not-found/deep/b/c/d': typeof NotFoundDeepBCDRoute '/foo/$bar/$qux': typeof FooBarQuxHereIndexRoute } export interface FileRoutesById { @@ -633,31 +494,21 @@ 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 '/posts': typeof PostsRouteWithChildren - '/primitive-beforeload-error': typeof PrimitiveBeforeloadErrorRoute '/raw-stream': typeof RawStreamRouteWithChildren '/scripts': typeof ScriptsRoute '/stream': typeof StreamRoute '/type-only-reexport': typeof TypeOnlyReexportRoute '/users': typeof UsersRouteWithChildren - '/not-found/deep': typeof NotFoundDeepRouteRouteWithChildren - '/not-found/parent-boundary': typeof NotFoundParentBoundaryRouteRouteWithChildren '/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 - '/not-found/via-beforeLoad-target-root': typeof NotFoundViaBeforeLoadTargetRootRoute '/not-found/via-loader': typeof NotFoundViaLoaderRoute '/posts/$postId': typeof PostsPostIdRoute '/raw-stream/client-call': typeof RawStreamClientCallRoute @@ -681,27 +532,20 @@ export interface FileRoutesById { '/redirect/': typeof RedirectIndexRoute '/search-params/': typeof SearchParamsIndexRoute '/users/': typeof UsersIndexRoute - '/not-found/deep/b': typeof NotFoundDeepBRouteRouteWithChildren '/_layout/_layout-2/layout-a': typeof LayoutLayout2LayoutARoute '/_layout/_layout-2/layout-b': typeof LayoutLayout2LayoutBRoute '/api/users/$id': typeof ApiUsersIdRoute - '/issue-6221/article/$id': typeof Issue6221ArticleIdRoute - '/not-found/parent-boundary/via-beforeLoad': typeof NotFoundParentBoundaryViaBeforeLoadRoute '/posts_/$postId/deep': typeof PostsPostIdDeepRoute '/redirect/$target/via-beforeLoad': typeof RedirectTargetViaBeforeLoadRoute '/redirect/$target/via-loader': typeof RedirectTargetViaLoaderRoute '/specialChars/malformed/$param': typeof SpecialCharsMalformedParamRoute '/specialChars/malformed/search': typeof SpecialCharsMalformedSearchRoute - '/not-found/deep/': typeof NotFoundDeepIndexRoute - '/not-found/parent-boundary/': typeof NotFoundParentBoundaryIndexRoute '/redirect/$target/': typeof RedirectTargetIndexRoute - '/not-found/deep/b/c': typeof NotFoundDeepBCRouteRouteWithChildren '/foo/$bar/$qux/_here': typeof FooBarQuxHereRouteWithChildren '/redirect/$target/serverFn/via-beforeLoad': typeof RedirectTargetServerFnViaBeforeLoadRoute '/redirect/$target/serverFn/via-loader': typeof RedirectTargetServerFnViaLoaderRoute '/redirect/$target/serverFn/via-useServerFn': typeof RedirectTargetServerFnViaUseServerFnRoute '/redirect/$target/serverFn/': typeof RedirectTargetServerFnIndexRoute - '/not-found/deep/b/c/d': typeof NotFoundDeepBCDRoute '/foo/$bar/$qux/_here/': typeof FooBarQuxHereIndexRoute } export interface FileRouteTypes { @@ -712,30 +556,20 @@ export interface FileRouteTypes { | '/search-params' | '/specialChars' | '/async-scripts' - | '/auth-docs' | '/client-only' | '/deferred' - | '/execution-local' - | '/execution-rpc' | '/inline-scripts' | '/links' - | '/plain-ts-type-assertion' | '/posts' - | '/primitive-beforeload-error' | '/raw-stream' | '/scripts' | '/stream' | '/type-only-reexport' | '/users' - | '/not-found/deep' - | '/not-found/parent-boundary' | '/specialChars/malformed' | '/api/users' - | '/auth-docs/private' - | '/issue-6221/dashboard' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' - | '/not-found/via-beforeLoad-target-root' | '/not-found/via-loader' | '/posts/$postId' | '/raw-stream/client-call' @@ -759,52 +593,37 @@ export interface FileRouteTypes { | '/redirect/' | '/search-params/' | '/users/' - | '/not-found/deep/b' | '/layout-a' | '/layout-b' | '/api/users/$id' - | '/issue-6221/article/$id' - | '/not-found/parent-boundary/via-beforeLoad' | '/posts/$postId/deep' | '/redirect/$target/via-beforeLoad' | '/redirect/$target/via-loader' | '/specialChars/malformed/$param' | '/specialChars/malformed/search' - | '/not-found/deep/' - | '/not-found/parent-boundary/' | '/redirect/$target/' - | '/not-found/deep/b/c' | '/foo/$bar/$qux' | '/redirect/$target/serverFn/via-beforeLoad' | '/redirect/$target/serverFn/via-loader' | '/redirect/$target/serverFn/via-useServerFn' | '/redirect/$target/serverFn/' - | '/not-found/deep/b/c/d' | '/foo/$bar/$qux/' fileRoutesByTo: FileRoutesByTo to: | '/' | '/specialChars' | '/async-scripts' - | '/auth-docs' | '/client-only' | '/deferred' - | '/execution-local' - | '/execution-rpc' | '/inline-scripts' | '/links' - | '/plain-ts-type-assertion' - | '/primitive-beforeload-error' | '/scripts' | '/stream' | '/type-only-reexport' | '/specialChars/malformed' | '/api/users' - | '/auth-docs/private' - | '/issue-6221/dashboard' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' - | '/not-found/via-beforeLoad-target-root' | '/not-found/via-loader' | '/posts/$postId' | '/raw-stream/client-call' @@ -827,26 +646,19 @@ export interface FileRouteTypes { | '/redirect' | '/search-params' | '/users' - | '/not-found/deep/b' | '/layout-a' | '/layout-b' | '/api/users/$id' - | '/issue-6221/article/$id' - | '/not-found/parent-boundary/via-beforeLoad' | '/posts/$postId/deep' | '/redirect/$target/via-beforeLoad' | '/redirect/$target/via-loader' | '/specialChars/malformed/$param' | '/specialChars/malformed/search' - | '/not-found/deep' - | '/not-found/parent-boundary' | '/redirect/$target' - | '/not-found/deep/b/c' | '/redirect/$target/serverFn/via-beforeLoad' | '/redirect/$target/serverFn/via-loader' | '/redirect/$target/serverFn/via-useServerFn' | '/redirect/$target/serverFn' - | '/not-found/deep/b/c/d' | '/foo/$bar/$qux' id: | '__root__' @@ -856,31 +668,21 @@ export interface FileRouteTypes { | '/specialChars' | '/_layout' | '/async-scripts' - | '/auth-docs' | '/client-only' | '/deferred' - | '/execution-local' - | '/execution-rpc' | '/inline-scripts' | '/links' - | '/plain-ts-type-assertion' | '/posts' - | '/primitive-beforeload-error' | '/raw-stream' | '/scripts' | '/stream' | '/type-only-reexport' | '/users' - | '/not-found/deep' - | '/not-found/parent-boundary' | '/specialChars/malformed' | '/_layout/_layout-2' | '/api/users' - | '/auth-docs/private' - | '/issue-6221/dashboard' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' - | '/not-found/via-beforeLoad-target-root' | '/not-found/via-loader' | '/posts/$postId' | '/raw-stream/client-call' @@ -904,27 +706,20 @@ export interface FileRouteTypes { | '/redirect/' | '/search-params/' | '/users/' - | '/not-found/deep/b' | '/_layout/_layout-2/layout-a' | '/_layout/_layout-2/layout-b' | '/api/users/$id' - | '/issue-6221/article/$id' - | '/not-found/parent-boundary/via-beforeLoad' | '/posts_/$postId/deep' | '/redirect/$target/via-beforeLoad' | '/redirect/$target/via-loader' | '/specialChars/malformed/$param' | '/specialChars/malformed/search' - | '/not-found/deep/' - | '/not-found/parent-boundary/' | '/redirect/$target/' - | '/not-found/deep/b/c' | '/foo/$bar/$qux/_here' | '/redirect/$target/serverFn/via-beforeLoad' | '/redirect/$target/serverFn/via-loader' | '/redirect/$target/serverFn/via-useServerFn' | '/redirect/$target/serverFn/' - | '/not-found/deep/b/c/d' | '/foo/$bar/$qux/_here/' fileRoutesById: FileRoutesById } @@ -935,165 +730,32 @@ 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 PostsRoute: typeof PostsRouteWithChildren - PrimitiveBeforeloadErrorRoute: typeof PrimitiveBeforeloadErrorRoute RawStreamRoute: typeof RawStreamRouteWithChildren ScriptsRoute: typeof ScriptsRoute StreamRoute: typeof StreamRoute TypeOnlyReexportRoute: typeof TypeOnlyReexportRoute UsersRoute: typeof UsersRouteWithChildren ApiUsersRoute: typeof ApiUsersRouteWithChildren - Issue6221DashboardRoute: typeof Issue6221DashboardRoute MultiCookieRedirectTargetRoute: typeof MultiCookieRedirectTargetRoute RedirectTargetRoute: typeof RedirectTargetRouteWithChildren MultiCookieRedirectIndexRoute: typeof MultiCookieRedirectIndexRoute RedirectIndexRoute: typeof RedirectIndexRoute - Issue6221ArticleIdRoute: typeof Issue6221ArticleIdRoute PostsPostIdDeepRoute: typeof PostsPostIdDeepRoute FooBarQuxHereRoute: typeof FooBarQuxHereRouteWithChildren } declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout': { - id: '/_layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/async-scripts': { - id: '/async-scripts' - path: '/async-scripts' - fullPath: '/async-scripts' - 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' - fullPath: '/client-only' - preLoaderRoute: typeof ClientOnlyRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - 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' - fullPath: '/inline-scripts' - preLoaderRoute: typeof InlineScriptsRouteImport - parentRoute: typeof rootRouteImport - } - '/links': { - id: '/links' - path: '/links' - fullPath: '/links' - preLoaderRoute: typeof LinksRouteImport - parentRoute: typeof rootRouteImport - } - '/not-found': { - id: '/not-found' - path: '/not-found' - fullPath: '/not-found' - preLoaderRoute: typeof NotFoundRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/plain-ts-type-assertion': { - id: '/plain-ts-type-assertion' - path: '/plain-ts-type-assertion' - fullPath: '/plain-ts-type-assertion' - preLoaderRoute: typeof PlainTsTypeAssertionRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/primitive-beforeload-error': { - id: '/primitive-beforeload-error' - path: '/primitive-beforeload-error' - fullPath: '/primitive-beforeload-error' - preLoaderRoute: typeof PrimitiveBeforeloadErrorRouteImport - parentRoute: typeof rootRouteImport - } - '/raw-stream': { - id: '/raw-stream' - path: '/raw-stream' - fullPath: '/raw-stream' - preLoaderRoute: typeof RawStreamRouteImport - parentRoute: typeof rootRouteImport - } - '/scripts': { - id: '/scripts' - path: '/scripts' - fullPath: '/scripts' - preLoaderRoute: typeof ScriptsRouteImport - parentRoute: typeof rootRouteImport - } - '/search-params': { - id: '/search-params' - path: '/search-params' - fullPath: '/search-params' - preLoaderRoute: typeof SearchParamsRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/specialChars': { - id: '/specialChars' - path: '/specialChars' - fullPath: '/specialChars' - preLoaderRoute: typeof SpecialCharsRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/stream': { - id: '/stream' - path: '/stream' - fullPath: '/stream' - preLoaderRoute: typeof StreamRouteImport + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/type-only-reexport': { @@ -1103,173 +765,110 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof TypeOnlyReexportRouteImport parentRoute: typeof rootRouteImport } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/stream': { + id: '/stream' + path: '/stream' + fullPath: '/stream' + preLoaderRoute: typeof StreamRouteImport parentRoute: typeof rootRouteImport } - '/_layout/_layout-2': { - id: '/_layout/_layout-2' + '/scripts': { + id: '/scripts' + path: '/scripts' + fullPath: '/scripts' + preLoaderRoute: typeof ScriptsRouteImport + parentRoute: typeof rootRouteImport + } + '/raw-stream': { + id: '/raw-stream' + path: '/raw-stream' + fullPath: '/raw-stream' + preLoaderRoute: typeof RawStreamRouteImport + parentRoute: typeof rootRouteImport + } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/links': { + id: '/links' + path: '/links' + fullPath: '/links' + preLoaderRoute: typeof LinksRouteImport + parentRoute: typeof rootRouteImport + } + '/inline-scripts': { + id: '/inline-scripts' + path: '/inline-scripts' + fullPath: '/inline-scripts' + preLoaderRoute: typeof InlineScriptsRouteImport + parentRoute: typeof rootRouteImport + } + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/client-only': { + id: '/client-only' + path: '/client-only' + fullPath: '/client-only' + preLoaderRoute: typeof ClientOnlyRouteImport + parentRoute: typeof rootRouteImport + } + '/async-scripts': { + id: '/async-scripts' + path: '/async-scripts' + fullPath: '/async-scripts' + preLoaderRoute: typeof AsyncScriptsRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout': { + id: '/_layout' path: '' fullPath: '/' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute - } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + preLoaderRoute: typeof LayoutRouteImport 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' - fullPath: '/issue-6221/dashboard' - preLoaderRoute: typeof Issue6221DashboardRouteImport + '/specialChars': { + id: '/specialChars' + path: '/specialChars' + fullPath: '/specialChars' + preLoaderRoute: typeof SpecialCharsRouteRouteImport parentRoute: typeof rootRouteImport } - '/multi-cookie-redirect/': { - id: '/multi-cookie-redirect/' - path: '/multi-cookie-redirect' - fullPath: '/multi-cookie-redirect/' - preLoaderRoute: typeof MultiCookieRedirectIndexRouteImport + '/search-params': { + id: '/search-params' + path: '/search-params' + fullPath: '/search-params' + preLoaderRoute: typeof SearchParamsRouteRouteImport parentRoute: typeof rootRouteImport } - '/multi-cookie-redirect/target': { - id: '/multi-cookie-redirect/target' - path: '/multi-cookie-redirect/target' - fullPath: '/multi-cookie-redirect/target' - preLoaderRoute: typeof MultiCookieRedirectTargetRouteImport + '/not-found': { + id: '/not-found' + path: '/not-found' + fullPath: '/not-found' + preLoaderRoute: typeof NotFoundRouteRouteImport parentRoute: typeof rootRouteImport } - '/not-found/': { - id: '/not-found/' + '/': { + id: '/' path: '/' - fullPath: '/not-found/' - preLoaderRoute: typeof NotFoundIndexRouteImport - parentRoute: typeof NotFoundRouteRoute - } - '/not-found/deep': { - id: '/not-found/deep' - path: '/deep' - fullPath: '/not-found/deep' - preLoaderRoute: typeof NotFoundDeepRouteRouteImport - parentRoute: typeof NotFoundRouteRoute - } - '/not-found/parent-boundary': { - id: '/not-found/parent-boundary' - path: '/parent-boundary' - fullPath: '/not-found/parent-boundary' - preLoaderRoute: typeof NotFoundParentBoundaryRouteRouteImport - parentRoute: typeof NotFoundRouteRoute - } - '/not-found/via-beforeLoad': { - id: '/not-found/via-beforeLoad' - path: '/via-beforeLoad' - fullPath: '/not-found/via-beforeLoad' - preLoaderRoute: typeof NotFoundViaBeforeLoadRouteImport - parentRoute: typeof NotFoundRouteRoute - } - '/not-found/via-beforeLoad-target-root': { - id: '/not-found/via-beforeLoad-target-root' - path: '/via-beforeLoad-target-root' - fullPath: '/not-found/via-beforeLoad-target-root' - preLoaderRoute: typeof NotFoundViaBeforeLoadTargetRootRouteImport - parentRoute: typeof NotFoundRouteRoute - } - '/not-found/via-loader': { - id: '/not-found/via-loader' - path: '/via-loader' - fullPath: '/not-found/via-loader' - preLoaderRoute: typeof NotFoundViaLoaderRouteImport - parentRoute: typeof NotFoundRouteRoute - } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/raw-stream/': { - id: '/raw-stream/' - path: '/' - fullPath: '/raw-stream/' - preLoaderRoute: typeof RawStreamIndexRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/client-call': { - id: '/raw-stream/client-call' - path: '/client-call' - fullPath: '/raw-stream/client-call' - preLoaderRoute: typeof RawStreamClientCallRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/ssr-binary-hint': { - id: '/raw-stream/ssr-binary-hint' - path: '/ssr-binary-hint' - fullPath: '/raw-stream/ssr-binary-hint' - preLoaderRoute: typeof RawStreamSsrBinaryHintRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/ssr-mixed': { - id: '/raw-stream/ssr-mixed' - path: '/ssr-mixed' - fullPath: '/raw-stream/ssr-mixed' - preLoaderRoute: typeof RawStreamSsrMixedRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/ssr-multiple': { - id: '/raw-stream/ssr-multiple' - path: '/ssr-multiple' - fullPath: '/raw-stream/ssr-multiple' - preLoaderRoute: typeof RawStreamSsrMultipleRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/ssr-single': { - id: '/raw-stream/ssr-single' - path: '/ssr-single' - fullPath: '/raw-stream/ssr-single' - preLoaderRoute: typeof RawStreamSsrSingleRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/ssr-text-hint': { - id: '/raw-stream/ssr-text-hint' - path: '/ssr-text-hint' - fullPath: '/raw-stream/ssr-text-hint' - preLoaderRoute: typeof RawStreamSsrTextHintRouteImport - parentRoute: typeof RawStreamRoute - } - '/redirect/': { - id: '/redirect/' - path: '/redirect' - fullPath: '/redirect/' - preLoaderRoute: typeof RedirectIndexRouteImport + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/redirect/$target': { - id: '/redirect/$target' - path: '/redirect/$target' - fullPath: '/redirect/$target' - preLoaderRoute: typeof RedirectTargetRouteImport - parentRoute: typeof rootRouteImport + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute } '/search-params/': { id: '/search-params/' @@ -1278,39 +877,53 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof SearchParamsIndexRouteImport parentRoute: typeof SearchParamsRouteRoute } - '/search-params/default': { - id: '/search-params/default' - path: '/default' - fullPath: '/search-params/default' - preLoaderRoute: typeof SearchParamsDefaultRouteImport - parentRoute: typeof SearchParamsRouteRoute + '/redirect/': { + id: '/redirect/' + path: '/redirect' + fullPath: '/redirect/' + preLoaderRoute: typeof RedirectIndexRouteImport + parentRoute: typeof rootRouteImport } - '/search-params/loader-throws-redirect': { - id: '/search-params/loader-throws-redirect' - path: '/loader-throws-redirect' - fullPath: '/search-params/loader-throws-redirect' - preLoaderRoute: typeof SearchParamsLoaderThrowsRedirectRouteImport - parentRoute: typeof SearchParamsRouteRoute + '/raw-stream/': { + id: '/raw-stream/' + path: '/' + fullPath: '/raw-stream/' + preLoaderRoute: typeof RawStreamIndexRouteImport + parentRoute: typeof RawStreamRoute } - '/specialChars/$param': { - id: '/specialChars/$param' - path: '/$param' - fullPath: '/specialChars/$param' - preLoaderRoute: typeof SpecialCharsParamRouteImport - parentRoute: typeof SpecialCharsRouteRoute + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute } - '/specialChars/hash': { - id: '/specialChars/hash' - path: '/hash' - fullPath: '/specialChars/hash' - preLoaderRoute: typeof SpecialCharsHashRouteImport - parentRoute: typeof SpecialCharsRouteRoute + '/not-found/': { + id: '/not-found/' + path: '/' + fullPath: '/not-found/' + preLoaderRoute: typeof NotFoundIndexRouteImport + parentRoute: typeof NotFoundRouteRoute } - '/specialChars/malformed': { - id: '/specialChars/malformed' - path: '/malformed' - fullPath: '/specialChars/malformed' - preLoaderRoute: typeof SpecialCharsMalformedRouteRouteImport + '/multi-cookie-redirect/': { + id: '/multi-cookie-redirect/' + path: '/multi-cookie-redirect' + fullPath: '/multi-cookie-redirect/' + preLoaderRoute: typeof MultiCookieRedirectIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/users/$userId': { + id: '/users/$userId' + path: '/$userId' + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute + } + '/specialChars/대한민국': { + id: '/specialChars/대한민국' + path: '/대한민국' + fullPath: '/specialChars/대한민국' + preLoaderRoute: typeof SpecialCharsChar45824Char54620Char48124Char44397RouteImport parentRoute: typeof SpecialCharsRouteRoute } '/specialChars/search': { @@ -1320,90 +933,132 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof SpecialCharsSearchRouteImport parentRoute: typeof SpecialCharsRouteRoute } - '/specialChars/대한민국': { - id: '/specialChars/대한민국' - path: '/대한민국' - fullPath: '/specialChars/대한민국' - preLoaderRoute: typeof SpecialCharsChar45824Char54620Char48124Char44397RouteImport + '/specialChars/hash': { + id: '/specialChars/hash' + path: '/hash' + fullPath: '/specialChars/hash' + preLoaderRoute: typeof SpecialCharsHashRouteImport parentRoute: typeof SpecialCharsRouteRoute } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute + '/specialChars/$param': { + id: '/specialChars/$param' + path: '/$param' + fullPath: '/specialChars/$param' + preLoaderRoute: typeof SpecialCharsParamRouteImport + parentRoute: typeof SpecialCharsRouteRoute } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute + '/search-params/loader-throws-redirect': { + id: '/search-params/loader-throws-redirect' + path: '/loader-throws-redirect' + fullPath: '/search-params/loader-throws-redirect' + preLoaderRoute: typeof SearchParamsLoaderThrowsRedirectRouteImport + parentRoute: typeof SearchParamsRouteRoute } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route + '/search-params/default': { + id: '/search-params/default' + path: '/default' + fullPath: '/search-params/default' + preLoaderRoute: typeof SearchParamsDefaultRouteImport + parentRoute: typeof SearchParamsRouteRoute } - '/_layout/_layout-2/layout-b': { - id: '/_layout/_layout-2/layout-b' - path: '/layout-b' - fullPath: '/layout-b' - preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport - parentRoute: typeof LayoutLayout2Route - } - '/api/users/$id': { - id: '/api/users/$id' - path: '/$id' - fullPath: '/api/users/$id' - preLoaderRoute: typeof ApiUsersIdRouteImport - parentRoute: typeof ApiUsersRoute - } - '/issue-6221/article/$id': { - id: '/issue-6221/article/$id' - path: '/issue-6221/article/$id' - fullPath: '/issue-6221/article/$id' - preLoaderRoute: typeof Issue6221ArticleIdRouteImport + '/redirect/$target': { + id: '/redirect/$target' + path: '/redirect/$target' + fullPath: '/redirect/$target' + preLoaderRoute: typeof RedirectTargetRouteImport parentRoute: typeof rootRouteImport } - '/not-found/deep/': { - id: '/not-found/deep/' - path: '/' - fullPath: '/not-found/deep/' - preLoaderRoute: typeof NotFoundDeepIndexRouteImport - parentRoute: typeof NotFoundDeepRouteRoute + '/raw-stream/ssr-text-hint': { + id: '/raw-stream/ssr-text-hint' + path: '/ssr-text-hint' + fullPath: '/raw-stream/ssr-text-hint' + preLoaderRoute: typeof RawStreamSsrTextHintRouteImport + parentRoute: typeof RawStreamRoute } - '/not-found/deep/b': { - id: '/not-found/deep/b' - path: '/b' - fullPath: '/not-found/deep/b' - preLoaderRoute: typeof NotFoundDeepBRouteRouteImport - parentRoute: typeof NotFoundDeepRouteRoute + '/raw-stream/ssr-single': { + id: '/raw-stream/ssr-single' + path: '/ssr-single' + fullPath: '/raw-stream/ssr-single' + preLoaderRoute: typeof RawStreamSsrSingleRouteImport + parentRoute: typeof RawStreamRoute } - '/not-found/parent-boundary/': { - id: '/not-found/parent-boundary/' - path: '/' - fullPath: '/not-found/parent-boundary/' - preLoaderRoute: typeof NotFoundParentBoundaryIndexRouteImport - parentRoute: typeof NotFoundParentBoundaryRouteRoute + '/raw-stream/ssr-multiple': { + id: '/raw-stream/ssr-multiple' + path: '/ssr-multiple' + fullPath: '/raw-stream/ssr-multiple' + preLoaderRoute: typeof RawStreamSsrMultipleRouteImport + parentRoute: typeof RawStreamRoute } - '/not-found/parent-boundary/via-beforeLoad': { - id: '/not-found/parent-boundary/via-beforeLoad' + '/raw-stream/ssr-mixed': { + id: '/raw-stream/ssr-mixed' + path: '/ssr-mixed' + fullPath: '/raw-stream/ssr-mixed' + preLoaderRoute: typeof RawStreamSsrMixedRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-binary-hint': { + id: '/raw-stream/ssr-binary-hint' + path: '/ssr-binary-hint' + fullPath: '/raw-stream/ssr-binary-hint' + preLoaderRoute: typeof RawStreamSsrBinaryHintRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/client-call': { + id: '/raw-stream/client-call' + path: '/client-call' + fullPath: '/raw-stream/client-call' + preLoaderRoute: typeof RawStreamClientCallRouteImport + parentRoute: typeof RawStreamRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute + } + '/not-found/via-loader': { + id: '/not-found/via-loader' + path: '/via-loader' + fullPath: '/not-found/via-loader' + preLoaderRoute: typeof NotFoundViaLoaderRouteImport + parentRoute: typeof NotFoundRouteRoute + } + '/not-found/via-beforeLoad': { + id: '/not-found/via-beforeLoad' path: '/via-beforeLoad' - fullPath: '/not-found/parent-boundary/via-beforeLoad' - preLoaderRoute: typeof NotFoundParentBoundaryViaBeforeLoadRouteImport - parentRoute: typeof NotFoundParentBoundaryRouteRoute + fullPath: '/not-found/via-beforeLoad' + preLoaderRoute: typeof NotFoundViaBeforeLoadRouteImport + parentRoute: typeof NotFoundRouteRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport + '/multi-cookie-redirect/target': { + id: '/multi-cookie-redirect/target' + path: '/multi-cookie-redirect/target' + fullPath: '/multi-cookie-redirect/target' + preLoaderRoute: typeof MultiCookieRedirectTargetRouteImport parentRoute: typeof rootRouteImport } + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout/_layout-2': { + id: '/_layout/_layout-2' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute + } + '/specialChars/malformed': { + id: '/specialChars/malformed' + path: '/malformed' + fullPath: '/specialChars/malformed' + preLoaderRoute: typeof SpecialCharsMalformedRouteRouteImport + parentRoute: typeof SpecialCharsRouteRoute + } '/redirect/$target/': { id: '/redirect/$target/' path: '/' @@ -1411,6 +1066,27 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof RedirectTargetIndexRouteImport parentRoute: typeof RedirectTargetRoute } + '/specialChars/malformed/search': { + id: '/specialChars/malformed/search' + path: '/search' + fullPath: '/specialChars/malformed/search' + preLoaderRoute: typeof SpecialCharsMalformedSearchRouteImport + parentRoute: typeof SpecialCharsMalformedRouteRoute + } + '/specialChars/malformed/$param': { + id: '/specialChars/malformed/$param' + path: '/$param' + fullPath: '/specialChars/malformed/$param' + preLoaderRoute: typeof SpecialCharsMalformedParamRouteImport + parentRoute: typeof SpecialCharsMalformedRouteRoute + } + '/redirect/$target/via-loader': { + id: '/redirect/$target/via-loader' + path: '/via-loader' + fullPath: '/redirect/$target/via-loader' + preLoaderRoute: typeof RedirectTargetViaLoaderRouteImport + parentRoute: typeof RedirectTargetRoute + } '/redirect/$target/via-beforeLoad': { id: '/redirect/$target/via-beforeLoad' path: '/via-beforeLoad' @@ -1418,40 +1094,33 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof RedirectTargetViaBeforeLoadRouteImport parentRoute: typeof RedirectTargetRoute } - '/redirect/$target/via-loader': { - id: '/redirect/$target/via-loader' - path: '/via-loader' - fullPath: '/redirect/$target/via-loader' - preLoaderRoute: typeof RedirectTargetViaLoaderRouteImport - parentRoute: typeof RedirectTargetRoute - } - '/specialChars/malformed/$param': { - id: '/specialChars/malformed/$param' - path: '/$param' - fullPath: '/specialChars/malformed/$param' - preLoaderRoute: typeof SpecialCharsMalformedParamRouteImport - parentRoute: typeof SpecialCharsMalformedRouteRoute - } - '/specialChars/malformed/search': { - id: '/specialChars/malformed/search' - path: '/search' - fullPath: '/specialChars/malformed/search' - preLoaderRoute: typeof SpecialCharsMalformedSearchRouteImport - parentRoute: typeof SpecialCharsMalformedRouteRoute - } - '/foo/$bar/$qux/_here': { - id: '/foo/$bar/$qux/_here' - path: '/foo/$bar/$qux' - fullPath: '/foo/$bar/$qux' - preLoaderRoute: typeof FooBarQuxHereRouteImport + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport parentRoute: typeof rootRouteImport } - '/not-found/deep/b/c': { - id: '/not-found/deep/b/c' - path: '/c' - fullPath: '/not-found/deep/b/c' - preLoaderRoute: typeof NotFoundDeepBCRouteRouteImport - parentRoute: typeof NotFoundDeepBRouteRoute + '/api/users/$id': { + id: '/api/users/$id' + path: '/$id' + fullPath: '/api/users/$id' + preLoaderRoute: typeof ApiUsersIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/_layout/_layout-2/layout-b': { + id: '/_layout/_layout-2/layout-b' + path: '/layout-b' + fullPath: '/layout-b' + preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport + parentRoute: typeof LayoutLayout2Route + } + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route } '/redirect/$target/serverFn/': { id: '/redirect/$target/serverFn/' @@ -1460,20 +1129,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof RedirectTargetServerFnIndexRouteImport parentRoute: typeof RedirectTargetRoute } - '/redirect/$target/serverFn/via-beforeLoad': { - id: '/redirect/$target/serverFn/via-beforeLoad' - path: '/serverFn/via-beforeLoad' - fullPath: '/redirect/$target/serverFn/via-beforeLoad' - preLoaderRoute: typeof RedirectTargetServerFnViaBeforeLoadRouteImport - parentRoute: typeof RedirectTargetRoute - } - '/redirect/$target/serverFn/via-loader': { - id: '/redirect/$target/serverFn/via-loader' - path: '/serverFn/via-loader' - fullPath: '/redirect/$target/serverFn/via-loader' - preLoaderRoute: typeof RedirectTargetServerFnViaLoaderRouteImport - parentRoute: typeof RedirectTargetRoute - } '/redirect/$target/serverFn/via-useServerFn': { id: '/redirect/$target/serverFn/via-useServerFn' path: '/serverFn/via-useServerFn' @@ -1481,6 +1136,27 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof RedirectTargetServerFnViaUseServerFnRouteImport parentRoute: typeof RedirectTargetRoute } + '/redirect/$target/serverFn/via-loader': { + id: '/redirect/$target/serverFn/via-loader' + path: '/serverFn/via-loader' + fullPath: '/redirect/$target/serverFn/via-loader' + preLoaderRoute: typeof RedirectTargetServerFnViaLoaderRouteImport + parentRoute: typeof RedirectTargetRoute + } + '/redirect/$target/serverFn/via-beforeLoad': { + id: '/redirect/$target/serverFn/via-beforeLoad' + path: '/serverFn/via-beforeLoad' + fullPath: '/redirect/$target/serverFn/via-beforeLoad' + preLoaderRoute: typeof RedirectTargetServerFnViaBeforeLoadRouteImport + parentRoute: typeof RedirectTargetRoute + } + '/foo/$bar/$qux/_here': { + id: '/foo/$bar/$qux/_here' + path: '/foo/$bar/$qux' + fullPath: '/foo/$bar/$qux' + preLoaderRoute: typeof FooBarQuxHereRouteImport + parentRoute: typeof rootRouteImport + } '/foo/$bar/$qux/_here/': { id: '/foo/$bar/$qux/_here/' path: '/' @@ -1488,83 +1164,17 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof FooBarQuxHereIndexRouteImport parentRoute: typeof FooBarQuxHereRoute } - '/not-found/deep/b/c/d': { - id: '/not-found/deep/b/c/d' - path: '/d' - fullPath: '/not-found/deep/b/c/d' - preLoaderRoute: typeof NotFoundDeepBCDRouteImport - parentRoute: typeof NotFoundDeepBCRouteRoute - } } } -interface NotFoundDeepBCRouteRouteChildren { - NotFoundDeepBCDRoute: typeof NotFoundDeepBCDRoute -} - -const NotFoundDeepBCRouteRouteChildren: NotFoundDeepBCRouteRouteChildren = { - NotFoundDeepBCDRoute: NotFoundDeepBCDRoute, -} - -const NotFoundDeepBCRouteRouteWithChildren = - NotFoundDeepBCRouteRoute._addFileChildren(NotFoundDeepBCRouteRouteChildren) - -interface NotFoundDeepBRouteRouteChildren { - NotFoundDeepBCRouteRoute: typeof NotFoundDeepBCRouteRouteWithChildren -} - -const NotFoundDeepBRouteRouteChildren: NotFoundDeepBRouteRouteChildren = { - NotFoundDeepBCRouteRoute: NotFoundDeepBCRouteRouteWithChildren, -} - -const NotFoundDeepBRouteRouteWithChildren = - NotFoundDeepBRouteRoute._addFileChildren(NotFoundDeepBRouteRouteChildren) - -interface NotFoundDeepRouteRouteChildren { - NotFoundDeepBRouteRoute: typeof NotFoundDeepBRouteRouteWithChildren - NotFoundDeepIndexRoute: typeof NotFoundDeepIndexRoute -} - -const NotFoundDeepRouteRouteChildren: NotFoundDeepRouteRouteChildren = { - NotFoundDeepBRouteRoute: NotFoundDeepBRouteRouteWithChildren, - NotFoundDeepIndexRoute: NotFoundDeepIndexRoute, -} - -const NotFoundDeepRouteRouteWithChildren = - NotFoundDeepRouteRoute._addFileChildren(NotFoundDeepRouteRouteChildren) - -interface NotFoundParentBoundaryRouteRouteChildren { - NotFoundParentBoundaryViaBeforeLoadRoute: typeof NotFoundParentBoundaryViaBeforeLoadRoute - NotFoundParentBoundaryIndexRoute: typeof NotFoundParentBoundaryIndexRoute -} - -const NotFoundParentBoundaryRouteRouteChildren: NotFoundParentBoundaryRouteRouteChildren = - { - NotFoundParentBoundaryViaBeforeLoadRoute: - NotFoundParentBoundaryViaBeforeLoadRoute, - NotFoundParentBoundaryIndexRoute: NotFoundParentBoundaryIndexRoute, - } - -const NotFoundParentBoundaryRouteRouteWithChildren = - NotFoundParentBoundaryRouteRoute._addFileChildren( - NotFoundParentBoundaryRouteRouteChildren, - ) - interface NotFoundRouteRouteChildren { - NotFoundDeepRouteRoute: typeof NotFoundDeepRouteRouteWithChildren - NotFoundParentBoundaryRouteRoute: typeof NotFoundParentBoundaryRouteRouteWithChildren NotFoundViaBeforeLoadRoute: typeof NotFoundViaBeforeLoadRoute - NotFoundViaBeforeLoadTargetRootRoute: typeof NotFoundViaBeforeLoadTargetRootRoute NotFoundViaLoaderRoute: typeof NotFoundViaLoaderRoute NotFoundIndexRoute: typeof NotFoundIndexRoute } const NotFoundRouteRouteChildren: NotFoundRouteRouteChildren = { - NotFoundDeepRouteRoute: NotFoundDeepRouteRouteWithChildren, - NotFoundParentBoundaryRouteRoute: - NotFoundParentBoundaryRouteRouteWithChildren, NotFoundViaBeforeLoadRoute: NotFoundViaBeforeLoadRoute, - NotFoundViaBeforeLoadTargetRootRoute: NotFoundViaBeforeLoadTargetRootRoute, NotFoundViaLoaderRoute: NotFoundViaLoaderRoute, NotFoundIndexRoute: NotFoundIndexRoute, } @@ -1649,18 +1259,6 @@ const LayoutRouteChildren: LayoutRouteChildren = { const LayoutRouteWithChildren = LayoutRoute._addFileChildren(LayoutRouteChildren) -interface AuthDocsRouteChildren { - AuthDocsPrivateRoute: typeof AuthDocsPrivateRoute -} - -const AuthDocsRouteChildren: AuthDocsRouteChildren = { - AuthDocsPrivateRoute: AuthDocsPrivateRoute, -} - -const AuthDocsRouteWithChildren = AuthDocsRoute._addFileChildren( - AuthDocsRouteChildren, -) - interface PostsRouteChildren { PostsPostIdRoute: typeof PostsPostIdRoute PostsIndexRoute: typeof PostsIndexRoute @@ -1766,28 +1364,21 @@ 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, PostsRoute: PostsRouteWithChildren, - PrimitiveBeforeloadErrorRoute: PrimitiveBeforeloadErrorRoute, RawStreamRoute: RawStreamRouteWithChildren, ScriptsRoute: ScriptsRoute, StreamRoute: StreamRoute, TypeOnlyReexportRoute: TypeOnlyReexportRoute, UsersRoute: UsersRouteWithChildren, ApiUsersRoute: ApiUsersRouteWithChildren, - Issue6221DashboardRoute: Issue6221DashboardRoute, MultiCookieRedirectTargetRoute: MultiCookieRedirectTargetRoute, RedirectTargetRoute: RedirectTargetRouteWithChildren, MultiCookieRedirectIndexRoute: MultiCookieRedirectIndexRoute, RedirectIndexRoute: RedirectIndexRoute, - Issue6221ArticleIdRoute: Issue6221ArticleIdRoute, PostsPostIdDeepRoute: PostsPostIdDeepRoute, FooBarQuxHereRoute: FooBarQuxHereRouteWithChildren, } diff --git a/e2e/react-start/basic/src/routes/__root.tsx b/e2e/react-start/basic/src/routes/__root.tsx index ed521817d6..3aa315c67e 100644 --- a/e2e/react-start/basic/src/routes/__root.tsx +++ b/e2e/react-start/basic/src/routes/__root.tsx @@ -1,18 +1,16 @@ /// import * as React from 'react' import { - ClientOnly, HeadContent, Link, Outlet, Scripts, createRootRoute, - useRouterState, } from '@tanstack/react-router' import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary' import { NotFound } from '~/components/NotFound' -import '~/styles/app.css' +import appCss from '~/styles/app.css?url' import { seo } from '~/utils/seo' export const Route = createRootRoute({ @@ -32,6 +30,7 @@ export const Route = createRootRoute({ }), ], links: [ + { rel: 'stylesheet', href: appCss }, { rel: 'apple-touch-icon', sizes: '180x180', @@ -94,11 +93,6 @@ const RouterDevtools = ) function RootDocument({ children }: { children: React.ReactNode }) { - const { isLoading, status } = useRouterState({ - select: (state) => ({ isLoading: state.isLoading, status: state.status }), - structuralSharing: true, - }) - return ( @@ -181,14 +175,6 @@ function RootDocument({ children }: { children: React.ReactNode }) { > redirect {' '} - - not-found - {' '} Client Only {' '} - - Server function loader - {' '}

- - - {children}
This is an inline styled div
diff --git a/e2e/react-start/basic/src/routes/api.users.ts b/e2e/react-start/basic/src/routes/api.users.ts index d6fff7c5af..9e055549ef 100644 --- a/e2e/react-start/basic/src/routes/api.users.ts +++ b/e2e/react-start/basic/src/routes/api.users.ts @@ -3,14 +3,18 @@ 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')({ server: { handlers: { GET: async ({ request }) => { console.info('Fetching users... @', request.url) - const res = await axios.get>( - 'https://jsonplaceholder.typicode.com/users', - ) + const res = await axios.get>(`${queryURL}/users`) const list = res.data.slice(0, 10) diff --git a/e2e/react-start/basic/src/routes/api/users.$id.ts b/e2e/react-start/basic/src/routes/api/users.$id.ts index 797dffb637..ac665381f1 100644 --- a/e2e/react-start/basic/src/routes/api/users.$id.ts +++ b/e2e/react-start/basic/src/routes/api/users.$id.ts @@ -2,15 +2,19 @@ import { createFileRoute } from '@tanstack/react-router' import axios from 'redaxios' import type { User } from '~/utils/users' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} + export const Route = createFileRoute('/api/users/$id')({ server: { handlers: { GET: async ({ request, params }) => { console.info(`Fetching users by id=${params.id}... @`, request.url) try { - const res = await axios.get( - `https://jsonplaceholder.typicode.com/users/${params.id}`, - ) + const res = await axios.get(`${queryURL}/users/` + params.id) return Response.json({ id: res.data.id, diff --git a/e2e/react-start/basic/src/routes/auth-docs.private.tsx b/e2e/react-start/basic/src/routes/auth-docs.private.tsx deleted file mode 100644 index 85fc8a0fc9..0000000000 --- a/e2e/react-start/basic/src/routes/auth-docs.private.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { createFileRoute, redirect } from '@tanstack/react-router' -import { getPrivateDataFn } from '../utils/auth-docs' - -export const Route = createFileRoute('/auth-docs/private')({ - beforeLoad: ({ context }) => { - if (!context.user) { - throw redirect({ to: '/auth-docs' }) - } - }, - loader: () => getPrivateDataFn(), - component: PrivatePage, -}) - -function PrivatePage() { - const message = Route.useLoaderData() - return

{message}

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

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

-
-
- - - -
-

{error}

-
- - -

{privateResult}

- -
- ) -} diff --git a/e2e/react-start/basic/src/routes/deferred.tsx b/e2e/react-start/basic/src/routes/deferred.tsx index a6bd45f8c2..9c6e3064b8 100644 --- a/e2e/react-start/basic/src/routes/deferred.tsx +++ b/e2e/react-start/basic/src/routes/deferred.tsx @@ -3,13 +3,13 @@ import { createServerFn } from '@tanstack/react-start' import { Suspense, useState } from 'react' const personServerFn = createServerFn({ method: 'GET' }) - .validator((data: { name: string }) => data) + .inputValidator((data: { name: string }) => data) .handler(({ data }) => { return { name: data.name, randomNumber: Math.floor(Math.random() * 100) } }) const slowServerFn = createServerFn({ method: 'GET' }) - .validator((data: { name: string }) => data) + .inputValidator((data: { name: string }) => data) .handler(async ({ data }) => { await new Promise((r) => setTimeout(r, 1000)) return { name: data.name, randomNumber: Math.floor(Math.random() * 100) } diff --git a/e2e/react-start/basic/src/routes/execution-local.tsx b/e2e/react-start/basic/src/routes/execution-local.tsx deleted file mode 100644 index 477cd81740..0000000000 --- a/e2e/react-start/basic/src/routes/execution-local.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { readOnlyOnServer } from '~/utils/execution-functions' - -// This intentionally fails during browser navigation. It is the negative case -// for the environment-functions troubleshooting guide. -export const Route = createFileRoute('/execution-local')({ - loader: () => readOnlyOnServer(), - component: Result, - errorComponent: ({ error }) => ( -

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

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

{Route.useLoaderData()}

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

{Route.useLoaderData()}

- - Call the server-only helper directly - - - ) -} diff --git a/e2e/react-start/basic/src/routes/issue-6221.article.$id.tsx b/e2e/react-start/basic/src/routes/issue-6221.article.$id.tsx deleted file mode 100644 index c923a5f1cb..0000000000 --- a/e2e/react-start/basic/src/routes/issue-6221.article.$id.tsx +++ /dev/null @@ -1,42 +0,0 @@ -import { Link, createFileRoute } from '@tanstack/react-router' -import { createClientOnlyFn } from '@tanstack/react-start' - -const isAuthed = createClientOnlyFn( - () => localStorage.getItem('issue-6221-auth') === 'good', -) - -const fetchArticle = async (id: string) => { - await new Promise((resolve) => setTimeout(resolve, 1000)) - return isAuthed() - ? { - title: `Article Title for ${id}`, - content: `Article content for ${id}`, - } - : null -} - -export const Route = createFileRoute('/issue-6221/article/$id')({ - ssr: false, - loader: ({ params }) => fetchArticle(params.id), - head: ({ loaderData }) => ({ - meta: [{ title: loaderData?.title ?? 'title n/a' }], - }), - component: Article, -}) - -function Article() { - const article = Route.useLoaderData() - - return ( -
- - Dashboard - - {article ? ( -
{article.content}
- ) : ( -
Article Not Accessible.
- )} -
- ) -} diff --git a/e2e/react-start/basic/src/routes/issue-6221.dashboard.tsx b/e2e/react-start/basic/src/routes/issue-6221.dashboard.tsx deleted file mode 100644 index 8c93da669c..0000000000 --- a/e2e/react-start/basic/src/routes/issue-6221.dashboard.tsx +++ /dev/null @@ -1,6 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/issue-6221/dashboard')({ - head: () => ({ meta: [{ title: 'Dashboard' }] }), - component: () =>
Dashboard
, -}) diff --git a/e2e/react-start/basic/src/routes/not-found/deep/b/c/d.tsx b/e2e/react-start/basic/src/routes/not-found/deep/b/c/d.tsx deleted file mode 100644 index 04ecde7707..0000000000 --- a/e2e/react-start/basic/src/routes/not-found/deep/b/c/d.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import { createFileRoute, notFound } from '@tanstack/react-router' -import type { NotFoundRouteProps } from '@tanstack/react-router' - -export const Route = createFileRoute('/not-found/deep/b/c/d')({ - loaderDeps: ({ search }) => ({ - throwAt: search.throwAt, - }), - beforeLoad: ({ search }) => { - if (search.throwAt === 'd') { - throw notFound({ - data: { source: 'd-beforeLoad' }, - }) - } - }, - loader: ({ deps }) => { - if (deps.throwAt === 'c') { - throw new Error('d-loader-should-not-run-when-c-beforeLoad-throws') - } - return { ready: true } - }, - component: RouteComponent, - notFoundComponent: (props: NotFoundRouteProps) => ( -
- Not Found at /not-found/deep/b/c/d ( - {(props.data as { source?: string })?.source ?? 'unknown'}) -
- ), -}) - -function RouteComponent() { - return ( -
- Hello "/not-found/deep/b/c/d"! -
- ) -} diff --git a/e2e/react-start/basic/src/routes/not-found/deep/b/c/route.tsx b/e2e/react-start/basic/src/routes/not-found/deep/b/c/route.tsx deleted file mode 100644 index 6a33d013f7..0000000000 --- a/e2e/react-start/basic/src/routes/not-found/deep/b/c/route.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import { Outlet, createFileRoute, notFound } from '@tanstack/react-router' -import type { NotFoundRouteProps } from '@tanstack/react-router' - -export const Route = createFileRoute('/not-found/deep/b/c')({ - beforeLoad: ({ search }) => { - if (search.throwAt === 'c') { - throw notFound({ - data: { source: 'c-beforeLoad' }, - }) - } - }, - component: () => , - notFoundComponent: (props: NotFoundRouteProps) => ( -
- Not Found at /not-found/deep/b/c ( - {(props.data as { source?: string })?.source ?? 'unknown'}) -
- ), -}) diff --git a/e2e/react-start/basic/src/routes/not-found/deep/b/route.tsx b/e2e/react-start/basic/src/routes/not-found/deep/b/route.tsx deleted file mode 100644 index 92a9c4ee36..0000000000 --- a/e2e/react-start/basic/src/routes/not-found/deep/b/route.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import { Outlet, createFileRoute, notFound } from '@tanstack/react-router' -import type { NotFoundRouteProps } from '@tanstack/react-router' - -export const Route = createFileRoute('/not-found/deep/b')({ - beforeLoad: ({ search }) => { - if (search.throwAt === 'b') { - throw notFound({ - data: { source: 'b-beforeLoad' }, - }) - } - }, - component: () => , - notFoundComponent: (props: NotFoundRouteProps) => ( -
- Not Found at /not-found/deep/b ( - {(props.data as { source?: string })?.source ?? 'unknown'}) -
- ), -}) diff --git a/e2e/react-start/basic/src/routes/not-found/deep/index.tsx b/e2e/react-start/basic/src/routes/not-found/deep/index.tsx deleted file mode 100644 index fcfa1e6f01..0000000000 --- a/e2e/react-start/basic/src/routes/not-found/deep/index.tsx +++ /dev/null @@ -1,42 +0,0 @@ -import { Link, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/not-found/deep/')({ - component: RouteComponent, -}) - -function RouteComponent() { - return ( -
-
- - /not-found/deep/b/c/d?throwAt=d - -
-
- - /not-found/deep/b/c/d?throwAt=c - -
-
- - /not-found/deep/b/c/d?throwAt=b - -
-
- ) -} diff --git a/e2e/react-start/basic/src/routes/not-found/deep/route.tsx b/e2e/react-start/basic/src/routes/not-found/deep/route.tsx deleted file mode 100644 index 9e6870c858..0000000000 --- a/e2e/react-start/basic/src/routes/not-found/deep/route.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import z from 'zod' - -export const Route = createFileRoute('/not-found/deep')({ - validateSearch: z.object({ - throwAt: z.enum(['b', 'c', 'd']).optional(), - }), - component: () => , -}) diff --git a/e2e/react-start/basic/src/routes/not-found/index.tsx b/e2e/react-start/basic/src/routes/not-found/index.tsx index 73fa45fba7..e754f83c74 100644 --- a/e2e/react-start/basic/src/routes/not-found/index.tsx +++ b/e2e/react-start/basic/src/routes/not-found/index.tsx @@ -25,36 +25,6 @@ export const Route = createFileRoute('/not-found/')({ via-loader
-
- - via-beforeLoad-target-root (shows global not-found) - -
-
- - parent-boundary test cases - -
-
- - deep test cases - -
) }, diff --git a/e2e/react-start/basic/src/routes/not-found/parent-boundary/index.tsx b/e2e/react-start/basic/src/routes/not-found/parent-boundary/index.tsx deleted file mode 100644 index ba84aaccb5..0000000000 --- a/e2e/react-start/basic/src/routes/not-found/parent-boundary/index.tsx +++ /dev/null @@ -1,31 +0,0 @@ -import { Link, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/not-found/parent-boundary/')({ - component: RouteComponent, -}) - -function RouteComponent() { - return ( -
-
- - via-beforeLoad (with routeId) - -
-
- - via-beforeLoad (without routeId) - -
-
- ) -} diff --git a/e2e/react-start/basic/src/routes/not-found/parent-boundary/route.tsx b/e2e/react-start/basic/src/routes/not-found/parent-boundary/route.tsx deleted file mode 100644 index c8784d2220..0000000000 --- a/e2e/react-start/basic/src/routes/not-found/parent-boundary/route.tsx +++ /dev/null @@ -1,31 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import type { NotFoundRouteProps } from '@tanstack/react-router' - -export const Route = createFileRoute('/not-found/parent-boundary')({ - loader: () => ({ - parentLoaderData: 'ready', - }), - component: RouteComponent, - notFoundComponent: ParentBoundaryNotFoundComponent, -}) - -function RouteComponent() { - return ( -
- -
- ) -} - -function ParentBoundaryNotFoundComponent(props: NotFoundRouteProps) { - const loaderData = Route.useLoaderData() - - return ( -
-
{loaderData.parentLoaderData}
-
- {(props.data as { source?: string })?.source ?? 'unknown'} -
-
- ) -} diff --git a/e2e/react-start/basic/src/routes/not-found/parent-boundary/via-beforeLoad.tsx b/e2e/react-start/basic/src/routes/not-found/parent-boundary/via-beforeLoad.tsx deleted file mode 100644 index b6e6ab0aa0..0000000000 --- a/e2e/react-start/basic/src/routes/not-found/parent-boundary/via-beforeLoad.tsx +++ /dev/null @@ -1,32 +0,0 @@ -import { createFileRoute, notFound } from '@tanstack/react-router' -import z from 'zod' -import { Route as ParentBoundaryRoute } from './route' - -export const Route = createFileRoute( - '/not-found/parent-boundary/via-beforeLoad', -)({ - validateSearch: z.object({ - target: z.enum(['parent', 'none']).optional(), - }), - beforeLoad: ({ search }) => { - if (search.target === 'none') { - throw notFound({ - data: { source: 'without-routeId' }, - }) - } - - throw notFound({ - routeId: ParentBoundaryRoute.id, - data: { source: 'with-routeId' }, - }) - }, - component: RouteComponent, -}) - -function RouteComponent() { - return ( -
- Hello "/not-found/parent-boundary/via-beforeLoad"! -
- ) -} diff --git a/e2e/react-start/basic/src/routes/not-found/via-beforeLoad-target-root.tsx b/e2e/react-start/basic/src/routes/not-found/via-beforeLoad-target-root.tsx deleted file mode 100644 index 1f36244cce..0000000000 --- a/e2e/react-start/basic/src/routes/not-found/via-beforeLoad-target-root.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute, notFound, rootRouteId } from '@tanstack/react-router' - -export const Route = createFileRoute('/not-found/via-beforeLoad-target-root')({ - beforeLoad: () => { - throw notFound({ routeId: rootRouteId }) - }, - component: RouteComponent, -}) - -function RouteComponent() { - return ( -
- Hello "/not-found/via-beforeLoad-target-root"! -
- ) -} diff --git a/e2e/react-start/basic/src/routes/plain-ts-type-assertion.tsx b/e2e/react-start/basic/src/routes/plain-ts-type-assertion.tsx deleted file mode 100644 index 7538f2f14e..0000000000 --- a/e2e/react-start/basic/src/routes/plain-ts-type-assertion.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { cast } from '~/utils/cast' - -export const Route = createFileRoute('/plain-ts-type-assertion')({ - component: PlainTsTypeAssertion, -}) - -const regressionValue = cast('plain .ts cast parsed') - -function PlainTsTypeAssertion() { - return ( -
-

Plain TS Type Assertion

-

{regressionValue}

-
- ) -} diff --git a/e2e/react-start/basic/src/routes/posts.tsx b/e2e/react-start/basic/src/routes/posts.tsx index 22fb7e60a8..0f69c18341 100644 --- a/e2e/react-start/basic/src/routes/posts.tsx +++ b/e2e/react-start/basic/src/routes/posts.tsx @@ -1,4 +1,3 @@ -import { useState } from 'react' import { Link, Outlet, createFileRoute } from '@tanstack/react-router' import { fetchPosts } from '~/utils/posts' @@ -17,16 +16,9 @@ export const Route = createFileRoute('/posts')({ function PostsComponent() { const posts = Route.useLoaderData() - const [hydrationCount, setHydrationCount] = useState(0) return (
-
    {[...posts, { id: 'i-do-not-exist', title: 'Non-existent Post' }].map( (post) => { diff --git a/e2e/react-start/basic/src/routes/primitive-beforeload-error.tsx b/e2e/react-start/basic/src/routes/primitive-beforeload-error.tsx deleted file mode 100644 index e76ec5c73e..0000000000 --- a/e2e/react-start/basic/src/routes/primitive-beforeload-error.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/primitive-beforeload-error')({ - beforeLoad: () => { - throw 'primitive beforeLoad error' - }, - component: () => { - return ( -
    - This should not render. -
    - ) - }, - errorComponent: ({ error }) => { - return ( -
    - {String(error)} -
    - ) - }, -}) diff --git a/e2e/react-start/basic/src/routes/raw-stream/client-call.tsx b/e2e/react-start/basic/src/routes/raw-stream/client-call.tsx index faf98c7a37..8179d56808 100644 --- a/e2e/react-start/basic/src/routes/raw-stream/client-call.tsx +++ b/e2e/react-start/basic/src/routes/raw-stream/client-call.tsx @@ -1,32 +1,6 @@ import { createFileRoute } from '@tanstack/react-router' import * as React from 'react' import { - singleRawStreamFn, - multipleRawStreamsFn, - jsonEndsFirstFn, - rawEndsFirstFn, - largeBinaryFn, - mixedStreamingFn, - textHintPureTextFn, - textHintPureBinaryFn, - textHintMixedFn, - binaryHintTextFn, - binaryHintBinaryFn, - interleavedStreamsFn, - burstPauseBurstFn, - threeStreamsFn, - emptyStreamFn, - errorStreamFn, - lateRawStreamFn, - multipleLateStreamsFn, - mixedImmediateLateFn, - createStreamConsumer, - consumeBinaryStream, - collectBytes, - compareBytes, - TEST7_EXPECTED, - TEST8_EXPECTED, - TEST9_EXPECTED, TEST10_EXPECTED, TEST11_EXPECTED, TEST12_STREAM_A_EXPECTED, @@ -35,10 +9,29 @@ import { TEST14_STREAM_A_EXPECTED, TEST14_STREAM_B_EXPECTED, TEST14_STREAM_C_EXPECTED, - LATE_STREAM_EXPECTED, - LATE_STREAM_A_EXPECTED, - LATE_STREAM_B_EXPECTED, - IMMEDIATE_STREAM_EXPECTED, + TEST7_EXPECTED, + TEST8_EXPECTED, + TEST9_EXPECTED, + binaryHintBinaryFn, + binaryHintTextFn, + burstPauseBurstFn, + collectBytes, + compareBytes, + consumeBinaryStream, + createStreamConsumer, + emptyStreamFn, + errorStreamFn, + interleavedStreamsFn, + jsonEndsFirstFn, + largeBinaryFn, + mixedStreamingFn, + multipleRawStreamsFn, + rawEndsFirstFn, + singleRawStreamFn, + textHintMixedFn, + textHintPureBinaryFn, + textHintPureTextFn, + threeStreamsFn, } from '../../raw-stream-fns' export const Route = createFileRoute('/raw-stream/client-call')({ @@ -556,109 +549,6 @@ function ClientCallTests() { {JSON.stringify(results.test16)}
- - {/* Late RawStream Tests Section */} -

Late RawStream Tests (RPC)

-

- These tests verify RawStreams wrapped in Promises (discovered after - initial serialization phase). -

- - {/* Test 17: Single Late RawStream */} -
-

Test 17: Single Late RawStream

- -
{JSON.stringify(results.test17)}
-
- - {/* Test 18: Multiple Late RawStreams */} -
-

Test 18: Multiple Late RawStreams

- -
{JSON.stringify(results.test18)}
-
- - {/* Test 19: Mixed Immediate and Late RawStreams */} -
-

- Test 19: Mixed Immediate and Late RawStreams -

- -
{JSON.stringify(results.test19)}
-
) } diff --git a/e2e/react-start/basic/src/routes/specialChars/search.tsx b/e2e/react-start/basic/src/routes/specialChars/search.tsx index 5840d425ab..152f39f527 100644 --- a/e2e/react-start/basic/src/routes/specialChars/search.tsx +++ b/e2e/react-start/basic/src/routes/specialChars/search.tsx @@ -1,36 +1,19 @@ import { createFileRoute } from '@tanstack/react-router' import z from 'zod' -const isBrowser = typeof window !== 'undefined' - export const Route = createFileRoute('/specialChars/search')({ validateSearch: z.object({ searchParam: z.string(), }), - beforeLoad: () => ({ - beforeLoadOn: isBrowser ? 'client' : 'server', - }), - loader: async () => { - console.log(`[loader] Running on ${isBrowser ? 'client' : 'server'}`) - return { - loadedOn: isBrowser ? 'client' : 'server', - } - }, component: RouteComponent, }) function RouteComponent() { const search = Route.useSearch() - const { beforeLoadOn } = Route.useRouteContext() - const { loadedOn } = Route.useLoaderData() return (
Hello "/specialChars/search"! -
- Before load on: {beforeLoadOn} -
-
Loaded on: {loadedOn}
{search.searchParam}
) diff --git a/e2e/react-start/basic/src/utils/auth-docs.ts b/e2e/react-start/basic/src/utils/auth-docs.ts deleted file mode 100644 index 22b36ee808..0000000000 --- a/e2e/react-start/basic/src/utils/auth-docs.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { createServerFn } from '@tanstack/react-start' -import { redirect } from '@tanstack/react-router' -import { getCookie, setCookie } from '@tanstack/react-start/server' -import { getIronSession } from 'iron-session' - -function getSession() { - return getIronSession<{ email: string }>( - { read: getCookie, write: setCookie }, - { - cookieName: 'auth-docs-test', - password: 'authentication-docs-browser-test-secret-only-2026', - ttl: 60 * 60, - cookieOptions: { - httpOnly: true, - secure: false, - sameSite: 'lax', - path: '/', - }, - }, - ) -} - -export const getCurrentUserFn = createServerFn({ method: 'GET' }).handler( - async () => { - const session = await getSession() - return session.email ? { email: session.email } : null - }, -) - -export const loginFn = createServerFn({ method: 'POST' }) - .validator((data: { email: string; password: string }) => data) - .handler(async ({ data }) => { - // Fixed credentials belong only to this browser-test fixture. - if ( - data.email !== 'reader@example.com' || - data.password !== 'test-password' - ) { - return { error: 'Invalid credentials' } - } - const session = await getSession() - session.email = data.email - await session.save() - throw redirect({ to: '/auth-docs/private' }) - }) - -export const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await getSession() - session.destroy() - throw redirect({ to: '/auth-docs' }) -}) - -export const getPrivateDataFn = createServerFn({ method: 'GET' }).handler( - async () => { - const session = await getSession() - if (!session.email) { - throw new Error('Unauthorized') - } - return 'Private account data' - }, -) diff --git a/e2e/react-start/basic/src/utils/cast.ts b/e2e/react-start/basic/src/utils/cast.ts deleted file mode 100644 index 65c76b343a..0000000000 --- a/e2e/react-start/basic/src/utils/cast.ts +++ /dev/null @@ -1,3 +0,0 @@ -export function cast(value: unknown): T { - return value -} diff --git a/e2e/react-start/basic/src/utils/execution-functions.ts b/e2e/react-start/basic/src/utils/execution-functions.ts deleted file mode 100644 index 97e66573d8..0000000000 --- a/e2e/react-start/basic/src/utils/execution-functions.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { createServerFn, createServerOnlyFn } from '@tanstack/react-start' - -export const readOnlyOnServer = createServerOnlyFn(() => 'Read on the server') - -export const readThroughRpc = createServerFn().handler(() => readOnlyOnServer()) diff --git a/e2e/react-start/basic/src/utils/posts.tsx b/e2e/react-start/basic/src/utils/posts.tsx index 9fdff27673..b2d9f3edec 100644 --- a/e2e/react-start/basic/src/utils/posts.tsx +++ b/e2e/react-start/basic/src/utils/posts.tsx @@ -8,12 +8,18 @@ export type PostType = { body: string } +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} + export const fetchPost = createServerFn({ method: 'GET' }) - .validator((postId: string) => postId) + .inputValidator((postId: string) => postId) .handler(async ({ data: postId }) => { console.info(`Fetching post with id ${postId}...`) const post = await axios - .get(`https://jsonplaceholder.typicode.com/posts/${postId}`) + .get(`${queryURL}/posts/${postId}`) .then((r) => r.data) .catch((err) => { console.error(err) @@ -30,7 +36,7 @@ export const fetchPosts = createServerFn({ method: 'GET' }).handler( async () => { console.info('Fetching posts...') return axios - .get>('https://jsonplaceholder.typicode.com/posts') + .get>(`${queryURL}/posts`) .then((r) => r.data.slice(0, 10)) }, ) diff --git a/e2e/react-start/basic/src/utils/users.tsx b/e2e/react-start/basic/src/utils/users.tsx index 7ba645b383..46be4b1580 100644 --- a/e2e/react-start/basic/src/utils/users.tsx +++ b/e2e/react-start/basic/src/utils/users.tsx @@ -3,3 +3,7 @@ export type User = { name: string email: string } + +const PORT = process.env.VITE_SERVER_PORT || 3000 + +export const DEPLOY_URL = `http://localhost:${PORT}` diff --git a/e2e/react-start/basic/start-mode-config.ts b/e2e/react-start/basic/start-mode-config.ts deleted file mode 100644 index 39ad676625..0000000000 --- a/e2e/react-start/basic/start-mode-config.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { isPrerender } from './tests/utils/isPrerender' -import { isSpaMode } from './tests/utils/isSpaMode' - -const rsbuildClientOutput: 'module' | 'iife' | undefined = (() => { - const output = process.env.TSS_RSB_CLIENT_OUTPUT - - if (output === undefined) return undefined - if (output === 'module') return 'module' - if (output === 'iife') return 'iife' - - throw new Error( - `Invalid TSS_RSB_CLIENT_OUTPUT: ${output}. Expected "module" or "iife".`, - ) -})() - -export function getStartModeConfig() { - return { - spa: isSpaMode - ? { - enabled: true, - prerender: { - outputPath: 'index.html', - }, - } - : undefined, - prerender: isPrerender - ? { - enabled: true, - filter: (page: { path: string }) => - ![ - '/this-route-does-not-exist', - '/redirect', - '/i-do-not-exist', - '/not-found', - '/primitive-beforeload-error', - '/specialChars/search', - '/specialChars/hash', - '/specialChars/malformed', - '/users', - ].some((p) => page.path.includes(p)), - maxRedirects: 100, - } - : undefined, - rsbuild: rsbuildClientOutput - ? { - client: { - output: rsbuildClientOutput, - }, - } - : undefined, - } -} diff --git a/e2e/react-start/basic/tests/auth-docs.spec.ts b/e2e/react-start/basic/tests/auth-docs.spec.ts deleted file mode 100644 index 47a57c9da2..0000000000 --- a/e2e/react-start/basic/tests/auth-docs.spec.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { expect, test } from '@playwright/test' -import { isSpaMode } from './utils/isSpaMode' - -test('authentication docs pattern handles login, logout, route context, and server authorization', async ({ - page, -}) => { - await page.goto('/auth-docs/private') - await expect(page).toHaveURL(/\/auth-docs$/) - await expect(page.getByTestId('auth-docs-user')).toHaveText('Signed out') - - await page - .getByRole('button', { name: 'Request private data directly' }) - .click() - await expect(page.getByTestId('auth-docs-private-result')).toHaveText( - 'Access denied', - ) - - await page.getByLabel('Email', { exact: true }).fill('reader@example.com') - await page.getByLabel('Password', { exact: true }).fill('wrong-password') - await page.getByRole('button', { name: 'Login', exact: true }).click() - await expect(page.getByRole('alert')).toHaveText('Invalid credentials') - await expect(page.getByTestId('auth-docs-user')).toHaveText('Signed out') - - await page.getByLabel('Password', { exact: true }).fill('test-password') - await page.getByRole('button', { name: 'Login', exact: true }).click() - await expect(page).toHaveURL(/\/auth-docs\/private$/) - await expect(page.getByTestId('auth-docs-user')).toHaveText( - 'reader@example.com', - ) - await expect(page.getByTestId('auth-docs-private-page')).toHaveText( - 'Private account data', - ) - - const response = await page.reload() - expect(response?.status()).toBe(200) - if (isSpaMode) { - // The shared SPA shell must not contain authenticated account data. - expect(await response?.text()).not.toContain('reader@example.com') - expect(await response?.text()).not.toContain('Private account data') - } else { - expect(response?.headers()['cache-control']).toBe('private, no-store') - } - await expect(page.getByTestId('auth-docs-user')).toHaveText( - 'reader@example.com', - ) - await page.getByRole('button', { name: 'Logout', exact: true }).click() - await expect(page).toHaveURL(/\/auth-docs$/) - await expect(page.getByTestId('auth-docs-user')).toHaveText('Signed out') - await page - .getByRole('button', { name: 'Request private data directly' }) - .click() - await expect(page.getByTestId('auth-docs-private-result')).toHaveText( - 'Access denied', - ) - await page.goto('/auth-docs/private') - await expect(page).toHaveURL(/\/auth-docs$/) -}) - -test('the authentication form cannot submit credentials before hydration', async ({ - browser, - baseURL, -}) => { - const context = await browser.newContext({ - javaScriptEnabled: false, - baseURL, - }) - const page = await context.newPage() - try { - await page.goto('/auth-docs') - if (isSpaMode) { - // Without JavaScript, the SPA shell cannot render credential controls. - await expect(page.locator('form')).toHaveCount(0) - await expect(page.getByLabel('Email', { exact: true })).toHaveCount(0) - await expect(page.getByLabel('Password', { exact: true })).toHaveCount(0) - await expect( - page.getByRole('button', { name: 'Login', exact: true }), - ).toHaveCount(0) - } else { - await expect(page.locator('form')).toHaveAttribute('method', 'post') - await expect(page.getByLabel('Email', { exact: true })).toBeDisabled() - await expect(page.getByLabel('Password', { exact: true })).toBeDisabled() - await expect( - page.getByRole('button', { name: 'Login', exact: true }), - ).toBeDisabled() - } - } finally { - await context.close() - } -}) diff --git a/e2e/react-start/basic/tests/client-only.spec.ts b/e2e/react-start/basic/tests/client-only.spec.ts index 299744f636..a3b6f99442 100644 --- a/e2e/react-start/basic/tests/client-only.spec.ts +++ b/e2e/react-start/basic/tests/client-only.spec.ts @@ -1,6 +1,5 @@ import { expect } from '@playwright/test' import { test } from '@tanstack/router-e2e-utils' -import { isSpaMode } from './utils/isSpaMode' /** * These tests verify the compiler optimization. @@ -16,15 +15,7 @@ import { isSpaMode } from './utils/isSpaMode' test('ClientOnly renders fallback on server, then client content after hydration', async ({ page, - request, }) => { - const response = await request.get('/client-only') - expect(response.status()).toBe(200) - const html = await response.text() - expect(html).not.toContain('data-testid="window-size"') - if (!isSpaMode) { - expect(html).toContain('Loading window size...') - } // Navigate directly to the client-only route // If the compiler optimization isn't working, this would crash the server // because WindowSize.tsx accesses `window` at module scope diff --git a/e2e/react-start/basic/tests/client-output.spec.ts b/e2e/react-start/basic/tests/client-output.spec.ts deleted file mode 100644 index 951d6668bc..0000000000 --- a/e2e/react-start/basic/tests/client-output.spec.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' - -test.skip( - process.env.TSS_RSB_CLIENT_OUTPUT !== 'iife', - 'IIFE client output assertions only run in rsbuild/ssr/iife mode', -) - -test('SSR HTML emits IIFE client scripts and classic script preloads', async ({ - page, -}) => { - const response = await page.goto('/posts') - const html = await response!.text() - - expect(html).not.toContain('rel="modulepreload"') - expect(html).toMatch(/]+rel="preload"[^>]+as="script"/) - - const clientEntry = html.match( - /]+src="([^"]*\/assets\/js\/index[^"]*)"[^>]*>/, - ) - expect(clientEntry).toBeTruthy() - expect(clientEntry![0]).toContain('async') - expect(clientEntry![0]).not.toContain('type="module"') - - await expect( - page.getByRole('link', { name: 'sunt aut facere repe' }), - ).toBeVisible() - - await page.getByRole('link', { name: 'sunt aut facere repe' }).click() - - await expect(page.getByRole('heading')).toContainText('sunt aut facere') -}) diff --git a/e2e/react-start/basic/tests/environment-functions.spec.ts b/e2e/react-start/basic/tests/environment-functions.spec.ts deleted file mode 100644 index 410b1d999e..0000000000 --- a/e2e/react-start/basic/tests/environment-functions.spec.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { expect, test } from '@playwright/test' -import { isSpaMode } from './utils/isSpaMode' - -const guardError = - 'createServerOnlyFn() functions can only be called on the server!' - -test('a server-only loader works on the server but rejects client navigation', async ({ - page, - request, -}) => { - const direct = await request.get('/execution-local') - expect(direct.status()).toBe(200) - if (!isSpaMode) { - expect(await direct.text()).toContain('Read on the server') - } - await page.goto('/execution-rpc') - await expect(page.getByTestId('execution-result')).toHaveText( - 'Read on the server', - ) - await page - .getByRole('link', { name: 'Call the server-only helper directly' }) - .click() - await expect(page.getByRole('alert')).toHaveText(guardError) -}) - -test('a server function preserves the loader result on direct requests and navigation', async ({ - page, - request, -}) => { - const direct = await request.get('/execution-rpc') - expect(direct.status()).toBe(200) - if (!isSpaMode) { - expect(await direct.text()).toContain('Read on the server') - } - await page.goto('/') - await page - .getByRole('link', { name: 'Server function loader', exact: true }) - .click() - await expect(page.getByTestId('execution-result')).toHaveText( - 'Read on the server', - ) - await page.reload() - await expect(page.getByTestId('execution-result')).toHaveText( - 'Read on the server', - ) -}) diff --git a/e2e/react-start/basic/tests/error-component.spec.ts b/e2e/react-start/basic/tests/error-component.spec.ts deleted file mode 100644 index 3f2beb967c..0000000000 --- a/e2e/react-start/basic/tests/error-component.spec.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' -import { isSpaMode } from './utils/isSpaMode' - -test.use({ - whitelistErrors: [ - 'Failed to load resource: the server responded with a status of 500', - 'primitive beforeLoad error', - ], -}) - -test('beforeLoad primitive throw renders error component on direct visit', async ({ - page, -}) => { - const response = await page.goto('/primitive-beforeload-error') - await page.waitForLoadState('networkidle') - - expect(response?.status()).toBe(isSpaMode ? 200 : 500) - await expect( - page.getByTestId('primitive-beforeload-error-component'), - ).toHaveText('primitive beforeLoad error') - await expect( - page.getByTestId('primitive-beforeload-route-component'), - ).not.toBeInViewport() -}) diff --git a/e2e/react-start/basic/tests/fixture-api.spec.ts b/e2e/react-start/basic/tests/fixture-api.spec.ts deleted file mode 100644 index 6c9b26dc4c..0000000000 --- a/e2e/react-start/basic/tests/fixture-api.spec.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { expect, test } from '@playwright/test' - -test('server API receives canned users without a fixture listener', async ({ - request, -}) => { - const response = await request.get('/api/users') - expect(response.ok()).toBe(true) - const users = await response.json() - expect(users).toHaveLength(10) - expect(users[0]).toMatchObject({ id: 1, name: 'Leanne Graham' }) -}) diff --git a/e2e/react-start/basic/tests/issue-6221-head.spec.ts b/e2e/react-start/basic/tests/issue-6221-head.spec.ts deleted file mode 100644 index 96274ce0f9..0000000000 --- a/e2e/react-start/basic/tests/issue-6221-head.spec.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' -import { isPreview } from './utils/isPreview' -import { isSpaMode } from './utils/isSpaMode' - -// Ported to React from the regression app in -// https://github.com/TanStack/router/pull/6222 -test.skip( - isSpaMode || isPreview, - 'head() coverage for an ssr:false route requires the SSR test mode', -) - -test('browser back uses fresh loaderData for both the body and head (#6221)', async ({ - page, -}) => { - await page.goto('/') - await page.evaluate(() => localStorage.setItem('issue-6221-auth', 'good')) - - await page.goto('/issue-6221/article/1') - - await expect(page.getByTestId('issue-6221-article')).toHaveText( - 'Article content for 1', - ) - await expect(page).toHaveTitle('Article Title for 1') - - await page.evaluate(() => localStorage.removeItem('issue-6221-auth')) - await page.reload() - await expect(page.getByText('Article Not Accessible.')).toBeVisible() - await expect(page).toHaveTitle('title n/a') - - await page.evaluate(() => localStorage.setItem('issue-6221-auth', 'good')) - await page.getByTestId('issue-6221-dashboard-link').click() - await expect(page.getByTestId('issue-6221-dashboard')).toBeVisible() - await expect(page).toHaveTitle('Dashboard') - - await page.goBack() - await expect(page.getByTestId('issue-6221-article')).toHaveText( - 'Article content for 1', - ) - await expect(page).toHaveTitle('Article Title for 1') -}) diff --git a/e2e/react-start/basic/tests/navigation.spec.ts b/e2e/react-start/basic/tests/navigation.spec.ts index ce69a9d92a..36ed021c44 100644 --- a/e2e/react-start/basic/tests/navigation.spec.ts +++ b/e2e/react-start/basic/tests/navigation.spec.ts @@ -17,15 +17,6 @@ test('Navigating to post', async ({ page }) => { await expect(page.getByRole('heading')).toContainText('sunt aut facere') }) -test('plain .ts modules with angle-bracket type assertions build and render', async ({ - page, -}) => { - await page.goto('/plain-ts-type-assertion') - await expect(page.getByTestId('plain-ts-parser-regression')).toContainText( - 'plain .ts cast parsed', - ) -}) - test('Navigating to user', async ({ page }) => { await page.goto('/') await page.waitForURL('/') @@ -39,19 +30,15 @@ test('Navigating nested layouts', async ({ page }) => { await page.waitForURL('/') await page.getByRole('link', { name: 'Layout', exact: true }).click() - await page.waitForURL('/layout-a') await expect(page.locator('body')).toContainText("I'm a layout") await expect(page.locator('body')).toContainText("I'm a nested layout") + + await page.getByRole('link', { name: 'Layout A' }).click() await expect(page.locator('body')).toContainText("I'm layout A!") await page.getByRole('link', { name: 'Layout B' }).click() - await page.waitForURL('/layout-b') await expect(page.locator('body')).toContainText("I'm layout B!") - - await page.getByRole('link', { name: 'Layout A' }).click() - await page.waitForURL('/layout-a') - await expect(page.locator('body')).toContainText("I'm layout A!") }) test('client side navigating to a route with scripts', async ({ page }) => { @@ -59,7 +46,7 @@ test('client side navigating to a route with scripts', async ({ page }) => { await page.waitForURL('/') await page.getByRole('link', { name: 'Scripts', exact: true }).click() await expect(page.getByTestId('scripts-test-heading')).toBeInViewport() - await page.waitForFunction(() => (window as any).SCRIPT_1 === true) + expect(await page.evaluate('window.SCRIPT_1')).toBe(true) expect(await page.evaluate('window.SCRIPT_2')).toBe(undefined) }) @@ -67,7 +54,7 @@ test('directly going to a route with scripts', async ({ page }) => { await page.goto('/scripts') await page.waitForURL('/scripts') await page.waitForLoadState('networkidle') - await page.waitForFunction(() => (window as any).SCRIPT_1 === true) + expect(await page.evaluate('window.SCRIPT_1')).toBe(true) expect(await page.evaluate('window.SCRIPT_2')).toBe(undefined) }) diff --git a/e2e/react-start/basic/tests/not-found.spec.ts b/e2e/react-start/basic/tests/not-found.spec.ts index 339f841b21..6a98b568b3 100644 --- a/e2e/react-start/basic/tests/not-found.spec.ts +++ b/e2e/react-start/basic/tests/not-found.spec.ts @@ -1,7 +1,7 @@ import { expect } from '@playwright/test' import combinateImport from 'combinate' import { test } from '@tanstack/router-e2e-utils' -import { isSpaMode } from './utils/isSpaMode' +import { isSpaMode } from '../tests/utils/isSpaMode' // somehow playwright does not correctly import default exports const combinate = (combinateImport as any).default as typeof combinateImport @@ -9,27 +9,10 @@ const combinate = (combinateImport as any).default as typeof combinateImport test.use({ whitelistErrors: [ 'Failed to load resource: the server responded with a status of 404', + 'NotFound error during hydration for routeId', ], }) test.describe('not-found', () => { - test('direct nested not-found hydrates its already-rendered parent route', async ({ - page, - }) => { - test.skip(isSpaMode, 'issue #5106 requires a server-rendered direct visit') - - const response = await page.goto('/posts/i-do-not-exist') - await page.waitForLoadState('networkidle') - - const serverHtml = await response?.text() - expect(serverHtml).toContain('posts-parent-hydration-counter') - expect(serverHtml).toContain('Post not found') - await expect(page.getByText('Post not found')).toBeInViewport() - const counter = page.getByTestId('posts-parent-hydration-counter') - await expect(counter).toHaveText('Parent hydration count: 0') - await counter.click() - await expect(counter).toHaveText('Parent hydration count: 1') - }) - test(`global not found`, async ({ page }) => { const response = await page.goto(`/this-page-does-not-exist/foo/bar`) @@ -42,7 +25,8 @@ test.describe('not-found', () => { test.describe('throw notFound()', () => { const navigationTestMatrix = combinate({ - thrower: ['beforeLoad', 'loader'] as const, + // TODO beforeLoad! + thrower: [/* 'beforeLoad',*/ 'loader'] as const, preload: [false, true] as const, }) @@ -72,7 +56,9 @@ test.describe('not-found', () => { }) }) const directVisitTestMatrix = combinate({ - thrower: ['beforeLoad', 'loader'] as const, + // TODO beforeLoad! + + thrower: [/* 'beforeLoad',*/ 'loader'] as const, }) directVisitTestMatrix.forEach(({ thrower }) => { @@ -87,97 +73,5 @@ test.describe('not-found', () => { ).not.toBeInViewport() }) }) - - test('direct visit: child beforeLoad notFound with routeId renders parent boundary with parent loader data', async ({ - page, - }) => { - await page.goto('/not-found/parent-boundary/via-beforeLoad') - await page.waitForLoadState('networkidle') - - await expect( - page.getByTestId('parent-boundary-notFound-component'), - ).toBeInViewport() - await expect(page.getByTestId('parent-loader-data')).toHaveText('ready') - await expect( - page.getByTestId('parent-boundary-notFound-source'), - ).toHaveText('with-routeId') - await expect( - page.getByTestId('parent-boundary-child-route-component'), - ).not.toBeInViewport() - }) - - test('direct visit: child beforeLoad notFound without routeId still hydrates and renders parent boundary', async ({ - page, - }) => { - await page.goto('/not-found/parent-boundary/via-beforeLoad?target=none') - await page.waitForLoadState('networkidle') - - await expect( - page.getByTestId('parent-boundary-notFound-component'), - ).toBeInViewport() - await expect(page.getByTestId('parent-loader-data')).toHaveText('ready') - await expect( - page.getByTestId('parent-boundary-notFound-source'), - ).toHaveText('without-routeId') - await expect( - page.getByTestId('parent-boundary-child-route-component'), - ).not.toBeInViewport() - }) - - test('direct visit: beforeLoad notFound with routeId targets root boundary', async ({ - page, - }) => { - await page.goto('/not-found/via-beforeLoad-target-root') - await page.waitForLoadState('networkidle') - - await expect( - page.getByTestId('default-not-found-component'), - ).toBeInViewport() - await expect( - page.getByTestId('via-beforeLoad-target-root-route-component'), - ).not.toBeInViewport() - }) - - test('direct visit: deep hierarchy d throws in beforeLoad and hydrates route d boundary', async ({ - page, - }) => { - await page.goto('/not-found/deep/b/c/d?throwAt=d') - await page.waitForLoadState('networkidle') - - await expect( - page.getByTestId('deep-d-notFound-component'), - ).toBeInViewport() - await expect( - page.getByTestId('deep-d-route-component'), - ).not.toBeInViewport() - }) - - test('direct visit: deep hierarchy c throws in beforeLoad, d loader does not run, and c boundary hydrates', async ({ - page, - }) => { - await page.goto('/not-found/deep/b/c/d?throwAt=c') - await page.waitForLoadState('networkidle') - - await expect( - page.getByTestId('deep-c-notFound-component'), - ).toBeInViewport() - await expect( - page.getByTestId('deep-d-route-component'), - ).not.toBeInViewport() - }) - - test('direct visit: deep hierarchy b throws in beforeLoad and b boundary hydrates', async ({ - page, - }) => { - await page.goto('/not-found/deep/b/c/d?throwAt=b') - await page.waitForLoadState('networkidle') - - await expect( - page.getByTestId('deep-b-notFound-component'), - ).toBeInViewport() - await expect( - page.getByTestId('deep-d-route-component'), - ).not.toBeInViewport() - }) }) }) diff --git a/e2e/react-start/basic/tests/open-redirect-prevention.spec.ts b/e2e/react-start/basic/tests/open-redirect-prevention.spec.ts index bc88c33605..e497109889 100644 --- a/e2e/react-start/basic/tests/open-redirect-prevention.spec.ts +++ b/e2e/react-start/basic/tests/open-redirect-prevention.spec.ts @@ -77,14 +77,22 @@ test.describe('Open redirect prevention', () => { page, baseURL, }) => { - // %0d is kept encoded, so /%0d/test-path/ stays as-is and won't become //test-path/ - await page.goto('/%0d/test-path/') + // When control characters are stripped from paths like /%0d/evil.com/ + // the result could be //evil.com/ which is a protocol-relative URL + // Our fix collapses these to /evil.com/ to prevent external redirects + // This is already tested above, but we verify the collapsed path works + const res = await page.goto('/%0d/test-path/') await page.waitForLoadState('networkidle') // Should stay on the same origin expect(page.url().startsWith(baseURL!)).toBe(true) const url = new URL(page.url()) expect(url.origin).toBe(new URL(baseURL!).origin) + // Path should be collapsed to /test-path (not //test-path/) + expect(url.pathname).toMatch(/^\/test-path\/?$/) + if (!isSpaMode) { + expect(res?.request().redirectedFrom()?.url()).not.toBe(undefined) + } }) }) diff --git a/e2e/react-start/basic/tests/prerendering.spec.ts b/e2e/react-start/basic/tests/prerendering.spec.ts index ddcf720a4c..8506ff9b06 100644 --- a/e2e/react-start/basic/tests/prerendering.spec.ts +++ b/e2e/react-start/basic/tests/prerendering.spec.ts @@ -4,17 +4,13 @@ import { expect } from '@playwright/test' import { test } from '@tanstack/router-e2e-utils' import { isPrerender } from './utils/isPrerender' -const distDir = join( - process.cwd(), - process.env.E2E_DIST_DIR ?? 'dist', - 'client', -) - test.describe('Prerender Static Path Discovery', () => { test.skip(!isPrerender, 'Skipping since not in prerender mode') test.describe('Build Output Verification', () => { test('should automatically discover and prerender static routes', () => { // Check that static routes were automatically discovered and prerendered + const distDir = join(process.cwd(), 'dist', 'client') + // These static routes should be automatically discovered and prerendered expect(existsSync(join(distDir, 'index.html'))).toBe(true) expect(existsSync(join(distDir, 'posts/index.html'))).toBe(true) @@ -38,6 +34,7 @@ test.describe('Prerender Static Path Discovery', () => { test.describe('Static Files Verification', () => { test('should contain prerendered content in posts.html', () => { + const distDir = join(process.cwd(), 'dist', 'client') expect(existsSync(join(distDir, 'posts/index.html'))).toBe(true) // "Select a post." should be in the prerendered HTML diff --git a/e2e/react-start/basic/tests/raw-stream.spec.ts b/e2e/react-start/basic/tests/raw-stream.spec.ts index 3bc6ea88b8..5b0c6a0fff 100644 --- a/e2e/react-start/basic/tests/raw-stream.spec.ts +++ b/e2e/react-start/basic/tests/raw-stream.spec.ts @@ -642,73 +642,3 @@ test.describe('RawStream - Edge Cases (RPC)', () => { expect(result).toContain('Error stream test') }) }) - -test.describe('RawStream - Late RawStream Tests (RPC)', () => { - test('Single late RawStream - Promise resolves correctly', async ({ - page, - }) => { - await page.goto('/raw-stream/client-call') - await page.waitForURL('/raw-stream/client-call') - - await page.getByTestId('test17-btn').waitFor({ state: 'visible' }) - await page.waitForTimeout(HYDRATION_WAIT) - - await page.getByTestId('test17-btn').click() - - await expect(page.getByTestId('test17-result')).toContainText( - '"match":true', - { timeout: 15000 }, - ) - await expect(page.getByTestId('test17-result')).toContainText( - 'Late stream test', - ) - }) - - test('Multiple late RawStreams - different Promise delays', async ({ - page, - }) => { - await page.goto('/raw-stream/client-call') - await page.waitForURL('/raw-stream/client-call') - - await page.getByTestId('test18-btn').waitFor({ state: 'visible' }) - await page.waitForTimeout(HYDRATION_WAIT) - - await page.getByTestId('test18-btn').click() - - // Both streams should match - await expect(page.getByTestId('test18-result')).toContainText( - '"match":true', - { timeout: 15000 }, - ) - // Verify both streams match by checking result - const result = await page.getByTestId('test18-result').textContent() - const parsed = JSON.parse(result || '{}') - expect(parsed.streamA?.match).toBe(true) - expect(parsed.streamB?.match).toBe(true) - expect(parsed.message).toBe('Multiple late streams test') - }) - - test('Mixed immediate and late RawStreams - both work correctly', async ({ - page, - }) => { - await page.goto('/raw-stream/client-call') - await page.waitForURL('/raw-stream/client-call') - - await page.getByTestId('test19-btn').waitFor({ state: 'visible' }) - await page.waitForTimeout(HYDRATION_WAIT) - - await page.getByTestId('test19-btn').click() - - // Both immediate and late streams should match - await expect(page.getByTestId('test19-result')).toContainText( - '"match":true', - { timeout: 15000 }, - ) - // Verify both streams match by checking result - const result = await page.getByTestId('test19-result').textContent() - const parsed = JSON.parse(result || '{}') - expect(parsed.immediate?.match).toBe(true) - expect(parsed.late?.match).toBe(true) - expect(parsed.message).toBe('Mixed immediate and late test') - }) -}) diff --git a/e2e/react-start/basic/tests/redirect.spec.ts b/e2e/react-start/basic/tests/redirect.spec.ts index 010ecec155..bc36de9623 100644 --- a/e2e/react-start/basic/tests/redirect.spec.ts +++ b/e2e/react-start/basic/tests/redirect.spec.ts @@ -1,28 +1,23 @@ import queryString from 'node:querystring' import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' import combinateImport from 'combinate' -import type { Page } from '@playwright/test' +import { + getDummyServerPort, + getTestServerPort, + test, +} from '@tanstack/router-e2e-utils' +import { isSpaMode } from '../tests/utils/isSpaMode' +import { isPreview } from '../tests/utils/isPreview' +import packageJson from '../package.json' with { type: 'json' } // somehow playwright does not correctly import default exports const combinate = (combinateImport as any).default as typeof combinateImport -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort( + `${packageJson.name}${isSpaMode ? '_spa' : ''}${isPreview ? '_preview' : ''}`, +) -const EXTERNAL_ORIGIN = `http://127.0.0.1:${PORT}` -const POSTS_URL = `http://localhost:${PORT}/posts` - -async function waitForRouterIdle(page: Page) { - await expect(page.getByTestId('router-isLoading')).toHaveText('false') - await expect(page.getByTestId('router-status')).toHaveText('idle') -} - -async function waitForPostsIndex(page: Page) { - await page.waitForURL(POSTS_URL) - expect(page.url()).toBe(POSTS_URL) - await waitForRouterIdle(page) - await expect(page.getByTestId('PostsIndexComponent')).toBeInViewport() -} +const EXTERNAL_HOST_PORT = await getDummyServerPort(packageJson.name) test.describe('redirects', () => { test.describe('internal', () => { @@ -45,7 +40,7 @@ test.describe('redirects', () => { `via-${thrower}${reloadDocument ? '-reloadDocument' : ''}`, ) - await waitForRouterIdle(page) + await page.waitForLoadState('networkidle') let requestHappened = false const requestPromise = new Promise((resolve) => { @@ -73,7 +68,10 @@ test.describe('redirects', () => { await link.click() - await waitForPostsIndex(page) + const url = `http://localhost:${PORT}/posts` + await page.waitForURL(url) + expect(page.url()).toBe(url) + await expect(page.getByTestId('PostsIndexComponent')).toBeInViewport() expect(fullPageLoad).toBe(reloadDocument) }) }, @@ -89,8 +87,12 @@ test.describe('redirects', () => { page, }) => { await page.goto(`/redirect/internal/via-${thrower}`) + await page.waitForLoadState('networkidle') - await waitForPostsIndex(page) + const url = `http://localhost:${PORT}/posts` + + expect(page.url()).toBe(url) + await expect(page.getByTestId('PostsIndexComponent')).toBeInViewport() }) }) }) @@ -106,12 +108,12 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, }) if (scenario === 'navigate') { await page.goto(`/redirect/external?${q}`) - await waitForRouterIdle(page) + await page.waitForLoadState('networkidle') const link = page.getByTestId(`via-${thrower}`) await link.focus() await link.click() @@ -119,7 +121,7 @@ test.describe('redirects', () => { await page.goto(`/redirect/external/via-${thrower}?${q}`) } - const url = `${EXTERNAL_ORIGIN}/` + const url = `http://localhost:${EXTERNAL_HOST_PORT}/` await page.waitForURL(url) expect(page.url()).toBe(url) @@ -142,13 +144,13 @@ test.describe('redirects', () => { }) => { let fullPageLoad = false const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, reloadDocument, }) if (scenario === 'navigate') { await page.goto(`/redirect/${target}/serverFn?${q}`) - await waitForRouterIdle(page) + await page.waitForLoadState('networkidle') const link = page.getByTestId( `via-${thrower}${reloadDocument ? '-reloadDocument' : ''}`, @@ -159,20 +161,22 @@ test.describe('redirects', () => { }) await link.focus() - await waitForRouterIdle(page) + await page.waitForLoadState('networkidle') await link.click() } else { await page.goto(`/redirect/${target}/serverFn/via-${thrower}?${q}`) } - const url = target === 'internal' ? POSTS_URL : `${EXTERNAL_ORIGIN}/` + const url = + target === 'internal' + ? `http://localhost:${PORT}/posts` + : `http://localhost:${EXTERNAL_HOST_PORT}/` await page.waitForURL(url) expect(page.url()).toBe(url) if (target === 'internal' && scenario === 'navigate') { - await waitForRouterIdle(page) await expect( page.getByTestId('PostsIndexComponent'), ).toBeInViewport() @@ -194,13 +198,13 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, reloadDocument, }) await page.goto(`/redirect/${target}/serverFn/via-useServerFn?${q}`) - await waitForRouterIdle(page) + await page.waitForLoadState('networkidle') const button = page.getByTestId('redirect-on-click') @@ -211,11 +215,13 @@ test.describe('redirects', () => { await button.click() - const url = target === 'internal' ? POSTS_URL : `${EXTERNAL_ORIGIN}/` + const url = + target === 'internal' + ? `http://localhost:${PORT}/posts` + : `http://localhost:${EXTERNAL_HOST_PORT}/` await page.waitForURL(url) expect(page.url()).toBe(url) if (target === 'internal') { - await waitForRouterIdle(page) await expect(page.getByTestId('PostsIndexComponent')).toBeInViewport() expect(fullPageLoad).toBe(reloadDocument) } diff --git a/e2e/react-start/basic/tests/search-params.spec.ts b/e2e/react-start/basic/tests/search-params.spec.ts index cdf5a21b4a..74c1aa54dc 100644 --- a/e2e/react-start/basic/tests/search-params.spec.ts +++ b/e2e/react-start/basic/tests/search-params.spec.ts @@ -1,6 +1,6 @@ import { expect } from '@playwright/test' import { test } from '@tanstack/router-e2e-utils' -import { isSpaMode } from './utils/isSpaMode' +import { isSpaMode } from 'tests/utils/isSpaMode' import { isPrerender } from './utils/isPrerender' import type { Response } from '@playwright/test' diff --git a/e2e/react-start/basic/tests/setup/dev-server.setup.ts b/e2e/react-start/basic/tests/setup/dev-server.setup.ts deleted file mode 100644 index d16ff0bb54..0000000000 --- a/e2e/react-start/basic/tests/setup/dev-server.setup.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' - -export default async function setup() { - const port = Number(process.env.E2E_APP_PORT ?? 0) - const baseURL = `http://localhost:${port}` - - await waitForServer(baseURL) - await preOptimizeDevServer({ - baseURL, - warmup: async (page) => { - await page.getByRole('heading').getByText('Welcome Home').waitFor() - await page.goto(`${baseURL}/specialChars/search?searchParam=warmup`) - await page.getByTestId('special-search-loaded-info').waitFor() - await page.goto(`${baseURL}/posts`) - await page.getByRole('link', { name: 'sunt aut facere repe' }).waitFor() - await page.waitForLoadState('networkidle') - }, - }) -} diff --git a/e2e/react-start/basic/tests/setup/global.setup.ts b/e2e/react-start/basic/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-start/basic/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-start/basic/tests/setup/global.teardown.ts b/e2e/react-start/basic/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-start/basic/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-start/basic/tests/spa-shell.spec.ts b/e2e/react-start/basic/tests/spa-shell.spec.ts deleted file mode 100644 index f42195e762..0000000000 --- a/e2e/react-start/basic/tests/spa-shell.spec.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' -import { isSpaMode } from './utils/isSpaMode' - -// The prod SPA run and the dev SPA runs (`E2E_DEV_SERVER`) all run this file. -// The dev runs run nothing else. -test.skip(!isSpaMode, 'only SPA mode answers documents with the shell') - -// Its loader and beforeLoad report where they ran. -const searchRoute = '/specialChars/search?searchParam=shell' - -test('a document request gets the shell, not the rendered route', async ({ - request, -}) => { - const response = await request.get(searchRoute) - - expect(response.status()).toBe(200) - const html = await response.text() - // The root route's document renders... - expect(html).toContain('This Route Does Not Exist') - // ...but not the matched route, nor its loader's output. - expect(html).not.toContain('special-search-loaded-info') - expect(html).not.toContain('Loaded on: server') -}) - -test('the route loads in the browser', async ({ page }) => { - await page.goto(searchRoute) - - await expect(page.getByTestId('special-search-loaded-info')).toHaveText( - 'Loaded on: client', - ) - await expect(page.getByTestId('special-search-before-load-info')).toHaveText( - 'Before load on: client', - ) - await expect(page.getByTestId('special-search-param')).toHaveText('shell') -}) - -test('client navigation works from the shell', async ({ page }) => { - await page.goto('/') - await expect(page.getByRole('heading')).toContainText('Welcome Home') - await expect(page.getByTestId('router-status')).toHaveText('idle') - - // A full page load would drop this. - await page.evaluate(() => { - ;(window as any).__spaShellPage = true - }) - await page.getByRole('link', { name: 'Posts' }).click() - await page.waitForURL('/posts') - await expect( - page.getByRole('link', { name: 'sunt aut facere repe' }), - ).toBeVisible() - expect(await page.evaluate(() => (window as any).__spaShellPage)).toBe(true) -}) diff --git a/e2e/react-start/basic/tests/special-characters.spec.ts b/e2e/react-start/basic/tests/special-characters.spec.ts index 188d1f10a6..ce800a77ef 100644 --- a/e2e/react-start/basic/tests/special-characters.spec.ts +++ b/e2e/react-start/basic/tests/special-characters.spec.ts @@ -64,22 +64,6 @@ test.describe('Unicode route rendering', () => { expect(param).toBe('대|') }) - - test('should not cause redirect loop for curly braces in path params', async ({ - page, - baseURL, - }) => { - // %7B/%7D (curly braces) must not trigger infinite 307 redirects - const res = await page.goto('/specialChars/%7B%7Bapp_name%7D%7D') - await page.waitForLoadState('load') - - // Should not redirect — URL stays encoded - expect(page.url()).toBe(`${baseURL}/specialChars/%7B%7Bapp_name%7D%7D`) - expect(res!.status()).toBe(200) - - const param = await page.getByTestId('special-param').textContent() - expect(param).toBe('{{app_name}}') - }) }) test.describe('Special characters in search params', () => { @@ -93,28 +77,11 @@ test.describe('Unicode route rendering', () => { `${baseURL}/specialChars/search?searchParam=%EB%8C%80|`, ) - await page.waitForLoadState('networkidle') - const searchParam = await page .getByTestId('special-search-param') .textContent() expect(searchParam).toBe('대|') - - const loadedOn = await page - .getByTestId('special-search-loaded-info') - .textContent() - const beforeLoadOn = await page - .getByTestId('special-search-before-load-info') - .textContent() - - if (isSpaMode) { - expect(loadedOn).toBe('Loaded on: client') - expect(beforeLoadOn).toBe('Before load on: client') - } else { - expect(loadedOn).toBe('Loaded on: server') - expect(beforeLoadOn).toBe('Before load on: server') - } }) test('should render route correctly on router navigation', async ({ @@ -208,12 +175,6 @@ test.describe('Unicode route rendering', () => { }) test.describe('malformed paths', () => { - const malformedPathnames = [ - '/specialChars/malformed/%E0%A4', - '/specialChars/malformed/%80', - '/specialChars/malformed/%FF', - ] - test.use({ whitelistErrors: [ 'Failed to load resource: the server responded with a status of 404', @@ -221,22 +182,24 @@ test.describe('Unicode route rendering', () => { ], }) - for (const pathname of malformedPathnames) { - test(`un-matched malformed path "${pathname}" should return bad request on direct navigation`, async ({ - page, - }) => { - const res = await page.goto(pathname) + test('un-matched malformed paths should return not found on direct navigation', async ({ + page, + }) => { + const res = await page.goto('/specialChars/malformed/%E0%A4') - await page.waitForLoadState(`load`) + await page.waitForLoadState(`load`) - // in spa mode this is caught and handled at server level - if (!isSpaMode) { - expect(res!.status()).toBe(400) - } else { - expect(res!.status()).toBe(400) - } - }) - } + // in spa mode this is caught and handled at server level + if (!isSpaMode) { + expect(res!.status()).toBe(404) + + await expect( + page.getByTestId('default-not-found-component'), + ).toBeInViewport() + } else { + expect(res!.status()).toBe(400) + } + }) test('malformed path params should return not found on router link', async ({ page, diff --git a/e2e/react-start/basic/tests/utils/getPackageName.ts b/e2e/react-start/basic/tests/utils/getPackageName.ts deleted file mode 100644 index 6bd2e0499e..0000000000 --- a/e2e/react-start/basic/tests/utils/getPackageName.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' - -let packageName: string | undefined - -export function getPackageName() { - if (!packageName) { - const packageJson = JSON.parse( - readFileSync(join(process.cwd(), 'package.json'), 'utf-8'), - ) as { name: string } - - packageName = packageJson.name - } - - return packageName -} diff --git a/e2e/react-start/basic/tsconfig.json b/e2e/react-start/basic/tsconfig.json index e486543b96..b3a2d67dfa 100644 --- a/e2e/react-start/basic/tsconfig.json +++ b/e2e/react-start/basic/tsconfig.json @@ -8,13 +8,12 @@ "moduleResolution": "Bundler", "lib": ["DOM", "DOM.Iterable", "ES2022"], "isolatedModules": true, - "allowImportingTsExtensions": true, "resolveJsonModule": true, "skipLibCheck": true, "target": "ES2022", - "types": ["node"], "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/react-start/basic/vite.config.ts b/e2e/react-start/basic/vite.config.ts index 2a9478eea6..d196ac9538 100644 --- a/e2e/react-start/basic/vite.config.ts +++ b/e2e/react-start/basic/vite.config.ts @@ -1,19 +1,48 @@ import { defineConfig } from 'vite' +import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import viteReact from '@vitejs/plugin-react' +import { isSpaMode } from './tests/utils/isSpaMode' +import { isPrerender } from './tests/utils/isPrerender' import tailwindcss from '@tailwindcss/vite' -import { getStartModeConfig } from './start-mode-config' -const outDir = process.env.E2E_DIST_DIR ?? 'dist' -const startModeConfig = getStartModeConfig() +const spaModeConfiguration = { + enabled: true, + prerender: { + outputPath: 'index.html', + }, +} + +const prerenderConfiguration = { + enabled: true, + filter: (page: { path: string }) => + ![ + '/this-route-does-not-exist', + '/redirect', + '/i-do-not-exist', + '/not-found/via-beforeLoad', + '/not-found/via-loader', + '/specialChars/search', + '/specialChars/hash', + '/specialChars/malformed', + '/users', + ].some((p) => page.path.includes(p)), + maxRedirects: 100, +} export default defineConfig({ - resolve: { tsconfigPaths: true }, - build: { - outDir, - }, server: { port: 3000, }, - plugins: [tailwindcss(), tanstackStart(startModeConfig), viteReact()], + plugins: [ + tailwindcss(), + tsConfigPaths({ + projects: ['./tsconfig.json'], + }), + tanstackStart({ + spa: isSpaMode ? spaModeConfiguration : undefined, + prerender: isPrerender ? prerenderConfiguration : undefined, + }), + viteReact(), + ], }) diff --git a/e2e/react-start/clerk-basic/.devcontainer/devcontainer.json b/e2e/react-start/clerk-basic/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/react-start/clerk-basic/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/react-start/clerk-basic/package.json b/e2e/react-start/clerk-basic/package.json index 7838b4cee1..743517466f 100644 --- a/e2e/react-start/clerk-basic/package.json +++ b/e2e/react-start/clerk-basic/package.json @@ -8,7 +8,7 @@ "dev:e2e": "vite dev", "build": "exit 0; vite build", "start": "node .output/server/index.mjs", - "test:e2e": "exit 0; playwright test --project=chromium" + "test:e2e": "exit 0; rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@clerk/tanstack-react-start": "^0.19.0", @@ -17,20 +17,20 @@ "@tanstack/react-start": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "catalog:", - "tailwind-merge": "^3.6.0" + "redaxios": "^0.5.1", + "tailwind-merge": "^2.6.0", + "vite": "^7.3.1" }, "devDependencies": { - "@playwright/test": "^1.61.0", - "@tailwindcss/vite": "^4.2.2", + "@playwright/test": "^1.50.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", - "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.3.4", + "tailwindcss": "4.1.18", + "typescript": "^5.7.2", + "vite-tsconfig-paths": "^5.1.4", + "@tailwindcss/vite": "4.1.18" } } diff --git a/e2e/react-start/clerk-basic/playwright.config.ts b/e2e/react-start/clerk-basic/playwright.config.ts index 82678ac00b..18b8905468 100644 --- a/e2e/react-start/clerk-basic/playwright.config.ts +++ b/e2e/react-start/clerk-basic/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/clerk-basic/src/components/DefaultCatchBoundary.tsx b/e2e/react-start/clerk-basic/src/components/DefaultCatchBoundary.tsx index 405fb5f4a7..ef2daa1ea1 100644 --- a/e2e/react-start/clerk-basic/src/components/DefaultCatchBoundary.tsx +++ b/e2e/react-start/clerk-basic/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/react-router' import type { ErrorComponentProps } from '@tanstack/react-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) console.error(error) diff --git a/e2e/react-start/clerk-basic/src/routeTree.gen.ts b/e2e/react-start/clerk-basic/src/routeTree.gen.ts index d8111b637a..a6767e0efd 100644 --- a/e2e/react-start/clerk-basic/src/routeTree.gen.ts +++ b/e2e/react-start/clerk-basic/src/routeTree.gen.ts @@ -9,22 +9,22 @@ // 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 AuthedRouteImport } from './routes/_authed' +import { Route as IndexRouteImport } from './routes/index' import { Route as AuthedPostsRouteImport } from './routes/_authed/posts' import { Route as AuthedPostsIndexRouteImport } from './routes/_authed/posts.index' -import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' import { Route as AuthedProfileSplatRouteImport } from './routes/_authed/profile.$' +import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' +const AuthedRoute = AuthedRouteImport.update({ + id: '/_authed', + getParentRoute: () => rootRouteImport, +} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const AuthedRoute = AuthedRouteImport.update({ - id: '/_authed', - getParentRoute: () => rootRouteImport, -} as any) const AuthedPostsRoute = AuthedPostsRouteImport.update({ id: '/posts', path: '/posts', @@ -35,16 +35,16 @@ const AuthedPostsIndexRoute = AuthedPostsIndexRouteImport.update({ path: '/', getParentRoute: () => AuthedPostsRoute, } as any) -const AuthedPostsPostIdRoute = AuthedPostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => AuthedPostsRoute, -} as any) const AuthedProfileSplatRoute = AuthedProfileSplatRouteImport.update({ id: '/profile/$', path: '/profile/$', getParentRoute: () => AuthedRoute, } as any) +const AuthedPostsPostIdRoute = AuthedPostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => AuthedPostsRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -90,6 +90,13 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { + '/_authed': { + id: '/_authed' + path: '' + fullPath: '' + preLoaderRoute: typeof AuthedRouteImport + parentRoute: typeof rootRouteImport + } '/': { id: '/' path: '/' @@ -97,13 +104,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/_authed': { - id: '/_authed' - path: '' - fullPath: '/' - preLoaderRoute: typeof AuthedRouteImport - parentRoute: typeof rootRouteImport - } '/_authed/posts': { id: '/_authed/posts' path: '/posts' @@ -118,13 +118,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthedPostsIndexRouteImport parentRoute: typeof AuthedPostsRoute } - '/_authed/posts/$postId': { - id: '/_authed/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof AuthedPostsPostIdRouteImport - parentRoute: typeof AuthedPostsRoute - } '/_authed/profile/$': { id: '/_authed/profile/$' path: '/profile/$' @@ -132,6 +125,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthedProfileSplatRouteImport parentRoute: typeof AuthedRoute } + '/_authed/posts/$postId': { + id: '/_authed/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof AuthedPostsPostIdRouteImport + parentRoute: typeof AuthedPostsRoute + } } } diff --git a/e2e/react-start/clerk-basic/src/routes/_authed.tsx b/e2e/react-start/clerk-basic/src/routes/_authed.tsx index 440d0e3f3c..226ae0829f 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 instanceof Error && error.message === 'Not authenticated') { + if (error.message === 'Not authenticated') { return (
diff --git a/e2e/react-start/clerk-basic/src/utils/posts.ts b/e2e/react-start/clerk-basic/src/utils/posts.ts index 532e883ac0..b30810a5a3 100644 --- a/e2e/react-start/clerk-basic/src/utils/posts.ts +++ b/e2e/react-start/clerk-basic/src/utils/posts.ts @@ -9,7 +9,7 @@ export type PostType = { } export const fetchPost = createServerFn({ method: 'GET' }) - .validator((postId: string) => postId) + .inputValidator((postId: string) => postId) .handler(async ({ data: postId }) => { console.info(`Fetching post with id ${postId}...`) const post = await axios diff --git a/e2e/react-start/clerk-basic/tsconfig.json b/e2e/react-start/clerk-basic/tsconfig.json index cef9369516..3a9fb7cd71 100644 --- a/e2e/react-start/clerk-basic/tsconfig.json +++ b/e2e/react-start/clerk-basic/tsconfig.json @@ -13,6 +13,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/react-start/clerk-basic/vite.config.ts b/e2e/react-start/clerk-basic/vite.config.ts index 6c9a4c347a..3e946e6645 100644 --- a/e2e/react-start/clerk-basic/vite.config.ts +++ b/e2e/react-start/clerk-basic/vite.config.ts @@ -1,9 +1,16 @@ import { defineConfig } from 'vite' +import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import viteReact from '@vitejs/plugin-react' import tailwindcss from '@tailwindcss/vite' export default defineConfig({ - resolve: { tsconfigPaths: true }, - plugins: [tailwindcss(), tanstackStart(), viteReact()], + plugins: [ + tailwindcss(), + tsConfigPaths({ + projects: ['./tsconfig.json'], + }), + tanstackStart(), + viteReact(), + ], }) diff --git a/e2e/react-start/csp/.devcontainer/devcontainer.json b/e2e/react-start/csp/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/react-start/csp/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/react-start/csp/package.json b/e2e/react-start/csp/package.json index fd8987bcef..66117ba3e6 100644 --- a/e2e/react-start/csp/package.json +++ b/e2e/react-start/csp/package.json @@ -8,23 +8,22 @@ "dev:e2e": "vite dev", "build": "vite build && tsc --noEmit", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", "@tanstack/react-start": "workspace:^", "react": "^19.0.0", - "react-dom": "^19.0.0" + "react-dom": "^19.0.0", + "vite": "^7.3.1" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "srvx": "^1.0.0", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "srvx": "^0.11.2", + "typescript": "^5.7.2" } } diff --git a/e2e/react-start/csp/playwright.config.ts b/e2e/react-start/csp/playwright.config.ts index 87b32e1f50..5f9de5709e 100644 --- a/e2e/react-start/csp/playwright.config.ts +++ b/e2e/react-start/csp/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/csp/src/vite-env.d.ts b/e2e/react-start/csp/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/react-start/csp/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/react-start/csp/tests/csp.spec.ts b/e2e/react-start/csp/tests/csp.spec.ts index ef6b2dadc6..5bdfd93e9b 100644 --- a/e2e/react-start/csp/tests/csp.spec.ts +++ b/e2e/react-start/csp/tests/csp.spec.ts @@ -1,21 +1,6 @@ -import { expect, type Page } from '@playwright/test' +import { expect } from '@playwright/test' import { test } from '@tanstack/router-e2e-utils' -async function getRawHtml(page: Page) { - let rawHtml = '' - - await page.route('/', async (route) => { - const response = await route.fetch() - rawHtml = await response.text() - await route.fulfill({ response, body: rawHtml }) - }) - - const response = await page.goto('/') - await page.unrouteAll({ behavior: 'ignoreErrors' }) - - return { rawHtml, response } -} - test('CSP header is set with nonce', async ({ page }) => { const response = await page.goto('/') const csp = response?.headers()['content-security-policy'] @@ -36,10 +21,9 @@ test('Inline styles have nonce attribute', async ({ page }) => { }) test('External script has nonce attribute', async ({ page }) => { - const { rawHtml } = await getRawHtml(page) - expect(rawHtml).toMatch( - /]*\bsrc="\/external\.js")(?=[^>]*\bnonce="[^"]+")[^>]*>/, - ) + await page.goto('/') + const externalScript = page.locator('script[src="/external.js"]') + await expect(externalScript).toHaveAttribute('nonce') }) test('External stylesheet has nonce attribute', async ({ page }) => { @@ -50,7 +34,15 @@ test('External stylesheet has nonce attribute', async ({ page }) => { test('Nonces match between header and elements', async ({ page }) => { // Intercept the HTML response to get raw content before browser strips nonces - const { rawHtml, response } = await getRawHtml(page) + let rawHtml = '' + await page.route('/', async (route) => { + const response = await route.fetch() + rawHtml = await response.text() + await route.fulfill({ response }) + }) + + const response = await page.goto('/') + await page.unrouteAll({ behavior: 'ignoreErrors' }) const csp = response?.headers()['content-security-policy'] || '' diff --git a/e2e/react-start/csp/tsconfig.json b/e2e/react-start/csp/tsconfig.json index cef9369516..3a9fb7cd71 100644 --- a/e2e/react-start/csp/tsconfig.json +++ b/e2e/react-start/csp/tsconfig.json @@ -13,6 +13,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/react-start/css-inline/package.json b/e2e/react-start/css-inline/package.json deleted file mode 100644 index 6c5dd031c6..0000000000 --- a/e2e/react-start/css-inline/package.json +++ /dev/null @@ -1,113 +0,0 @@ -{ - "name": "tanstack-react-start-e2e-css-inline", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "build": "pnpm build:vite && pnpm build:rsbuild", - "build:vite": "vite build && tsc --noEmit", - "build:rsbuild": "rsbuild build && tsc --noEmit", - "start": "node server.js", - "test:e2e:vite": "E2E_TOOLCHAIN=vite playwright test --project=chromium", - "test:e2e:vite:transform-assets": "E2E_TOOLCHAIN=vite CSS_INLINE_TRANSFORM_ASSETS=true playwright test --project=chromium", - "test:e2e:rsbuild": "E2E_TOOLCHAIN=rsbuild playwright test --project=chromium", - "test:e2e:rsbuild:transform-assets": "E2E_TOOLCHAIN=rsbuild CSS_INLINE_TRANSFORM_ASSETS=true playwright test --project=chromium", - "test:e2e": "pnpm run test:e2e:vite && pnpm run test:e2e:vite:transform-assets && pnpm run test:e2e:rsbuild && pnpm run test:e2e:rsbuild:transform-assets" - }, - "dependencies": { - "@tanstack/react-router": "workspace:^", - "@tanstack/react-start": "workspace:^", - "express": "^5.2.1", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "srvx": "^1.0.0" - }, - "devDependencies": { - "@playwright/test": "^1.61.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", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" - }, - "nx": { - "targets": { - "test:e2e": { - "parallelism": false, - "outputs": [ - "...", - "{projectRoot}/dist-vite-ssr", - "{projectRoot}/dist-vite-ssr-transform-assets", - "{projectRoot}/dist-vite-transform-assets-ssr", - "{projectRoot}/dist-rsbuild-ssr", - "{projectRoot}/dist-rsbuild-ssr-transform-assets", - "{projectRoot}/dist-rsbuild-transform-assets-ssr" - ] - }, - "build": { - "outputs": [ - "...", - "{projectRoot}/dist-vite-ssr", - "{projectRoot}/dist-rsbuild-ssr" - ] - }, - "test:e2e--vite-ssr": { - "outputs": [ - "...", - "{projectRoot}/dist-vite-ssr" - ] - }, - "test:e2e--vite-ssr--transform-assets": { - "outputs": [ - "...", - "{projectRoot}/dist-vite-ssr-transform-assets" - ] - }, - "test:e2e--rsbuild-ssr": { - "outputs": [ - "...", - "{projectRoot}/dist-rsbuild-ssr" - ] - }, - "test:e2e--rsbuild-ssr--transform-assets": { - "outputs": [ - "...", - "{projectRoot}/dist-rsbuild-ssr-transform-assets" - ] - } - }, - "metadata": { - "playwrightModes": [ - { - "toolchain": "vite", - "mode": "ssr" - }, - { - "toolchain": "vite", - "mode": "ssr", - "name": "transform-assets", - "env": { - "CSS_INLINE_TRANSFORM_ASSETS": "true" - } - }, - { - "toolchain": "rsbuild", - "mode": "ssr" - }, - { - "toolchain": "rsbuild", - "mode": "ssr", - "name": "transform-assets", - "env": { - "CSS_INLINE_TRANSFORM_ASSETS": "true" - } - } - ] - } - } -} diff --git a/e2e/react-start/css-inline/playwright.config.ts b/e2e/react-start/css-inline/playwright.config.ts deleted file mode 100644 index 78e7b75252..0000000000 --- a/e2e/react-start/css-inline/playwright.config.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' - -const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' -const inlineCssTransformAssets = - process.env.CSS_INLINE_TRANSFORM_ASSETS || 'false' -if (!['true', 'false'].includes(inlineCssTransformAssets)) { - throw new Error( - `CSS_INLINE_TRANSFORM_ASSETS must be "true" or "false". Received: ${JSON.stringify(inlineCssTransformAssets)}`, - ) -} - -const isInlineCssTransformAssets = inlineCssTransformAssets === 'true' -const transformAssetsSuffix = isInlineCssTransformAssets - ? '-transform-assets' - : '' -const distDir = - process.env.E2E_DIST_DIR ?? `dist-${toolchain}${transformAssetsSuffix}-ssr` - -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 build:${toolchain} && pnpm start`, - wait: appServerReady, - reuseExistingServer: false, - stdout: 'pipe', - env: { - E2E_DIST_DIR: distDir, - PORT: String(PORT), - CSS_INLINE_TRANSFORM_ASSETS: inlineCssTransformAssets, - }, - }, - - projects: [ - { - name: 'chromium', - use: { ...devices['Desktop Chrome'] }, - }, - ], -}) diff --git a/e2e/react-start/css-inline/rsbuild.config.ts b/e2e/react-start/css-inline/rsbuild.config.ts deleted file mode 100644 index 8957fc9a06..0000000000 --- a/e2e/react-start/css-inline/rsbuild.config.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { defineConfig } from '@rsbuild/core' -import { pluginReact } from '@rsbuild/plugin-react' -import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' - -const outDir = process.env.E2E_DIST_DIR ?? 'dist-rsbuild-ssr' -const transformInlineCssAssets = - process.env.CSS_INLINE_TRANSFORM_ASSETS === 'true' - -export default defineConfig({ - plugins: [ - pluginReact(), - tanstackStart({ - server: { - build: { - inlineCss: transformInlineCssAssets - ? { enabled: true, transformAssets: true } - : true, - }, - }, - }), - ], - output: { - distPath: { - root: outDir, - }, - }, -}) diff --git a/e2e/react-start/css-inline/server.js b/e2e/react-start/css-inline/server.js deleted file mode 100644 index 27b2357284..0000000000 --- a/e2e/react-start/css-inline/server.js +++ /dev/null @@ -1,46 +0,0 @@ -import fs from 'node:fs' -import path from 'node:path' -import express from 'express' -import { toNodeHandler } from 'srvx/node' - -const port = Number(process.env.PORT ?? 3000) -const distDir = process.env.E2E_DIST_DIR || 'dist-vite-ssr' -const distClientDir = path.resolve(distDir, 'client') - -function resolveDistServerEntryPath() { - const candidates = [ - path.resolve(distDir, 'server', 'server.js'), - path.resolve(distDir, 'server', 'index.js'), - path.resolve(distDir, 'server', 'index.mjs'), - ] - - return ( - candidates.find((candidate) => fs.existsSync(candidate)) ?? candidates[0] - ) -} - -async function createStartServer() { - const server = (await import(resolveDistServerEntryPath())).default - const nodeHandler = toNodeHandler(server.fetch) - const app = express() - - app.use(express.static(distClientDir, { redirect: false })) - app.use(async (req, res, next) => { - try { - await nodeHandler(req, res) - } catch (error) { - next(error) - } - }) - - return app -} - -createStartServer().then((app) => { - 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/components/NestedPanel.tsx b/e2e/react-start/css-inline/src/components/NestedPanel.tsx deleted file mode 100644 index d564a47eea..0000000000 --- a/e2e/react-start/css-inline/src/components/NestedPanel.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import styles from '~/styles/nested-panel.module.css' - -export function NestedPanel({ label }: { label: string }) { - return ( -
- {label} -
- ) -} diff --git a/e2e/react-start/css-inline/src/components/Shell.tsx b/e2e/react-start/css-inline/src/components/Shell.tsx deleted file mode 100644 index 4fd9b00877..0000000000 --- a/e2e/react-start/css-inline/src/components/Shell.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { Link, Outlet } from '@tanstack/react-router' -import { useEffect } from 'react' -import styles from '~/styles/shell.module.css' - -export function Shell() { - useEffect(() => { - ;(window as any).__CSS_INLINE_E2E_HYDRATED__ = true - }, []) - - return ( -
- - -
- ) -} diff --git a/e2e/react-start/css-inline/src/routeTree.gen.ts b/e2e/react-start/css-inline/src/routeTree.gen.ts deleted file mode 100644 index 1b5e5886b1..0000000000 --- a/e2e/react-start/css-inline/src/routeTree.gen.ts +++ /dev/null @@ -1,169 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as AppRouteRouteImport } from './routes/app/route' -import { Route as AppDashboardRouteRouteImport } from './routes/app/dashboard/route' -import { Route as AppDashboardIndexRouteImport } from './routes/app/dashboard/index' -import { Route as AppDashboardDetailsRouteImport } from './routes/app/dashboard/details' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AppRouteRoute = AppRouteRouteImport.update({ - id: '/app', - path: '/app', - getParentRoute: () => rootRouteImport, -} as any) -const AppDashboardRouteRoute = AppDashboardRouteRouteImport.update({ - id: '/dashboard', - path: '/dashboard', - getParentRoute: () => AppRouteRoute, -} as any) -const AppDashboardIndexRoute = AppDashboardIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => AppDashboardRouteRoute, -} as any) -const AppDashboardDetailsRoute = AppDashboardDetailsRouteImport.update({ - id: '/details', - path: '/details', - getParentRoute: () => AppDashboardRouteRoute, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/app': typeof AppRouteRouteWithChildren - '/app/dashboard': typeof AppDashboardRouteRouteWithChildren - '/app/dashboard/details': typeof AppDashboardDetailsRoute - '/app/dashboard/': typeof AppDashboardIndexRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/app': typeof AppRouteRouteWithChildren - '/app/dashboard/details': typeof AppDashboardDetailsRoute - '/app/dashboard': typeof AppDashboardIndexRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/app': typeof AppRouteRouteWithChildren - '/app/dashboard': typeof AppDashboardRouteRouteWithChildren - '/app/dashboard/details': typeof AppDashboardDetailsRoute - '/app/dashboard/': typeof AppDashboardIndexRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/app' - | '/app/dashboard' - | '/app/dashboard/details' - | '/app/dashboard/' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/app' | '/app/dashboard/details' | '/app/dashboard' - id: - | '__root__' - | '/' - | '/app' - | '/app/dashboard' - | '/app/dashboard/details' - | '/app/dashboard/' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - AppRouteRoute: typeof AppRouteRouteWithChildren -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/app': { - id: '/app' - path: '/app' - fullPath: '/app' - preLoaderRoute: typeof AppRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/app/dashboard': { - id: '/app/dashboard' - path: '/dashboard' - fullPath: '/app/dashboard' - preLoaderRoute: typeof AppDashboardRouteRouteImport - parentRoute: typeof AppRouteRoute - } - '/app/dashboard/': { - id: '/app/dashboard/' - path: '/' - fullPath: '/app/dashboard/' - preLoaderRoute: typeof AppDashboardIndexRouteImport - parentRoute: typeof AppDashboardRouteRoute - } - '/app/dashboard/details': { - id: '/app/dashboard/details' - path: '/details' - fullPath: '/app/dashboard/details' - preLoaderRoute: typeof AppDashboardDetailsRouteImport - parentRoute: typeof AppDashboardRouteRoute - } - } -} - -interface AppDashboardRouteRouteChildren { - AppDashboardDetailsRoute: typeof AppDashboardDetailsRoute - AppDashboardIndexRoute: typeof AppDashboardIndexRoute -} - -const AppDashboardRouteRouteChildren: AppDashboardRouteRouteChildren = { - AppDashboardDetailsRoute: AppDashboardDetailsRoute, - AppDashboardIndexRoute: AppDashboardIndexRoute, -} - -const AppDashboardRouteRouteWithChildren = - AppDashboardRouteRoute._addFileChildren(AppDashboardRouteRouteChildren) - -interface AppRouteRouteChildren { - AppDashboardRouteRoute: typeof AppDashboardRouteRouteWithChildren -} - -const AppRouteRouteChildren: AppRouteRouteChildren = { - AppDashboardRouteRoute: AppDashboardRouteRouteWithChildren, -} - -const AppRouteRouteWithChildren = AppRouteRoute._addFileChildren( - AppRouteRouteChildren, -) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - AppRouteRoute: AppRouteRouteWithChildren, -} -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/css-inline/src/router.tsx b/e2e/react-start/css-inline/src/router.tsx deleted file mode 100644 index 68365b748e..0000000000 --- a/e2e/react-start/css-inline/src/router.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export const getRouter = () => { - return createRouter({ - routeTree, - defaultPreload: 'intent', - }) -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/e2e/react-start/css-inline/src/routes/__root.tsx b/e2e/react-start/css-inline/src/routes/__root.tsx deleted file mode 100644 index 52ebd8d5f6..0000000000 --- a/e2e/react-start/css-inline/src/routes/__root.tsx +++ /dev/null @@ -1,30 +0,0 @@ -/// -import { HeadContent, Scripts, createRootRoute } from '@tanstack/react-router' -import { Shell } from '~/components/Shell' -import type { ReactNode } from 'react' - -export const Route = createRootRoute({ - head: () => ({ - meta: [ - { charSet: 'utf-8' }, - { name: 'viewport', content: 'width=device-width, initial-scale=1' }, - { title: 'Inline CSS E2E' }, - ], - }), - component: Shell, - shellComponent: RootDocument, -}) - -function RootDocument({ children }: { children: ReactNode }) { - return ( - - - - - - {children} - - - - ) -} diff --git a/e2e/react-start/css-inline/src/routes/app/dashboard/details.tsx b/e2e/react-start/css-inline/src/routes/app/dashboard/details.tsx deleted file mode 100644 index 8a0890bca4..0000000000 --- a/e2e/react-start/css-inline/src/routes/app/dashboard/details.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { NestedPanel } from '~/components/NestedPanel' -import styles from '~/styles/dashboard-details.module.css' - -export const Route = createFileRoute('/app/dashboard/details')({ - component: DashboardDetails, -}) - -function DashboardDetails() { - return ( -
-

Details route

- -
- ) -} 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 deleted file mode 100644 index 35205cc9cf..0000000000 --- a/e2e/react-start/css-inline/src/routes/app/dashboard/index.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -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, -}) - -function DashboardIndex() { - return ( -
-

Inline dashboard

- -
- ) -} diff --git a/e2e/react-start/css-inline/src/routes/app/dashboard/route.tsx b/e2e/react-start/css-inline/src/routes/app/dashboard/route.tsx deleted file mode 100644 index 6d1fcd2fec..0000000000 --- a/e2e/react-start/css-inline/src/routes/app/dashboard/route.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import styles from '~/styles/dashboard-layout.module.css' - -export const Route = createFileRoute('/app/dashboard')({ - component: DashboardLayout, -}) - -function DashboardLayout() { - return ( -
-

Dashboard route layout CSS

- -
- ) -} diff --git a/e2e/react-start/css-inline/src/routes/app/route.tsx b/e2e/react-start/css-inline/src/routes/app/route.tsx deleted file mode 100644 index a9490663b6..0000000000 --- a/e2e/react-start/css-inline/src/routes/app/route.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' -import styles from '~/styles/app-layout.module.css' - -export const Route = createFileRoute('/app')({ - component: AppLayout, -}) - -function AppLayout() { - return ( -
-

Nested app shell

- -
- ) -} diff --git a/e2e/react-start/css-inline/src/routes/index.tsx b/e2e/react-start/css-inline/src/routes/index.tsx deleted file mode 100644 index e348f64525..0000000000 --- a/e2e/react-start/css-inline/src/routes/index.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { Link, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: Home, -}) - -function Home() { - return ( -
-

Inline CSS home

- Open dashboard -
- ) -} diff --git a/e2e/react-start/css-inline/src/server.ts b/e2e/react-start/css-inline/src/server.ts deleted file mode 100644 index 3fd3005e59..0000000000 --- a/e2e/react-start/css-inline/src/server.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { - createStartHandler, - defaultStreamHandler, -} from '@tanstack/react-start/server' -import { createServerEntry } from '@tanstack/react-start/server-entry' -import type { TransformAssetsFn } from '@tanstack/react-start/server' - -const transformInlineCssAssets = - process.env.CSS_INLINE_TRANSFORM_ASSETS === 'true' -const transformAssets: TransformAssetsFn = ({ kind, url }) => { - if (kind === 'css-url') { - return `${url}${url.includes('?') ? '&' : '?'}cdn=1` - } - - return url -} - -const handler = createStartHandler({ - handler: defaultStreamHandler, - // The request option below should win over this handler-level default. - inlineCss: false, - ...(transformInlineCssAssets - ? { - transformAssets, - } - : {}), -}) - -export default createServerEntry({ - fetch(request) { - return handler(request, { - inlineCss: request.headers.get('x-inline-css') !== 'false', - }) - }, -}) diff --git a/e2e/react-start/css-inline/src/styles/app-layout.module.css b/e2e/react-start/css-inline/src/styles/app-layout.module.css deleted file mode 100644 index b5f2678ed9..0000000000 --- a/e2e/react-start/css-inline/src/styles/app-layout.module.css +++ /dev/null @@ -1,11 +0,0 @@ -.layout { - border: 4px solid rgb(22, 163, 74); - border-radius: 18px; - background: rgb(220, 252, 231); - padding: 18px; -} - -.heading { - color: rgb(21, 128, 61); - margin: 0 0 16px; -} diff --git a/e2e/react-start/css-inline/src/styles/dashboard-details.module.css b/e2e/react-start/css-inline/src/styles/dashboard-details.module.css deleted file mode 100644 index 4162d3fae6..0000000000 --- a/e2e/react-start/css-inline/src/styles/dashboard-details.module.css +++ /dev/null @@ -1,7 +0,0 @@ -.details { - background: rgb(255, 237, 213); - border: 3px solid rgb(234, 88, 12); - border-radius: 14px; - color: rgb(154, 52, 18); - padding: 20px; -} diff --git a/e2e/react-start/css-inline/src/styles/dashboard-index.module.css b/e2e/react-start/css-inline/src/styles/dashboard-index.module.css deleted file mode 100644 index 36974ec4a6..0000000000 --- a/e2e/react-start/css-inline/src/styles/dashboard-index.module.css +++ /dev/null @@ -1,12 +0,0 @@ -.card { - background-color: rgb(254, 249, 195); - background-image: url('./inline-dot.svg'); - border: 3px solid rgb(202, 138, 4); - border-radius: 14px; - padding: 20px; -} - -.title { - color: rgb(133, 77, 14); - margin-top: 0; -} diff --git a/e2e/react-start/css-inline/src/styles/dashboard-layout.module.css b/e2e/react-start/css-inline/src/styles/dashboard-layout.module.css deleted file mode 100644 index a6165a77dc..0000000000 --- a/e2e/react-start/css-inline/src/styles/dashboard-layout.module.css +++ /dev/null @@ -1,13 +0,0 @@ -.dashboard { - border-left: 8px solid rgb(124, 58, 237); - background: rgb(245, 243, 255); - padding: 18px; -} - -.kicker { - color: rgb(109, 40, 217); - font-size: 14px; - font-weight: 700; - letter-spacing: 0.08em; - text-transform: uppercase; -} diff --git a/e2e/react-start/css-inline/src/styles/inline-dot.svg b/e2e/react-start/css-inline/src/styles/inline-dot.svg deleted file mode 100644 index 846de3ee38..0000000000 --- a/e2e/react-start/css-inline/src/styles/inline-dot.svg +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - This file is intentionally larger than Vite's default inline asset limit so - the CSS inline e2e fixture exercises emitted CSS URL rewriting instead of - data URL inlining. - 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 - 111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 - 222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222 - 333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333 - 444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444 - 555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555 - 666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666 - 777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777 - 888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888 - 999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999 - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb - cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc - dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd - eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee - ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff - gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg - hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh - iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii - jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj - - diff --git a/e2e/react-start/css-inline/src/styles/nested-panel.module.css b/e2e/react-start/css-inline/src/styles/nested-panel.module.css deleted file mode 100644 index 93c929307b..0000000000 --- a/e2e/react-start/css-inline/src/styles/nested-panel.module.css +++ /dev/null @@ -1,11 +0,0 @@ -.panel { - background: rgb(219, 234, 254); - border: 2px dashed rgb(37, 99, 235); - border-radius: 10px; - margin-top: 16px; - padding: 12px; -} - -.label { - color: rgb(30, 64, 175); -} diff --git a/e2e/react-start/css-inline/src/styles/shell.module.css b/e2e/react-start/css-inline/src/styles/shell.module.css deleted file mode 100644 index 9b01ebe2ab..0000000000 --- a/e2e/react-start/css-inline/src/styles/shell.module.css +++ /dev/null @@ -1,18 +0,0 @@ -.shell { - min-height: 100vh; - color: rgb(15, 23, 42); - background: rgb(240, 249, 255); - font-family: Arial, sans-serif; - padding: 24px; -} - -.nav { - display: flex; - gap: 16px; - margin-bottom: 24px; -} - -.nav a { - color: rgb(3, 105, 161); - font-weight: 700; -} diff --git a/e2e/react-start/css-inline/tests/css-inline.spec.ts b/e2e/react-start/css-inline/tests/css-inline.spec.ts deleted file mode 100644 index 89d7d3992f..0000000000 --- a/e2e/react-start/css-inline/tests/css-inline.spec.ts +++ /dev/null @@ -1,253 +0,0 @@ -import { expect } from '@playwright/test' -import { collectBrowserErrors, test } from '@tanstack/router-e2e-utils' - -const buildUrl = (baseURL: string, pathname: string) => - baseURL.replace(/\/$/, '') + pathname - -async function getStyle(page: any, testId: string, property: string) { - return page.getByTestId(testId).evaluate((element: Element, prop: string) => { - return getComputedStyle(element).getPropertyValue(prop) - }, property) -} - -async function getInlineCssTexts(page: any) { - return page - .locator('style') - .evaluateAll((elements: Array) => - elements - .map((element) => element.textContent ?? '') - .filter((text) => text.includes('background')), - ) -} - -async function waitForHydration(page: any) { - await page.waitForFunction(() => { - return (window as any).__CSS_INLINE_E2E_HYDRATED__ === true - }) -} - -test('SSR inlines active nested route CSS without manifest stylesheet links', async ({ - page, - request, - baseURL, -}) => { - const errors: Array = [] - page.on('console', (message) => { - if (message.type() === 'error') { - errors.push(message.text()) - } - }) - - const url = buildUrl(baseURL!, '/app/dashboard') - const response = await request.get(url) - const html = await response.text() - - expect(response.ok()).toBe(true) - expect(html).toContain('data-testid="dashboard-card"') - expect(html).not.toContain('data-tanstack-router-inline-css') - expect(html).not.toContain('data-allow-mismatch') - expect(html).not.toMatch(/]+rel="stylesheet"/) - expect(html).not.toContain('rel:"stylesheet"') - const styleMatches = Array.from( - html.matchAll(/]*>([\s\S]*?)<\/style>/g), - ) - expect(styleMatches).toHaveLength(1) - const inlineCss = styleMatches[0]?.[1] - expect(inlineCss?.length).toBeGreaterThan(100) - expect(inlineCss).not.toContain('\n') - if (process.env.CSS_INLINE_TRANSFORM_ASSETS === 'true') { - expect(inlineCss).toContain('cdn=1') - } else { - expect(inlineCss).not.toContain('cdn=1') - } - - await page.goto(url) - - await expect(page.getByTestId('dashboard-card')).toBeVisible() - await expect(page.getByTestId('nested-panel')).toBeVisible() - - await expect - .poll(() => getStyle(page, 'shell', 'background-color')) - .toBe('rgb(240, 249, 255)') - await expect - .poll(() => getStyle(page, 'app-layout', 'background-color')) - .toBe('rgb(220, 252, 231)') - await expect - .poll(() => getStyle(page, 'dashboard-layout', 'border-left-color')) - .toBe('rgb(124, 58, 237)') - await expect - .poll(() => getStyle(page, 'dashboard-card', 'background-color')) - .toBe('rgb(254, 249, 195)') - await expect - .poll(() => getStyle(page, 'nested-panel', 'background-color')) - .toBe('rgb(219, 234, 254)') - - const backgroundImage = await getStyle( - page, - 'dashboard-card', - 'background-image', - ) - expect(backgroundImage).not.toBe('none') - - const inlineStyleText = (await getInlineCssTexts(page))[0] - expect(inlineStyleText?.length).toBeGreaterThan(100) - - expect(errors.filter((error) => /hydration|Hydration/.test(error))).toEqual( - [], - ) -}) - -test('runtime request options can disable inline CSS', async ({ - page, - request, - baseURL, -}) => { - const url = buildUrl(baseURL!, '/app/dashboard') - const response = await request.get(url, { - headers: { - 'x-inline-css': 'false', - }, - }) - const html = await response.text() - - expect(response.ok()).toBe(true) - expect(html).toMatch(/]+rel="stylesheet"/) - expect(html).not.toMatch(/]*>[\s\S]*background[\s\S]*<\/style>/) - - await page.setExtraHTTPHeaders({ - 'x-inline-css': 'false', - }) - await page.goto(url) - - await expect(page.getByTestId('dashboard-card')).toBeVisible() - await expect.poll(() => getInlineCssTexts(page)).toHaveLength(0) - await expect - .poll(() => getStyle(page, 'dashboard-card', 'background-color')) - .toBe('rgb(254, 249, 195)') -}) - -test('client navigation keeps nested CSS module styles applied', async ({ - page, - baseURL, -}) => { - await page.goto(buildUrl(baseURL!, '/')) - await waitForHydration(page) - await page.getByTestId('nav-details').click() - await page.waitForURL('**/app/dashboard/details') - - await expect(page.getByTestId('details-card')).toBeVisible() - await expect - .poll(() => getStyle(page, 'details-card', 'background-color')) - .toBe('rgb(255, 237, 213)') - await expect - .poll(() => getStyle(page, 'nested-panel', 'border-top-color')) - .toBe('rgb(37, 99, 235)') -}) - -test('client navigation preserves the SSR inline shell stylesheet', async ({ - page, - baseURL, -}) => { - 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)) - .toEqual([expect.stringContaining('background')]) - await expect - .poll(() => getStyle(page, 'shell', 'background-color')) - .toBe('rgb(240, 249, 255)') - - 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 - .poll(() => getInlineCssTexts(page)) - .toEqual([expect.stringContaining('background')]) - await expect - .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-inline/tsconfig.json b/e2e/react-start/css-inline/tsconfig.json deleted file mode 100644 index cc479423a1..0000000000 --- a/e2e/react-start/css-inline/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "include": ["**/*.ts", "**/*.tsx", "**/*.d.ts"], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "react-jsx", - "module": "ESNext", - "moduleResolution": "Bundler", - "lib": ["DOM", "DOM.Iterable", "ES2024"], - "isolatedModules": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "target": "ES2024", - "allowJs": true, - "forceConsistentCasingInFileNames": true, - "paths": { - "~/*": ["./src/*"] - }, - "noEmit": true - } -} diff --git a/e2e/react-start/css-inline/vite.config.ts b/e2e/react-start/css-inline/vite.config.ts deleted file mode 100644 index ccb64b4346..0000000000 --- a/e2e/react-start/css-inline/vite.config.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { defineConfig } from 'vite' -import { tanstackStart } from '@tanstack/react-start/plugin/vite' -import viteReact from '@vitejs/plugin-react' - -const outDir = process.env.E2E_DIST_DIR ?? 'dist-vite-ssr' -const transformInlineCssAssets = - process.env.CSS_INLINE_TRANSFORM_ASSETS === 'true' - -export default defineConfig({ - resolve: { tsconfigPaths: true }, - build: { - outDir, - }, - server: { - port: 3000, - }, - plugins: [ - tanstackStart({ - server: { - build: { - inlineCss: transformInlineCssAssets - ? { enabled: true, transformAssets: true } - : true, - }, - }, - }), - viteReact(), - ], -}) diff --git a/e2e/react-start/css-modules/.devcontainer/devcontainer.json b/e2e/react-start/css-modules/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/react-start/css-modules/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/react-start/css-modules/.gitignore b/e2e/react-start/css-modules/.gitignore index a1fbca128d..229709a89d 100644 --- a/e2e/react-start/css-modules/.gitignore +++ b/e2e/react-start/css-modules/.gitignore @@ -3,4 +3,3 @@ dist test-results playwright-report port*.txt -.cloudflare diff --git a/e2e/react-start/css-modules/cloudflare.config.ts b/e2e/react-start/css-modules/cloudflare.config.ts deleted file mode 100644 index e2bd5e13f1..0000000000 --- a/e2e/react-start/css-modules/cloudflare.config.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { defineConfig } from 'cf/config' - -// Used by rsbuild-plugin-cloudflare (E2E_RSBUILD_CLOUDFLARE=true). -// The Vite Cloudflare variant still reads wrangler.jsonc. -export default defineConfig({ - worker: { - name: 'tanstack-start-css-modules', - entrypoint: '@tanstack/react-start/server-entry', - compatibilityDate: '2026-11-01', - }, -}) diff --git a/e2e/react-start/css-modules/package.json b/e2e/react-start/css-modules/package.json index 25c11d7321..73b874f8f7 100644 --- a/e2e/react-start/css-modules/package.json +++ b/e2e/react-start/css-modules/package.json @@ -12,8 +12,6 @@ "dev:e2e:basepath": "VITE_BASE_PATH=/my-app vite dev --port $PORT", "dev:cloudflare": "echo 'Cloudflare dev mode has React duplication issues - use build+preview instead' && exit 1", "dev:e2e:cloudflare": "echo 'Cloudflare dev mode has React duplication issues - use build+preview instead' && exit 1", - "dev:e2e:rsbuild": "rsbuild dev --port $PORT", - "dev:e2e:rsbuild-cloudflare": "E2E_RSBUILD_CLOUDFLARE=true rsbuild dev --port $PORT", "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", @@ -21,16 +19,11 @@ "test:e2e:dev:nitro": "MODE=dev VITE_CONFIG=nitro playwright test --project=chromium", "test:e2e:dev:basepath": "MODE=dev VITE_CONFIG=basepath playwright test --project=chromium", "_test:e2e:dev:cloudflare": "MODE=dev VITE_CONFIG=cloudflare playwright test --project=chromium", - "test:e2e:dev:rsbuild": "MODE=dev VITE_CONFIG=rsbuild playwright test --project=chromium", - "test:e2e:dev:rsbuild-cloudflare": "MODE=dev VITE_CONFIG=rsbuild-cloudflare playwright test --project=chromium", - "test:e2e:prod:default": "MODE=prod playwright test --project=chromium", - "test:e2e:prod": "pnpm run test:e2e:prod:default && pnpm run test:e2e:prod:css-code-split-false", - "test:e2e:prod:css-code-split-false": "MODE=prod VITE_CSS_CODE_SPLIT=false playwright test tests/css.prod.spec.ts --project=chromium", - "test:e2e": "pnpm run test:e2e:dev && pnpm run test:e2e:prod", - "test:e2e:nitro": "pnpm run test:e2e:dev:nitro", - "test:e2e:basepath": "pnpm run test:e2e:dev:basepath", - "_test:e2e:cloudflare": "echo 'Cloudflare dev mode disabled - React duplication issues' && exit 0", - "build:rsbuild": "rsbuild build && tsc --noEmit" + "test:e2e:prod": "playwright test --project=chromium", + "test:e2e": "rm -rf port*.txt; pnpm run test:e2e:dev", + "test:e2e:nitro": "rm -rf port*.txt; pnpm run test:e2e:dev:nitro", + "test:e2e:basepath": "rm -rf port*.txt; pnpm run test:e2e:dev:basepath", + "_test:e2e:cloudflare": "echo 'Cloudflare dev mode disabled - React duplication issues' && exit 0" }, "dependencies": { "@tanstack/react-router": "workspace:*", @@ -39,38 +32,19 @@ "react-dom": "^19.0.0" }, "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", + "@cloudflare/vite-plugin": "^1.15.1", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:*", "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@typescript/native": "npm:typescript@^7.0.2", - "@vitejs/plugin-react": "^6.0.1", - "cf": "1.0.0-beta.28", - "nitro": "^3.0.260903-beta", - "rsbuild-plugin-cloudflare": "^0.0.4", + "@vitejs/plugin-react": "^4.3.4", + "nitro": "3.0.1-alpha.2", "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" - } - ] - } + "srvx": "^0.11.2", + "typescript": "^5.7.2", + "vite": "^7.3.1", + "vite-tsconfig-paths": "^5.1.4", + "wrangler": "^4.22.0" } } diff --git a/e2e/react-start/css-modules/playwright.config.ts b/e2e/react-start/css-modules/playwright.config.ts index 7e7ad3d9b3..644798ca99 100644 --- a/e2e/react-start/css-modules/playwright.config.ts +++ b/e2e/react-start/css-modules/playwright.config.ts @@ -1,41 +1,37 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } const mode = process.env.MODE ?? 'prod' const isDev = mode === 'dev' -const distDir = process.env.E2E_DIST_DIR const viteConfig = process.env.VITE_CONFIG // 'nitro' | 'basepath' | 'cloudflare' | undefined -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort( + viteConfig ? `${packageJson.name}-${viteConfig}` : packageJson.name, +) // When using basepath config, the app is served at /my-app const basePath = viteConfig === 'basepath' ? '/my-app' : '' const baseURL = `http://localhost:${PORT}${basePath}` // Select the appropriate dev command based on VITE_CONFIG -const devCommand = viteConfig - ? `pnpm dev:e2e:${viteConfig}` - : 'pnpm dev:e2e --port 0' +const devCommand = viteConfig ? `pnpm dev:e2e:${viteConfig}` : 'pnpm dev:e2e' export default defineConfig({ testDir: './tests', - testMatch: isDev ? '**/*.dev.spec.ts' : '**/*.prod.spec.ts', workers: 1, reporter: [['line']], globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', use: { baseURL, }, webServer: { - command: isDev - ? devCommand - : distDir - ? `pnpm exec srvx --prod --dir=. -s ${distDir}/client --entry ${distDir}/server/server.js` - : `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: isDev ? devCommand : `pnpm build && PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { VITE_NODE_ENV: 'test', diff --git a/e2e/react-start/css-modules/rsbuild.config.ts b/e2e/react-start/css-modules/rsbuild.config.ts deleted file mode 100644 index 499ed67ebc..0000000000 --- a/e2e/react-start/css-modules/rsbuild.config.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { defineConfig } from '@rsbuild/core' -import { pluginReact } from '@rsbuild/plugin-react' -import { pluginSass } from '@rsbuild/plugin-sass' -import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' -import { cloudflare } from 'rsbuild-plugin-cloudflare' - -// E2E_RSBUILD_CLOUDFLARE: Set to 'true' to run the SSR environment in workerd -const useCloudflare = process.env.E2E_RSBUILD_CLOUDFLARE === 'true' - -export default defineConfig({ - plugins: [ - pluginReact(), - pluginSass(), - ...(useCloudflare - ? [ - cloudflare({ - rsbuildEnvironment: { name: 'ssr' }, - inspectorPort: false, - }), - ] - : []), - tanstackStart(), - ], - output: { - distPath: { - root: process.env.E2E_DIST_DIR ?? 'dist-rsbuild-ssr', - }, - }, - tools: { - rspack(config, { environment }) { - if (environment.name === 'ssr') { - config.output ??= {} - config.output.filename = 'server.js' - } - if (environment.name !== 'client') { - return - } - config.optimization ??= {} - // Extract the shared component and its helper into their own chunks so - // a route depends on a shared chunk that depends on another shared chunk. - config.optimization.splitChunks = { - cacheGroups: { - sharedHeader: { - test: /[\\/]src[\\/]components[\\/]/, - chunks: 'async', - minChunks: 2, - minSize: 0, - enforce: true, - name: 'shared-header', - }, - sharedFormat: { - test: /[\\/]src[\\/]utils[\\/]/, - chunks: 'async', - minChunks: 2, - minSize: 0, - enforce: true, - name: 'shared-format', - }, - }, - } - }, - }, -}) diff --git a/e2e/react-start/css-modules/src/components/Header.module.css b/e2e/react-start/css-modules/src/components/Header.module.css deleted file mode 100644 index e6878a5410..0000000000 --- a/e2e/react-start/css-modules/src/components/Header.module.css +++ /dev/null @@ -1,14 +0,0 @@ -.header { - --repro-shared-header: 1; - display: grid; - grid-template-columns: minmax(0, 1fr) auto; - align-items: center; - height: 64px; - padding-inline: 16px; - background: #e4f2e9; -} - -.header h1 { - margin: 0; - font-size: 24px; -} diff --git a/e2e/react-start/css-modules/src/components/Header.tsx b/e2e/react-start/css-modules/src/components/Header.tsx deleted file mode 100644 index f16b12e8ff..0000000000 --- a/e2e/react-start/css-modules/src/components/Header.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { formatTitle } from '../utils/formatTitle' -import styles from './Header.module.css' - -export function Header({ title }: { title: string }) { - return ( -
-

{formatTitle(title)}

- -
- ) -} diff --git a/e2e/react-start/css-modules/src/routeTree.gen.ts b/e2e/react-start/css-modules/src/routeTree.gen.ts index 2789a3490a..d19ae80e5a 100644 --- a/e2e/react-start/css-modules/src/routeTree.gen.ts +++ b/e2e/react-start/css-modules/src/routeTree.gen.ts @@ -9,37 +9,14 @@ // 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 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' +import { Route as QuotesRouteImport } from './routes/quotes' +import { Route as ModulesRouteImport } from './routes/modules' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - 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', +const SassMixinRoute = SassMixinRouteImport.update({ + id: '/sass-mixin', + path: '/sass-mixin', getParentRoute: () => rootRouteImport, } as any) const QuotesRoute = QuotesRouteImport.update({ @@ -47,26 +24,25 @@ const QuotesRoute = QuotesRouteImport.update({ path: '/quotes', getParentRoute: () => rootRouteImport, } as any) -const SassMixinRoute = SassMixinRouteImport.update({ - id: '/sass-mixin', - path: '/sass-mixin', +const ModulesRoute = ModulesRouteImport.update({ + id: '/modules', + path: '/modules', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute - '/alpha': typeof AlphaRoute - '/beta': typeof BetaRoute - '/gamma': typeof GammaRoute '/modules': typeof ModulesRoute '/quotes': typeof QuotesRoute '/sass-mixin': typeof SassMixinRoute } export interface FileRoutesByTo { '/': typeof IndexRoute - '/alpha': typeof AlphaRoute - '/beta': typeof BetaRoute - '/gamma': typeof GammaRoute '/modules': typeof ModulesRoute '/quotes': typeof QuotesRoute '/sass-mixin': typeof SassMixinRoute @@ -74,36 +50,20 @@ export interface FileRoutesByTo { export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute - '/alpha': typeof AlphaRoute - '/beta': typeof BetaRoute - '/gamma': typeof GammaRoute '/modules': typeof ModulesRoute '/quotes': typeof QuotesRoute '/sass-mixin': typeof SassMixinRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - '/' | '/alpha' | '/beta' | '/gamma' | '/modules' | '/quotes' | '/sass-mixin' + fullPaths: '/' | '/modules' | '/quotes' | '/sass-mixin' fileRoutesByTo: FileRoutesByTo - to: - '/' | '/alpha' | '/beta' | '/gamma' | '/modules' | '/quotes' | '/sass-mixin' - id: - | '__root__' - | '/' - | '/alpha' - | '/beta' - | '/gamma' - | '/modules' - | '/quotes' - | '/sass-mixin' + to: '/' | '/modules' | '/quotes' | '/sass-mixin' + id: '__root__' | '/' | '/modules' | '/quotes' | '/sass-mixin' fileRoutesById: FileRoutesById } export interface RootRouteChildren { IndexRoute: typeof IndexRoute - AlphaRoute: typeof AlphaRoute - BetaRoute: typeof BetaRoute - GammaRoute: typeof GammaRoute ModulesRoute: typeof ModulesRoute QuotesRoute: typeof QuotesRoute SassMixinRoute: typeof SassMixinRoute @@ -111,39 +71,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - 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' - fullPath: '/modules' - preLoaderRoute: typeof ModulesRouteImport + '/sass-mixin': { + id: '/sass-mixin' + path: '/sass-mixin' + fullPath: '/sass-mixin' + preLoaderRoute: typeof SassMixinRouteImport parentRoute: typeof rootRouteImport } '/quotes': { @@ -153,11 +85,18 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof QuotesRouteImport parentRoute: typeof rootRouteImport } - '/sass-mixin': { - id: '/sass-mixin' - path: '/sass-mixin' - fullPath: '/sass-mixin' - preLoaderRoute: typeof SassMixinRouteImport + '/modules': { + id: '/modules' + path: '/modules' + fullPath: '/modules' + preLoaderRoute: typeof ModulesRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } } @@ -165,9 +104,6 @@ declare module '@tanstack/react-router' { const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, - AlphaRoute: AlphaRoute, - BetaRoute: BetaRoute, - GammaRoute: GammaRoute, ModulesRoute: ModulesRoute, QuotesRoute: QuotesRoute, SassMixinRoute: SassMixinRoute, diff --git a/e2e/react-start/css-modules/src/routes/alpha.tsx b/e2e/react-start/css-modules/src/routes/alpha.tsx deleted file mode 100644 index e894cd758f..0000000000 --- a/e2e/react-start/css-modules/src/routes/alpha.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { Header } from '../components/Header' -import styles from '../styles/alpha.module.css' - -export const Route = createFileRoute('/alpha')({ component: Alpha }) - -function Alpha() { - return ( -
-
-
- ) -} diff --git a/e2e/react-start/css-modules/src/routes/beta.tsx b/e2e/react-start/css-modules/src/routes/beta.tsx deleted file mode 100644 index 4f139ac41a..0000000000 --- a/e2e/react-start/css-modules/src/routes/beta.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { Header } from '../components/Header' -import styles from '../styles/beta.module.css' - -export const Route = createFileRoute('/beta')({ component: Beta }) - -function Beta() { - return ( -
-
-
- ) -} diff --git a/e2e/react-start/css-modules/src/routes/gamma.tsx b/e2e/react-start/css-modules/src/routes/gamma.tsx deleted file mode 100644 index a8e036b85f..0000000000 --- a/e2e/react-start/css-modules/src/routes/gamma.tsx +++ /dev/null @@ -1,8 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { formatTitle } from '../utils/formatTitle' - -export const Route = createFileRoute('/gamma')({ component: Gamma }) - -function Gamma() { - return
{formatTitle('Gamma')}
-} diff --git a/e2e/react-start/css-modules/src/styles/alpha.module.css b/e2e/react-start/css-modules/src/styles/alpha.module.css deleted file mode 100644 index 12a606a8d3..0000000000 --- a/e2e/react-start/css-modules/src/styles/alpha.module.css +++ /dev/null @@ -1,4 +0,0 @@ -.page { - --repro-alpha: 1; - border: 4px solid #226844; -} diff --git a/e2e/react-start/css-modules/src/styles/beta.module.css b/e2e/react-start/css-modules/src/styles/beta.module.css deleted file mode 100644 index 719686a76b..0000000000 --- a/e2e/react-start/css-modules/src/styles/beta.module.css +++ /dev/null @@ -1,4 +0,0 @@ -.page { - --repro-beta: 1; - border: 4px solid #ac344c; -} diff --git a/e2e/react-start/css-modules/src/utils/formatTitle.ts b/e2e/react-start/css-modules/src/utils/formatTitle.ts deleted file mode 100644 index d0325ac63e..0000000000 --- a/e2e/react-start/css-modules/src/utils/formatTitle.ts +++ /dev/null @@ -1,3 +0,0 @@ -export function formatTitle(title: string) { - return `${title} (repro-format-title)` -} diff --git a/e2e/react-start/css-modules/tests/css.dev.spec.ts b/e2e/react-start/css-modules/tests/css.dev.spec.ts deleted file mode 100644 index e08a74354c..0000000000 --- a/e2e/react-start/css-modules/tests/css.dev.spec.ts +++ /dev/null @@ -1,236 +0,0 @@ -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' - -// Whitelist errors that can occur in CI: -// - net::ERR_NAME_NOT_RESOLVED: transient network issues -// - 504 (Outdated Optimize Dep): Vite dependency optimization reload -const whitelistErrors = [ - 'Failed to load resource: net::ERR_NAME_NOT_RESOLVED', - 'Failed to load resource: the server responded with a status of 504', -] -test.skip(process.env.MODE === 'prod', 'Dev-only repro') - -test.describe('CSS styles in SSR (dev mode)', () => { - test.use({ whitelistErrors }) - - // Helper to build full URL from baseURL and path - // Playwright's goto with absolute paths (like '/modules') ignores baseURL's path portion - // So we need to manually construct the full URL - const buildUrl = (baseURL: string, path: string) => { - return baseURL.replace(/\/$/, '') + path - } - - test.describe('with JavaScript disabled', () => { - test.use({ javaScriptEnabled: false, whitelistErrors }) - - test('global CSS is applied on initial page load', async ({ - page, - baseURL, - }) => { - await page.goto(buildUrl(baseURL!, '/')) - - const element = page.getByTestId('global-styled') - await expect(element).toBeVisible() - - // Verify the CSS is applied by checking computed styles - // #3b82f6 (blue-500) in RGB is rgb(59, 130, 246) - const backgroundColor = await element.evaluate( - (el) => getComputedStyle(el).backgroundColor, - ) - expect(backgroundColor).toBe('rgb(59, 130, 246)') - - const padding = await element.evaluate( - (el) => getComputedStyle(el).padding, - ) - expect(padding).toBe('24px') - - const borderRadius = await element.evaluate( - (el) => getComputedStyle(el).borderRadius, - ) - expect(borderRadius).toBe('12px') - }) - - test('CSS modules are applied on initial page load', async ({ - page, - baseURL, - }) => { - await page.goto(buildUrl(baseURL!, '/modules')) - - const card = page.getByTestId('module-card') - await expect(card).toBeVisible() - - // Verify class is scoped (hashed) - const className = await card.getAttribute('class') - expect(className).toBeTruthy() - expect(className).not.toBe('card') - // The class should contain some hash characters (CSS modules add a hash) - expect(className!.length).toBeGreaterThan(5) - - // Verify computed styles from card.module.css - // #f0fdf4 (green-50) in RGB is rgb(240, 253, 244) - const backgroundColor = await card.evaluate( - (el) => getComputedStyle(el).backgroundColor, - ) - expect(backgroundColor).toBe('rgb(240, 253, 244)') - - const padding = await card.evaluate((el) => getComputedStyle(el).padding) - expect(padding).toBe('16px') - - const borderRadius = await card.evaluate( - (el) => getComputedStyle(el).borderRadius, - ) - expect(borderRadius).toBe('8px') - }) - - test('global CSS class names are NOT scoped', async ({ page, baseURL }) => { - await page.goto(buildUrl(baseURL!, '/')) - - const element = page.getByTestId('global-styled') - await expect(element).toBeVisible() - - // Get the class attribute - it should be the plain class name (not hashed) - const className = await element.getAttribute('class') - expect(className).toBe('global-container') - }) - - test('Sass mixin styles are applied on initial page load', async ({ - page, - baseURL, - }) => { - await page.goto(buildUrl(baseURL!, '/sass-mixin')) - - const element = page.getByTestId('mixin-styled') - await expect(element).toBeVisible() - - // Verify the mixin is applied (display: flex from center-mixin) - const display = await element.evaluate( - (el) => getComputedStyle(el).display, - ) - expect(display).toBe('flex') - - const justifyContent = await element.evaluate( - (el) => getComputedStyle(el).justifyContent, - ) - expect(justifyContent).toBe('center') - - const alignItems = await element.evaluate( - (el) => getComputedStyle(el).alignItems, - ) - expect(alignItems).toBe('center') - - // Verify other styles from mixin-consumer.scss - // #a855f7 (purple-500) in RGB is rgb(168, 85, 247) - const backgroundColor = await element.evaluate( - (el) => getComputedStyle(el).backgroundColor, - ) - expect(backgroundColor).toBe('rgb(168, 85, 247)') - - const padding = await element.evaluate( - (el) => getComputedStyle(el).padding, - ) - expect(padding).toBe('24px') - }) - - test('CSS with quoted content is fully extracted', async ({ - page, - baseURL, - }) => { - await page.goto(buildUrl(baseURL!, '/quotes')) - - // Verify the element using CSS with content:"..." is styled - const quoteElement = page.getByTestId('quote-styled') - await expect(quoteElement).toBeVisible() - - // #ef4444 (red-500) in RGB is rgb(239, 68, 68) - const quoteBackgroundColor = await quoteElement.evaluate( - (el) => getComputedStyle(el).backgroundColor, - ) - expect(quoteBackgroundColor).toBe('rgb(239, 68, 68)') - - // Verify styles AFTER the quoted content are also extracted - // This is the key test - the regex bug would cut off CSS at the first quote - const afterQuoteElement = page.getByTestId('after-quote-styled') - await expect(afterQuoteElement).toBeVisible() - - // #f59e0b (amber-500) in RGB is rgb(245, 158, 11) - const afterQuoteBackgroundColor = await afterQuoteElement.evaluate( - (el) => getComputedStyle(el).backgroundColor, - ) - expect(afterQuoteBackgroundColor).toBe('rgb(245, 158, 11)') - }) - }) - - test('styles persist after hydration', async ({ page, baseURL }) => { - await page.goto(buildUrl(baseURL!, '/')) - - // Wait for hydration and styles to be applied - const element = page.getByTestId('global-styled') - await expect(element).toBeVisible() - - // Wait for CSS to be applied (background color should not be transparent) - await expect(async () => { - const backgroundColor = await element.evaluate( - (el) => getComputedStyle(el).backgroundColor, - ) - expect(backgroundColor).toBe('rgb(59, 130, 246)') - }).toPass({ timeout: 5000 }) - }) - - test('CSS modules styles persist after hydration', async ({ - page, - baseURL, - }) => { - await page.goto(buildUrl(baseURL!, '/modules')) - - // Wait for hydration and styles to be applied - const card = page.getByTestId('module-card') - await expect(card).toBeVisible() - - // Wait for CSS to be applied (background color should not be transparent) - await expect(async () => { - const backgroundColor = await card.evaluate( - (el) => getComputedStyle(el).backgroundColor, - ) - expect(backgroundColor).toBe('rgb(240, 253, 244)') - }).toPass({ timeout: 5000 }) - }) - - test('styles work correctly after client-side navigation', async ({ - page, - baseURL, - }) => { - // Start from home - await page.goto(buildUrl(baseURL!, '/')) - - // Verify initial styles - const globalElement = page.getByTestId('global-styled') - await expect(globalElement).toBeVisible() - let backgroundColor = await globalElement.evaluate( - (el) => getComputedStyle(el).backgroundColor, - ) - expect(backgroundColor).toBe('rgb(59, 130, 246)') - - // Navigate to modules page - await page.getByTestId('nav-modules').click() - await page.waitForURL('**/modules') - - // Verify CSS modules styles - const card = page.getByTestId('module-card') - await expect(card).toBeVisible() - backgroundColor = await card.evaluate( - (el) => getComputedStyle(el).backgroundColor, - ) - expect(backgroundColor).toBe('rgb(240, 253, 244)') - - // Navigate back to home - await page.getByTestId('nav-home').click() - await page.waitForURL(/\/([^/]*)(\/)?($|\?)/) - - // Verify global styles still work - await expect(globalElement).toBeVisible() - backgroundColor = await globalElement.evaluate( - (el) => getComputedStyle(el).backgroundColor, - ) - expect(backgroundColor).toBe('rgb(59, 130, 246)') - }) -}) diff --git a/e2e/react-start/css-modules/tests/css.prod.spec.ts b/e2e/react-start/css-modules/tests/css.prod.spec.ts deleted file mode 100644 index 3e5c5214e9..0000000000 --- a/e2e/react-start/css-modules/tests/css.prod.spec.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' - -test.skip(process.env.MODE !== 'prod', 'Prod-only coverage') -test.skip( - process.env.VITE_CSS_CODE_SPLIT !== 'false', - 'Requires cssCodeSplit=false mode', -) - -test.describe('CSS modules with cssCodeSplit disabled', () => { - test.describe('with JavaScript disabled', () => { - test.use({ javaScriptEnabled: false }) - - test('CSS modules are applied on initial page load', async ({ page }) => { - await page.goto('/modules') - - const card = page.getByTestId('module-card') - await expect(card).toBeVisible() - - const className = await card.getAttribute('class') - expect(className).toBeTruthy() - expect(className).not.toBe('card') - expect(className!.length).toBeGreaterThan(5) - - const backgroundColor = await card.evaluate( - (el) => getComputedStyle(el).backgroundColor, - ) - expect(backgroundColor).toBe('rgb(240, 253, 244)') - - const padding = await card.evaluate((el) => getComputedStyle(el).padding) - expect(padding).toBe('16px') - - const borderRadius = await card.evaluate( - (el) => getComputedStyle(el).borderRadius, - ) - expect(borderRadius).toBe('8px') - }) - }) - - test('CSS modules styles persist after hydration', async ({ page }) => { - await page.goto('/modules') - - const card = page.getByTestId('module-card') - await expect(card).toBeVisible() - - await expect(async () => { - const backgroundColor = await card.evaluate( - (el) => getComputedStyle(el).backgroundColor, - ) - expect(backgroundColor).toBe('rgb(240, 253, 244)') - }).toPass({ timeout: 5000 }) - }) - - test('styles work correctly after client-side navigation', async ({ - page, - }) => { - await page.goto('/') - - const globalElement = page.getByTestId('global-styled') - await expect(globalElement).toBeVisible() - - let backgroundColor = await globalElement.evaluate( - (el) => getComputedStyle(el).backgroundColor, - ) - expect(backgroundColor).toBe('rgb(59, 130, 246)') - - await page.getByTestId('nav-modules').click() - await page.waitForURL('**/modules') - - const card = page.getByTestId('module-card') - await expect(card).toBeVisible() - - await expect(async () => { - const backgroundColor = await card.evaluate( - (el) => getComputedStyle(el).backgroundColor, - ) - expect(backgroundColor).toBe('rgb(240, 253, 244)') - }).toPass({ timeout: 5000 }) - }) -}) diff --git a/e2e/react-start/css-modules/tests/css.spec.ts b/e2e/react-start/css-modules/tests/css.spec.ts new file mode 100644 index 0000000000..a823b5a693 --- /dev/null +++ b/e2e/react-start/css-modules/tests/css.spec.ts @@ -0,0 +1,266 @@ +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' + +// Whitelist errors that can occur in CI: +// - net::ERR_NAME_NOT_RESOLVED: transient network issues +// - 504 (Outdated Optimize Dep): Vite dependency optimization reload +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('CSS styles in SSR (dev mode)', () => { + test.use({ whitelistErrors }) + + // Warmup: trigger Vite's dependency optimization before running tests + // This prevents "optimized dependencies changed. reloading" during actual tests + // We use a real browser context since dep optimization happens on JS load, not HTTP requests + test.beforeAll(async ({ browser, baseURL }) => { + const context = await browser.newContext() + const page = await context.newPage() + try { + // Load both pages to trigger dependency optimization + await page.goto(baseURL!) + await page.waitForTimeout(2000) // Wait for deps to optimize + await page.goto(`${baseURL}/modules`) + await page.waitForTimeout(2000) + // Load again after optimization completes + await page.goto(baseURL!) + await page.waitForTimeout(1000) + } catch { + // Ignore errors during warmup + } finally { + await context.close() + } + }) + + // Helper to build full URL from baseURL and path + // Playwright's goto with absolute paths (like '/modules') ignores baseURL's path portion + // So we need to manually construct the full URL + const buildUrl = (baseURL: string, path: string) => { + return baseURL.replace(/\/$/, '') + path + } + + test.describe('with JavaScript disabled', () => { + test.use({ javaScriptEnabled: false, whitelistErrors }) + + test('global CSS is applied on initial page load', async ({ + page, + baseURL, + }) => { + await page.goto(buildUrl(baseURL!, '/')) + + const element = page.getByTestId('global-styled') + await expect(element).toBeVisible() + + // Verify the CSS is applied by checking computed styles + // #3b82f6 (blue-500) in RGB is rgb(59, 130, 246) + const backgroundColor = await element.evaluate( + (el) => getComputedStyle(el).backgroundColor, + ) + expect(backgroundColor).toBe('rgb(59, 130, 246)') + + const padding = await element.evaluate( + (el) => getComputedStyle(el).padding, + ) + expect(padding).toBe('24px') + + const borderRadius = await element.evaluate( + (el) => getComputedStyle(el).borderRadius, + ) + expect(borderRadius).toBe('12px') + }) + + test('CSS modules are applied on initial page load', async ({ + page, + baseURL, + }) => { + await page.goto(buildUrl(baseURL!, '/modules')) + + const card = page.getByTestId('module-card') + await expect(card).toBeVisible() + + // Verify class is scoped (hashed) + const className = await card.getAttribute('class') + expect(className).toBeTruthy() + expect(className).not.toBe('card') + // The class should contain some hash characters (CSS modules add a hash) + expect(className!.length).toBeGreaterThan(5) + + // Verify computed styles from card.module.css + // #f0fdf4 (green-50) in RGB is rgb(240, 253, 244) + const backgroundColor = await card.evaluate( + (el) => getComputedStyle(el).backgroundColor, + ) + expect(backgroundColor).toBe('rgb(240, 253, 244)') + + const padding = await card.evaluate((el) => getComputedStyle(el).padding) + expect(padding).toBe('16px') + + const borderRadius = await card.evaluate( + (el) => getComputedStyle(el).borderRadius, + ) + expect(borderRadius).toBe('8px') + }) + + test('global CSS class names are NOT scoped', async ({ page, baseURL }) => { + await page.goto(buildUrl(baseURL!, '/')) + + const element = page.getByTestId('global-styled') + await expect(element).toBeVisible() + + // Get the class attribute - it should be the plain class name (not hashed) + const className = await element.getAttribute('class') + expect(className).toBe('global-container') + }) + + test('Sass mixin styles are applied on initial page load', async ({ + page, + baseURL, + }) => { + await page.goto(buildUrl(baseURL!, '/sass-mixin')) + + const element = page.getByTestId('mixin-styled') + await expect(element).toBeVisible() + + // Verify the mixin is applied (display: flex from center-mixin) + const display = await element.evaluate( + (el) => getComputedStyle(el).display, + ) + expect(display).toBe('flex') + + const justifyContent = await element.evaluate( + (el) => getComputedStyle(el).justifyContent, + ) + expect(justifyContent).toBe('center') + + const alignItems = await element.evaluate( + (el) => getComputedStyle(el).alignItems, + ) + expect(alignItems).toBe('center') + + // Verify other styles from mixin-consumer.scss + // #a855f7 (purple-500) in RGB is rgb(168, 85, 247) + const backgroundColor = await element.evaluate( + (el) => getComputedStyle(el).backgroundColor, + ) + expect(backgroundColor).toBe('rgb(168, 85, 247)') + + const padding = await element.evaluate( + (el) => getComputedStyle(el).padding, + ) + expect(padding).toBe('24px') + }) + + test('CSS with quoted content is fully extracted', async ({ + page, + baseURL, + }) => { + await page.goto(buildUrl(baseURL!, '/quotes')) + + // Verify the element using CSS with content:"..." is styled + const quoteElement = page.getByTestId('quote-styled') + await expect(quoteElement).toBeVisible() + + // #ef4444 (red-500) in RGB is rgb(239, 68, 68) + const quoteBackgroundColor = await quoteElement.evaluate( + (el) => getComputedStyle(el).backgroundColor, + ) + expect(quoteBackgroundColor).toBe('rgb(239, 68, 68)') + + // Verify styles AFTER the quoted content are also extracted + // This is the key test - the regex bug would cut off CSS at the first quote + const afterQuoteElement = page.getByTestId('after-quote-styled') + await expect(afterQuoteElement).toBeVisible() + + // #f59e0b (amber-500) in RGB is rgb(245, 158, 11) + const afterQuoteBackgroundColor = await afterQuoteElement.evaluate( + (el) => getComputedStyle(el).backgroundColor, + ) + expect(afterQuoteBackgroundColor).toBe('rgb(245, 158, 11)') + }) + }) + + test('styles persist after hydration', async ({ page, baseURL }) => { + await page.goto(buildUrl(baseURL!, '/')) + + // Wait for hydration and styles to be applied + const element = page.getByTestId('global-styled') + await expect(element).toBeVisible() + + // Wait for CSS to be applied (background color should not be transparent) + await expect(async () => { + const backgroundColor = await element.evaluate( + (el) => getComputedStyle(el).backgroundColor, + ) + expect(backgroundColor).toBe('rgb(59, 130, 246)') + }).toPass({ timeout: 5000 }) + }) + + test('CSS modules styles persist after hydration', async ({ + page, + baseURL, + }) => { + await page.goto(buildUrl(baseURL!, '/modules')) + + // Wait for hydration and styles to be applied + const card = page.getByTestId('module-card') + await expect(card).toBeVisible() + + // Wait for CSS to be applied (background color should not be transparent) + await expect(async () => { + const backgroundColor = await card.evaluate( + (el) => getComputedStyle(el).backgroundColor, + ) + expect(backgroundColor).toBe('rgb(240, 253, 244)') + }).toPass({ timeout: 5000 }) + }) + + test('styles work correctly after client-side navigation', async ({ + page, + baseURL, + }) => { + // Start from home + await page.goto(buildUrl(baseURL!, '/')) + + // Verify initial styles with retry to handle potential Vite dep optimization reload + const globalElement = page.getByTestId('global-styled') + await expect(async () => { + await expect(globalElement).toBeVisible() + const backgroundColor = await globalElement.evaluate( + (el) => getComputedStyle(el).backgroundColor, + ) + expect(backgroundColor).toBe('rgb(59, 130, 246)') + }).toPass({ timeout: 10000 }) + + // Navigate to modules page + await page.getByTestId('nav-modules').click() + // Use glob pattern to match with or without basepath + await page.waitForURL('**/modules') + + // Verify CSS modules styles with retry to handle potential Vite dep optimization reload + const card = page.getByTestId('module-card') + await expect(async () => { + await expect(card).toBeVisible() + const backgroundColor = await card.evaluate( + (el) => getComputedStyle(el).backgroundColor, + ) + expect(backgroundColor).toBe('rgb(240, 253, 244)') + }).toPass({ timeout: 10000 }) + + // Navigate back to home + await page.getByTestId('nav-home').click() + // Match home URL with or without trailing slash and optional query string + // Matches: /, /?, /my-app, /my-app/, /my-app?foo=bar + await page.waitForURL(/\/([^/]*)(\/)?($|\?)/) + + // Verify global styles still work with retry + await expect(async () => { + await expect(globalElement).toBeVisible() + const backgroundColor = await globalElement.evaluate( + (el) => getComputedStyle(el).backgroundColor, + ) + expect(backgroundColor).toBe('rgb(59, 130, 246)') + }).toPass({ timeout: 10000 }) + }) +}) diff --git a/e2e/react-start/css-modules/tests/setup/global.setup.ts b/e2e/react-start/css-modules/tests/setup/global.setup.ts index 7c0fce762a..3593d10ab9 100644 --- a/e2e/react-start/css-modules/tests/setup/global.setup.ts +++ b/e2e/react-start/css-modules/tests/setup/global.setup.ts @@ -1,48 +1,6 @@ -import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } export default async function setup() { - if (process.env.MODE !== 'dev') return - - const viteConfig = process.env.VITE_CONFIG // 'nitro' | 'basepath' | 'cloudflare' | undefined - const port = Number(process.env.E2E_APP_PORT ?? 0) - const basePath = viteConfig === 'basepath' ? '/my-app' : '' - const baseURL = `http://localhost:${port}${basePath}` - - await waitForServer(baseURL) - await preOptimizeDevServer({ - baseURL, - readyTestId: 'global-styled', - warmup: async (page) => { - await page.goto(`${baseURL}/modules`, { waitUntil: 'domcontentloaded' }) - await page.getByTestId('module-card').waitFor({ state: 'visible' }) - await page.waitForLoadState('networkidle') - - await page.goto(`${baseURL}/sass-mixin`, { - waitUntil: 'domcontentloaded', - }) - await page.getByTestId('mixin-styled').waitFor({ state: 'visible' }) - await page.waitForLoadState('networkidle') - - await page.goto(`${baseURL}/quotes`, { waitUntil: 'domcontentloaded' }) - await page.getByTestId('quote-styled').waitFor({ state: 'visible' }) - await page.getByTestId('after-quote-styled').waitFor({ - state: 'visible', - }) - await page.waitForLoadState('networkidle') - - await page.goto(`${baseURL}/`, { waitUntil: 'domcontentloaded' }) - await page.getByTestId('global-styled').waitFor({ state: 'visible' }) - await page.waitForLoadState('networkidle') - - await page.getByTestId('nav-modules').click() - await page.waitForURL('**/modules') - await page.getByTestId('module-card').waitFor({ state: 'visible' }) - await page.waitForLoadState('networkidle') - - await page.getByTestId('nav-home').click() - await page.waitForURL(/\/([^/]*)(\/)?($|\?)/) - await page.getByTestId('global-styled').waitFor({ state: 'visible' }) - await page.waitForLoadState('networkidle') - }, - }) + await e2eStartDummyServer(packageJson.name) } diff --git a/e2e/react-start/css-modules/tests/setup/global.teardown.ts b/e2e/react-start/css-modules/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-start/css-modules/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-start/css-modules/tests/shared-css.prod.spec.ts b/e2e/react-start/css-modules/tests/shared-css.prod.spec.ts deleted file mode 100644 index 9a9595f819..0000000000 --- a/e2e/react-start/css-modules/tests/shared-css.prod.spec.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' -import type { Page } from '@playwright/test' - -test.skip( - process.env.VITE_CSS_CODE_SPLIT === 'false', - 'Route stylesheet isolation requires CSS code splitting', -) -test.use({ javaScriptEnabled: false }) - -async function getStylesheetContent(page: Page) { - const hrefs = await page - .locator('link[rel="stylesheet"]') - .evaluateAll((links: Array) => - links.map((link) => link.href), - ) - expect(hrefs.length).toBeGreaterThan(0) - const stylesheets = await Promise.all( - hrefs.map(async (href) => { - const response = await page.request.get(href) - expect(response.ok()).toBe(true) - return response.text() - }), - ) - return stylesheets.join('\n') -} - -for (const route of ['alpha', 'beta']) { - test(`${route} has complete and isolated CSS without JavaScript`, async ({ - page, - }) => { - await page.goto(`/${route}`) - - const header = page.getByTestId('shared-header') - await expect(header).toHaveCSS('display', 'grid') - await expect(header).toHaveCSS('height', '64px') - await expect(page.getByTestId('route-page')).toHaveCSS( - `--repro-${route}`, - '1', - ) - - const css = await getStylesheetContent(page) - expect(css).toContain('--repro-shared-header') - expect(css).toContain(`--repro-${route}`) - expect(css).not.toContain(`--repro-${route === 'alpha' ? 'beta' : 'alpha'}`) - }) -} - -function getScriptPreloadHrefs(html: string) { - return Array.from(html.matchAll(/]*>/g), (match) => match[0]) - .filter( - (tag) => - /\brel="modulepreload"/.test(tag) || - (/\brel="preload"/.test(tag) && /\bas="script"/.test(tag)), - ) - .map((tag) => tag.match(/\bhref="([^"]+)"/)?.[1]) - .filter((href): href is string => !!href) -} - -test('alpha preloads the shared header chunk and the chunk it depends on', async ({ - page, -}) => { - const response = await page.request.get('/alpha') - expect(response.ok()).toBe(true) - - const hrefs = getScriptPreloadHrefs(await response.text()) - expect(hrefs.length).toBeGreaterThan(0) - - const scripts = await Promise.all( - hrefs.map(async (href) => { - const script = await page.request.get(href) - expect(script.ok()).toBe(true) - return script.text() - }), - ) - - expect(scripts.some((code) => code.includes('shared-header'))).toBe(true) - expect(scripts.some((code) => code.includes('repro-format-title'))).toBe(true) -}) - -test('home does not load the shared header or route styles', async ({ - page, -}) => { - await page.goto('/') - await expect(page.getByTestId('global-styled')).toHaveCSS( - 'background-color', - 'rgb(59, 130, 246)', - ) - - const css = await getStylesheetContent(page) - expect(css).not.toContain('--repro-shared-header') - expect(css).not.toContain('--repro-alpha') - expect(css).not.toContain('--repro-beta') -}) diff --git a/e2e/react-start/css-modules/tsconfig.json b/e2e/react-start/css-modules/tsconfig.json index cef9369516..3a9fb7cd71 100644 --- a/e2e/react-start/css-modules/tsconfig.json +++ b/e2e/react-start/css-modules/tsconfig.json @@ -13,6 +13,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/react-start/css-modules/vite.config.cloudflare.ts b/e2e/react-start/css-modules/vite.config.cloudflare.ts index e29e67b1b2..7015976b97 100644 --- a/e2e/react-start/css-modules/vite.config.cloudflare.ts +++ b/e2e/react-start/css-modules/vite.config.cloudflare.ts @@ -1,11 +1,14 @@ import { defineConfig } from 'vite' +import tsConfigPaths from 'vite-tsconfig-paths' import { cloudflare } from '@cloudflare/vite-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import viteReact from '@vitejs/plugin-react' export default defineConfig({ - resolve: { tsconfigPaths: true }, plugins: [ + tsConfigPaths({ + projects: ['./tsconfig.json'], + }), cloudflare({ viteEnvironment: { name: 'ssr' }, inspectorPort: false }), tanstackStart(), viteReact(), diff --git a/e2e/react-start/css-modules/vite.config.ts b/e2e/react-start/css-modules/vite.config.ts index c9c27f7f9a..9dacdf984a 100644 --- a/e2e/react-start/css-modules/vite.config.ts +++ b/e2e/react-start/css-modules/vite.config.ts @@ -1,30 +1,27 @@ import { defineConfig } from 'vite' +import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import viteReact from '@vitejs/plugin-react' // Environment variables for different test configurations: // - VITE_BASE_PATH: Set to '/my-app' for basepath testing // - VITE_USE_NITRO: Set to 'true' to enable Nitro server -// - VITE_CSS_CODE_SPLIT: Set to 'false' to disable CSS code splitting in prod const basePath = process.env.VITE_BASE_PATH const useNitro = process.env.VITE_USE_NITRO === 'true' -const cssCodeSplit = process.env.VITE_CSS_CODE_SPLIT !== 'false' export default defineConfig(async () => { // Dynamically import nitro only when needed to avoid loading it when not used const nitroPlugin = useNitro ? [(await import('nitro/vite')).nitro()] : [] return { - resolve: { tsconfigPaths: true }, base: basePath, server: { port: 3000, }, - build: { - outDir: process.env.E2E_DIST_DIR ?? 'dist', - cssCodeSplit, - }, plugins: [ + tsConfigPaths({ + projects: ['./tsconfig.json'], + }), // Nitro is placed BEFORE tanstackStart to test that our CSS middleware // works regardless of plugin order (nitro has a catch-all middleware) ...nitroPlugin, diff --git a/e2e/react-start/custom-basepath/.devcontainer/devcontainer.json b/e2e/react-start/custom-basepath/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/react-start/custom-basepath/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/react-start/custom-basepath/express-server.ts b/e2e/react-start/custom-basepath/express-server.ts index b9bf393466..87dcfb50da 100644 --- a/e2e/react-start/custom-basepath/express-server.ts +++ b/e2e/react-start/custom-basepath/express-server.ts @@ -1,6 +1,5 @@ import express from 'express' import { toNodeHandler } from 'srvx/node' -import type { AddressInfo } from 'node:net' import type { NodeHttp1Handler } from 'srvx' const DEVELOPMENT = process.env.NODE_ENV === 'development' @@ -41,11 +40,6 @@ if (DEVELOPMENT) { }) } -const httpServer = app.listen(PORT, (error) => { - if (error) { - throw error - } - console.log( - `E2E app: http://localhost:${(httpServer.address() as AddressInfo).port}`, - ) +app.listen(PORT, () => { + console.log(`Server is running on http://localhost:${PORT}`) }) diff --git a/e2e/react-start/custom-basepath/package.json b/e2e/react-start/custom-basepath/package.json index e93949eea2..d2df8be146 100644 --- a/e2e/react-start/custom-basepath/package.json +++ b/e2e/react-start/custom-basepath/package.json @@ -8,32 +8,32 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "tsx express-server.ts", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", "@tanstack/react-start": "workspace:^", - "express": "^5.2.1", + "express": "^4.21.2", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "catalog:" + "redaxios": "^0.5.1" }, "devDependencies": { - "@playwright/test": "^1.61.0", - "@tailwindcss/vite": "^4.2.2", + "@playwright/test": "^1.50.1", + "@tailwindcss/vite": "^4.1.18", "@tanstack/router-e2e-utils": "workspace:^", - "@types/express": "^5.0.6", + "@types/express": "^5.0.3", "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", + "@vitejs/plugin-react": "^4.3.4", "cross-env": "^10.0.0", - "srvx": "^1.0.0", - "tailwindcss": "^4.2.2", + "srvx": "^0.11.2", + "tailwindcss": "^4.1.18", "tsx": "^4.20.3", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "typescript": "^5.7.2", + "vite": "^7.3.1", + "vite-tsconfig-paths": "^5.1.4" } } diff --git a/e2e/react-start/custom-basepath/playwright.config.ts b/e2e/react-start/custom-basepath/playwright.config.ts index e113ce64ad..5095425f47 100644 --- a/e2e/react-start/custom-basepath/playwright.config.ts +++ b/e2e/react-start/custom-basepath/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}/custom/basepath` /** @@ -13,19 +18,19 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', - env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, - }, }, projects: [ diff --git a/e2e/react-start/custom-basepath/src/components/DefaultCatchBoundary.tsx b/e2e/react-start/custom-basepath/src/components/DefaultCatchBoundary.tsx index 405fb5f4a7..ef2daa1ea1 100644 --- a/e2e/react-start/custom-basepath/src/components/DefaultCatchBoundary.tsx +++ b/e2e/react-start/custom-basepath/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/react-router' import type { ErrorComponentProps } from '@tanstack/react-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) console.error(error) diff --git a/e2e/react-start/custom-basepath/src/routeTree.gen.ts b/e2e/react-start/custom-basepath/src/routeTree.gen.ts index 18cc9b5163..986f31bbbb 100644 --- a/e2e/react-start/custom-basepath/src/routeTree.gen.ts +++ b/e2e/react-start/custom-basepath/src/routeTree.gen.ts @@ -9,40 +9,25 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as LogoutRouteImport } from './routes/logout' -import { Route as NavigateTestRouteImport } from './routes/navigate-test' -import { Route as PostsRouteImport } from './routes/posts' import { Route as UsersRouteImport } from './routes/users' -import { Route as ApiUsersRouteImport } from './routes/api.users' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as RedirectIndexRouteImport } from './routes/redirect/index' -import { Route as RedirectThrowItRouteImport } from './routes/redirect/throw-it' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as NavigateTestRouteImport } from './routes/navigate-test' +import { Route as LogoutRouteImport } from './routes/logout' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as IndexRouteImport } from './routes/index' import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as RedirectIndexRouteImport } from './routes/redirect/index' +import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' +import { Route as RedirectThrowItRouteImport } from './routes/redirect/throw-it' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as ApiUsersRouteImport } from './routes/api.users' import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' +import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', - getParentRoute: () => rootRouteImport, -} as any) -const LogoutRoute = LogoutRouteImport.update({ - id: '/logout', - path: '/logout', - getParentRoute: () => rootRouteImport, -} as any) -const NavigateTestRoute = NavigateTestRouteImport.update({ - id: '/navigate-test', - path: '/navigate-test', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const PostsRoute = PostsRouteImport.update({ @@ -50,34 +35,24 @@ const PostsRoute = PostsRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const NavigateTestRoute = NavigateTestRouteImport.update({ + id: '/navigate-test', + path: '/navigate-test', getParentRoute: () => rootRouteImport, } as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const LogoutRoute = LogoutRouteImport.update({ + id: '/logout', + path: '/logout', getParentRoute: () => rootRouteImport, } as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => PostsRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const RedirectIndexRoute = RedirectIndexRouteImport.update({ - id: '/redirect/', - path: '/redirect/', - getParentRoute: () => rootRouteImport, -} as any) -const RedirectThrowItRoute = RedirectThrowItRouteImport.update({ - id: '/redirect/throw-it', - path: '/redirect/throw-it', getParentRoute: () => rootRouteImport, } as any) const UsersIndexRoute = UsersIndexRouteImport.update({ @@ -85,21 +60,46 @@ const UsersIndexRoute = UsersIndexRouteImport.update({ path: '/', getParentRoute: () => UsersRoute, } as any) +const RedirectIndexRoute = RedirectIndexRouteImport.update({ + id: '/redirect/', + path: '/redirect/', + getParentRoute: () => rootRouteImport, +} as any) +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) const UsersUserIdRoute = UsersUserIdRouteImport.update({ id: '/$userId', path: '/$userId', getParentRoute: () => UsersRoute, } as any) -const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => ApiUsersRoute, +const RedirectThrowItRoute = RedirectThrowItRouteImport.update({ + id: '/redirect/throw-it', + path: '/redirect/throw-it', + getParentRoute: () => rootRouteImport, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', + getParentRoute: () => rootRouteImport, } as any) const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ id: '/posts_/$postId/deep', path: '/posts/$postId/deep', getParentRoute: () => rootRouteImport, } as any) +const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => ApiUsersRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -113,7 +113,7 @@ export interface FileRoutesByFullPath { '/redirect/throw-it': typeof RedirectThrowItRoute '/users/$userId': typeof UsersUserIdRoute '/posts/': typeof PostsIndexRoute - '/redirect/': typeof RedirectIndexRoute + '/redirect': typeof RedirectIndexRoute '/users/': typeof UsersIndexRoute '/api/users/$id': typeof ApiUsersIdRoute '/posts/$postId/deep': typeof PostsPostIdDeepRoute @@ -165,7 +165,7 @@ export interface FileRouteTypes { | '/redirect/throw-it' | '/users/$userId' | '/posts/' - | '/redirect/' + | '/redirect' | '/users/' | '/api/users/$id' | '/posts/$postId/deep' @@ -218,32 +218,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/logout': { - id: '/logout' - path: '/logout' - fullPath: '/logout' - preLoaderRoute: typeof LogoutRouteImport - parentRoute: typeof rootRouteImport - } - '/navigate-test': { - id: '/navigate-test' - path: '/navigate-test' - fullPath: '/navigate-test' - preLoaderRoute: typeof NavigateTestRouteImport + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/posts': { @@ -253,46 +232,32 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/navigate-test': { + id: '/navigate-test' + path: '/navigate-test' + fullPath: '/navigate-test' + preLoaderRoute: typeof NavigateTestRouteImport parentRoute: typeof rootRouteImport } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + '/logout': { + id: '/logout' + path: '/logout' + fullPath: '/logout' + preLoaderRoute: typeof LogoutRouteImport parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/redirect/': { - id: '/redirect/' - path: '/redirect' - fullPath: '/redirect/' - preLoaderRoute: typeof RedirectIndexRouteImport - parentRoute: typeof rootRouteImport - } - '/redirect/throw-it': { - id: '/redirect/throw-it' - path: '/redirect/throw-it' - fullPath: '/redirect/throw-it' - preLoaderRoute: typeof RedirectThrowItRouteImport + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/users/': { @@ -302,6 +267,20 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof UsersIndexRouteImport parentRoute: typeof UsersRoute } + '/redirect/': { + id: '/redirect/' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute + } '/users/$userId': { id: '/users/$userId' path: '/$userId' @@ -309,12 +288,26 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof UsersUserIdRouteImport parentRoute: typeof UsersRoute } - '/api/users/$id': { - id: '/api/users/$id' - path: '/$id' - fullPath: '/api/users/$id' - preLoaderRoute: typeof ApiUsersIdRouteImport - parentRoute: typeof ApiUsersRoute + '/redirect/throw-it': { + id: '/redirect/throw-it' + path: '/redirect/throw-it' + fullPath: '/redirect/throw-it' + preLoaderRoute: typeof RedirectThrowItRouteImport + parentRoute: typeof rootRouteImport + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute + } + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport + parentRoute: typeof rootRouteImport } '/posts_/$postId/deep': { id: '/posts_/$postId/deep' @@ -323,6 +316,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsPostIdDeepRouteImport parentRoute: typeof rootRouteImport } + '/api/users/$id': { + id: '/api/users/$id' + path: '/$id' + fullPath: '/api/users/$id' + preLoaderRoute: typeof ApiUsersIdRouteImport + parentRoute: typeof ApiUsersRoute + } } } diff --git a/e2e/react-start/custom-basepath/src/routes/api.users.ts b/e2e/react-start/custom-basepath/src/routes/api.users.ts index 6fc8cde830..9e055549ef 100644 --- a/e2e/react-start/custom-basepath/src/routes/api.users.ts +++ b/e2e/react-start/custom-basepath/src/routes/api.users.ts @@ -3,7 +3,11 @@ import axios from 'redaxios' import type { User } from '~/utils/users' -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const Route = createFileRoute('/api/users')({ server: { diff --git a/e2e/react-start/custom-basepath/src/routes/api/users.$id.ts b/e2e/react-start/custom-basepath/src/routes/api/users.$id.ts index 81c071afb5..57682660fd 100644 --- a/e2e/react-start/custom-basepath/src/routes/api/users.$id.ts +++ b/e2e/react-start/custom-basepath/src/routes/api/users.$id.ts @@ -2,7 +2,11 @@ import axios from 'redaxios' import type { User } from '~/utils/users' import { createFileRoute } from '@tanstack/react-router' -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const Route = createFileRoute('/api/users/$id')({ server: { diff --git a/e2e/react-start/custom-basepath/src/routes/deferred.tsx b/e2e/react-start/custom-basepath/src/routes/deferred.tsx index a6bd45f8c2..9c6e3064b8 100644 --- a/e2e/react-start/custom-basepath/src/routes/deferred.tsx +++ b/e2e/react-start/custom-basepath/src/routes/deferred.tsx @@ -3,13 +3,13 @@ import { createServerFn } from '@tanstack/react-start' import { Suspense, useState } from 'react' const personServerFn = createServerFn({ method: 'GET' }) - .validator((data: { name: string }) => data) + .inputValidator((data: { name: string }) => data) .handler(({ data }) => { return { name: data.name, randomNumber: Math.floor(Math.random() * 100) } }) const slowServerFn = createServerFn({ method: 'GET' }) - .validator((data: { name: string }) => data) + .inputValidator((data: { name: string }) => data) .handler(async ({ data }) => { await new Promise((r) => setTimeout(r, 1000)) return { name: data.name, randomNumber: Math.floor(Math.random() * 100) } diff --git a/e2e/react-start/custom-basepath/src/utils/posts.tsx b/e2e/react-start/custom-basepath/src/utils/posts.tsx index d9b98a8c9c..b2d9f3edec 100644 --- a/e2e/react-start/custom-basepath/src/utils/posts.tsx +++ b/e2e/react-start/custom-basepath/src/utils/posts.tsx @@ -8,10 +8,14 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = createServerFn({ method: 'GET' }) - .validator((postId: string) => postId) + .inputValidator((postId: string) => postId) .handler(async ({ data: postId }) => { console.info(`Fetching post with id ${postId}...`) const post = await axios diff --git a/e2e/react-start/custom-basepath/src/utils/users.tsx b/e2e/react-start/custom-basepath/src/utils/users.tsx index 7ba645b383..46be4b1580 100644 --- a/e2e/react-start/custom-basepath/src/utils/users.tsx +++ b/e2e/react-start/custom-basepath/src/utils/users.tsx @@ -3,3 +3,7 @@ export type User = { name: string email: string } + +const PORT = process.env.VITE_SERVER_PORT || 3000 + +export const DEPLOY_URL = `http://localhost:${PORT}` diff --git a/e2e/react-start/custom-basepath/tests/setup/global.setup.ts b/e2e/react-start/custom-basepath/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-start/custom-basepath/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/react-start/custom-basepath/tests/setup/global.teardown.ts b/e2e/react-start/custom-basepath/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-start/custom-basepath/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/react-start/custom-basepath/tsconfig.json b/e2e/react-start/custom-basepath/tsconfig.json index 3824b148e1..d35a4b17f4 100644 --- a/e2e/react-start/custom-basepath/tsconfig.json +++ b/e2e/react-start/custom-basepath/tsconfig.json @@ -13,6 +13,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/react-start/custom-basepath/vite.config.ts b/e2e/react-start/custom-basepath/vite.config.ts index 5a0edefca4..75559f50a1 100644 --- a/e2e/react-start/custom-basepath/vite.config.ts +++ b/e2e/react-start/custom-basepath/vite.config.ts @@ -1,16 +1,19 @@ import { defineConfig } from 'vite' +import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import viteReact from '@vitejs/plugin-react' import tailwindcss from '@tailwindcss/vite' export default defineConfig({ - resolve: { tsconfigPaths: true }, base: '/custom/basepath', server: { port: 3000, }, plugins: [ tailwindcss(), + tsConfigPaths({ + projects: ['./tsconfig.json'], + }), tanstackStart({ vite: { installDevServerMiddleware: true }, }), diff --git a/e2e/react-start/custom-server-rsbuild/.gitignore b/e2e/react-start/custom-server-rsbuild/.gitignore deleted file mode 100644 index a79d5cf129..0000000000 --- a/e2e/react-start/custom-server-rsbuild/.gitignore +++ /dev/null @@ -1,20 +0,0 @@ -node_modules -package-lock.json -yarn.lock - -.DS_Store -.cache -.env -.vercel -.output - -/build/ -/api/ -/server/build -/public/build -# Sentry Config File -.env.sentry-build-plugin -/test-results/ -/playwright-report/ -/blob-report/ -/playwright/.cache/ diff --git a/e2e/react-start/custom-server-rsbuild/express-server.ts b/e2e/react-start/custom-server-rsbuild/express-server.ts deleted file mode 100644 index 68537956b4..0000000000 --- a/e2e/react-start/custom-server-rsbuild/express-server.ts +++ /dev/null @@ -1,91 +0,0 @@ -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' -const PORT = Number.parseInt(process.env.PORT || '3000') - -type FetchServerEntry = { - default: { fetch: (req: Request) => Promise } -} - -const app = express() - -if (DEVELOPMENT) { - // Set up rsbuild in middleware mode: - // https://rsbuild.rs/config/server/middleware-mode - const { createRsbuild, loadConfig } = await import('@rsbuild/core') - const { content: userConfig } = await loadConfig({ cwd: process.cwd() }) - - const rsbuild = await createRsbuild({ - rsbuildConfig: { - ...userConfig, - server: { - ...(userConfig.server ?? {}), - middlewareMode: true, - }, - }, - }) - - const devServer = await rsbuild.createDevServer() - - const serverEntry = - await devServer.environments.ssr.loadBundle('index') - const handler = toNodeHandler(serverEntry.default.fetch) as NodeHttp1Handler - - // Intercept server-fn URLs BEFORE rsbuild's built-in middlewares so they - // don't get swallowed by htmlCompletion/assetsMiddleware — long base64 - // function IDs in the path can look like asset routes. - app.use(async (req, res, next) => { - if (!req.url.startsWith('/_serverFn')) return next() - try { - await handler(req, res) - } catch (error) { - next(error) - } - }) - - // Rsbuild asset middlewares (JS/CSS/HMR). - app.use(devServer.middlewares) - - // Catch-all SSR for page navigations. - app.use(async (req, res, next) => { - try { - await handler(req, res) - } catch (error) { - next(error) - } - }) - - const httpServer = app.listen(PORT, async (error) => { - if (error) { - throw error - } - await devServer.afterListen() - console.log( - `E2E app: http://localhost:${(httpServer.address() as AddressInfo).port}`, - ) - }) - devServer.connectWebSocket({ server: httpServer }) -} else { - const { default: handler } = - (await import('./dist/server/index.js')) as FetchServerEntry - const nodeHandler = toNodeHandler(handler.fetch) as NodeHttp1Handler - app.use(express.static('dist/client')) - app.use(async (req, res, next) => { - try { - await nodeHandler(req, res) - } catch (error) { - next(error) - } - }) - 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 deleted file mode 100644 index 1c5b3af393..0000000000 --- a/e2e/react-start/custom-server-rsbuild/package.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "tanstack-react-start-e2e-custom-server-rsbuild", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "cross-env NODE_ENV=development tsx express-server.ts", - "dev:e2e": "cross-env NODE_ENV=development tsx express-server.ts", - "build": "rsbuild build && tsc --noEmit", - "start": "tsx express-server.ts", - "test:e2e:dev": "cross-env MODE=dev playwright test --project=chromium", - "test:e2e:prod": "cross-env MODE=prod playwright test --project=chromium", - "test:e2e": "pnpm run test:e2e:dev && pnpm run test:e2e:prod" - }, - "dependencies": { - "@tanstack/react-router": "workspace:^", - "@tanstack/react-start": "workspace:^", - "express": "^5.2.1", - "react": "^19.0.0", - "react-dom": "^19.0.0" - }, - "devDependencies": { - "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", - "@rsbuild/plugin-react": "^2.0.0", - "@tailwindcss/postcss": "^4.2.2", - "@tanstack/router-e2e-utils": "workspace:^", - "@types/express": "^5.0.6", - "@types/node": "^22.10.2", - "@types/react": "^19.0.8", - "@types/react-dom": "^19.0.3", - "cross-env": "^10.0.0", - "srvx": "^1.0.0", - "tailwindcss": "^4.2.2", - "tsx": "^4.20.3", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2" - } -} diff --git a/e2e/react-start/custom-server-rsbuild/playwright.config.ts b/e2e/react-start/custom-server-rsbuild/playwright.config.ts deleted file mode 100644 index f0542500fd..0000000000 --- a/e2e/react-start/custom-server-rsbuild/playwright.config.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { defineConfig, devices } from '@playwright/test' - -const mode = process.env.MODE ?? 'prod' -const isDev = 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' : 'pnpm build && pnpm start', - wait: { stdout: /E2E app: http:\/\/localhost:(?\d+)/ }, - reuseExistingServer: false, - stdout: 'pipe', - env: { - PORT: String(PORT), - }, - }, - projects: [ - { - name: 'chromium', - use: { ...devices['Desktop Chrome'] }, - }, - ], -}) diff --git a/e2e/react-start/custom-server-rsbuild/postcss.config.mjs b/e2e/react-start/custom-server-rsbuild/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/react-start/custom-server-rsbuild/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/react-start/custom-server-rsbuild/rsbuild.config.ts b/e2e/react-start/custom-server-rsbuild/rsbuild.config.ts deleted file mode 100644 index 5f9aa96e16..0000000000 --- a/e2e/react-start/custom-server-rsbuild/rsbuild.config.ts +++ /dev/null @@ -1,65 +0,0 @@ -import path from 'node:path' -import { defineConfig } from '@rsbuild/core' -import { pluginReact } from '@rsbuild/plugin-react' -import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' - -// Stress-test fixture for `` and the start manifest under a -// non-default client chunk layout. The combination that matters for the -// repro is: -// -// - `client.output: 'iife'` — emit the client entry as a self-executing -// script. The manifest uses plain script tags and classic script preloads; -// setting IIFE here exercises that non-module asset path. -// -// - Client `runtimeChunk: 'single'` — extracts the webpack runtime into -// its own chunk. With IIFE plain scripts, the entry can't bootstrap -// until the runtime has executed, so `` has to emit a -// `', endIndex) - const scriptCloseIndex = html.indexOf('', endIndex) - const bodyCloseIndex = html.indexOf('', scriptCloseIndex) - const htmlCloseIndex = html.indexOf('', bodyCloseIndex) - - expect(endIndex).toBeGreaterThan(-1) - expect(scriptOpenIndex).toBeGreaterThan(previousScriptCloseIndex) - expect(scriptCloseIndex).toBeGreaterThan(endIndex) - expect(payloadIndex).toBeGreaterThan(-1) - expect(payloadIndex).toBeLessThan(endIndex) - expect(html.slice(endIndex, scriptCloseIndex)).toContain(LATE_RECORD_CLOSE) - expect(scriptCloseIndex).toBeLessThan(bodyCloseIndex) - expect(bodyCloseIndex).toBeLessThan(htmlCloseIndex) -} - -async function verifyHydration( - page: Page, - { timeout = 10_000 }: { timeout?: number } = {}, -) { - const button = page.getByTestId('hydration-check-btn') - const status = page.getByTestId('hydration-status') - - await expect(button).toBeVisible() - await expect(async () => { - await button.click() - await expect(status).toHaveText('hydrated', { timeout: 100 }) - }).toPass({ timeout }) - - await expect(page.locator(STREAM_PART_SELECTOR)).toHaveCount(0) - await expect( - page.locator('script').filter({ hasText: STREAM_BOUNDARY_MARKER }), - ).toHaveCount(0) -} - -export { test } - -export const testWithHydration = test.extend({ - page: async ({ page }, use) => { - await use(page) - await verifyHydration(page) - }, -}) - -export { expect } diff --git a/e2e/streaming-ssr-fixtures/index.ts b/e2e/streaming-ssr-fixtures/index.ts deleted file mode 100644 index a70ef94459..0000000000 --- a/e2e/streaming-ssr-fixtures/index.ts +++ /dev/null @@ -1,381 +0,0 @@ -export type SourceMarker = 'server' | 'client' - -export type ServerData = { - name: string - timestamp: number - source: 'server' -} - -export type DeferredMessage = { - message: string - source: SourceMarker -} - -export type QueryType = 'sync' | 'fast-async' | 'slow-async' - -export type QueryData = { - type: QueryType - id: number - value: string - source: SourceMarker -} - -export const deferredDataMessage = 'Deferred data loaded!' -export const deferredDataDelay = 1000 -export const deferredServerDelay = 800 -export const deferredImmediateName = 'Fast User' -export const deferredSlowName = 'Slow User' -export const deferredErrorMessage = 'Error in deferred object' - -export const fastSerialStaticData = 'This is static data' -export const fastSerialSmallValue = 'small-data' - -export const syncOnlyMessage = 'Hello from sync loader!' -export const syncOnlyItems = ['item-1', 'item-2', 'item-3'] as const - -export const slowRenderDeferredMessage = 'Deferred resolved!' -export const slowRenderDeferredDelay = 50 -export const slowRenderQuickName = 'Quick data' -export const slowRenderComponents = [ - 'Slow component 1', - 'Slow component 2', - 'Slow component 3', -] as const - -export const nestedLevelDelays = [200, 400, 600] as const -export const nestedPlainDelay = 300 -export const nestedPlainMessage = 'Plain deferred resolved!' - -export const streamPromiseValue = 'promise-resolved' -export const streamPromiseDelay = 150 -export const streamChunkDelay = 200 -export const streamChunks = Array.from({ length: 5 }, (_, i) => `chunk-${i}`) - -export const routerHtmlPayloadChars = 17 * 1024 * 1024 -export const routerHtmlPayloadChar = 'x' -export const routerHtmlPayloadDelay = 100 - -export const manyPromiseItems = [ - { - key: 'immediate1', - testId: 'immediate-1', - label: 'Immediate 1', - value: 'immediate-1', - delayMs: 0, - }, - { - key: 'immediate2', - testId: 'immediate-2', - label: 'Immediate 2', - value: 'immediate-2', - delayMs: 10, - }, - { - key: 'immediate3', - testId: 'immediate-3', - label: 'Immediate 3', - value: 'immediate-3', - delayMs: 20, - }, - { - key: 'fast1', - testId: 'fast-1', - label: 'Fast 1', - value: 'fast-1', - delayMs: 50, - }, - { - key: 'fast2', - testId: 'fast-2', - label: 'Fast 2', - value: 'fast-2', - delayMs: 75, - }, - { - key: 'fast3', - testId: 'fast-3', - label: 'Fast 3', - value: 'fast-3', - delayMs: 100, - }, - { - key: 'fast4', - testId: 'fast-4', - label: 'Fast 4', - value: 'fast-4', - delayMs: 125, - }, - { - key: 'medium1', - testId: 'medium-1', - label: 'Medium 1', - value: 'medium-1', - delayMs: 150, - }, - { - key: 'medium2', - testId: 'medium-2', - label: 'Medium 2', - value: 'medium-2', - delayMs: 200, - }, - { - key: 'medium3', - testId: 'medium-3', - label: 'Medium 3', - value: 'medium-3', - delayMs: 250, - }, - { - key: 'slow1', - testId: 'slow-1', - label: 'Slow 1', - value: 'slow-1', - delayMs: 300, - }, - { - key: 'slow2', - testId: 'slow-2', - label: 'Slow 2', - value: 'slow-2', - delayMs: 400, - }, - { - key: 'slow3', - testId: 'slow-3', - label: 'Slow 3', - value: 'slow-3', - delayMs: 500, - }, - { - key: 'verySlow1', - testId: 'very-slow-1', - label: 'Very Slow 1', - value: 'very-slow-1', - delayMs: 600, - }, - { - key: 'verySlow2', - testId: 'very-slow-2', - label: 'Very Slow 2', - value: 'very-slow-2', - delayMs: 800, - }, -] as const - -export const concurrentBatchCount = 5 -export const concurrentBatchDelays = [100, 200, 300] as const - -export const queryHeavyItems = [ - { - type: 'sync', - id: 1, - value: 'sync-value-1', - delayMs: 0, - testId: 'sync-query-1', - fallback: 'Loading sync 1...', - }, - { - type: 'sync', - id: 2, - value: 'sync-value-2', - delayMs: 0, - testId: 'sync-query-2', - fallback: 'Loading sync 2...', - }, - { - type: 'sync', - id: 3, - value: 'sync-value-3', - delayMs: 0, - testId: 'sync-query-3', - fallback: 'Loading sync 3...', - }, - { - type: 'fast-async', - id: 1, - value: 'fast-async-1', - delayMs: 50, - testId: 'fast-async-query-1', - fallback: 'Loading fast 1...', - }, - { - type: 'fast-async', - id: 2, - value: 'fast-async-2', - delayMs: 75, - testId: 'fast-async-query-2', - fallback: 'Loading fast 2...', - }, - { - type: 'fast-async', - id: 3, - value: 'fast-async-3', - delayMs: 100, - testId: 'fast-async-query-3', - fallback: 'Loading fast 3...', - }, - { - type: 'slow-async', - id: 1, - value: 'slow-async-1', - delayMs: 200, - testId: 'slow-async-query-1', - fallback: 'Loading slow 1...', - }, - { - type: 'slow-async', - id: 2, - value: 'slow-async-2', - delayMs: 300, - testId: 'slow-async-query-2', - fallback: 'Loading slow 2...', - }, - { - type: 'slow-async', - id: 3, - value: 'slow-async-3', - delayMs: 400, - testId: 'slow-async-query-3', - fallback: 'Loading slow 3...', - }, -] as const - -export function sourceMarker(): SourceMarker { - return typeof window === 'undefined' ? 'server' : 'client' -} - -export function delay(ms: number): Promise { - return new Promise((resolve) => setTimeout(resolve, ms)) -} - -export function makeServerData(name: string): ServerData { - return { - name, - timestamp: Date.now(), - source: 'server', - } -} - -export function makeDeferred(value: T, delayMs: number): Promise { - return new Promise((resolve) => setTimeout(() => resolve(value), delayMs)) -} - -export function makeDeferredMessage( - message: string, - delayMs: number, -): Promise { - return makeDeferred({ message, source: sourceMarker() }, delayMs) -} - -export function makeFastSerialSmallData() { - return { - value: fastSerialSmallValue, - timestamp: Date.now(), - source: 'server' as const, - } -} - -export function makeSyncOnlyData() { - return { - message: syncOnlyMessage, - timestamp: Date.now(), - items: syncOnlyItems, - source: sourceMarker(), - } -} - -export function makeLevelData(level: number) { - return { level, timestamp: Date.now() } -} - -export function makeQueryData(item: { - type: QueryType - id: number - value: string -}): QueryData { - return { - type: item.type, - id: item.id, - value: item.value, - source: sourceMarker(), - } -} - -export function createManyPromises() { - return Object.fromEntries( - manyPromiseItems.map((item) => [ - item.key, - makeDeferred(item.value, item.delayMs), - ]), - ) as Record<(typeof manyPromiseItems)[number]['key'], Promise> -} - -export function createConcurrentPromises( - count: number, - delayMs: number, -): Array> { - const sharedPromise = delay(delayMs) - return Array.from({ length: count }, (_, i) => - sharedPromise.then(() => `concurrent-${i + 1}`), - ) -} - -export function createConcurrentLoaderData() { - const batch1 = createConcurrentPromises( - concurrentBatchCount, - concurrentBatchDelays[0], - ) - const batch2 = createConcurrentPromises( - concurrentBatchCount, - concurrentBatchDelays[1], - ) - const batch3 = createConcurrentPromises( - concurrentBatchCount, - concurrentBatchDelays[2], - ) - - return { - concurrent1_1: batch1[0], - concurrent1_2: batch1[1], - concurrent1_3: batch1[2], - concurrent1_4: batch1[3], - concurrent1_5: batch1[4], - concurrent2_1: batch2[0], - concurrent2_2: batch2[1], - concurrent2_3: batch2[2], - concurrent2_4: batch2[3], - concurrent2_5: batch2[4], - concurrent3_1: batch3[0], - concurrent3_2: batch3[1], - concurrent3_3: batch3[2], - concurrent3_4: batch3[3], - concurrent3_5: batch3[4], - } -} - -export function createStreamPromise(): Promise { - return makeDeferred(streamPromiseValue, streamPromiseDelay) -} - -export function createChunkStream(): ReadableStream { - return new ReadableStream({ - async start(controller) { - for (const chunk of streamChunks) { - await delay(streamChunkDelay) - controller.enqueue(chunk) - } - controller.close() - }, - }) -} - -export function createRouterHtmlPayload() { - return makeDeferred( - { - value: routerHtmlPayloadChar.repeat(routerHtmlPayloadChars), - source: sourceMarker(), - }, - routerHtmlPayloadDelay, - ) -} diff --git a/e2e/streaming-ssr-specs/client-navigation.ts b/e2e/streaming-ssr-specs/client-navigation.ts deleted file mode 100644 index 759f8e0282..0000000000 --- a/e2e/streaming-ssr-specs/client-navigation.ts +++ /dev/null @@ -1,372 +0,0 @@ -import { expect, test, testWithHydration } from '../streaming-ssr-assertions' - -test.describe('Client-side navigation between all routes', () => { - test.beforeEach(async ({ page }) => { - // Start from home page - await page.goto('/') - await page.waitForLoadState('networkidle') - }) - - test('home -> sync-only -> home works', async ({ page }) => { - // Navigate to sync-only - await page - .getByRole('navigation') - .getByRole('link', { name: 'Sync Only' }) - .click() - await expect(page).toHaveURL('/sync-only') - await expect(page.getByTestId('sync-message')).toBeVisible() - - // Navigate back to home - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - await expect(page.getByTestId('index-title')).toBeVisible() - }) - - test('home -> deferred -> home works', async ({ page }) => { - // Navigate to deferred (use exact: true to avoid matching "Nested Deferred") - await page - .getByRole('navigation') - .getByRole('link', { name: 'Deferred', exact: true }) - .click() - await expect(page).toHaveURL('/deferred') - await expect(page.getByTestId('immediate-data')).toBeVisible() - - // Wait for deferred data - await expect(page.getByTestId('deferred-data')).toBeVisible({ - timeout: 5000, - }) - - // Navigate back to home - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - }) - - test('home -> stream -> home works (no stream locking error)', async ({ - page, - }) => { - // This test specifically validates the ReadableStream locking fix - // Console errors are monitored by the fixture automatically - - // Navigate to stream - await page - .getByRole('navigation') - .getByRole('link', { name: 'Stream' }) - .click() - await expect(page).toHaveURL('/stream') - - // Wait for stream to start (at least one chunk or promise resolved) - await expect(page.getByTestId('promise-data')).toBeVisible({ - timeout: 5000, - }) - - // Navigate back without waiting for stream completion. - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - }) - - test('home -> stream -> wait for completion -> home works', async ({ - page, - }) => { - // Navigate to stream - await page - .getByRole('navigation') - .getByRole('link', { name: 'Stream' }) - .click() - await expect(page).toHaveURL('/stream') - - // Wait for stream to complete - await expect(page.getByTestId('stream-complete')).toBeVisible({ - timeout: 10000, - }) - - // Navigate back to home - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - await expect(page.getByTestId('index-title')).toBeVisible() - }) - - test('home -> stream -> home -> stream again works (fresh stream each time)', async ({ - page, - }) => { - // Console errors are monitored by the fixture automatically - - // First navigation to stream - await page - .getByRole('navigation') - .getByRole('link', { name: 'Stream' }) - .click() - await expect(page).toHaveURL('/stream') - await expect(page.getByTestId('promise-data')).toBeVisible({ - timeout: 5000, - }) - - // Navigate back to home - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - - // Second navigation to stream - should get fresh stream without errors - await page - .getByRole('navigation') - .getByRole('link', { name: 'Stream' }) - .click() - await expect(page).toHaveURL('/stream') - - // Wait for stream to complete - await expect(page.getByTestId('stream-complete')).toBeVisible({ - timeout: 10000, - }) - - // Verify all chunks are present - await expect(page.getByTestId('stream-chunk-0')).toBeVisible() - await expect(page.getByTestId('stream-chunk-4')).toBeVisible() - }) - - test('home -> fast-serial -> home works', async ({ page }) => { - await page - .getByRole('navigation') - .getByRole('link', { name: 'Fast Serial' }) - .click() - await expect(page).toHaveURL('/fast-serial') - await expect(page.getByTestId('server-data')).toBeVisible() - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - }) - - test('home -> slow-render -> home works', async ({ page }) => { - await page - .getByRole('navigation') - .getByRole('link', { name: 'Slow Render' }) - .click() - await expect(page).toHaveURL('/slow-render') - await expect(page.getByTestId('quick-data')).toBeVisible() - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - }) - - test('home -> nested-deferred -> home works', async ({ page }) => { - await page - .getByRole('navigation') - .getByRole('link', { name: 'Nested Deferred' }) - .click() - await expect(page).toHaveURL('/nested-deferred') - - // Wait for all levels to load - await expect(page.getByTestId('level3-data')).toBeVisible({ timeout: 5000 }) - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - }) - - test('navigation without waiting for route data works', async ({ page }) => { - // Console errors are monitored by the fixture automatically - - // Change routes as soon as each URL updates, without waiting for route data. - await page - .getByRole('navigation') - .getByRole('link', { name: 'Sync Only' }) - .click() - await expect(page).toHaveURL('/sync-only') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Deferred', exact: true }) - .click() - await expect(page).toHaveURL('/deferred') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Stream' }) - .click() - await expect(page).toHaveURL('/stream') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Fast Serial' }) - .click() - await expect(page).toHaveURL('/fast-serial') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Slow Render' }) - .click() - await expect(page).toHaveURL('/slow-render') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Nested Deferred' }) - .click() - await expect(page).toHaveURL('/nested-deferred') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - }) -}) - -test.describe('Direct navigation followed by client navigation', () => { - test('direct to stream -> client nav to deferred works', async ({ page }) => { - // Direct navigation to stream - await page.goto('/stream') - await expect(page.getByTestId('promise-data')).toBeVisible({ - timeout: 5000, - }) - - // Client navigation to deferred (use exact: true) - await page - .getByRole('navigation') - .getByRole('link', { name: 'Deferred', exact: true }) - .click() - await expect(page).toHaveURL('/deferred') - await expect(page.getByTestId('immediate-data')).toBeVisible() - }) - - test('direct to deferred -> client nav to stream works', async ({ page }) => { - // Console errors are monitored by the fixture automatically - - // Direct navigation to deferred - await page.goto('/deferred') - await expect(page.getByTestId('immediate-data')).toBeVisible() - - // Client navigation to stream - await page - .getByRole('navigation') - .getByRole('link', { name: 'Stream' }) - .click() - await expect(page).toHaveURL('/stream') - await expect(page.getByTestId('stream-complete')).toBeVisible({ - timeout: 10000, - }) - }) - - test('direct to sync-only -> client nav to all routes works', async ({ - page, - }) => { - await page.goto('/sync-only') - await expect(page.getByTestId('sync-message')).toBeVisible() - - // Navigate through all routes - await page - .getByRole('navigation') - .getByRole('link', { name: 'Deferred', exact: true }) - .click() - await expect(page).toHaveURL('/deferred') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Stream' }) - .click() - await expect(page).toHaveURL('/stream') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Fast Serial' }) - .click() - await expect(page).toHaveURL('/fast-serial') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Home' }) - .click() - await expect(page).toHaveURL('/') - }) -}) - -testWithHydration.describe('Hydration after client navigation', () => { - testWithHydration( - 'interactive elements work after navigating to deferred', - async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Deferred', exact: true }) - .click() - await expect(page).toHaveURL('/deferred') - - // Wait for the page to be fully loaded - await expect(page.getByTestId('immediate-data')).toBeVisible() - }, - ) - - testWithHydration( - 'interactive elements work after navigating to fast-serial', - async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Fast Serial' }) - .click() - await expect(page).toHaveURL('/fast-serial') - - // Wait for page to load - await expect(page.getByTestId('server-data')).toBeVisible() - }, - ) - - testWithHydration( - 'interactive elements work after navigating to nested-deferred', - async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Nested Deferred' }) - .click() - await expect(page).toHaveURL('/nested-deferred') - - // Wait for page to load - await expect(page.getByTestId('plain-deferred')).toBeVisible({ - timeout: 5000, - }) - }, - ) - - testWithHydration( - 'interactive elements work after navigating to slow-render', - async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - await page - .getByRole('navigation') - .getByRole('link', { name: 'Slow Render' }) - .click() - await expect(page).toHaveURL('/slow-render') - - // Wait for page to load (slow-render has blocking loops) - await expect(page.getByTestId('quick-data')).toBeVisible() - }, - ) -}) diff --git a/e2e/streaming-ssr-specs/concurrent.ts b/e2e/streaming-ssr-specs/concurrent.ts deleted file mode 100644 index ef14f80367..0000000000 --- a/e2e/streaming-ssr-specs/concurrent.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { expect, test, testWithHydration } from '../streaming-ssr-assertions' - -test.describe('Concurrent promise resolution (15 promises in 3 batches)', () => { - test('all concurrent promises resolve correctly', async ({ page }) => { - await page.goto('/concurrent') - - // Batch 1 (5 promises at 100ms) - await expect(page.getByTestId('concurrent-1-1')).toContainText( - 'concurrent-1', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-1-2')).toContainText( - 'concurrent-2', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-1-3')).toContainText( - 'concurrent-3', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-1-4')).toContainText( - 'concurrent-4', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-1-5')).toContainText( - 'concurrent-5', - { timeout: 5000 }, - ) - - // Batch 2 (5 promises at 200ms) - await expect(page.getByTestId('concurrent-2-1')).toContainText( - 'concurrent-1', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-2-2')).toContainText( - 'concurrent-2', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-2-3')).toContainText( - 'concurrent-3', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-2-4')).toContainText( - 'concurrent-4', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-2-5')).toContainText( - 'concurrent-5', - { timeout: 5000 }, - ) - - // Batch 3 (5 promises at 300ms) - await expect(page.getByTestId('concurrent-3-1')).toContainText( - 'concurrent-1', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-3-2')).toContainText( - 'concurrent-2', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-3-3')).toContainText( - 'concurrent-3', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-3-4')).toContainText( - 'concurrent-4', - { timeout: 5000 }, - ) - await expect(page.getByTestId('concurrent-3-5')).toContainText( - 'concurrent-5', - { timeout: 5000 }, - ) - }) - - testWithHydration( - 'hydration works with concurrent resolutions', - async ({ page }) => { - await page.goto('/concurrent') - await page.waitForLoadState('networkidle') - - // Wait for all batches - await expect(page.getByTestId('concurrent-3-5')).toBeVisible({ - timeout: 5000, - }) - }, - ) -}) diff --git a/e2e/streaming-ssr-specs/deferred-rejection.ts b/e2e/streaming-ssr-specs/deferred-rejection.ts deleted file mode 100644 index 3e944b1c0c..0000000000 --- a/e2e/streaming-ssr-specs/deferred-rejection.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { expect, test } from '../streaming-ssr-assertions' - -test.use({ - whitelistErrors: ['Error in deferred object'], -}) - -test('rejected deferred Await renders the route error boundary without killing SSR', async ({ - page, -}) => { - await page.goto('/deferred-rejection') - - await expect(page.getByTestId('deferred-error-boundary')).toContainText( - 'Error in deferred object', - { timeout: 5000 }, - ) - - await page.goto('/sync-only') - await expect(page.getByTestId('sync-message')).toContainText( - 'Hello from sync loader!', - ) -}) diff --git a/e2e/streaming-ssr-specs/deferred.ts b/e2e/streaming-ssr-specs/deferred.ts deleted file mode 100644 index abece0b43e..0000000000 --- a/e2e/streaming-ssr-specs/deferred.ts +++ /dev/null @@ -1,113 +0,0 @@ -import { - expect, - expectDeferredRouteResponseOrder, - test, - testWithHydration, -} from '../streaming-ssr-assertions' - -test.describe('Deferred data streaming', () => { - test('finishes the router stream after renderer output', async ({ - baseURL, - }) => { - await expectDeferredRouteResponseOrder(baseURL) - }) - - test('renders immediate and deferred server data', async ({ page }) => { - await page.goto('/deferred') - - // Immediate loader data is rendered. - await expect(page.getByTestId('immediate-data')).toBeVisible() - await expect(page.getByTestId('immediate-data')).toContainText( - 'Immediate: Fast User', - ) - - // Verify immediate data came from server - await expect(page.getByTestId('immediate-source')).toContainText( - 'Immediate source: server', - ) - await expect(page.getByTestId('loader-source')).toContainText( - 'Loader source: server', - ) - - // Deferred data should eventually appear with server source - await expect(page.getByTestId('deferred-data')).toContainText( - 'Deferred data loaded!', - { timeout: 5000 }, - ) - await expect(page.getByTestId('deferred-data')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - await expect(page.getByTestId('deferred-server-data')).toContainText( - 'Server: Slow User', - { timeout: 5000 }, - ) - await expect(page.getByTestId('deferred-server-data')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - }) - - testWithHydration( - 'hydration works - interactive elements respond', - async ({ page }) => { - await page.goto('/deferred') - await page.waitForLoadState('networkidle') - - // Wait for all deferred content to load - await expect(page.getByTestId('deferred-data')).toBeVisible({ - timeout: 5000, - }) - - // Verify all data came from server after hydration - await expect(page.getByTestId('loader-source')).toContainText( - 'Loader source: server', - ) - await expect(page.getByTestId('deferred-data')).toContainText( - 'source: server', - ) - }, - ) - - test('client-side navigation to deferred route works', async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - // Navigate via client-side routing using nav link - await page.getByRole('link', { name: 'Deferred' }).first().click() - await expect(page).toHaveURL('/deferred') - - // Data should load - await expect(page.getByTestId('immediate-data')).toContainText('Fast User') - await expect(page.getByTestId('deferred-data')).toContainText( - 'Deferred data loaded!', - { timeout: 5000 }, - ) - }) - - test('all data sources are server', async ({ page }) => { - await page.goto('/deferred') - - // Wait for all deferred content - await expect(page.getByTestId('deferred-data')).toBeVisible({ - timeout: 5000, - }) - await expect(page.getByTestId('deferred-server-data')).toBeVisible({ - timeout: 5000, - }) - - // Count all elements showing 'server' source - should be 4: - // 1. immediate-source - // 2. loader-source - // 3. deferred-data (contains "source: server") - // 4. deferred-server-data (contains "source: server") - await expect(page.getByTestId('immediate-source')).toContainText('server') - await expect(page.getByTestId('loader-source')).toContainText('server') - await expect(page.getByTestId('deferred-data')).toContainText( - 'source: server', - ) - await expect(page.getByTestId('deferred-server-data')).toContainText( - 'source: server', - ) - }) -}) diff --git a/e2e/streaming-ssr-specs/fast-serial.ts b/e2e/streaming-ssr-specs/fast-serial.ts deleted file mode 100644 index 03201f0a55..0000000000 --- a/e2e/streaming-ssr-specs/fast-serial.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { - expect, - expectRouterHydrationMarkers, - test, - testWithHydration, -} from '../streaming-ssr-assertions' - -test.describe('Fast serialization (serialization completes before render)', () => { - test('initial HTML contains router bootstrap + barrier', async ({ page }) => { - let responseHtml = '' - await page.route('/fast-serial', async (route) => { - const response = await route.fetch() - responseHtml = await response.text() - await route.fulfill({ response }) - }) - - await page.goto('/fast-serial') - await expect(page.getByTestId('server-data')).toBeVisible() - - expectRouterHydrationMarkers(responseHtml) - }) - - test('renders all server data', async ({ page }) => { - await page.goto('/fast-serial') - await page.waitForLoadState('networkidle') - - // All data should be visible - await expect(page.getByTestId('server-data')).toContainText('small-data') - await expect(page.getByTestId('static-data')).toContainText( - 'This is static data', - ) - await expect(page.getByTestId('loader-timestamp')).toBeVisible() - - // Verify the loader and server function ran during SSR. - await expect(page.getByTestId('loader-source')).toContainText( - 'Loader source: server', - ) - await expect(page.getByTestId('server-fn-source')).toContainText( - 'Server function source: server', - ) - }) - - testWithHydration('hydration works correctly', async ({ page }) => { - await page.goto('/fast-serial') - await page.waitForLoadState('networkidle') - - // Verify data came from server after hydration - await expect(page.getByTestId('loader-source')).toContainText( - 'Loader source: server', - ) - }) - - test('direct navigation renders correctly', async ({ page }) => { - // Direct navigation (SSR) - await page.goto('/fast-serial') - - // Should render without errors and show server source - await expect(page.getByTestId('server-data')).toBeVisible() - await expect(page.getByTestId('loader-source')).toContainText( - 'Loader source: server', - ) - }) - - test('client-side navigation works', async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - // Navigate via nav link - await page.getByRole('link', { name: 'Fast Serial' }).first().click() - await expect(page).toHaveURL('/fast-serial') - - await expect(page.getByTestId('server-data')).toContainText('small-data') - }) -}) diff --git a/e2e/streaming-ssr-specs/home.ts b/e2e/streaming-ssr-specs/home.ts deleted file mode 100644 index d85e19bfa7..0000000000 --- a/e2e/streaming-ssr-specs/home.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { expect, test, testWithHydration } from '../streaming-ssr-assertions' - -test.describe('Home page', () => { - testWithHydration( - 'renders index page with all navigation links', - async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - await expect(page.getByTestId('index-title')).toContainText( - 'Streaming SSR Test Scenarios', - ) - // Check links exist (they're in the nav and the body) - await expect( - page.getByRole('link', { name: 'Deferred' }).first(), - ).toBeVisible() - await expect( - page.getByRole('link', { name: 'Stream' }).first(), - ).toBeVisible() - }, - ) - - testWithHydration( - 'navigation from home to routes works', - async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - // Use the link in the content (not nav) - await page.getByTestId('link-deferred').click() - await expect(page).toHaveURL('/deferred') - }, - ) -}) diff --git a/e2e/streaming-ssr-specs/many-promises.ts b/e2e/streaming-ssr-specs/many-promises.ts deleted file mode 100644 index 768859c7e4..0000000000 --- a/e2e/streaming-ssr-specs/many-promises.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { expect, test, testWithHydration } from '../streaming-ssr-assertions' - -test.describe('Many promises streaming (15 deferred)', () => { - test('all 15 promises eventually resolve', async ({ page }) => { - await page.goto('/many-promises') - - // Immediate group (0-20ms) - await expect(page.getByTestId('immediate-1')).toContainText('immediate-1', { - timeout: 5000, - }) - await expect(page.getByTestId('immediate-2')).toContainText('immediate-2', { - timeout: 5000, - }) - await expect(page.getByTestId('immediate-3')).toContainText('immediate-3', { - timeout: 5000, - }) - - // Fast group (50-125ms) - await expect(page.getByTestId('fast-1')).toContainText('fast-1', { - timeout: 5000, - }) - await expect(page.getByTestId('fast-2')).toContainText('fast-2', { - timeout: 5000, - }) - await expect(page.getByTestId('fast-3')).toContainText('fast-3', { - timeout: 5000, - }) - await expect(page.getByTestId('fast-4')).toContainText('fast-4', { - timeout: 5000, - }) - - // Medium group (150-250ms) - await expect(page.getByTestId('medium-1')).toContainText('medium-1', { - timeout: 5000, - }) - await expect(page.getByTestId('medium-2')).toContainText('medium-2', { - timeout: 5000, - }) - await expect(page.getByTestId('medium-3')).toContainText('medium-3', { - timeout: 5000, - }) - - // Slow group (300-500ms) - await expect(page.getByTestId('slow-1')).toContainText('slow-1', { - timeout: 5000, - }) - await expect(page.getByTestId('slow-2')).toContainText('slow-2', { - timeout: 5000, - }) - await expect(page.getByTestId('slow-3')).toContainText('slow-3', { - timeout: 5000, - }) - - // Very slow group (600-800ms) - await expect(page.getByTestId('very-slow-1')).toContainText('very-slow-1', { - timeout: 5000, - }) - await expect(page.getByTestId('very-slow-2')).toContainText('very-slow-2', { - timeout: 5000, - }) - }) - - testWithHydration('hydration works with many promises', async ({ page }) => { - await page.goto('/many-promises') - await page.waitForLoadState('networkidle') - - // Wait for all promises to resolve - await expect(page.getByTestId('very-slow-2')).toBeVisible({ timeout: 5000 }) - }) - - test('client-side navigation works', async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - // Navigate via nav link - await page.getByRole('link', { name: 'Many Promises' }).click() - await expect(page).toHaveURL('/many-promises') - - // All promises should eventually resolve - await expect(page.getByTestId('very-slow-2')).toBeVisible({ timeout: 5000 }) - }) -}) diff --git a/e2e/streaming-ssr-specs/nested-deferred.ts b/e2e/streaming-ssr-specs/nested-deferred.ts deleted file mode 100644 index 0146a23162..0000000000 --- a/e2e/streaming-ssr-specs/nested-deferred.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { expect, test, testWithHydration } from '../streaming-ssr-assertions' - -test.describe('Nested deferred (multiple levels of deferred data)', () => { - test('all levels of deferred data eventually resolve', async ({ page }) => { - await page.goto('/nested-deferred') - - // All deferred values should eventually resolve. - await expect(page.getByTestId('plain-deferred')).toContainText( - 'Plain deferred resolved!', - { timeout: 5000 }, - ) - - await expect(page.getByTestId('level1-data')).toContainText('Level 1:', { - timeout: 5000, - }) - - await expect(page.getByTestId('level2-data')).toContainText('Level 2:', { - timeout: 5000, - }) - - await expect(page.getByTestId('level3-data')).toContainText('Level 3:', { - timeout: 5000, - }) - }) - - testWithHydration( - 'hydration works with nested deferred', - async ({ page }) => { - await page.goto('/nested-deferred') - await page.waitForLoadState('networkidle') - - // Wait for all data - await expect(page.getByTestId('level3-data')).toBeVisible({ - timeout: 10000, - }) - }, - ) - - test('client-side navigation works', async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - // Navigate via nav link - await page.getByRole('link', { name: 'Nested Deferred' }).first().click() - await expect(page).toHaveURL('/nested-deferred') - - // All levels should eventually render - await expect(page.getByTestId('level3-data')).toBeVisible({ - timeout: 10000, - }) - }) -}) diff --git a/e2e/streaming-ssr-specs/preview-streaming.ts b/e2e/streaming-ssr-specs/preview-streaming.ts deleted file mode 100644 index 5087dff730..0000000000 --- a/e2e/streaming-ssr-specs/preview-streaming.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { - expectDeferredRouteResponseOrder, - test, -} from '../streaming-ssr-assertions' - -test.skip( - process.env.MODE !== 'preview', - 'Only runs against vite preview: pnpm test:e2e:preview', -) - -test('vite preview preserves deferred HTML order', async ({ baseURL }) => { - await expectDeferredRouteResponseOrder(baseURL) -}) diff --git a/e2e/streaming-ssr-specs/query-heavy.ts b/e2e/streaming-ssr-specs/query-heavy.ts deleted file mode 100644 index b33a64f366..0000000000 --- a/e2e/streaming-ssr-specs/query-heavy.ts +++ /dev/null @@ -1,142 +0,0 @@ -import { - expect, - expectQueryHeavyRouteStreamOrder, - test, - testWithHydration, -} from '../streaming-ssr-assertions' - -test.describe('Query heavy route (9 queries)', () => { - test('emits the complete router stream before document closes', async ({ - baseURL, - }) => { - await expectQueryHeavyRouteStreamOrder(baseURL) - }) - - test('all queries resolve with server data', async ({ page }) => { - await page.goto('/query-heavy') - - // Sync queries should show server source - await expect(page.getByTestId('sync-query-1')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - await expect(page.getByTestId('sync-query-2')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - await expect(page.getByTestId('sync-query-3')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - - // Fast async queries should show server source - await expect(page.getByTestId('fast-async-query-1')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - await expect(page.getByTestId('fast-async-query-2')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - await expect(page.getByTestId('fast-async-query-3')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - - // Slow async queries should show server source - await expect(page.getByTestId('slow-async-query-1')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - await expect(page.getByTestId('slow-async-query-2')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - await expect(page.getByTestId('slow-async-query-3')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - }) - - test('sync queries have correct values', async ({ page }) => { - await page.goto('/query-heavy') - - await expect(page.getByTestId('sync-query-1')).toContainText('sync-value-1') - await expect(page.getByTestId('sync-query-2')).toContainText('sync-value-2') - await expect(page.getByTestId('sync-query-3')).toContainText('sync-value-3') - }) - - test('async queries have correct values', async ({ page }) => { - await page.goto('/query-heavy') - - await expect(page.getByTestId('fast-async-query-1')).toContainText( - 'fast-async-1', - { timeout: 5000 }, - ) - await expect(page.getByTestId('fast-async-query-2')).toContainText( - 'fast-async-2', - { timeout: 5000 }, - ) - await expect(page.getByTestId('fast-async-query-3')).toContainText( - 'fast-async-3', - { timeout: 5000 }, - ) - - await expect(page.getByTestId('slow-async-query-1')).toContainText( - 'slow-async-1', - { timeout: 5000 }, - ) - await expect(page.getByTestId('slow-async-query-2')).toContainText( - 'slow-async-2', - { timeout: 5000 }, - ) - await expect(page.getByTestId('slow-async-query-3')).toContainText( - 'slow-async-3', - { timeout: 5000 }, - ) - }) - - testWithHydration('hydration works with many queries', async ({ page }) => { - await page.goto('/query-heavy') - await page.waitForLoadState('networkidle') - - // Wait for all queries to resolve - await expect(page.getByTestId('slow-async-query-3')).toBeVisible({ - timeout: 5000, - }) - }) - - test('client-side navigation works', async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - // Navigate via nav link - await page.getByRole('link', { name: 'Query Heavy' }).click() - await expect(page).toHaveURL('/query-heavy') - - // All queries should eventually resolve (on client) - await expect(page.getByTestId('slow-async-query-3')).toBeVisible({ - timeout: 5000, - }) - }) - - test('server query data hydrates without client refetch', async ({ - page, - }) => { - // If hydration missed the server data, these queries would re-execute on - // the client and show "client" as their source. - await page.goto('/query-heavy') - - // Wait for all queries - await expect(page.getByTestId('slow-async-query-3')).toBeVisible({ - timeout: 5000, - }) - - // Verify that all server results hydrated without a client refetch. - const serverSourceCount = await page - .locator('[data-testid*="query-"]') - .filter({ hasText: 'source: server' }) - .count() - expect(serverSourceCount).toBe(9) - }) -}) diff --git a/e2e/streaming-ssr-specs/slow-render.ts b/e2e/streaming-ssr-specs/slow-render.ts deleted file mode 100644 index 117559701e..0000000000 --- a/e2e/streaming-ssr-specs/slow-render.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { expect, test, testWithHydration } from '../streaming-ssr-assertions' - -test.describe('Slow render (render takes longer than serialization)', () => { - test('all data eventually renders with server source', async ({ page }) => { - await page.goto('/slow-render') - await page.waitForLoadState('networkidle') - - // Quick data should be available with server source - await expect(page.getByTestId('quick-data')).toContainText('Quick:') - await expect(page.getByTestId('quick-source')).toContainText( - 'Quick data source: server', - ) - await expect(page.getByTestId('loader-source')).toContainText( - 'Loader source: server', - ) - - // Deferred data should resolve with server source - await expect(page.getByTestId('deferred-resolved')).toContainText( - 'Deferred resolved!', - { timeout: 5000 }, - ) - await expect(page.getByTestId('deferred-resolved')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - - // Slow components should have rendered - await expect(page.getByTestId('slow-component-1')).toBeVisible() - await expect(page.getByTestId('slow-component-2')).toBeVisible() - await expect(page.getByTestId('slow-component-3')).toBeVisible() - }) - - testWithHydration('hydration works after slow render', async ({ page }) => { - await page.goto('/slow-render') - await page.waitForLoadState('networkidle') - - // Wait for content and verify server source - await expect(page.getByTestId('slow-component-1')).toBeVisible() - await expect(page.getByTestId('loader-source')).toContainText( - 'Loader source: server', - ) - }) - - test('client-side navigation works', async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - // Navigate via nav link - await page.getByRole('link', { name: 'Slow Render' }).first().click() - await expect(page).toHaveURL('/slow-render') - - await expect(page.getByTestId('quick-data')).toBeVisible({ timeout: 10000 }) - }) - - test('all data sources are server', async ({ page }) => { - await page.goto('/slow-render') - await page.waitForLoadState('networkidle') - - // Wait for deferred content - await expect(page.getByTestId('deferred-resolved')).toBeVisible({ - timeout: 5000, - }) - - // Verify all sources are server - await expect(page.getByTestId('quick-source')).toContainText('server') - await expect(page.getByTestId('loader-source')).toContainText('server') - await expect(page.getByTestId('deferred-resolved')).toContainText( - 'source: server', - ) - }) -}) diff --git a/e2e/streaming-ssr-specs/stream.ts b/e2e/streaming-ssr-specs/stream.ts deleted file mode 100644 index ee61f170de..0000000000 --- a/e2e/streaming-ssr-specs/stream.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { expect, test, testWithHydration } from '../streaming-ssr-assertions' - -const expectedStreamChunks = [ - 'chunk-0', - 'chunk-1', - 'chunk-2', - 'chunk-3', - 'chunk-4', -] - -test.describe('ReadableStream deserialization', () => { - testWithHydration('promise data deserializes correctly', async ({ page }) => { - await page.goto('/stream') - - await expect(page.getByTestId('promise-data')).toContainText( - 'promise-resolved', - { timeout: 5000 }, - ) - }) - - testWithHydration( - 'stream chunks deserialize in source order', - async ({ page }) => { - await page.goto('/stream') - - await expect(page.getByTestId('stream-complete')).toBeVisible({ - timeout: 10000, - }) - - const chunks = page - .getByTestId('stream-data') - .locator('[data-testid^="stream-chunk-"]') - await expect(chunks).toHaveText(expectedStreamChunks) - - // This browser assertion covers deserialization and source order. The - // raw `/deferred` assertion covers server-response and router ordering. - }, - ) - - testWithHydration( - 'client-side navigation to stream route works', - async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - // Navigate via nav link - await page.getByRole('link', { name: 'Stream' }).first().click() - await expect(page).toHaveURL('/stream') - - await expect(page.getByTestId('stream-complete')).toBeVisible({ - timeout: 10000, - }) - }, - ) -}) diff --git a/e2e/streaming-ssr-specs/sync-only.ts b/e2e/streaming-ssr-specs/sync-only.ts deleted file mode 100644 index 9850265109..0000000000 --- a/e2e/streaming-ssr-specs/sync-only.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { - expect, - expectRouterHydrationMarkers, - test, - testWithHydration, -} from '../streaming-ssr-assertions' - -/** - * Tests for synchronous serialization - no deferred data, no streaming. - * This is the most common case where all loader data is immediately available. - * The hydration scripts should be included in the initial HTML response. - */ - -test('Sync-only route renders with loader data', async ({ page }) => { - await page.goto('/sync-only') - - // Verify the page content is rendered - await expect(page.getByTestId('sync-title')).toContainText( - 'Synchronous Serialization Test', - ) - await expect(page.getByTestId('sync-message')).toContainText( - 'Hello from sync loader!', - ) - - // Verify loader data items are rendered - await expect(page.getByTestId('sync-item-item-1')).toBeVisible() - await expect(page.getByTestId('sync-item-item-2')).toBeVisible() - await expect(page.getByTestId('sync-item-item-3')).toBeVisible() - - // Verify the loader ran during SSR. - await expect(page.getByTestId('sync-source')).toContainText('Source: server') -}) - -testWithHydration('Sync-only route hydrates correctly', async ({ page }) => { - await page.goto('/sync-only') - - // Verify client-side navigation works (proves hydration succeeded) - await page.getByRole('navigation').getByRole('link', { name: 'Home' }).click() - await expect(page.getByTestId('index-title')).toBeVisible() - - // Navigate back to sync-only via client-side navigation (use nav link to be specific) - await page - .getByRole('navigation') - .getByRole('link', { name: 'Sync Only' }) - .click() - await expect(page.getByTestId('sync-title')).toBeVisible() -}) - -test('Sync-only route has bootstrap scripts in initial HTML', async ({ - page, -}) => { - // Intercept the response to check the raw HTML - let responseHtml = '' - await page.route('/sync-only', async (route) => { - const response = await route.fetch() - responseHtml = await response.text() - await route.fulfill({ response }) - }) - - await page.goto('/sync-only') - - // Wait for page to load - await expect(page.getByTestId('sync-title')).toBeVisible() - - // Bootstrap, end record, and the boundary rendered by . - expectRouterHydrationMarkers(responseHtml) -}) - -test('Navigating to sync-only from home page', async ({ page }) => { - await page.goto('/') - - await page.getByTestId('link-sync-only').click() - - await expect(page.getByTestId('sync-title')).toContainText( - 'Synchronous Serialization Test', - ) - await expect(page.getByTestId('sync-message')).toContainText( - 'Hello from sync loader!', - ) -}) diff --git a/e2e/vue-router/basepath-file-based/.devcontainer/devcontainer.json b/e2e/vue-router/basepath-file-based/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-router/basepath-file-based/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-router/basepath-file-based/package.json b/e2e/vue-router/basepath-file-based/package.json index 3af9176e83..1546588385 100644 --- a/e2e/vue-router/basepath-file-based/package.json +++ b/e2e/vue-router/basepath-file-based/package.json @@ -8,26 +8,26 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", + "@tailwindcss/vite": "^4.1.18", "@tanstack/router-plugin": "workspace:^", "@tanstack/vue-query": "^5.90.0", "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "catalog:", - "tailwindcss": "^4.2.2", + "redaxios": "^0.5.1", + "tailwindcss": "^4.1.18", "vue": "^3.5.16" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", - "@vitejs/plugin-vue": "^6.0.5", - "@vitejs/plugin-vue-jsx": "^5.1.5", + "@vitejs/plugin-vue": "^5.2.3", + "@vitejs/plugin-vue-jsx": "^4.1.2", "typescript": "~5.8.3", - "vite": "^8.0.14", - "vue-tsc": "^3.3.8" + "vite": "^7.3.1", + "vue-tsc": "^3.1.5" } } diff --git a/e2e/vue-router/basepath-file-based/playwright.config.ts b/e2e/vue-router/basepath-file-based/playwright.config.ts index 4eead86444..6069bbe59f 100644 --- a/e2e/vue-router/basepath-file-based/playwright.config.ts +++ b/e2e/vue-router/basepath-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/basepath-file-based/src/routeTree.gen.ts b/e2e/vue-router/basepath-file-based/src/routeTree.gen.ts index 75b8119285..82b561baf1 100644 --- a/e2e/vue-router/basepath-file-based/src/routeTree.gen.ts +++ b/e2e/vue-router/basepath-file-based/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 IndexRouteImport } from './routes/index' import { Route as AboutRouteImport } from './routes/about' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const AboutRoute = AboutRouteImport.update({ id: '/about', path: '/about', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/about': { id: '/about' path: '/about' @@ -65,6 +58,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/e2e/vue-router/basepath-file-based/tests/setup/global.setup.ts b/e2e/vue-router/basepath-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basepath-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basepath-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/basepath-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basepath-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-esbuild-file-based/.devcontainer/devcontainer.json b/e2e/vue-router/basic-esbuild-file-based/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-router/basic-esbuild-file-based/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-router/basic-esbuild-file-based/package.json b/e2e/vue-router/basic-esbuild-file-based/package.json index a51cf9149c..866969a75e 100644 --- a/e2e/vue-router/basic-esbuild-file-based/package.json +++ b/e2e/vue-router/basic-esbuild-file-based/package.json @@ -7,29 +7,29 @@ "build": "node src/esbuild.run.js build && vue-tsc --noEmit", "preview": "node src/esbuild.run.js preview", "start": "pnpm dev", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/router-plugin": "workspace:^", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", + "@tanstack/zod-adapter": "workspace:^", "postcss": "^8.5.1", - "redaxios": "catalog:", + "redaxios": "^0.5.1", "vue": "^3.5.16", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@eslint/js": "^9.36.0", - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", "@typescript-eslint/eslint-plugin": "^8.44.1", "@typescript-eslint/parser": "^8.44.1", - "esbuild": "^0.27.4", + "esbuild": "^0.25.0", "esbuild-plugin-vue3": "^0.5.1", "eslint-plugin-vue": "^9.33.0", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", + "typescript": "^5.8.3", "vue-eslint-parser": "^9.4.3", - "vue-tsc": "^3.3.8" + "vue-tsc": "^3.1.5" } } diff --git a/e2e/vue-router/basic-esbuild-file-based/playwright.config.ts b/e2e/vue-router/basic-esbuild-file-based/playwright.config.ts index 9d9c8d49a3..836ea41bd8 100644 --- a/e2e/vue-router/basic-esbuild-file-based/playwright.config.ts +++ b/e2e/vue-router/basic-esbuild-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-esbuild-file-based/src/esbuild.config.js b/e2e/vue-router/basic-esbuild-file-based/src/esbuild.config.js index 16f6fbca44..c4aba8798e 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/esbuild.config.js +++ b/e2e/vue-router/basic-esbuild-file-based/src/esbuild.config.js @@ -9,6 +9,7 @@ export default { }), tanstackRouter({ target: 'vue', + autoCodeSplitting: true, }), ], } diff --git a/e2e/vue-router/basic-esbuild-file-based/src/esbuild.run.js b/e2e/vue-router/basic-esbuild-file-based/src/esbuild.run.js index 0ab294f2bf..19e882c1a9 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/esbuild.run.js +++ b/e2e/vue-router/basic-esbuild-file-based/src/esbuild.run.js @@ -1,7 +1,8 @@ -import http from 'node:http' -import { createReadStream, promises as fs } from 'node:fs' -import path from 'node:path' import * as esbuild from 'esbuild' +import http from 'node:http' +import { createReadStream } from 'node:fs' +import { promises as fs } from 'node:fs' +import path from 'node:path' import esbuildConfig from './esbuild.config.js' const args = process.argv.slice(2) @@ -17,7 +18,7 @@ function getPort() { const fromArg = getArgValue('--port') const fromEnv = process.env.VITE_SERVER_PORT const port = Number(fromArg ?? fromEnv ?? 5601) - if (!Number.isFinite(port) || port < 0) { + if (!Number.isFinite(port) || port <= 0) { throw new Error(`Invalid port: ${String(fromArg ?? fromEnv)}`) } return port @@ -137,7 +138,7 @@ function startStaticServer({ port }) { return new Promise((resolve) => { server.listen(port, () => { - console.log(`E2E app: http://localhost:${server.address().port}`) + console.log(`http://localhost:${port}`) resolve(server) }) }) diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/(another-group)/onlyrouteinside.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/(another-group)/onlyrouteinside.tsx index 8869cefc01..83036509ba 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/(another-group)/onlyrouteinside.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/(another-group)/onlyrouteinside.tsx @@ -1,32 +1,28 @@ -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} -
-
- ) - }, -}) +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(another-group)/onlyrouteinside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(z.object({ hello: z.string().optional() })), component: OnlyRouteInsideComponent, }) const routeApi = getRouteApi('/(another-group)/onlyrouteinside') + +function OnlyRouteInsideComponent() { + const searchViaHook = useSearch({ from: '/(another-group)/onlyrouteinside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) +} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/_layout.insidelayout.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/_layout.insidelayout.tsx index f2998803fd..557503a0c2 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/_layout.insidelayout.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/_layout.insidelayout.tsx @@ -1,30 +1,28 @@ -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} -
-
- ) - }, -}) +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/_layout/insidelayout')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(z.object({ hello: z.string().optional() })), component: InsideLayoutComponent, }) const routeApi = getRouteApi('/(group)/_layout/insidelayout') + +function InsideLayoutComponent() { + const searchViaHook = useSearch({ from: '/(group)/_layout/insidelayout' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) +} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/inside.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/inside.tsx index 20e0d5afdb..bec12d8de2 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/inside.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/inside.tsx @@ -1,30 +1,28 @@ -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} -
-
- ) - }, -}) +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/inside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(z.object({ hello: z.string().optional() })), component: InsideComponent, }) const routeApi = getRouteApi('/(group)/inside') + +function InsideComponent() { + const searchViaHook = useSearch({ from: '/(group)/inside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) +} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/lazyinside.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/lazyinside.tsx index a46da658d6..56d8d6cae8 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/lazyinside.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/lazyinside.tsx @@ -1,30 +1,28 @@ -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} -
-
- ) - }, -}) +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/lazyinside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(z.object({ hello: z.string().optional() })), component: LazyInsideComponent, }) const routeApi = getRouteApi('/(group)/lazyinside') + +function LazyInsideComponent() { + const searchViaHook = useSearch({ from: '/(group)/lazyinside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) +} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/subfolder/inside.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/subfolder/inside.tsx index 715d2cc972..b4487d163d 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/subfolder/inside.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/subfolder/inside.tsx @@ -1,30 +1,28 @@ -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} -
-
- ) - }, -}) +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/subfolder/inside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(z.object({ hello: z.string().optional() })), component: SubfolderInsideComponent, }) const routeApi = getRouteApi('/(group)/subfolder/inside') + +function SubfolderInsideComponent() { + const searchViaHook = useSearch({ from: '/(group)/subfolder/inside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) +} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/__root.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/__root.tsx index 62c4af3aa4..59c9e6fa48 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/__root.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/__root.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { HeadContent, Link, @@ -11,97 +10,95 @@ import { import { TanStackRouterDevtools } from '@tanstack/vue-router-devtools' import NotFoundComponent from '../components/NotFoundComponent.vue' -const RootComponent = defineComponent({ - setup() { - const router = useRouter() - const canGoBack = useCanGoBack() - // test useRouterState doesn't crash client side navigation - const _state = useRouterState() - - return () => ( - <> - -
- - - Home - - - Posts - - - Layout - - - Only Route Inside Group - - - Inside Group - - - Inside Subfolder Inside Group - - - Inside Group Inside Layout - - - Lazy Inside Group - - - unicode path - - - This Route Does Not Exist - -
-
- - - - ) - }, -}) - export const Route = createRootRoute({ component: RootComponent, notFoundComponent: NotFoundComponent, }) + +function RootComponent() { + const router = useRouter() + const canGoBack = useCanGoBack() + // test useRouterState doesn't crash client side navigation + const _state = useRouterState() + + return ( + <> + +
+ + + Home + + + Posts + + + Layout + + + Only Route Inside Group + + + Inside Group + + + Inside Subfolder Inside Group + + + Inside Group Inside Layout + + + Lazy Inside Group + + + unicode path + + + This Route Does Not Exist + +
+
+ + + + ) +} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/posts.$postId.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/posts.$postId.tsx index 54ae789c8e..15d17387c8 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/posts.$postId.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/posts.$postId.tsx @@ -1,27 +1,24 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import PostErrorComponent from '../components/PostErrorComponent.vue' import { fetchPost } from '../posts' import type { PostType } from '../posts' -const PostComponent = defineComponent({ - setup() { - const post = Route.useLoaderData() - - return () => ( -
-

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

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

Post not found

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

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

+
{(post.value as PostType).body}
+
+ ) +} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/posts.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/posts.tsx index e0afd27b4c..ae580dfc02 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/posts.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/posts.tsx @@ -1,38 +1,7 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../posts' import type { PostType } from '../posts' -const PostsComponent = defineComponent({ - setup() { - const posts = Route.useLoaderData() - - return () => ( -
-
    - {[ - ...(posts.value as Array), - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ))} -
-
- -
- ) - }, -}) - export const Route = createFileRoute('/posts')({ head: () => ({ meta: [ @@ -44,3 +13,31 @@ export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) + +function PostsComponent() { + const posts = Route.useLoaderData() + + return ( +
+
    + {[ + ...(posts.value as Array), + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ))} +
+
+ +
+ ) +} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/posts_.$postId.edit.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/posts_.$postId.edit.tsx index 22979c93c9..57963c6b64 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/posts_.$postId.edit.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/posts_.$postId.edit.tsx @@ -1,28 +1,23 @@ -import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useParams } from '@tanstack/vue-router' -const PostEditComponent = defineComponent({ - setup() { - const paramsViaApi = api.useParams() - const paramsViaHook = useParams({ from: '/posts_/$postId/edit' }) - const paramsViaRouteHook = api.useParams() - - return () => ( -
-
{paramsViaHook.value.postId}
-
- {paramsViaRouteHook.value.postId} -
-
- {paramsViaApi.value.postId} -
-
- ) - }, -}) - export const Route = createFileRoute('/posts_/$postId/edit')({ component: PostEditComponent, }) const api = getRouteApi('/posts_/$postId/edit') + +function PostEditComponent() { + const paramsViaApi = api.useParams() + const paramsViaHook = useParams({ from: '/posts_/$postId/edit' }) + const paramsViaRouteHook = api.useParams() + + return ( +
+
{paramsViaHook.value.postId}
+
+ {paramsViaRouteHook.value.postId} +
+
{paramsViaApi.value.postId}
+
+ ) +} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/vite-env.d.ts b/e2e/vue-router/basic-esbuild-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/vue-router/basic-esbuild-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/vue-router/basic-esbuild-file-based/tests/app.spec.ts b/e2e/vue-router/basic-esbuild-file-based/tests/app.spec.ts index 7380859e7b..543746d64d 100644 --- a/e2e/vue-router/basic-esbuild-file-based/tests/app.spec.ts +++ b/e2e/vue-router/basic-esbuild-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import type { Page } from '@playwright/test' test.beforeEach(async ({ page }) => { diff --git a/e2e/vue-router/basic-esbuild-file-based/tests/setup/global.setup.ts b/e2e/vue-router/basic-esbuild-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basic-esbuild-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-esbuild-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/basic-esbuild-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basic-esbuild-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-file-based-jsx/.devcontainer/devcontainer.json b/e2e/vue-router/basic-file-based-jsx/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-router/basic-file-based-jsx/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-router/basic-file-based-jsx/package.json b/e2e/vue-router/basic-file-based-jsx/package.json index 9ab7f21e82..1636eea536 100644 --- a/e2e/vue-router/basic-file-based-jsx/package.json +++ b/e2e/vue-router/basic-file-based-jsx/package.json @@ -8,30 +8,31 @@ "build": "vite build && vue-tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", + "@tailwindcss/vite": "^4.1.18", "@tanstack/router-plugin": "workspace:^", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "catalog:", - "tailwindcss": "^4.2.2", + "@tanstack/zod-adapter": "workspace:^", + "redaxios": "^0.5.1", + "tailwindcss": "^4.1.18", "vue": "^3.5.16", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@eslint/js": "^9.36.0", - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", "@typescript-eslint/eslint-plugin": "^8.44.1", "@typescript-eslint/parser": "^8.44.1", - "@vitejs/plugin-vue": "^6.0.5", - "@vitejs/plugin-vue-jsx": "^5.1.5", + "@vitejs/plugin-vue": "^5.2.3", + "@vitejs/plugin-vue-jsx": "^4.1.2", "eslint-plugin-vue": "^9.33.0", "typescript": "~5.8.3", - "vite": "^8.0.14", + "vite": "^7.3.1", "vue-eslint-parser": "^9.4.3", - "vue-tsc": "^3.3.8" + "vue-tsc": "^3.1.5" } } diff --git a/e2e/vue-router/basic-file-based-jsx/playwright.config.ts b/e2e/vue-router/basic-file-based-jsx/playwright.config.ts index 4eead86444..836ea41bd8 100644 --- a/e2e/vue-router/basic-file-based-jsx/playwright.config.ts +++ b/e2e/vue-router/basic-file-based-jsx/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-file-based-jsx/src/posts.tsx b/e2e/vue-router/basic-file-based-jsx/src/posts.tsx index f7a1941605..1b4c92b41d 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/posts.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/basic-file-based-jsx/src/routeTree.gen.ts b/e2e/vue-router/basic-file-based-jsx/src/routeTree.gen.ts index 5922c5f7b1..01bb4b0d05 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 @@ -11,62 +11,34 @@ import { lazyRouteComponent } from '@tanstack/vue-router' import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as LayoutRouteImport } from './routes/_layout' -import { Route as EditingARouteImport } from './routes/editing-a' -import { Route as EditingBRouteImport } from './routes/editing-b' -import { Route as NotRemountDepsRouteImport } from './routes/notRemountDeps' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as RemountDepsRouteImport } from './routes/remountDeps' -import { Route as SfcComponentRouteImport } from './routes/sfcComponent' import { Route as Char45824Char54620Char48124Char44397RouteImport } from './routes/대한민국' -import { Route as anotherGroupOnlyrouteinsideRouteImport } from './routes/(another-group)/onlyrouteinside' -import { Route as groupLayoutRouteImport } from './routes/(group)/_layout' -import { Route as groupInsideRouteImport } from './routes/(group)/inside' -import { Route as groupLazyinsideRouteImport } from './routes/(group)/lazyinside' -import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' +import { Route as SfcComponentRouteImport } from './routes/sfcComponent' +import { Route as RemountDepsRouteImport } from './routes/remountDeps' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as NotRemountDepsRouteImport } from './routes/notRemountDeps' +import { Route as EditingBRouteImport } from './routes/editing-b' +import { Route as EditingARouteImport } from './routes/editing-a' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as IndexRouteImport } from './routes/index' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as groupLayoutInsidelayoutRouteImport } from './routes/(group)/_layout.insidelayout' -import { Route as groupSubfolderInsideRouteImport } from './routes/(group)/subfolder/inside' -import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' +import { Route as groupLazyinsideRouteImport } from './routes/(group)/lazyinside' +import { Route as groupInsideRouteImport } from './routes/(group)/inside' +import { Route as groupLayoutRouteImport } from './routes/(group)/_layout' +import { Route as anotherGroupOnlyrouteinsideRouteImport } from './routes/(another-group)/onlyrouteinside' import { Route as PostsPostIdEditRouteImport } from './routes/posts_.$postId.edit' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' +import { Route as groupSubfolderInsideRouteImport } from './routes/(group)/subfolder/inside' +import { Route as groupLayoutInsidelayoutRouteImport } from './routes/(group)/_layout.insidelayout' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', - getParentRoute: () => rootRouteImport, -} as any) -const EditingARoute = EditingARouteImport.update({ - id: '/editing-a', - path: '/editing-a', - getParentRoute: () => rootRouteImport, -} as any) -const EditingBRoute = EditingBRouteImport.update({ - id: '/editing-b', - path: '/editing-b', - getParentRoute: () => rootRouteImport, -} as any) -const NotRemountDepsRoute = NotRemountDepsRouteImport.update({ - id: '/notRemountDeps', - path: '/notRemountDeps', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const RemountDepsRoute = RemountDepsRouteImport.update({ - id: '/remountDeps', - path: '/remountDeps', - getParentRoute: () => rootRouteImport, -} as any) +const Char45824Char54620Char48124Char44397Route = + Char45824Char54620Char48124Char44397RouteImport.update({ + id: '/대한민국', + path: '/대한민국', + getParentRoute: () => rootRouteImport, + } as any) const SfcComponentRoute = SfcComponentRouteImport.update({ id: '/sfcComponent', path: '/sfcComponent', @@ -77,35 +49,39 @@ const SfcComponentRoute = SfcComponentRouteImport.update({ 'default', ), }) -const Char45824Char54620Char48124Char44397Route = - Char45824Char54620Char48124Char44397RouteImport.update({ - id: '/대한민국', - path: '/대한민국', - getParentRoute: () => rootRouteImport, - } as any) -const anotherGroupOnlyrouteinsideRoute = - anotherGroupOnlyrouteinsideRouteImport.update({ - id: '/(another-group)/onlyrouteinside', - path: '/onlyrouteinside', - getParentRoute: () => rootRouteImport, - } as any) -const groupLayoutRoute = groupLayoutRouteImport.update({ - id: '/(group)/_layout', +const RemountDepsRoute = RemountDepsRouteImport.update({ + id: '/remountDeps', + path: '/remountDeps', getParentRoute: () => rootRouteImport, } as any) -const groupInsideRoute = groupInsideRouteImport.update({ - id: '/(group)/inside', - path: '/inside', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const groupLazyinsideRoute = groupLazyinsideRouteImport.update({ - id: '/(group)/lazyinside', - path: '/lazyinside', +const NotRemountDepsRoute = NotRemountDepsRouteImport.update({ + id: '/notRemountDeps', + path: '/notRemountDeps', getParentRoute: () => rootRouteImport, } as any) -const LayoutLayout2Route = LayoutLayout2RouteImport.update({ - id: '/_layout-2', - getParentRoute: () => LayoutRoute, +const EditingBRoute = EditingBRouteImport.update({ + id: '/editing-b', + path: '/editing-b', + getParentRoute: () => rootRouteImport, +} as any) +const EditingARoute = EditingARouteImport.update({ + id: '/editing-a', + path: '/editing-a', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, } as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', @@ -117,31 +93,55 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRoute, } as any) -const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport.update({ - id: '/insidelayout', - path: '/insidelayout', - getParentRoute: () => groupLayoutRoute, +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, } as any) -const groupSubfolderInsideRoute = groupSubfolderInsideRouteImport.update({ - id: '/(group)/subfolder/inside', - path: '/subfolder/inside', +const groupLazyinsideRoute = groupLazyinsideRouteImport.update({ + id: '/(group)/lazyinside', + path: '/lazyinside', getParentRoute: () => rootRouteImport, } as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, +const groupInsideRoute = groupInsideRouteImport.update({ + id: '/(group)/inside', + path: '/inside', + getParentRoute: () => rootRouteImport, +} as any) +const groupLayoutRoute = groupLayoutRouteImport.update({ + id: '/(group)/_layout', + getParentRoute: () => rootRouteImport, +} as any) +const anotherGroupOnlyrouteinsideRoute = + anotherGroupOnlyrouteinsideRouteImport.update({ + id: '/(another-group)/onlyrouteinside', + path: '/onlyrouteinside', + getParentRoute: () => rootRouteImport, + } as any) +const PostsPostIdEditRoute = PostsPostIdEditRouteImport.update({ + id: '/posts_/$postId/edit', + path: '/posts/$postId/edit', + getParentRoute: () => rootRouteImport, } as any) const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ id: '/layout-b', path: '/layout-b', getParentRoute: () => LayoutLayout2Route, } as any) -const PostsPostIdEditRoute = PostsPostIdEditRouteImport.update({ - id: '/posts_/$postId/edit', - path: '/posts/$postId/edit', +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, +} as any) +const groupSubfolderInsideRoute = groupSubfolderInsideRouteImport.update({ + id: '/(group)/subfolder/inside', + path: '/subfolder/inside', getParentRoute: () => rootRouteImport, } as any) +const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport.update({ + id: '/insidelayout', + path: '/insidelayout', + getParentRoute: () => groupLayoutRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -291,53 +291,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout': { - id: '/_layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/editing-a': { - id: '/editing-a' - path: '/editing-a' - fullPath: '/editing-a' - preLoaderRoute: typeof EditingARouteImport - parentRoute: typeof rootRouteImport - } - '/editing-b': { - id: '/editing-b' - path: '/editing-b' - fullPath: '/editing-b' - preLoaderRoute: typeof EditingBRouteImport - parentRoute: typeof rootRouteImport - } - '/notRemountDeps': { - id: '/notRemountDeps' - path: '/notRemountDeps' - fullPath: '/notRemountDeps' - preLoaderRoute: typeof NotRemountDepsRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/remountDeps': { - id: '/remountDeps' - path: '/remountDeps' - fullPath: '/remountDeps' - preLoaderRoute: typeof RemountDepsRouteImport + '/대한민국': { + id: '/대한민국' + path: '/대한민국' + fullPath: '/대한민국' + preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteImport parentRoute: typeof rootRouteImport } '/sfcComponent': { @@ -347,48 +305,55 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof SfcComponentRouteImport parentRoute: typeof rootRouteImport } - '/대한민국': { - id: '/대한민국' - path: '/대한민국' - fullPath: '/대한민국' - preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteImport + '/remountDeps': { + id: '/remountDeps' + path: '/remountDeps' + fullPath: '/remountDeps' + preLoaderRoute: typeof RemountDepsRouteImport parentRoute: typeof rootRouteImport } - '/(another-group)/onlyrouteinside': { - id: '/(another-group)/onlyrouteinside' - path: '/onlyrouteinside' - fullPath: '/onlyrouteinside' - preLoaderRoute: typeof anotherGroupOnlyrouteinsideRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } - '/(group)/_layout': { - id: '/(group)/_layout' + '/notRemountDeps': { + id: '/notRemountDeps' + path: '/notRemountDeps' + fullPath: '/notRemountDeps' + preLoaderRoute: typeof NotRemountDepsRouteImport + parentRoute: typeof rootRouteImport + } + '/editing-b': { + id: '/editing-b' + path: '/editing-b' + fullPath: '/editing-b' + preLoaderRoute: typeof EditingBRouteImport + parentRoute: typeof rootRouteImport + } + '/editing-a': { + id: '/editing-a' + path: '/editing-a' + fullPath: '/editing-a' + preLoaderRoute: typeof EditingARouteImport + parentRoute: typeof rootRouteImport + } + '/_layout': { + id: '/_layout' path: '' + fullPath: '' + preLoaderRoute: typeof LayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' fullPath: '/' - preLoaderRoute: typeof groupLayoutRouteImport + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/(group)/inside': { - id: '/(group)/inside' - path: '/inside' - fullPath: '/inside' - preLoaderRoute: typeof groupInsideRouteImport - parentRoute: typeof rootRouteImport - } - '/(group)/lazyinside': { - id: '/(group)/lazyinside' - path: '/lazyinside' - fullPath: '/lazyinside' - preLoaderRoute: typeof groupLazyinsideRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout/_layout-2': { - id: '/_layout/_layout-2' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute - } '/posts/': { id: '/posts/' path: '/' @@ -403,26 +368,47 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRoute } - '/(group)/_layout/insidelayout': { - id: '/(group)/_layout/insidelayout' - path: '/insidelayout' - fullPath: '/insidelayout' - preLoaderRoute: typeof groupLayoutInsidelayoutRouteImport - parentRoute: typeof groupLayoutRoute + '/_layout/_layout-2': { + id: '/_layout/_layout-2' + path: '' + fullPath: '' + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute } - '/(group)/subfolder/inside': { - id: '/(group)/subfolder/inside' - path: '/subfolder/inside' - fullPath: '/subfolder/inside' - preLoaderRoute: typeof groupSubfolderInsideRouteImport + '/(group)/lazyinside': { + id: '/(group)/lazyinside' + path: '/lazyinside' + fullPath: '/lazyinside' + preLoaderRoute: typeof groupLazyinsideRouteImport parentRoute: typeof rootRouteImport } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route + '/(group)/inside': { + id: '/(group)/inside' + path: '/inside' + fullPath: '/inside' + preLoaderRoute: typeof groupInsideRouteImport + parentRoute: typeof rootRouteImport + } + '/(group)/_layout': { + id: '/(group)/_layout' + path: '' + fullPath: '' + preLoaderRoute: typeof groupLayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/(another-group)/onlyrouteinside': { + id: '/(another-group)/onlyrouteinside' + path: '/onlyrouteinside' + fullPath: '/onlyrouteinside' + preLoaderRoute: typeof anotherGroupOnlyrouteinsideRouteImport + parentRoute: typeof rootRouteImport + } + '/posts_/$postId/edit': { + id: '/posts_/$postId/edit' + path: '/posts/$postId/edit' + fullPath: '/posts/$postId/edit' + preLoaderRoute: typeof PostsPostIdEditRouteImport + parentRoute: typeof rootRouteImport } '/_layout/_layout-2/layout-b': { id: '/_layout/_layout-2/layout-b' @@ -431,13 +417,27 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport parentRoute: typeof LayoutLayout2Route } - '/posts_/$postId/edit': { - id: '/posts_/$postId/edit' - path: '/posts/$postId/edit' - fullPath: '/posts/$postId/edit' - preLoaderRoute: typeof PostsPostIdEditRouteImport + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route + } + '/(group)/subfolder/inside': { + id: '/(group)/subfolder/inside' + path: '/subfolder/inside' + fullPath: '/subfolder/inside' + preLoaderRoute: typeof groupSubfolderInsideRouteImport parentRoute: typeof rootRouteImport } + '/(group)/_layout/insidelayout': { + id: '/(group)/_layout/insidelayout' + path: '/insidelayout' + fullPath: '/insidelayout' + preLoaderRoute: typeof groupLayoutInsidelayoutRouteImport + parentRoute: typeof groupLayoutRoute + } } } diff --git a/e2e/vue-router/basic-file-based-jsx/src/routes/(another-group)/onlyrouteinside.tsx b/e2e/vue-router/basic-file-based-jsx/src/routes/(another-group)/onlyrouteinside.tsx index 8869cefc01..83036509ba 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routes/(another-group)/onlyrouteinside.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/routes/(another-group)/onlyrouteinside.tsx @@ -1,32 +1,28 @@ -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} -
-
- ) - }, -}) +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(another-group)/onlyrouteinside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(z.object({ hello: z.string().optional() })), component: OnlyRouteInsideComponent, }) const routeApi = getRouteApi('/(another-group)/onlyrouteinside') + +function OnlyRouteInsideComponent() { + const searchViaHook = useSearch({ from: '/(another-group)/onlyrouteinside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) +} diff --git a/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/_layout.insidelayout.tsx b/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/_layout.insidelayout.tsx index f2998803fd..557503a0c2 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/_layout.insidelayout.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/_layout.insidelayout.tsx @@ -1,30 +1,28 @@ -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} -
-
- ) - }, -}) +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/_layout/insidelayout')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(z.object({ hello: z.string().optional() })), component: InsideLayoutComponent, }) const routeApi = getRouteApi('/(group)/_layout/insidelayout') + +function InsideLayoutComponent() { + const searchViaHook = useSearch({ from: '/(group)/_layout/insidelayout' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) +} diff --git a/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/inside.tsx b/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/inside.tsx index 20e0d5afdb..bec12d8de2 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/inside.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/inside.tsx @@ -1,30 +1,28 @@ -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} -
-
- ) - }, -}) +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/inside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(z.object({ hello: z.string().optional() })), component: InsideComponent, }) const routeApi = getRouteApi('/(group)/inside') + +function InsideComponent() { + const searchViaHook = useSearch({ from: '/(group)/inside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) +} diff --git a/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/lazyinside.tsx b/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/lazyinside.tsx index a46da658d6..56d8d6cae8 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/lazyinside.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/lazyinside.tsx @@ -1,30 +1,28 @@ -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} -
-
- ) - }, -}) +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/lazyinside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(z.object({ hello: z.string().optional() })), component: LazyInsideComponent, }) const routeApi = getRouteApi('/(group)/lazyinside') + +function LazyInsideComponent() { + const searchViaHook = useSearch({ from: '/(group)/lazyinside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) +} diff --git a/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/subfolder/inside.tsx b/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/subfolder/inside.tsx index 715d2cc972..b4487d163d 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/subfolder/inside.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/subfolder/inside.tsx @@ -1,30 +1,28 @@ -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} -
-
- ) - }, -}) +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/subfolder/inside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(z.object({ hello: z.string().optional() })), component: SubfolderInsideComponent, }) const routeApi = getRouteApi('/(group)/subfolder/inside') + +function SubfolderInsideComponent() { + const searchViaHook = useSearch({ from: '/(group)/subfolder/inside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) +} diff --git a/e2e/vue-router/basic-file-based-jsx/src/routes/__root.tsx b/e2e/vue-router/basic-file-based-jsx/src/routes/__root.tsx index 62c4af3aa4..59c9e6fa48 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routes/__root.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/routes/__root.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { HeadContent, Link, @@ -11,97 +10,95 @@ import { import { TanStackRouterDevtools } from '@tanstack/vue-router-devtools' import NotFoundComponent from '../components/NotFoundComponent.vue' -const RootComponent = defineComponent({ - setup() { - const router = useRouter() - const canGoBack = useCanGoBack() - // test useRouterState doesn't crash client side navigation - const _state = useRouterState() - - return () => ( - <> - -
- - - Home - - - Posts - - - Layout - - - Only Route Inside Group - - - Inside Group - - - Inside Subfolder Inside Group - - - Inside Group Inside Layout - - - Lazy Inside Group - - - unicode path - - - This Route Does Not Exist - -
-
- - - - ) - }, -}) - export const Route = createRootRoute({ component: RootComponent, notFoundComponent: NotFoundComponent, }) + +function RootComponent() { + const router = useRouter() + const canGoBack = useCanGoBack() + // test useRouterState doesn't crash client side navigation + const _state = useRouterState() + + return ( + <> + +
+ + + Home + + + Posts + + + Layout + + + Only Route Inside Group + + + Inside Group + + + Inside Subfolder Inside Group + + + Inside Group Inside Layout + + + Lazy Inside Group + + + unicode path + + + This Route Does Not Exist + +
+
+ + + + ) +} diff --git a/e2e/vue-router/basic-file-based-jsx/src/routes/posts.$postId.tsx b/e2e/vue-router/basic-file-based-jsx/src/routes/posts.$postId.tsx index 54ae789c8e..15d17387c8 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routes/posts.$postId.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/routes/posts.$postId.tsx @@ -1,27 +1,24 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import PostErrorComponent from '../components/PostErrorComponent.vue' import { fetchPost } from '../posts' import type { PostType } from '../posts' -const PostComponent = defineComponent({ - setup() { - const post = Route.useLoaderData() - - return () => ( -
-

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

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

Post not found

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

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

+
{(post.value as PostType).body}
+
+ ) +} diff --git a/e2e/vue-router/basic-file-based-jsx/src/routes/posts.tsx b/e2e/vue-router/basic-file-based-jsx/src/routes/posts.tsx index e0afd27b4c..ae580dfc02 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routes/posts.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/routes/posts.tsx @@ -1,38 +1,7 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../posts' import type { PostType } from '../posts' -const PostsComponent = defineComponent({ - setup() { - const posts = Route.useLoaderData() - - return () => ( -
-
    - {[ - ...(posts.value as Array), - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ))} -
-
- -
- ) - }, -}) - export const Route = createFileRoute('/posts')({ head: () => ({ meta: [ @@ -44,3 +13,31 @@ export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) + +function PostsComponent() { + const posts = Route.useLoaderData() + + return ( +
+
    + {[ + ...(posts.value as Array), + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ))} +
+
+ +
+ ) +} diff --git a/e2e/vue-router/basic-file-based-jsx/src/routes/posts_.$postId.edit.tsx b/e2e/vue-router/basic-file-based-jsx/src/routes/posts_.$postId.edit.tsx index 22979c93c9..57963c6b64 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routes/posts_.$postId.edit.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/routes/posts_.$postId.edit.tsx @@ -1,28 +1,23 @@ -import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useParams } from '@tanstack/vue-router' -const PostEditComponent = defineComponent({ - setup() { - const paramsViaApi = api.useParams() - const paramsViaHook = useParams({ from: '/posts_/$postId/edit' }) - const paramsViaRouteHook = api.useParams() - - return () => ( -
-
{paramsViaHook.value.postId}
-
- {paramsViaRouteHook.value.postId} -
-
- {paramsViaApi.value.postId} -
-
- ) - }, -}) - export const Route = createFileRoute('/posts_/$postId/edit')({ component: PostEditComponent, }) const api = getRouteApi('/posts_/$postId/edit') + +function PostEditComponent() { + const paramsViaApi = api.useParams() + const paramsViaHook = useParams({ from: '/posts_/$postId/edit' }) + const paramsViaRouteHook = api.useParams() + + return ( +
+
{paramsViaHook.value.postId}
+
+ {paramsViaRouteHook.value.postId} +
+
{paramsViaApi.value.postId}
+
+ ) +} diff --git a/e2e/vue-router/basic-file-based-jsx/src/vite-env.d.ts b/e2e/vue-router/basic-file-based-jsx/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/vue-router/basic-file-based-jsx/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/vue-router/basic-file-based-jsx/tests/app.spec.ts b/e2e/vue-router/basic-file-based-jsx/tests/app.spec.ts index 7380859e7b..543746d64d 100644 --- a/e2e/vue-router/basic-file-based-jsx/tests/app.spec.ts +++ b/e2e/vue-router/basic-file-based-jsx/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import type { Page } from '@playwright/test' test.beforeEach(async ({ page }) => { diff --git a/e2e/vue-router/basic-file-based-jsx/tests/setup/global.setup.ts b/e2e/vue-router/basic-file-based-jsx/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basic-file-based-jsx/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-file-based-jsx/tests/setup/global.teardown.ts b/e2e/vue-router/basic-file-based-jsx/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basic-file-based-jsx/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-file-based-sfc/.devcontainer/devcontainer.json b/e2e/vue-router/basic-file-based-sfc/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-router/basic-file-based-sfc/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-router/basic-file-based-sfc/package.json b/e2e/vue-router/basic-file-based-sfc/package.json index e6ffa156f9..c40c877083 100644 --- a/e2e/vue-router/basic-file-based-sfc/package.json +++ b/e2e/vue-router/basic-file-based-sfc/package.json @@ -8,25 +8,26 @@ "build": "vite build && vue-tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", + "@tailwindcss/vite": "^4.1.18", "@tanstack/router-plugin": "workspace:^", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "catalog:", - "tailwindcss": "^4.2.2", + "@tanstack/zod-adapter": "workspace:^", + "redaxios": "^0.5.1", + "tailwindcss": "^4.1.18", "vue": "^3.5.16", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", - "@vitejs/plugin-vue": "^6.0.5", - "@vitejs/plugin-vue-jsx": "^5.1.5", + "@vitejs/plugin-vue": "^5.2.3", + "@vitejs/plugin-vue-jsx": "^4.1.2", "typescript": "~5.8.3", - "vite": "^8.0.14", - "vue-tsc": "^3.3.8" + "vite": "^7.3.1", + "vue-tsc": "^3.1.5" } } diff --git a/e2e/vue-router/basic-file-based-sfc/playwright.config.ts b/e2e/vue-router/basic-file-based-sfc/playwright.config.ts index 4eead86444..836ea41bd8 100644 --- a/e2e/vue-router/basic-file-based-sfc/playwright.config.ts +++ b/e2e/vue-router/basic-file-based-sfc/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-file-based-sfc/src/posts.ts b/e2e/vue-router/basic-file-based-sfc/src/posts.ts index f7a1941605..1b4c92b41d 100644 --- a/e2e/vue-router/basic-file-based-sfc/src/posts.ts +++ b/e2e/vue-router/basic-file-based-sfc/src/posts.ts @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/basic-file-based-sfc/src/routeTree.gen.ts b/e2e/vue-router/basic-file-based-sfc/src/routeTree.gen.ts index 0bfdddab3d..ed2e49db39 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 @@ -11,73 +11,45 @@ import { lazyRouteComponent } from '@tanstack/vue-router' import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as LayoutRouteImport } from './routes/_layout' -import { Route as EditingARouteImport } from './routes/editing-a' -import { Route as EditingBRouteImport } from './routes/editing-b' -import { Route as NotRemountDepsRouteImport } from './routes/notRemountDeps' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as RemountDepsRouteImport } from './routes/remountDeps' import { Route as Char45824Char54620Char48124Char44397RouteImport } from './routes/대한민국' -import { Route as anotherGroupOnlyrouteinsideRouteImport } from './routes/(another-group)/onlyrouteinside' -import { Route as groupLayoutRouteImport } from './routes/(group)/_layout' -import { Route as groupInsideRouteImport } from './routes/(group)/inside' -import { Route as groupLazyinsideRouteImport } from './routes/(group)/lazyinside' -import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' +import { Route as RemountDepsRouteImport } from './routes/remountDeps' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as NotRemountDepsRouteImport } from './routes/notRemountDeps' +import { Route as EditingBRouteImport } from './routes/editing-b' +import { Route as EditingARouteImport } from './routes/editing-a' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as IndexRouteImport } from './routes/index' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as groupLayoutInsidelayoutRouteImport } from './routes/(group)/_layout.insidelayout' -import { Route as groupSubfolderInsideRouteImport } from './routes/(group)/subfolder/inside' -import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' +import { Route as groupLazyinsideRouteImport } from './routes/(group)/lazyinside' +import { Route as groupInsideRouteImport } from './routes/(group)/inside' +import { Route as groupLayoutRouteImport } from './routes/(group)/_layout' +import { Route as anotherGroupOnlyrouteinsideRouteImport } from './routes/(another-group)/onlyrouteinside' import { Route as PostsPostIdEditRouteImport } from './routes/posts_.$postId.edit' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' +import { Route as groupSubfolderInsideRouteImport } from './routes/(group)/subfolder/inside' +import { Route as groupLayoutInsidelayoutRouteImport } from './routes/(group)/_layout.insidelayout' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const Char45824Char54620Char48124Char44397Route = + Char45824Char54620Char48124Char44397RouteImport.update({ + id: '/대한민국', + path: '/대한민국', + getParentRoute: () => rootRouteImport, + } as any).update({ + component: lazyRouteComponent( + () => import('./routes/대한민국.component.vue'), + 'default', + ), + }) +const RemountDepsRoute = RemountDepsRouteImport.update({ + id: '/remountDeps', + path: '/remountDeps', getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/index.component.vue'), - 'default', - ), -}) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', - getParentRoute: () => rootRouteImport, -} as any).update({ - component: lazyRouteComponent( - () => import('./routes/_layout.component.vue'), - 'default', - ), -}) -const EditingARoute = EditingARouteImport.update({ - id: '/editing-a', - path: '/editing-a', - getParentRoute: () => rootRouteImport, -} as any).update({ - component: lazyRouteComponent( - () => import('./routes/editing-a.component.vue'), - 'default', - ), -}) -const EditingBRoute = EditingBRouteImport.update({ - id: '/editing-b', - path: '/editing-b', - getParentRoute: () => rootRouteImport, -} as any).update({ - component: lazyRouteComponent( - () => import('./routes/editing-b.component.vue'), - 'default', - ), -}) -const NotRemountDepsRoute = NotRemountDepsRouteImport.update({ - id: '/notRemountDeps', - path: '/notRemountDeps', - getParentRoute: () => rootRouteImport, -} as any).update({ - component: lazyRouteComponent( - () => import('./routes/notRemountDeps.component.vue'), + () => import('./routes/remountDeps.component.vue'), 'default', ), }) @@ -91,80 +63,52 @@ const PostsRoute = PostsRouteImport.update({ 'default', ), }) -const RemountDepsRoute = RemountDepsRouteImport.update({ - id: '/remountDeps', - path: '/remountDeps', +const NotRemountDepsRoute = NotRemountDepsRouteImport.update({ + id: '/notRemountDeps', + path: '/notRemountDeps', getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/remountDeps.component.vue'), + () => import('./routes/notRemountDeps.component.vue'), 'default', ), }) -const Char45824Char54620Char48124Char44397Route = - Char45824Char54620Char48124Char44397RouteImport.update({ - id: '/대한민국', - path: '/대한민국', - getParentRoute: () => rootRouteImport, - } as any).update({ - component: lazyRouteComponent( - () => import('./routes/대한민국.component.vue'), - 'default', - ), - }) -const anotherGroupOnlyrouteinsideRoute = anotherGroupOnlyrouteinsideRouteImport - .update({ - id: '/(another-group)/onlyrouteinside', - path: '/onlyrouteinside', - getParentRoute: () => rootRouteImport, - } as any) - .update({ - component: lazyRouteComponent( - () => import('./routes/(another-group)/onlyrouteinside.component.vue'), - 'default', - ), - }) -const groupLayoutRoute = groupLayoutRouteImport - .update({ - id: '/(group)/_layout', - getParentRoute: () => rootRouteImport, - } as any) - .update({ - component: lazyRouteComponent( - () => import('./routes/(group)/_layout.component.vue'), - 'default', - ), - }) -const groupInsideRoute = groupInsideRouteImport - .update({ - id: '/(group)/inside', - path: '/inside', - getParentRoute: () => rootRouteImport, - } as any) - .update({ - component: lazyRouteComponent( - () => import('./routes/(group)/inside.component.vue'), - 'default', - ), - }) -const groupLazyinsideRoute = groupLazyinsideRouteImport - .update({ - id: '/(group)/lazyinside', - path: '/lazyinside', - getParentRoute: () => rootRouteImport, - } as any) - .update({ - component: lazyRouteComponent( - () => import('./routes/(group)/lazyinside.component.vue'), - 'default', - ), - }) -const LayoutLayout2Route = LayoutLayout2RouteImport.update({ - id: '/_layout-2', - getParentRoute: () => LayoutRoute, +const EditingBRoute = EditingBRouteImport.update({ + id: '/editing-b', + path: '/editing-b', + getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/_layout/_layout-2.component.vue'), + () => import('./routes/editing-b.component.vue'), + 'default', + ), +}) +const EditingARoute = EditingARouteImport.update({ + id: '/editing-a', + path: '/editing-a', + getParentRoute: () => rootRouteImport, +} as any).update({ + component: lazyRouteComponent( + () => import('./routes/editing-a.component.vue'), + 'default', + ), +}) +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', + getParentRoute: () => rootRouteImport, +} as any).update({ + component: lazyRouteComponent( + () => import('./routes/_layout.component.vue'), + 'default', + ), +}) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any).update({ + component: lazyRouteComponent( + () => import('./routes/index.component.vue'), 'default', ), }) @@ -192,37 +136,69 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ 'default', ), }) -const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, +} as any).update({ + component: lazyRouteComponent( + () => import('./routes/_layout/_layout-2.component.vue'), + 'default', + ), +}) +const groupLazyinsideRoute = groupLazyinsideRouteImport .update({ - id: '/insidelayout', - path: '/insidelayout', - getParentRoute: () => groupLayoutRoute, - } as any) - .update({ - component: lazyRouteComponent( - () => import('./routes/(group)/_layout.insidelayout.component.vue'), - 'default', - ), - }) -const groupSubfolderInsideRoute = groupSubfolderInsideRouteImport - .update({ - id: '/(group)/subfolder/inside', - path: '/subfolder/inside', + id: '/(group)/lazyinside', + path: '/lazyinside', getParentRoute: () => rootRouteImport, } as any) .update({ component: lazyRouteComponent( - () => import('./routes/(group)/subfolder/inside.component.vue'), + () => import('./routes/(group)/lazyinside.component.vue'), 'default', ), }) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, +const groupInsideRoute = groupInsideRouteImport + .update({ + id: '/(group)/inside', + path: '/inside', + getParentRoute: () => rootRouteImport, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(group)/inside.component.vue'), + 'default', + ), + }) +const groupLayoutRoute = groupLayoutRouteImport + .update({ + id: '/(group)/_layout', + getParentRoute: () => rootRouteImport, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(group)/_layout.component.vue'), + 'default', + ), + }) +const anotherGroupOnlyrouteinsideRoute = anotherGroupOnlyrouteinsideRouteImport + .update({ + id: '/(another-group)/onlyrouteinside', + path: '/onlyrouteinside', + getParentRoute: () => rootRouteImport, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(another-group)/onlyrouteinside.component.vue'), + 'default', + ), + }) +const PostsPostIdEditRoute = PostsPostIdEditRouteImport.update({ + id: '/posts_/$postId/edit', + path: '/posts/$postId/edit', + getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/_layout/_layout-2/layout-a.component.vue'), + () => import('./routes/posts_.$postId.edit.component.vue'), 'default', ), }) @@ -236,16 +212,40 @@ const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ 'default', ), }) -const PostsPostIdEditRoute = PostsPostIdEditRouteImport.update({ - id: '/posts_/$postId/edit', - path: '/posts/$postId/edit', - getParentRoute: () => rootRouteImport, +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, } as any).update({ component: lazyRouteComponent( - () => import('./routes/posts_.$postId.edit.component.vue'), + () => import('./routes/_layout/_layout-2/layout-a.component.vue'), 'default', ), }) +const groupSubfolderInsideRoute = groupSubfolderInsideRouteImport + .update({ + id: '/(group)/subfolder/inside', + path: '/subfolder/inside', + getParentRoute: () => rootRouteImport, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(group)/subfolder/inside.component.vue'), + 'default', + ), + }) +const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport + .update({ + id: '/insidelayout', + path: '/insidelayout', + getParentRoute: () => groupLayoutRoute, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(group)/_layout.insidelayout.component.vue'), + 'default', + ), + }) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -388,46 +388,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout': { - id: '/_layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/editing-a': { - id: '/editing-a' - path: '/editing-a' - fullPath: '/editing-a' - preLoaderRoute: typeof EditingARouteImport - parentRoute: typeof rootRouteImport - } - '/editing-b': { - id: '/editing-b' - path: '/editing-b' - fullPath: '/editing-b' - preLoaderRoute: typeof EditingBRouteImport - parentRoute: typeof rootRouteImport - } - '/notRemountDeps': { - id: '/notRemountDeps' - path: '/notRemountDeps' - fullPath: '/notRemountDeps' - preLoaderRoute: typeof NotRemountDepsRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport + '/대한민국': { + id: '/대한민국' + path: '/대한민국' + fullPath: '/대한민국' + preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteImport parentRoute: typeof rootRouteImport } '/remountDeps': { @@ -437,48 +402,48 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof RemountDepsRouteImport parentRoute: typeof rootRouteImport } - '/대한민국': { - id: '/대한민국' - path: '/대한민국' - fullPath: '/대한민국' - preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } - '/(another-group)/onlyrouteinside': { - id: '/(another-group)/onlyrouteinside' - path: '/onlyrouteinside' - fullPath: '/onlyrouteinside' - preLoaderRoute: typeof anotherGroupOnlyrouteinsideRouteImport + '/notRemountDeps': { + id: '/notRemountDeps' + path: '/notRemountDeps' + fullPath: '/notRemountDeps' + preLoaderRoute: typeof NotRemountDepsRouteImport parentRoute: typeof rootRouteImport } - '/(group)/_layout': { - id: '/(group)/_layout' + '/editing-b': { + id: '/editing-b' + path: '/editing-b' + fullPath: '/editing-b' + preLoaderRoute: typeof EditingBRouteImport + parentRoute: typeof rootRouteImport + } + '/editing-a': { + id: '/editing-a' + path: '/editing-a' + fullPath: '/editing-a' + preLoaderRoute: typeof EditingARouteImport + parentRoute: typeof rootRouteImport + } + '/_layout': { + id: '/_layout' path: '' + fullPath: '' + preLoaderRoute: typeof LayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' fullPath: '/' - preLoaderRoute: typeof groupLayoutRouteImport + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/(group)/inside': { - id: '/(group)/inside' - path: '/inside' - fullPath: '/inside' - preLoaderRoute: typeof groupInsideRouteImport - parentRoute: typeof rootRouteImport - } - '/(group)/lazyinside': { - id: '/(group)/lazyinside' - path: '/lazyinside' - fullPath: '/lazyinside' - preLoaderRoute: typeof groupLazyinsideRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout/_layout-2': { - id: '/_layout/_layout-2' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute - } '/posts/': { id: '/posts/' path: '/' @@ -493,26 +458,47 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRoute } - '/(group)/_layout/insidelayout': { - id: '/(group)/_layout/insidelayout' - path: '/insidelayout' - fullPath: '/insidelayout' - preLoaderRoute: typeof groupLayoutInsidelayoutRouteImport - parentRoute: typeof groupLayoutRoute + '/_layout/_layout-2': { + id: '/_layout/_layout-2' + path: '' + fullPath: '' + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute } - '/(group)/subfolder/inside': { - id: '/(group)/subfolder/inside' - path: '/subfolder/inside' - fullPath: '/subfolder/inside' - preLoaderRoute: typeof groupSubfolderInsideRouteImport + '/(group)/lazyinside': { + id: '/(group)/lazyinside' + path: '/lazyinside' + fullPath: '/lazyinside' + preLoaderRoute: typeof groupLazyinsideRouteImport parentRoute: typeof rootRouteImport } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route + '/(group)/inside': { + id: '/(group)/inside' + path: '/inside' + fullPath: '/inside' + preLoaderRoute: typeof groupInsideRouteImport + parentRoute: typeof rootRouteImport + } + '/(group)/_layout': { + id: '/(group)/_layout' + path: '' + fullPath: '' + preLoaderRoute: typeof groupLayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/(another-group)/onlyrouteinside': { + id: '/(another-group)/onlyrouteinside' + path: '/onlyrouteinside' + fullPath: '/onlyrouteinside' + preLoaderRoute: typeof anotherGroupOnlyrouteinsideRouteImport + parentRoute: typeof rootRouteImport + } + '/posts_/$postId/edit': { + id: '/posts_/$postId/edit' + path: '/posts/$postId/edit' + fullPath: '/posts/$postId/edit' + preLoaderRoute: typeof PostsPostIdEditRouteImport + parentRoute: typeof rootRouteImport } '/_layout/_layout-2/layout-b': { id: '/_layout/_layout-2/layout-b' @@ -521,13 +507,27 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport parentRoute: typeof LayoutLayout2Route } - '/posts_/$postId/edit': { - id: '/posts_/$postId/edit' - path: '/posts/$postId/edit' - fullPath: '/posts/$postId/edit' - preLoaderRoute: typeof PostsPostIdEditRouteImport + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route + } + '/(group)/subfolder/inside': { + id: '/(group)/subfolder/inside' + path: '/subfolder/inside' + fullPath: '/subfolder/inside' + preLoaderRoute: typeof groupSubfolderInsideRouteImport parentRoute: typeof rootRouteImport } + '/(group)/_layout/insidelayout': { + id: '/(group)/_layout/insidelayout' + path: '/insidelayout' + fullPath: '/insidelayout' + preLoaderRoute: typeof groupLayoutInsidelayoutRouteImport + parentRoute: typeof groupLayoutRoute + } } } diff --git a/e2e/vue-router/basic-file-based-sfc/src/routes/(another-group)/onlyrouteinside.ts b/e2e/vue-router/basic-file-based-sfc/src/routes/(another-group)/onlyrouteinside.ts index f427c79321..491bb03649 100644 --- a/e2e/vue-router/basic-file-based-sfc/src/routes/(another-group)/onlyrouteinside.ts +++ b/e2e/vue-router/basic-file-based-sfc/src/routes/(another-group)/onlyrouteinside.ts @@ -1,6 +1,7 @@ import { createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(another-group)/onlyrouteinside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(z.object({ hello: z.string().optional() })), }) diff --git a/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/_layout.insidelayout.ts b/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/_layout.insidelayout.ts index 3b605763af..49ef8f7bb9 100644 --- a/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/_layout.insidelayout.ts +++ b/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/_layout.insidelayout.ts @@ -1,6 +1,7 @@ import { createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/_layout/insidelayout')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(z.object({ hello: z.string().optional() })), }) diff --git a/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/inside.ts b/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/inside.ts index 456e8fe169..f7b06f6a94 100644 --- a/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/inside.ts +++ b/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/inside.ts @@ -1,6 +1,7 @@ import { createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/inside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(z.object({ hello: z.string().optional() })), }) diff --git a/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/lazyinside.ts b/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/lazyinside.ts index 7fba56aae4..b66d18a729 100644 --- a/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/lazyinside.ts +++ b/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/lazyinside.ts @@ -1,6 +1,7 @@ import { createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/lazyinside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(z.object({ hello: z.string().optional() })), }) diff --git a/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/subfolder/inside.ts b/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/subfolder/inside.ts index 21e5d7ba0a..50aa8a44ad 100644 --- a/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/subfolder/inside.ts +++ b/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/subfolder/inside.ts @@ -1,6 +1,7 @@ import { createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' +import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/subfolder/inside')({ - validateSearch: z.object({ hello: z.string().optional() }), + validateSearch: zodValidator(z.object({ hello: z.string().optional() })), }) diff --git a/e2e/vue-router/basic-file-based-sfc/src/vite-env.d.ts b/e2e/vue-router/basic-file-based-sfc/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/vue-router/basic-file-based-sfc/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/vue-router/basic-file-based-sfc/tests/app.spec.ts b/e2e/vue-router/basic-file-based-sfc/tests/app.spec.ts index 7380859e7b..543746d64d 100644 --- a/e2e/vue-router/basic-file-based-sfc/tests/app.spec.ts +++ b/e2e/vue-router/basic-file-based-sfc/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import type { Page } from '@playwright/test' test.beforeEach(async ({ page }) => { diff --git a/e2e/vue-router/basic-file-based-sfc/tests/setup/global.setup.ts b/e2e/vue-router/basic-file-based-sfc/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basic-file-based-sfc/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-file-based-sfc/tests/setup/global.teardown.ts b/e2e/vue-router/basic-file-based-sfc/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basic-file-based-sfc/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-scroll-restoration/.devcontainer/devcontainer.json b/e2e/vue-router/basic-scroll-restoration/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-router/basic-scroll-restoration/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-router/basic-scroll-restoration/package.json b/e2e/vue-router/basic-scroll-restoration/package.json index f4616a5651..b893ec3797 100644 --- a/e2e/vue-router/basic-scroll-restoration/package.json +++ b/e2e/vue-router/basic-scroll-restoration/package.json @@ -8,24 +8,24 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", + "@tailwindcss/vite": "^4.1.18", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-virtual": "^3.13.0", - "redaxios": "catalog:", + "redaxios": "^0.5.1", "vue": "^3.5.16", - "tailwindcss": "^4.2.2" + "tailwindcss": "^4.1.18" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", - "@vitejs/plugin-vue": "^6.0.5", - "@vitejs/plugin-vue-jsx": "^5.1.5", - "vite": "^8.0.14", - "vue-tsc": "^3.3.8", - "typescript": "~5.9.0" + "@vitejs/plugin-vue": "^5.2.3", + "@vitejs/plugin-vue-jsx": "^4.1.2", + "typescript": "~5.8.3", + "vite": "^7.3.1", + "vue-tsc": "^3.1.5" } } diff --git a/e2e/vue-router/basic-scroll-restoration/playwright.config.ts b/e2e/vue-router/basic-scroll-restoration/playwright.config.ts index 6a684ac89e..0c5cee43e4 100644 --- a/e2e/vue-router/basic-scroll-restoration/playwright.config.ts +++ b/e2e/vue-router/basic-scroll-restoration/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-scroll-restoration/src/vite-env.d.ts b/e2e/vue-router/basic-scroll-restoration/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/vue-router/basic-scroll-restoration/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/vue-router/basic-virtual-file-based/.devcontainer/devcontainer.json b/e2e/vue-router/basic-virtual-file-based/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-router/basic-virtual-file-based/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-router/basic-virtual-file-based/package.json b/e2e/vue-router/basic-virtual-file-based/package.json index 3701c2254c..804ca1d673 100644 --- a/e2e/vue-router/basic-virtual-file-based/package.json +++ b/e2e/vue-router/basic-virtual-file-based/package.json @@ -8,27 +8,27 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", + "@tailwindcss/vite": "^4.1.18", "@tanstack/router-plugin": "workspace:^", "@tanstack/virtual-file-routes": "workspace:^", "@tanstack/vue-query": "^5.90.0", "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "catalog:", - "tailwindcss": "^4.2.2", + "redaxios": "^0.5.1", + "tailwindcss": "^4.1.18", "vue": "^3.5.16" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", - "@vitejs/plugin-vue": "^6.0.5", - "@vitejs/plugin-vue-jsx": "^5.1.5", + "@vitejs/plugin-vue": "^5.2.3", + "@vitejs/plugin-vue-jsx": "^4.1.2", "typescript": "~5.8.3", - "vite": "^8.0.14", - "vue-tsc": "^3.3.8" + "vite": "^7.3.1", + "vue-tsc": "^3.1.5" } } diff --git a/e2e/vue-router/basic-virtual-file-based/playwright.config.ts b/e2e/vue-router/basic-virtual-file-based/playwright.config.ts index 4eead86444..836ea41bd8 100644 --- a/e2e/vue-router/basic-virtual-file-based/playwright.config.ts +++ b/e2e/vue-router/basic-virtual-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-virtual-file-based/src/posts.tsx b/e2e/vue-router/basic-virtual-file-based/src/posts.tsx index 5f5463a668..8576a3799a 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/posts.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/basic-virtual-file-based/src/routeTree.gen.ts b/e2e/vue-router/basic-virtual-file-based/src/routeTree.gen.ts index 1bae3d69a1..49926e7792 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routeTree.gen.ts +++ b/e2e/vue-router/basic-virtual-file-based/src/routeTree.gen.ts @@ -8,77 +8,79 @@ // 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 homeRouteImport } from './routes/home' -import { Route as layoutFirstLayoutRouteImport } from './routes/layout/first-layout' -import { Route as postsPostsRouteImport } from './routes/posts/posts' -import { Route as layoutSecondLayoutRouteImport } from './routes/layout/second-layout' -import { Route as ClassicHelloRouteRouteImport } from './routes/file-based-subtree/hello/route' -import { Route as postsPostsHomeRouteImport } from './routes/posts/posts-home' -import { Route as postsPostsDetailRouteImport } from './routes/posts/posts-detail' -import { Route as aRouteImport } from './routes/a' -import { Route as bRouteImport } from './routes/b' -import { Route as ClassicHelloIndexRouteImport } from './routes/file-based-subtree/hello/index' -import { Route as ClassicHelloUniverseRouteImport } from './routes/file-based-subtree/hello/universe' -import { Route as ClassicHelloWorldRouteImport } from './routes/file-based-subtree/hello/world' +import type { CreateFileRoute, FileRoutesByPath } from '@tanstack/vue-router' -const homeRoute = homeRouteImport.update({ - id: '/', - path: '/', +import { Route as rootRouteImport } from './routes/root' +import { Route as postsPostsRouteImport } from './routes/posts/posts' +import { Route as layoutFirstLayoutRouteImport } from './routes/layout/first-layout' +import { Route as homeRouteImport } from './routes/home' +import { Route as postsPostsDetailRouteImport } from './routes/posts/posts-detail' +import { Route as layoutSecondLayoutRouteImport } from './routes/layout/second-layout' +import { Route as postsPostsHomeRouteImport } from './routes/posts/posts-home' +import { Route as ClassicHelloRouteRouteImport } from './routes/file-based-subtree/hello/route' +import { Route as ClassicHelloIndexRouteImport } from './routes/file-based-subtree/hello/index' +import { Route as ClassicHelloWorldRouteImport } from './routes/file-based-subtree/hello/world' +import { Route as ClassicHelloUniverseRouteImport } from './routes/file-based-subtree/hello/universe' +import { Route as bRouteImport } from './routes/b' +import { Route as aRouteImport } from './routes/a' + +const postsPostsRoute = postsPostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) const layoutFirstLayoutRoute = layoutFirstLayoutRouteImport.update({ id: '/_first', getParentRoute: () => rootRouteImport, } as any) -const postsPostsRoute = postsPostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const layoutSecondLayoutRoute = layoutSecondLayoutRouteImport.update({ - id: '/_second', - getParentRoute: () => layoutFirstLayoutRoute, -} as any) -const ClassicHelloRouteRoute = ClassicHelloRouteRouteImport.update({ - id: '/classic/hello', - path: '/classic/hello', - getParentRoute: () => rootRouteImport, -} as any) -const postsPostsHomeRoute = postsPostsHomeRouteImport.update({ +const homeRoute = homeRouteImport.update({ id: '/', path: '/', - getParentRoute: () => postsPostsRoute, + getParentRoute: () => rootRouteImport, } as any) const postsPostsDetailRoute = postsPostsDetailRouteImport.update({ id: '/$postId', path: '/$postId', getParentRoute: () => postsPostsRoute, } as any) -const aRoute = aRouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => layoutSecondLayoutRoute, +const layoutSecondLayoutRoute = layoutSecondLayoutRouteImport.update({ + id: '/_second', + getParentRoute: () => layoutFirstLayoutRoute, } as any) -const bRoute = bRouteImport.update({ - id: '/layout-b', - path: '/layout-b', - getParentRoute: () => layoutSecondLayoutRoute, +const postsPostsHomeRoute = postsPostsHomeRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => postsPostsRoute, +} as any) +const ClassicHelloRouteRoute = ClassicHelloRouteRouteImport.update({ + id: '/classic/hello', + path: '/classic/hello', + getParentRoute: () => rootRouteImport, } as any) const ClassicHelloIndexRoute = ClassicHelloIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => ClassicHelloRouteRoute, } as any) +const ClassicHelloWorldRoute = ClassicHelloWorldRouteImport.update({ + id: '/world', + path: '/world', + getParentRoute: () => ClassicHelloRouteRoute, +} as any) const ClassicHelloUniverseRoute = ClassicHelloUniverseRouteImport.update({ id: '/universe', path: '/universe', getParentRoute: () => ClassicHelloRouteRoute, } as any) -const ClassicHelloWorldRoute = ClassicHelloWorldRouteImport.update({ - id: '/world', - path: '/world', - getParentRoute: () => ClassicHelloRouteRoute, +const bRoute = bRouteImport.update({ + id: '/layout-b', + path: '/layout-b', + getParentRoute: () => layoutSecondLayoutRoute, +} as any) +const aRoute = aRouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => layoutSecondLayoutRoute, } as any) export interface FileRoutesByFullPath { @@ -166,20 +168,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof homeRouteImport - parentRoute: typeof rootRouteImport - } - '/_first': { - id: '/_first' - path: '' - fullPath: '/' - preLoaderRoute: typeof layoutFirstLayoutRouteImport - parentRoute: typeof rootRouteImport - } '/posts': { id: '/posts' path: '/posts' @@ -187,26 +175,19 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof postsPostsRouteImport parentRoute: typeof rootRouteImport } - '/_first/_second': { - id: '/_first/_second' + '/_first': { + id: '/_first' path: '' - fullPath: '/' - preLoaderRoute: typeof layoutSecondLayoutRouteImport - parentRoute: typeof layoutFirstLayoutRoute - } - '/classic/hello': { - id: '/classic/hello' - path: '/classic/hello' - fullPath: '/classic/hello' - preLoaderRoute: typeof ClassicHelloRouteRouteImport + fullPath: '' + preLoaderRoute: typeof layoutFirstLayoutRouteImport parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' + '/': { + id: '/' path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof postsPostsHomeRouteImport - parentRoute: typeof postsPostsRoute + fullPath: '/' + preLoaderRoute: typeof homeRouteImport + parentRoute: typeof rootRouteImport } '/posts/$postId': { id: '/posts/$postId' @@ -215,19 +196,26 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof postsPostsDetailRouteImport parentRoute: typeof postsPostsRoute } - '/_first/_second/layout-a': { - id: '/_first/_second/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof aRouteImport - parentRoute: typeof layoutSecondLayoutRoute + '/_first/_second': { + id: '/_first/_second' + path: '' + fullPath: '' + preLoaderRoute: typeof layoutSecondLayoutRouteImport + parentRoute: typeof layoutFirstLayoutRoute } - '/_first/_second/layout-b': { - id: '/_first/_second/layout-b' - path: '/layout-b' - fullPath: '/layout-b' - preLoaderRoute: typeof bRouteImport - parentRoute: typeof layoutSecondLayoutRoute + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof postsPostsHomeRouteImport + parentRoute: typeof postsPostsRoute + } + '/classic/hello': { + id: '/classic/hello' + path: '/classic/hello' + fullPath: '/classic/hello' + preLoaderRoute: typeof ClassicHelloRouteRouteImport + parentRoute: typeof rootRouteImport } '/classic/hello/': { id: '/classic/hello/' @@ -236,13 +224,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ClassicHelloIndexRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/classic/hello/universe': { - id: '/classic/hello/universe' - path: '/universe' - fullPath: '/classic/hello/universe' - preLoaderRoute: typeof ClassicHelloUniverseRouteImport - parentRoute: typeof ClassicHelloRouteRoute - } '/classic/hello/world': { id: '/classic/hello/world' path: '/world' @@ -250,9 +231,139 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ClassicHelloWorldRouteImport parentRoute: typeof ClassicHelloRouteRoute } + '/classic/hello/universe': { + id: '/classic/hello/universe' + path: '/universe' + fullPath: '/classic/hello/universe' + preLoaderRoute: typeof ClassicHelloUniverseRouteImport + parentRoute: typeof ClassicHelloRouteRoute + } + '/_first/_second/layout-b': { + id: '/_first/_second/layout-b' + path: '/layout-b' + fullPath: '/layout-b' + preLoaderRoute: typeof bRouteImport + parentRoute: typeof layoutSecondLayoutRoute + } + '/_first/_second/layout-a': { + id: '/_first/_second/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof aRouteImport + parentRoute: typeof layoutSecondLayoutRoute + } } } +declare module './routes/home' { + const createFileRoute: CreateFileRoute< + '/', + FileRoutesByPath['/']['parentRoute'], + FileRoutesByPath['/']['id'], + FileRoutesByPath['/']['path'], + FileRoutesByPath['/']['fullPath'] + > +} +declare module './routes/layout/first-layout' { + const createFileRoute: CreateFileRoute< + '/_first', + FileRoutesByPath['/_first']['parentRoute'], + FileRoutesByPath['/_first']['id'], + FileRoutesByPath['/_first']['path'], + FileRoutesByPath['/_first']['fullPath'] + > +} +declare module './routes/posts/posts' { + const createFileRoute: CreateFileRoute< + '/posts', + FileRoutesByPath['/posts']['parentRoute'], + FileRoutesByPath['/posts']['id'], + FileRoutesByPath['/posts']['path'], + FileRoutesByPath['/posts']['fullPath'] + > +} +declare module './routes/file-based-subtree/hello/route' { + const createFileRoute: CreateFileRoute< + '/classic/hello', + FileRoutesByPath['/classic/hello']['parentRoute'], + FileRoutesByPath['/classic/hello']['id'], + FileRoutesByPath['/classic/hello']['path'], + FileRoutesByPath['/classic/hello']['fullPath'] + > +} +declare module './routes/posts/posts-home' { + const createFileRoute: CreateFileRoute< + '/posts/', + FileRoutesByPath['/posts/']['parentRoute'], + FileRoutesByPath['/posts/']['id'], + FileRoutesByPath['/posts/']['path'], + FileRoutesByPath['/posts/']['fullPath'] + > +} +declare module './routes/layout/second-layout' { + const createFileRoute: CreateFileRoute< + '/_first/_second', + FileRoutesByPath['/_first/_second']['parentRoute'], + FileRoutesByPath['/_first/_second']['id'], + FileRoutesByPath['/_first/_second']['path'], + FileRoutesByPath['/_first/_second']['fullPath'] + > +} +declare module './routes/posts/posts-detail' { + const createFileRoute: CreateFileRoute< + '/posts/$postId', + FileRoutesByPath['/posts/$postId']['parentRoute'], + FileRoutesByPath['/posts/$postId']['id'], + FileRoutesByPath['/posts/$postId']['path'], + FileRoutesByPath['/posts/$postId']['fullPath'] + > +} +declare module './routes/a' { + const createFileRoute: CreateFileRoute< + '/_first/_second/layout-a', + FileRoutesByPath['/_first/_second/layout-a']['parentRoute'], + FileRoutesByPath['/_first/_second/layout-a']['id'], + FileRoutesByPath['/_first/_second/layout-a']['path'], + FileRoutesByPath['/_first/_second/layout-a']['fullPath'] + > +} +declare module './routes/b' { + const createFileRoute: CreateFileRoute< + '/_first/_second/layout-b', + FileRoutesByPath['/_first/_second/layout-b']['parentRoute'], + FileRoutesByPath['/_first/_second/layout-b']['id'], + FileRoutesByPath['/_first/_second/layout-b']['path'], + FileRoutesByPath['/_first/_second/layout-b']['fullPath'] + > +} +declare module './routes/file-based-subtree/hello/universe' { + const createFileRoute: CreateFileRoute< + '/classic/hello/universe', + FileRoutesByPath['/classic/hello/universe']['parentRoute'], + FileRoutesByPath['/classic/hello/universe']['id'], + FileRoutesByPath['/classic/hello/universe']['path'], + FileRoutesByPath['/classic/hello/universe']['fullPath'] + > +} +declare module './routes/file-based-subtree/hello/world' { + const createFileRoute: CreateFileRoute< + '/classic/hello/world', + FileRoutesByPath['/classic/hello/world']['parentRoute'], + FileRoutesByPath['/classic/hello/world']['id'], + FileRoutesByPath['/classic/hello/world']['path'], + FileRoutesByPath['/classic/hello/world']['fullPath'] + > +} +declare module './routes/file-based-subtree/hello/index' { + const createFileRoute: CreateFileRoute< + '/classic/hello/', + FileRoutesByPath['/classic/hello/']['parentRoute'], + FileRoutesByPath['/classic/hello/']['id'], + FileRoutesByPath['/classic/hello/']['path'], + FileRoutesByPath['/classic/hello/']['fullPath'] + > +} + interface layoutSecondLayoutRouteChildren { aRoute: typeof aRoute bRoute: typeof bRoute diff --git a/e2e/vue-router/basic-virtual-file-based/src/routes/a.tsx b/e2e/vue-router/basic-virtual-file-based/src/routes/a.tsx index 133d40f19e..a190b24202 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routes/a.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/routes/a.tsx @@ -1,5 +1,4 @@ -import { createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute('/_first/_second/layout-a')({ +export const Route = createFileRoute({ component: LayoutAComponent, }) diff --git a/e2e/vue-router/basic-virtual-file-based/src/routes/b.tsx b/e2e/vue-router/basic-virtual-file-based/src/routes/b.tsx index caae6c1ded..505f8f6fbf 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routes/b.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/routes/b.tsx @@ -1,5 +1,4 @@ -import { createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute('/_first/_second/layout-b')({ +export const Route = createFileRoute({ component: LayoutBComponent, }) diff --git a/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/index.tsx b/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/index.tsx index 9b0d21d191..f86335e291 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/index.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/index.tsx @@ -1,4 +1,3 @@ -import { createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute('/classic/hello/')({ +export const Route = createFileRoute({ component: () =>
This is the index
, }) diff --git a/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/route.tsx b/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/route.tsx index 24c72f2fb9..f07d58fd3e 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/route.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/route.tsx @@ -1,6 +1,6 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' +import { Link, Outlet } from '@tanstack/vue-router' -export const Route = createFileRoute('/classic/hello')({ +export const Route = createFileRoute({ component: () => (
Hello! diff --git a/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/universe.tsx b/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/universe.tsx index 650dd2ee62..20b07c41cc 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/universe.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/universe.tsx @@ -1,4 +1,3 @@ -import { createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute('/classic/hello/universe')({ +export const Route = createFileRoute({ component: () =>
Hello /classic/hello/universe!
, }) diff --git a/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/world.tsx b/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/world.tsx index c752e6b5a4..4af11357a2 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/world.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/world.tsx @@ -1,4 +1,3 @@ -import { createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute('/classic/hello/world')({ +export const Route = createFileRoute({ component: () =>
Hello /classic/hello/world!
, }) diff --git a/e2e/vue-router/basic-virtual-file-based/src/routes/home.tsx b/e2e/vue-router/basic-virtual-file-based/src/routes/home.tsx index acf99ce567..510db79b73 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routes/home.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/routes/home.tsx @@ -1,5 +1,4 @@ -import { createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute('/')({ +export const Route = createFileRoute({ component: Home, }) diff --git a/e2e/vue-router/basic-virtual-file-based/src/routes/layout/first-layout.tsx b/e2e/vue-router/basic-virtual-file-based/src/routes/layout/first-layout.tsx index 7b82bcd7c5..9e66c18e33 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routes/layout/first-layout.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/routes/layout/first-layout.tsx @@ -1,6 +1,6 @@ -import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { Outlet } from '@tanstack/vue-router' -export const Route = createFileRoute('/_first')({ +export const Route = createFileRoute({ component: LayoutComponent, }) diff --git a/e2e/vue-router/basic-virtual-file-based/src/routes/layout/second-layout.tsx b/e2e/vue-router/basic-virtual-file-based/src/routes/layout/second-layout.tsx index cc1dafa5a1..acb6d2c8ae 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routes/layout/second-layout.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/routes/layout/second-layout.tsx @@ -1,6 +1,6 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' +import { Link, Outlet } from '@tanstack/vue-router' -export const Route = createFileRoute('/_first/_second')({ +export const Route = createFileRoute({ component: LayoutComponent, }) diff --git a/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts-detail.tsx b/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts-detail.tsx index aa5387a4d8..9b416bcf82 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,5 +1,4 @@ -import { defineComponent } from 'vue' -import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' +import { ErrorComponent } from '@tanstack/vue-router' import { fetchPost } from '../../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -7,20 +6,7 @@ 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')({ +export const Route = createFileRoute({ loader: async ({ params: { postId } }) => fetchPost(postId), errorComponent: PostErrorComponent as any, notFoundComponent: () => { @@ -28,3 +14,14 @@ export const Route = createFileRoute('/posts/$postId')({ }, component: PostComponent, }) + +function PostComponent() { + const post = Route.useLoaderData() + + return ( +
+

{post.value?.title}

+
{post.value?.body}
+
+ ) +} diff --git a/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts-home.tsx b/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts-home.tsx index 67a4268fae..13529228bb 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts-home.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts-home.tsx @@ -1,5 +1,4 @@ -import { createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute('/posts/')({ +export const Route = createFileRoute({ component: PostsIndexComponent, }) diff --git a/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts.tsx b/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts.tsx index 2a4e8deddd..5942bac97e 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts.tsx @@ -1,42 +1,39 @@ -import { defineComponent } from 'vue' -import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' +import { Link, Outlet } 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')({ +export const Route = createFileRoute({ 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/src/vite-env.d.ts b/e2e/vue-router/basic-virtual-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/vue-router/basic-virtual-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/vue-router/basic-virtual-file-based/tests/app.spec.ts b/e2e/vue-router/basic-virtual-file-based/tests/app.spec.ts index fbf093cd51..3e5a69ccaa 100644 --- a/e2e/vue-router/basic-virtual-file-based/tests/app.spec.ts +++ b/e2e/vue-router/basic-virtual-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/basic-virtual-file-based/tests/setup/global.setup.ts b/e2e/vue-router/basic-virtual-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basic-virtual-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-virtual-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/basic-virtual-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basic-virtual-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-virtual-file-based/vite.config.ts b/e2e/vue-router/basic-virtual-file-based/vite.config.ts index d9f5956b33..50924307e6 100644 --- a/e2e/vue-router/basic-virtual-file-based/vite.config.ts +++ b/e2e/vue-router/basic-virtual-file-based/vite.config.ts @@ -12,6 +12,7 @@ export default defineConfig({ tanstackRouter({ target: 'vue', autoCodeSplitting: true, + verboseFileRoutes: false, virtualRouteConfig: routes, }), vue(), diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/.devcontainer/devcontainer.json b/e2e/vue-router/basic-virtual-named-export-config-file-based/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/package.json b/e2e/vue-router/basic-virtual-named-export-config-file-based/package.json index d3a69ed573..3bef0ddd85 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,27 +8,27 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", + "@tailwindcss/vite": "^4.1.18", "@tanstack/router-plugin": "workspace:^", "@tanstack/virtual-file-routes": "workspace:^", "@tanstack/vue-query": "^5.90.0", "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "catalog:", - "tailwindcss": "^4.2.2", + "redaxios": "^0.5.1", + "tailwindcss": "^4.1.18", "vue": "^3.5.16" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", - "@vitejs/plugin-vue": "^6.0.5", - "@vitejs/plugin-vue-jsx": "^5.1.5", + "@vitejs/plugin-vue": "^5.2.3", + "@vitejs/plugin-vue-jsx": "^4.1.2", "typescript": "~5.8.3", - "vite": "^8.0.14", - "vue-tsc": "^3.3.8" + "vite": "^7.3.1", + "vue-tsc": "^3.1.5" } } diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/playwright.config.ts b/e2e/vue-router/basic-virtual-named-export-config-file-based/playwright.config.ts index 4eead86444..836ea41bd8 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/playwright.config.ts +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/posts.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/posts.tsx index 5f5463a668..8576a3799a 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/posts.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/a.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/a.tsx index 133d40f19e..a190b24202 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/a.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/a.tsx @@ -1,5 +1,4 @@ -import { createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute('/_first/_second/layout-a')({ +export const Route = createFileRoute({ component: LayoutAComponent, }) diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/b.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/b.tsx index caae6c1ded..505f8f6fbf 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/b.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/b.tsx @@ -1,5 +1,4 @@ -import { createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute('/_first/_second/layout-b')({ +export const Route = createFileRoute({ component: LayoutBComponent, }) diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/index.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/index.tsx index 9b0d21d191..f86335e291 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/index.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/index.tsx @@ -1,4 +1,3 @@ -import { createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute('/classic/hello/')({ +export const Route = createFileRoute({ component: () =>
This is the index
, }) diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/route.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/route.tsx index 24c72f2fb9..f07d58fd3e 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/route.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/route.tsx @@ -1,6 +1,6 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' +import { Link, Outlet } from '@tanstack/vue-router' -export const Route = createFileRoute('/classic/hello')({ +export const Route = createFileRoute({ component: () => (
Hello! diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/universe.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/universe.tsx index 650dd2ee62..20b07c41cc 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/universe.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/universe.tsx @@ -1,4 +1,3 @@ -import { createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute('/classic/hello/universe')({ +export const Route = createFileRoute({ component: () =>
Hello /classic/hello/universe!
, }) diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/world.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/world.tsx index c752e6b5a4..4af11357a2 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/world.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/world.tsx @@ -1,4 +1,3 @@ -import { createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute('/classic/hello/world')({ +export const Route = createFileRoute({ component: () =>
Hello /classic/hello/world!
, }) diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/home.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/home.tsx index acf99ce567..510db79b73 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/home.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/home.tsx @@ -1,5 +1,4 @@ -import { createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute('/')({ +export const Route = createFileRoute({ component: Home, }) diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/layout/first-layout.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/layout/first-layout.tsx index 7b82bcd7c5..9e66c18e33 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/layout/first-layout.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/layout/first-layout.tsx @@ -1,6 +1,6 @@ -import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { Outlet } from '@tanstack/vue-router' -export const Route = createFileRoute('/_first')({ +export const Route = createFileRoute({ component: LayoutComponent, }) diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/layout/second-layout.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/layout/second-layout.tsx index cc1dafa5a1..acb6d2c8ae 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/layout/second-layout.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/layout/second-layout.tsx @@ -1,6 +1,6 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' +import { Link, Outlet } from '@tanstack/vue-router' -export const Route = createFileRoute('/_first/_second')({ +export const Route = createFileRoute({ component: LayoutComponent, }) diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts-detail.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts-detail.tsx index aa5387a4d8..9b416bcf82 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,5 +1,4 @@ -import { defineComponent } from 'vue' -import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' +import { ErrorComponent } from '@tanstack/vue-router' import { fetchPost } from '../../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -7,20 +6,7 @@ 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')({ +export const Route = createFileRoute({ loader: async ({ params: { postId } }) => fetchPost(postId), errorComponent: PostErrorComponent as any, notFoundComponent: () => { @@ -28,3 +14,14 @@ export const Route = createFileRoute('/posts/$postId')({ }, component: PostComponent, }) + +function PostComponent() { + const post = Route.useLoaderData() + + return ( +
+

{post.value?.title}

+
{post.value?.body}
+
+ ) +} diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts-home.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts-home.tsx index 67a4268fae..13529228bb 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts-home.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts-home.tsx @@ -1,5 +1,4 @@ -import { createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute('/posts/')({ +export const Route = createFileRoute({ component: PostsIndexComponent, }) diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx index 2a4e8deddd..5942bac97e 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx @@ -1,42 +1,39 @@ -import { defineComponent } from 'vue' -import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' +import { Link, Outlet } 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')({ +export const Route = createFileRoute({ 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/src/vite-env.d.ts b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts b/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts index fbf093cd51..3e5a69ccaa 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts b/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/vite.config.ts b/e2e/vue-router/basic-virtual-named-export-config-file-based/vite.config.ts index f02a0c0d95..a5ba51ea2f 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/vite.config.ts +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/vite.config.ts @@ -11,6 +11,7 @@ export default defineConfig({ tanstackRouter({ target: 'vue', autoCodeSplitting: true, + verboseFileRoutes: false, virtualRouteConfig: './routes.ts', }), vue(), diff --git a/e2e/vue-router/basic-vue-query-file-based/.devcontainer/devcontainer.json b/e2e/vue-router/basic-vue-query-file-based/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-router/basic-vue-query-file-based/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-router/basic-vue-query-file-based/package.json b/e2e/vue-router/basic-vue-query-file-based/package.json index 3b4422d8d8..1fd90ccb3b 100644 --- a/e2e/vue-router/basic-vue-query-file-based/package.json +++ b/e2e/vue-router/basic-vue-query-file-based/package.json @@ -8,27 +8,27 @@ "build": "vite build && vue-tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "workspace:^", + "@tailwindcss/vite": "^4.1.18", "@tanstack/vue-query": "^5.90.0", "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "catalog:", - "tailwindcss": "^4.2.2", + "@tanstack/router-plugin": "workspace:^", + "redaxios": "^0.5.1", + "tailwindcss": "^4.1.18", "vue": "^3.5.16", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", - "@vitejs/plugin-vue": "^6.0.5", - "@vitejs/plugin-vue-jsx": "^5.1.5", + "@vitejs/plugin-vue": "^5.2.3", + "@vitejs/plugin-vue-jsx": "^4.1.2", "typescript": "~5.8.3", - "vite": "^8.0.14", - "vue-tsc": "^3.3.8" + "vite": "^7.3.1", + "vue-tsc": "^3.1.5" } } diff --git a/e2e/vue-router/basic-vue-query-file-based/playwright.config.ts b/e2e/vue-router/basic-vue-query-file-based/playwright.config.ts index fbda9bd451..6e7c123f74 100644 --- a/e2e/vue-router/basic-vue-query-file-based/playwright.config.ts +++ b/e2e/vue-router/basic-vue-query-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -12,15 +17,17 @@ export default defineConfig({ workers: 1, reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-vue-query-file-based/src/posts.tsx b/e2e/vue-router/basic-vue-query-file-based/src/posts.tsx index 1f6cb8e308..1becc2c242 100644 --- a/e2e/vue-router/basic-vue-query-file-based/src/posts.tsx +++ b/e2e/vue-router/basic-vue-query-file-based/src/posts.tsx @@ -8,7 +8,11 @@ export type PostType = { export class PostNotFoundError extends Error {} -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/basic-vue-query-file-based/src/routeTree.gen.ts b/e2e/vue-router/basic-vue-query-file-based/src/routeTree.gen.ts index 0af0e21dbd..ef4bc90b1f 100644 --- a/e2e/vue-router/basic-vue-query-file-based/src/routeTree.gen.ts +++ b/e2e/vue-router/basic-vue-query-file-based/src/routeTree.gen.ts @@ -9,33 +9,29 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as LayoutRouteImport } from './routes/_layout' import { Route as PostsRouteImport } from './routes/posts' -import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as IndexRouteImport } from './routes/index' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' +import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) const LayoutRoute = LayoutRouteImport.update({ id: '/_layout', getParentRoute: () => rootRouteImport, } as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const LayoutLayout2Route = LayoutLayout2RouteImport.update({ - id: '/_layout-2', - getParentRoute: () => LayoutRoute, -} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -46,16 +42,20 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRoute, } as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, } as any) const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ id: '/layout-b', path: '/layout-b', getParentRoute: () => LayoutLayout2Route, } as any) +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -114,20 +114,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout': { - id: '/_layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutRouteImport - parentRoute: typeof rootRouteImport - } '/posts': { id: '/posts' path: '/posts' @@ -135,12 +121,19 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } - '/_layout/_layout-2': { - id: '/_layout/_layout-2' + '/_layout': { + id: '/_layout' path: '' + fullPath: '' + preLoaderRoute: typeof LayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' fullPath: '/' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/posts/': { id: '/posts/' @@ -156,12 +149,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRoute } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route + '/_layout/_layout-2': { + id: '/_layout/_layout-2' + path: '' + fullPath: '' + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute } '/_layout/_layout-2/layout-b': { id: '/_layout/_layout-2/layout-b' @@ -170,6 +163,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport parentRoute: typeof LayoutLayout2Route } + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route + } } } diff --git a/e2e/vue-router/basic-vue-query-file-based/src/routes/posts.$postId.tsx b/e2e/vue-router/basic-vue-query-file-based/src/routes/posts.$postId.tsx index e8b66ddf5d..72109fc891 100644 --- a/e2e/vue-router/basic-vue-query-file-based/src/routes/posts.$postId.tsx +++ b/e2e/vue-router/basic-vue-query-file-based/src/routes/posts.$postId.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { ErrorComponent, useRouter } from '@tanstack/vue-router' import { useQuery } from '@tanstack/vue-query' @@ -6,21 +5,6 @@ import { PostNotFoundError } from '../posts' import { postQueryOptions } from '../postQueryOptions' import type { ErrorComponentProps } from '@tanstack/vue-router' -const PostComponent = defineComponent({ - setup() { - const params = Route.useParams() - useQuery(() => postQueryOptions(params.value.postId)) - const post = Route.useLoaderData() - - return () => ( -
-

{post.value.title}

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

{post.value.title}

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

{post.value.title}

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

{post.value.title}

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

{post.value.title}

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

{post.value.title}

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

ParamsNamedFoo

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

ParamsNamedFooPrefix

+

ParamsNamedFoo

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

ParamsNamedFooSuffix

+

ParamsNamedFooPrefix

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

ParamsNamedFooSuffix

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

ParamsWildcardSplat

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

ParamsWildcardSplatPrefix

+

ParamsWildcardSplat

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

ParamsWildcardSplatSuffix

+

ParamsWildcardSplatPrefix

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

ParamsWildcardSplatSuffix

+
{JSON.stringify(p.value)}
+
+ ) + }, }) const routeTree = rootRoute.addChildren([ diff --git a/e2e/vue-router/basic/src/posts.lazy.tsx b/e2e/vue-router/basic/src/posts.lazy.tsx index a236404d84..b2df740010 100644 --- a/e2e/vue-router/basic/src/posts.lazy.tsx +++ b/e2e/vue-router/basic/src/posts.lazy.tsx @@ -1,39 +1,36 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createLazyRoute } from '@tanstack/vue-router' -const PostsComponent = defineComponent({ - setup() { - const posts = Route.useLoaderData() - - return () => ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
- -
- ) - }, -}) - export const Route = createLazyRoute('/posts')({ component: PostsComponent, }) + +function PostsComponent() { + const posts = Route.useLoaderData() + + return ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+ +
+ ) +} diff --git a/e2e/vue-router/basic/src/posts.ts b/e2e/vue-router/basic/src/posts.ts index f72d16fee3..e859645746 100644 --- a/e2e/vue-router/basic/src/posts.ts +++ b/e2e/vue-router/basic/src/posts.ts @@ -8,7 +8,11 @@ type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/vue-router/basic/src/vite-env.d.ts b/e2e/vue-router/basic/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/vue-router/basic/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/vue-router/basic/tests/app.spec.ts b/e2e/vue-router/basic/tests/app.spec.ts index 9c0a6b6901..ec0e24d8a4 100644 --- a/e2e/vue-router/basic/tests/app.spec.ts +++ b/e2e/vue-router/basic/tests/app.spec.ts @@ -1,7 +1,8 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from '../package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/basic/tests/params.spec.ts b/e2e/vue-router/basic/tests/params.spec.ts index f673138047..ac18f39864 100644 --- a/e2e/vue-router/basic/tests/params.spec.ts +++ b/e2e/vue-router/basic/tests/params.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.describe('params operations + prefix/suffix', () => { test.beforeEach(async ({ page }) => { diff --git a/e2e/vue-router/basic/tests/setup/global.setup.ts b/e2e/vue-router/basic/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basic/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/basic/tests/setup/global.teardown.ts b/e2e/vue-router/basic/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basic/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/generator-cli-only/.devcontainer/devcontainer.json b/e2e/vue-router/generator-cli-only/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-router/generator-cli-only/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-router/generator-cli-only/package.json b/e2e/vue-router/generator-cli-only/package.json index f9324643ac..b25bb3b94c 100644 --- a/e2e/vue-router/generator-cli-only/package.json +++ b/e2e/vue-router/generator-cli-only/package.json @@ -8,24 +8,24 @@ "build": "tsr generate && vite build && tsc --noEmit", "preview": "vite preview", "start": "tsr generate && vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", + "@tailwindcss/vite": "^4.1.18", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/router-cli": "workspace:^", - "redaxios": "catalog:", + "redaxios": "^0.5.1", "vue": "^3.5.16", - "tailwindcss": "^4.2.2" + "tailwindcss": "^4.1.18" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", - "@vitejs/plugin-vue": "^6.0.5", - "@vitejs/plugin-vue-jsx": "^5.1.5", + "@vitejs/plugin-vue": "^5.2.3", + "@vitejs/plugin-vue-jsx": "^4.1.2", "typescript": "~5.8.3", - "vite": "^8.0.14", - "vue-tsc": "^3.3.8" + "vite": "^7.3.1", + "vue-tsc": "^3.1.5" } } diff --git a/e2e/vue-router/generator-cli-only/playwright.config.ts b/e2e/vue-router/generator-cli-only/playwright.config.ts index 4eead86444..c9d9a76ae7 100644 --- a/e2e/vue-router/generator-cli-only/playwright.config.ts +++ b/e2e/vue-router/generator-cli-only/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/generator-cli-only/src/posts.ts b/e2e/vue-router/generator-cli-only/src/posts.ts index f72d16fee3..e859645746 100644 --- a/e2e/vue-router/generator-cli-only/src/posts.ts +++ b/e2e/vue-router/generator-cli-only/src/posts.ts @@ -8,7 +8,11 @@ type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/vue-router/generator-cli-only/src/routeTree.gen.ts b/e2e/vue-router/generator-cli-only/src/routeTree.gen.ts index decb53754c..aabddd8880 100644 --- a/e2e/vue-router/generator-cli-only/src/routeTree.gen.ts +++ b/e2e/vue-router/generator-cli-only/src/routeTree.gen.ts @@ -9,20 +9,15 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as PostsRouteRouteImport } from './routes/posts.route' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' +import { Route as IndexRouteImport } from './routes/index' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, @@ -32,11 +27,11 @@ const PostsRouteRoute = PostsRouteRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, - } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -47,11 +42,10 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRouteRoute, } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, } as any) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ @@ -59,6 +53,12 @@ const PathlessLayoutNestedLayoutRouteBRoute = path: '/route-b', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -117,17 +117,10 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/_pathlessLayout': { id: '/_pathlessLayout' path: '' - fullPath: '/' + fullPath: '' preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } @@ -138,12 +131,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' + '/': { + id: '/' + path: '/' fullPath: '/' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/posts/': { id: '/posts/' @@ -159,12 +152,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRouteRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' + path: '' + fullPath: '' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -173,6 +166,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute + } } } diff --git a/e2e/vue-router/generator-cli-only/src/routes/posts.$postId.tsx b/e2e/vue-router/generator-cli-only/src/routes/posts.$postId.tsx index bb2d728afd..f4f1b04f88 100644 --- a/e2e/vue-router/generator-cli-only/src/routes/posts.$postId.tsx +++ b/e2e/vue-router/generator-cli-only/src/routes/posts.$postId.tsx @@ -1,21 +1,7 @@ -import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' -const PostComponent = defineComponent({ - setup() { - const post = Route.useLoaderData() - - return () => ( -
-

{post.value.title}

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

{post.value.title}

+
{post.value.body}
+
+ ) +} diff --git a/e2e/vue-router/generator-cli-only/src/routes/posts.route.tsx b/e2e/vue-router/generator-cli-only/src/routes/posts.route.tsx index 518bdc3d70..eaaa35fd5c 100644 --- a/e2e/vue-router/generator-cli-only/src/routes/posts.route.tsx +++ b/e2e/vue-router/generator-cli-only/src/routes/posts.route.tsx @@ -1,42 +1,39 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../posts' -const PostsLayoutComponent = defineComponent({ - setup() { - const posts = Route.useLoaderData() - - return () => ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
-
- -
- ) - }, -}) - export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsLayoutComponent, }) + +function PostsLayoutComponent() { + const posts = Route.useLoaderData() + + return ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+
+ +
+ ) +} diff --git a/e2e/vue-router/generator-cli-only/src/vite-env.d.ts b/e2e/vue-router/generator-cli-only/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/vue-router/generator-cli-only/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/vue-router/generator-cli-only/tests/app.spec.ts b/e2e/vue-router/generator-cli-only/tests/app.spec.ts index ced5ac9310..5a83a314f2 100644 --- a/e2e/vue-router/generator-cli-only/tests/app.spec.ts +++ b/e2e/vue-router/generator-cli-only/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/generator-cli-only/tests/setup/global.setup.ts b/e2e/vue-router/generator-cli-only/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/generator-cli-only/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/generator-cli-only/tests/setup/global.teardown.ts b/e2e/vue-router/generator-cli-only/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/generator-cli-only/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/js-only-file-based/.devcontainer/devcontainer.json b/e2e/vue-router/js-only-file-based/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-router/js-only-file-based/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-router/js-only-file-based/package.json b/e2e/vue-router/js-only-file-based/package.json index cda098978c..cf5d295884 100644 --- a/e2e/vue-router/js-only-file-based/package.json +++ b/e2e/vue-router/js-only-file-based/package.json @@ -8,24 +8,24 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", + "@tailwindcss/vite": "^4.1.18", "@tanstack/router-plugin": "workspace:^", "@tanstack/vue-query": "^5.90.0", "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "catalog:", - "tailwindcss": "^4.2.2", + "redaxios": "^0.5.1", + "tailwindcss": "^4.1.18", "vue": "^3.5.16" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", - "@vitejs/plugin-vue": "^6.0.5", - "@vitejs/plugin-vue-jsx": "^5.1.5", - "vite": "^8.0.14" + "@vitejs/plugin-vue": "^5.2.3", + "@vitejs/plugin-vue-jsx": "^4.1.2", + "vite": "^7.3.1" } } diff --git a/e2e/vue-router/js-only-file-based/playwright.config.ts b/e2e/vue-router/js-only-file-based/playwright.config.ts index 0925936d55..4f93bc1413 100644 --- a/e2e/vue-router/js-only-file-based/playwright.config.ts +++ b/e2e/vue-router/js-only-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,15 +18,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/js-only-file-based/src/posts.js b/e2e/vue-router/js-only-file-based/src/posts.js index 36c1c281f6..979e5e381c 100644 --- a/e2e/vue-router/js-only-file-based/src/posts.js +++ b/e2e/vue-router/js-only-file-based/src/posts.js @@ -2,7 +2,11 @@ import axios from 'redaxios' export class NotFoundError extends Error {} -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/vue-router/js-only-file-based/src/routeTree.gen.ts b/e2e/vue-router/js-only-file-based/src/routeTree.gen.ts index decb53754c..aabddd8880 100644 --- a/e2e/vue-router/js-only-file-based/src/routeTree.gen.ts +++ b/e2e/vue-router/js-only-file-based/src/routeTree.gen.ts @@ -9,20 +9,15 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as PostsRouteRouteImport } from './routes/posts.route' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' +import { Route as IndexRouteImport } from './routes/index' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, @@ -32,11 +27,11 @@ const PostsRouteRoute = PostsRouteRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, - } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -47,11 +42,10 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRouteRoute, } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, } as any) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ @@ -59,6 +53,12 @@ const PathlessLayoutNestedLayoutRouteBRoute = path: '/route-b', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -117,17 +117,10 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/_pathlessLayout': { id: '/_pathlessLayout' path: '' - fullPath: '/' + fullPath: '' preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } @@ -138,12 +131,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' + '/': { + id: '/' + path: '/' fullPath: '/' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/posts/': { id: '/posts/' @@ -159,12 +152,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRouteRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' + path: '' + fullPath: '' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -173,6 +166,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute + } } } diff --git a/e2e/vue-router/js-only-file-based/src/routes/posts.$postId.jsx b/e2e/vue-router/js-only-file-based/src/routes/posts.$postId.jsx index 05599a6780..b769e23862 100644 --- a/e2e/vue-router/js-only-file-based/src/routes/posts.$postId.jsx +++ b/e2e/vue-router/js-only-file-based/src/routes/posts.$postId.jsx @@ -1,22 +1,8 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { ErrorComponent } from '@tanstack/vue-router' import { fetchPost } from '../posts' -const PostComponent = defineComponent({ - setup() { - const post = Route.useLoaderData() - - return () => ( -
-

{post.value.title}

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

{post.value.title}

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

{post.value.title}

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

{post.value.title}

+
{post.value.body}
+
+ ) +} diff --git a/e2e/vue-router/rspack-basic-file-based/src/routes/posts.tsx b/e2e/vue-router/rspack-basic-file-based/src/routes/posts.tsx index 90744370ff..653918c370 100644 --- a/e2e/vue-router/rspack-basic-file-based/src/routes/posts.tsx +++ b/e2e/vue-router/rspack-basic-file-based/src/routes/posts.tsx @@ -1,43 +1,40 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../posts' -const PostsComponent = defineComponent({ - setup() { - const posts = Route.useLoaderData() - - return () => ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
-
- -
- ) - }, -}) - export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) + +function PostsComponent() { + const posts = Route.useLoaderData() + + return ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+
+ +
+ ) +} diff --git a/e2e/vue-router/rspack-basic-file-based/src/vite-env.d.ts b/e2e/vue-router/rspack-basic-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/vue-router/rspack-basic-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/vue-router/rspack-basic-file-based/tests/app.spec.ts b/e2e/vue-router/rspack-basic-file-based/tests/app.spec.ts index d230263bfe..10beff655f 100644 --- a/e2e/vue-router/rspack-basic-file-based/tests/app.spec.ts +++ b/e2e/vue-router/rspack-basic-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/rspack-basic-file-based/tests/setup/global.setup.ts b/e2e/vue-router/rspack-basic-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/rspack-basic-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/rspack-basic-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/rspack-basic-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/rspack-basic-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/rspack-basic-file-based/tsconfig.json b/e2e/vue-router/rspack-basic-file-based/tsconfig.json index 8fc6c76d61..25149257a3 100644 --- a/e2e/vue-router/rspack-basic-file-based/tsconfig.json +++ b/e2e/vue-router/rspack-basic-file-based/tsconfig.json @@ -13,6 +13,6 @@ "useDefineForClassFields": true, "allowJs": true }, - "include": ["src", "tests"], + "include": ["src", "playwright.config.ts", "tests"], "exclude": ["node_modules", "dist"] } diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/.devcontainer/devcontainer.json b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/package.json b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/package.json index 536435a09e..bc44c76d11 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,28 +7,27 @@ "build": "rsbuild build && tsc --noEmit", "preview": "rsbuild preview", "start": "rsbuild preview", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "catalog:", + "redaxios": "^0.5.1", "vue": "^3.5.16" }, "devDependencies": { - "@playwright/test": "^1.61.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", - "@tailwindcss/postcss": "^4.2.2", + "@playwright/test": "^1.50.1", + "@rsbuild/core": "^1.2.4", + "@rsbuild/plugin-babel": "^1.0.6", + "@rsbuild/plugin-vue": "^1.2.2", + "@rsbuild/plugin-vue-jsx": "^1.1.1", + "@tailwindcss/postcss": "^4.1.18", "@tanstack/router-e2e-utils": "workspace:^", "@tanstack/router-plugin": "workspace:^", "@tanstack/virtual-file-routes": "workspace:^", "postcss": "^8.5.1", - "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vue-tsc": "^3.3.8" + "tailwindcss": "^4.1.18", + "typescript": "^5.7.2", + "vue-tsc": "^3.1.5" } } diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts index 1c1d021f2f..bf3adc082c 100644 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +17,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && pnpm start --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `PUBLIC_NODE_ENV="test" PUBLIC_EXTERNAL_PORT=${EXTERNAL_PORT} PUBLIC_SERVER_PORT=${PORT} pnpm build && PUBLIC_SERVER_PORT=${PORT} pnpm start --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/rsbuild.config.ts b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/rsbuild.config.ts index e5c7e8b77e..b09f6ccda8 100644 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/rsbuild.config.ts +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/rsbuild.config.ts @@ -12,6 +12,19 @@ export default defineConfig({ pluginVue(), pluginVueJsx(), ], + source: { + define: { + // Rsbuild only defines `import.meta.env.PUBLIC_*` when the env var exists. + // When it doesn't, rspack can transform `import.meta.env` to `void 0`, which + // makes `import.meta.env.PUBLIC_*` crash at runtime. + 'import.meta.env.PUBLIC_NODE_ENV': JSON.stringify( + process.env.PUBLIC_NODE_ENV ?? '', + ), + 'import.meta.env.PUBLIC_EXTERNAL_PORT': JSON.stringify( + process.env.PUBLIC_EXTERNAL_PORT ?? '', + ), + }, + }, tools: { rspack: { plugins: [ diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx index 5f5463a668..0b557a0f65 100644 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.PUBLIC_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.PUBLIC_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/routes/posts/posts-detail.tsx b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/routes/posts/posts-detail.tsx index 5e3fe4d130..cb1924e993 100644 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/routes/posts/posts-detail.tsx +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/routes/posts/posts-detail.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -7,19 +6,6 @@ export function PostErrorComponent({ error }: ErrorComponentProps) { return } -const PostComponent = defineComponent({ - setup() { - const post = Route.useLoaderData() - - return () => ( -
-

{post.value.title}

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

{post.value.title}

+
{post.value.body}
+
+ ) +} diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx index 2a4e8deddd..265faaf650 100644 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx @@ -1,42 +1,39 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../../posts' -const PostsComponent = defineComponent({ - setup() { - const posts = Route.useLoaderData() - - return () => ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
-
- -
- ) - }, -}) - export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) + +function PostsComponent() { + const posts = Route.useLoaderData() + + return ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+
+ +
+ ) +} diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/vite-env.d.ts b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts index d230263bfe..10beff655f 100644 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tsconfig.json b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tsconfig.json index ff457aa547..23855253ad 100644 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tsconfig.json +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tsconfig.json @@ -13,6 +13,6 @@ "useDefineForClassFields": true, "allowJs": true }, - "include": ["src", "tests", "./routes.ts"], + "include": ["src", "playwright.config.ts", "tests", "./routes.ts"], "exclude": ["node_modules", "dist"] } diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/.devcontainer/devcontainer.json b/e2e/vue-router/scroll-restoration-sandbox-vite/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/index-BwsVWHwV.js b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/index-BwsVWHwV.js new file mode 100644 index 0000000000..1f78534259 --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/index-BwsVWHwV.js @@ -0,0 +1,18 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/page-with-search-BhJv4yJI.js","assets/scroll-block-BAas_Ct-.js","assets/normal-page-BPOVyYTF.js","assets/virtual-page.lazy-BCqvdivF.js","assets/lazy-with-loader-page.lazy-BzLmn584.js","assets/lazy-page.lazy-BzoMuhUY.js"])))=>i.map(i=>d[i]); +(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))n(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&n(o)}).observe(document,{childList:!0,subtree:!0});function s(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(r){if(r.ep)return;r.ep=!0;const i=s(r);fetch(r.href,i)}})();/** +* @vue/shared v3.5.25 +* (c) 2018-present Yuxi (Evan) You and Vue contributors +* @license MIT +**/function Or(e){const t=Object.create(null);for(const s of e.split(","))t[s]=1;return s=>s in t}const me={},_s=[],Xe=()=>{},Eo=()=>!1,In=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),Ar=e=>e.startsWith("onUpdate:"),be=Object.assign,Nr=(e,t)=>{const s=e.indexOf(t);s>-1&&e.splice(s,1)},tc=Object.prototype.hasOwnProperty,le=(e,t)=>tc.call(e,t),X=Array.isArray,bs=e=>Ln(e)==="[object Map]",sc=e=>Ln(e)==="[object Set]",Y=e=>typeof e=="function",xe=e=>typeof e=="string",as=e=>typeof e=="symbol",ge=e=>e!==null&&typeof e=="object",Oo=e=>(ge(e)||Y(e))&&Y(e.then)&&Y(e.catch),nc=Object.prototype.toString,Ln=e=>nc.call(e),rc=e=>Ln(e).slice(8,-1),ic=e=>Ln(e)==="[object Object]",Fr=e=>xe(e)&&e!=="NaN"&&e[0]!=="-"&&""+parseInt(e,10)===e,xs=Or(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),Mn=e=>{const t=Object.create(null);return(s=>t[s]||(t[s]=e(s)))},oc=/-\w/g,Pt=Mn(e=>e.replace(oc,t=>t.slice(1).toUpperCase())),ac=/\B([A-Z])/g,Zt=Mn(e=>e.replace(ac,"-$1").toLowerCase()),Ao=Mn(e=>e.charAt(0).toUpperCase()+e.slice(1)),Un=Mn(e=>e?`on${Ao(e)}`:""),xt=(e,t)=>!Object.is(e,t),Hn=(e,...t)=>{for(let s=0;s{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:n,value:s})},cc=e=>{const t=parseFloat(e);return isNaN(t)?e:t},lc=e=>{const t=xe(e)?Number(e):NaN;return isNaN(t)?e:t};let Ri;const En=()=>Ri||(Ri=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});function $r(e){if(X(e)){const t={};for(let s=0;s{if(s){const n=s.split(fc);n.length>1&&(t[n[0].trim()]=n[1].trim())}}),t}function Br(e){let t="";if(xe(e))t=e;else if(X(e))for(let s=0;s0&&--this._on===0&&(Ee=this.prevScope,this.prevScope=void 0)}stop(t){if(this._active){this._active=!1;let s,n;for(s=0,n=this.effects.length;s0)return;if(Ss){let t=Ss;for(Ss=void 0;t;){const s=t.next;t.next=void 0,t.flags&=-9,t=s}}let e;for(;ws;){let t=ws;for(ws=void 0;t;){const s=t.next;if(t.next=void 0,t.flags&=-9,t.flags&1)try{t.trigger()}catch(n){e||(e=n)}t=s}}if(e)throw e}function jo(e){for(let t=e.deps;t;t=t.nextDep)t.version=-1,t.prevActiveLink=t.dep.activeLink,t.dep.activeLink=t}function Do(e){let t,s=e.depsTail,n=s;for(;n;){const r=n.prevDep;n.version===-1?(n===s&&(s=r),Vr(n),yc(n)):t=n,n.dep.activeLink=n.prevActiveLink,n.prevActiveLink=void 0,n=r}e.deps=t,e.depsTail=s}function lr(e){for(let t=e.deps;t;t=t.nextDep)if(t.dep.version!==t.version||t.dep.computed&&(Vo(t.dep.computed)||t.dep.version!==t.version))return!0;return!!e._dirty}function Vo(e){if(e.flags&4&&!(e.flags&16)||(e.flags&=-17,e.globalVersion===Ms)||(e.globalVersion=Ms,!e.isSSR&&e.flags&128&&(!e.deps&&!e._dirty||!lr(e))))return;e.flags|=2;const t=e.dep,s=pe,n=He;pe=e,He=!0;try{jo(e);const r=e.fn(e._value);(t.version===0||xt(r,e._value))&&(e.flags|=128,e._value=r,t.version++)}catch(r){throw t.version++,r}finally{pe=s,He=n,Do(e),e.flags&=-3}}function Vr(e,t=!1){const{dep:s,prevSub:n,nextSub:r}=e;if(n&&(n.nextSub=r,e.prevSub=void 0),r&&(r.prevSub=n,e.nextSub=void 0),s.subs===e&&(s.subs=n,!n&&s.computed)){s.computed.flags&=-5;for(let i=s.computed.deps;i;i=i.nextDep)Vr(i,!0)}!t&&!--s.sc&&s.map&&s.map.delete(s.key)}function yc(e){const{prevDep:t,nextDep:s}=e;t&&(t.nextDep=s,e.prevDep=void 0),s&&(s.prevDep=t,e.nextDep=void 0)}function _c(e,t){e.effect instanceof an&&(e=e.effect.fn);const s=new an(e);t&&be(s,t);try{s.run()}catch(r){throw s.stop(),r}const n=s.run.bind(s);return n.effect=s,n}let He=!0;const Uo=[];function ct(){Uo.push(He),He=!1}function lt(){const e=Uo.pop();He=e===void 0?!0:e}function Ci(e){const{cleanup:t}=e;if(e.cleanup=void 0,t){const s=pe;pe=void 0;try{t()}finally{pe=s}}}let Ms=0,bc=class{constructor(t,s){this.sub=t,this.dep=s,this.version=s.version,this.nextDep=this.prevDep=this.nextSub=this.prevSub=this.prevActiveLink=void 0}};class Ur{constructor(t){this.computed=t,this.version=0,this.activeLink=void 0,this.subs=void 0,this.map=void 0,this.key=void 0,this.sc=0,this.__v_skip=!0}track(t){if(!pe||!He||pe===this.computed)return;let s=this.activeLink;if(s===void 0||s.sub!==pe)s=this.activeLink=new bc(pe,this),pe.deps?(s.prevDep=pe.depsTail,pe.depsTail.nextDep=s,pe.depsTail=s):pe.deps=pe.depsTail=s,Ho(s);else if(s.version===-1&&(s.version=this.version,s.nextDep)){const n=s.nextDep;n.prevDep=s.prevDep,s.prevDep&&(s.prevDep.nextDep=n),s.prevDep=pe.depsTail,s.nextDep=void 0,pe.depsTail.nextDep=s,pe.depsTail=s,pe.deps===s&&(pe.deps=n)}return s}trigger(t){this.version++,Ms++,this.notify(t)}notify(t){jr();try{for(let s=this.subs;s;s=s.prevSub)s.sub.notify()&&s.sub.dep.notify()}finally{Dr()}}}function Ho(e){if(e.dep.sc++,e.sub.flags&4){const t=e.dep.computed;if(t&&!e.dep.subs){t.flags|=20;for(let n=t.deps;n;n=n.nextDep)Ho(n)}const s=e.dep.subs;s!==e&&(e.prevSub=s,s&&(s.nextSub=e)),e.dep.subs=e}}const ur=new WeakMap,Ft=Symbol(""),fr=Symbol(""),Es=Symbol("");function Se(e,t,s){if(He&&pe){let n=ur.get(e);n||ur.set(e,n=new Map);let r=n.get(s);r||(n.set(s,r=new Ur),r.map=n,r.key=s),r.track()}}function ot(e,t,s,n,r,i){const o=ur.get(e);if(!o){Ms++;return}const a=c=>{c&&c.trigger()};if(jr(),t==="clear")o.forEach(a);else{const c=X(e),u=c&&Fr(s);if(c&&s==="length"){const f=Number(n);o.forEach((l,d)=>{(d==="length"||d===Es||!as(d)&&d>=f)&&a(l)})}else switch((s!==void 0||o.has(void 0))&&a(o.get(s)),u&&a(o.get(Es)),t){case"add":c?u&&a(o.get("length")):(a(o.get(Ft)),bs(e)&&a(o.get(fr)));break;case"delete":c||(a(o.get(Ft)),bs(e)&&a(o.get(fr)));break;case"set":bs(e)&&a(o.get(Ft));break}}Dr()}function zt(e){const t=ae(e);return t===e?t:(Se(t,"iterate",Es),Ze(e)?t:t.map(ut))}function Hr(e){return Se(e=ae(e),"iterate",Es),e}function ht(e,t){return kt(e)?Jt(e)?Os(ut(t)):Os(t):ut(t)}const xc={__proto__:null,[Symbol.iterator](){return Wn(this,Symbol.iterator,e=>ht(this,e))},concat(...e){return zt(this).concat(...e.map(t=>X(t)?zt(t):t))},entries(){return Wn(this,"entries",e=>(e[1]=ht(this,e[1]),e))},every(e,t){return rt(this,"every",e,t,void 0,arguments)},filter(e,t){return rt(this,"filter",e,t,s=>s.map(n=>ht(this,n)),arguments)},find(e,t){return rt(this,"find",e,t,s=>ht(this,s),arguments)},findIndex(e,t){return rt(this,"findIndex",e,t,void 0,arguments)},findLast(e,t){return rt(this,"findLast",e,t,s=>ht(this,s),arguments)},findLastIndex(e,t){return rt(this,"findLastIndex",e,t,void 0,arguments)},forEach(e,t){return rt(this,"forEach",e,t,void 0,arguments)},includes(...e){return zn(this,"includes",e)},indexOf(...e){return zn(this,"indexOf",e)},join(e){return zt(this).join(e)},lastIndexOf(...e){return zn(this,"lastIndexOf",e)},map(e,t){return rt(this,"map",e,t,void 0,arguments)},pop(){return hs(this,"pop")},push(...e){return hs(this,"push",e)},reduce(e,...t){return Pi(this,"reduce",e,t)},reduceRight(e,...t){return Pi(this,"reduceRight",e,t)},shift(){return hs(this,"shift")},some(e,t){return rt(this,"some",e,t,void 0,arguments)},splice(...e){return hs(this,"splice",e)},toReversed(){return zt(this).toReversed()},toSorted(e){return zt(this).toSorted(e)},toSpliced(...e){return zt(this).toSpliced(...e)},unshift(...e){return hs(this,"unshift",e)},values(){return Wn(this,"values",e=>ht(this,e))}};function Wn(e,t,s){const n=Hr(e),r=n[t]();return n!==e&&!Ze(e)&&(r._next=r.next,r.next=()=>{const i=r._next();return i.done||(i.value=s(i.value)),i}),r}const wc=Array.prototype;function rt(e,t,s,n,r,i){const o=Hr(e),a=o!==e&&!Ze(e),c=o[t];if(c!==wc[t]){const l=c.apply(e,i);return a?ut(l):l}let u=s;o!==e&&(a?u=function(l,d){return s.call(this,ht(e,l),d,e)}:s.length>2&&(u=function(l,d){return s.call(this,l,d,e)}));const f=c.call(o,u,n);return a&&r?r(f):f}function Pi(e,t,s,n){const r=Hr(e);let i=s;return r!==e&&(Ze(e)?s.length>3&&(i=function(o,a,c){return s.call(this,o,a,c,e)}):i=function(o,a,c){return s.call(this,o,ht(e,a),c,e)}),r[t](i,...n)}function zn(e,t,s){const n=ae(e);Se(n,"iterate",Es);const r=n[t](...s);return(r===-1||r===!1)&&Kr(s[0])?(s[0]=ae(s[0]),n[t](...s)):r}function hs(e,t,s=[]){ct(),jr();const n=ae(e)[t].apply(e,s);return Dr(),lt(),n}const Sc=Or("__proto__,__v_isRef,__isVue"),Zo=new Set(Object.getOwnPropertyNames(Symbol).filter(e=>e!=="arguments"&&e!=="caller").map(e=>Symbol[e]).filter(as));function Rc(e){as(e)||(e=String(e));const t=ae(this);return Se(t,"has",e),t.hasOwnProperty(e)}class Wo{constructor(t=!1,s=!1){this._isReadonly=t,this._isShallow=s}get(t,s,n){if(s==="__v_skip")return t.__v_skip;const r=this._isReadonly,i=this._isShallow;if(s==="__v_isReactive")return!r;if(s==="__v_isReadonly")return r;if(s==="__v_isShallow")return i;if(s==="__v_raw")return n===(r?i?Ac:Go:i?qo:Ko).get(t)||Object.getPrototypeOf(t)===Object.getPrototypeOf(n)?t:void 0;const o=X(t);if(!r){let c;if(o&&(c=xc[s]))return c;if(s==="hasOwnProperty")return Rc}const a=Reflect.get(t,s,Re(t)?t:n);if((as(s)?Zo.has(s):Sc(s))||(r||Se(t,"get",s),i))return a;if(Re(a)){const c=o&&Fr(s)?a:a.value;return r&&ge(c)?cn(c):c}return ge(a)?r?cn(a):Wr(a):a}}class zo extends Wo{constructor(t=!1){super(!1,t)}set(t,s,n,r){let i=t[s];const o=X(t)&&Fr(s);if(!this._isShallow){const u=kt(i);if(!Ze(n)&&!kt(n)&&(i=ae(i),n=ae(n)),!o&&Re(i)&&!Re(n))return u||(i.value=n),!0}const a=o?Number(s)e,Gs=e=>Reflect.getPrototypeOf(e);function Ic(e,t,s){return function(...n){const r=this.__v_raw,i=ae(r),o=bs(i),a=e==="entries"||e===Symbol.iterator&&o,c=e==="keys"&&o,u=r[e](...n),f=s?dr:t?Os:ut;return!t&&Se(i,"iterate",c?fr:Ft),{next(){const{value:l,done:d}=u.next();return d?{value:l,done:d}:{value:a?[f(l[0]),f(l[1])]:f(l),done:d}},[Symbol.iterator](){return this}}}}function Js(e){return function(...t){return e==="delete"?!1:e==="clear"?void 0:this}}function Lc(e,t){const s={get(r){const i=this.__v_raw,o=ae(i),a=ae(r);e||(xt(r,a)&&Se(o,"get",r),Se(o,"get",a));const{has:c}=Gs(o),u=t?dr:e?Os:ut;if(c.call(o,r))return u(i.get(r));if(c.call(o,a))return u(i.get(a));i!==o&&i.get(r)},get size(){const r=this.__v_raw;return!e&&Se(ae(r),"iterate",Ft),r.size},has(r){const i=this.__v_raw,o=ae(i),a=ae(r);return e||(xt(r,a)&&Se(o,"has",r),Se(o,"has",a)),r===a?i.has(r):i.has(r)||i.has(a)},forEach(r,i){const o=this,a=o.__v_raw,c=ae(a),u=t?dr:e?Os:ut;return!e&&Se(c,"iterate",Ft),a.forEach((f,l)=>r.call(i,u(f),u(l),o))}};return be(s,e?{add:Js("add"),set:Js("set"),delete:Js("delete"),clear:Js("clear")}:{add(r){!t&&!Ze(r)&&!kt(r)&&(r=ae(r));const i=ae(this);return Gs(i).has.call(i,r)||(i.add(r),ot(i,"add",r,r)),this},set(r,i){!t&&!Ze(i)&&!kt(i)&&(i=ae(i));const o=ae(this),{has:a,get:c}=Gs(o);let u=a.call(o,r);u||(r=ae(r),u=a.call(o,r));const f=c.call(o,r);return o.set(r,i),u?xt(i,f)&&ot(o,"set",r,i):ot(o,"add",r,i),this},delete(r){const i=ae(this),{has:o,get:a}=Gs(i);let c=o.call(i,r);c||(r=ae(r),c=o.call(i,r)),a&&a.call(i,r);const u=i.delete(r);return c&&ot(i,"delete",r,void 0),u},clear(){const r=ae(this),i=r.size!==0,o=r.clear();return i&&ot(r,"clear",void 0,void 0),o}}),["keys","values","entries",Symbol.iterator].forEach(r=>{s[r]=Ic(r,e,t)}),s}function Zr(e,t){const s=Lc(e,t);return(n,r,i)=>r==="__v_isReactive"?!e:r==="__v_isReadonly"?e:r==="__v_raw"?n:Reflect.get(le(s,r)&&r in n?s:n,r,i)}const Mc={get:Zr(!1,!1)},Ec={get:Zr(!1,!0)},Oc={get:Zr(!0,!1)};const Ko=new WeakMap,qo=new WeakMap,Go=new WeakMap,Ac=new WeakMap;function Nc(e){switch(e){case"Object":case"Array":return 1;case"Map":case"Set":case"WeakMap":case"WeakSet":return 2;default:return 0}}function Fc(e){return e.__v_skip||!Object.isExtensible(e)?0:Nc(rc(e))}function Wr(e){return kt(e)?e:zr(e,!1,Pc,Mc,Ko)}function $c(e){return zr(e,!1,Tc,Ec,qo)}function cn(e){return zr(e,!0,kc,Oc,Go)}function zr(e,t,s,n,r){if(!ge(e)||e.__v_raw&&!(t&&e.__v_isReactive))return e;const i=Fc(e);if(i===0)return e;const o=r.get(e);if(o)return o;const a=new Proxy(e,i===2?n:s);return r.set(e,a),a}function Jt(e){return kt(e)?Jt(e.__v_raw):!!(e&&e.__v_isReactive)}function kt(e){return!!(e&&e.__v_isReadonly)}function Ze(e){return!!(e&&e.__v_isShallow)}function Kr(e){return e?!!e.__v_raw:!1}function ae(e){const t=e&&e.__v_raw;return t?ae(t):e}function hr(e){return!le(e,"__v_skip")&&Object.isExtensible(e)&&No(e,"__v_skip",!0),e}const ut=e=>ge(e)?Wr(e):e,Os=e=>ge(e)?cn(e):e;function Re(e){return e?e.__v_isRef===!0:!1}function we(e){return Jo(e,!1)}function Bc(e){return Jo(e,!0)}function Jo(e,t){return Re(e)?e:new jc(e,t)}class jc{constructor(t,s){this.dep=new Ur,this.__v_isRef=!0,this.__v_isShallow=!1,this._rawValue=s?t:ae(t),this._value=s?t:ut(t),this.__v_isShallow=s}get value(){return this.dep.track(),this._value}set value(t){const s=this._rawValue,n=this.__v_isShallow||Ze(t)||kt(t);t=n?t:ae(t),xt(t,s)&&(this._rawValue=t,this._value=n?t:ut(t),this.dep.trigger())}}function Dc(e){return Re(e)?e.value:e}const Vc={get:(e,t,s)=>t==="__v_raw"?e:Dc(Reflect.get(e,t,s)),set:(e,t,s,n)=>{const r=e[t];return Re(r)&&!Re(s)?(r.value=s,!0):Reflect.set(e,t,s,n)}};function Yo(e){return Jt(e)?e:new Proxy(e,Vc)}class Uc{constructor(t,s,n){this.fn=t,this.setter=s,this._value=void 0,this.dep=new Ur(this),this.__v_isRef=!0,this.deps=void 0,this.depsTail=void 0,this.flags=16,this.globalVersion=Ms-1,this.next=void 0,this.effect=this,this.__v_isReadonly=!s,this.isSSR=n}notify(){if(this.flags|=16,!(this.flags&8)&&pe!==this)return Bo(this,!0),!0}get value(){const t=this.dep.track();return Vo(this),t&&(t.version=this.dep.version),this._value}set value(t){this.setter&&this.setter(t)}}function Hc(e,t,s=!1){let n,r;return Y(e)?n=e:(n=e.get,r=e.set),new Uc(n,r,s)}const Ys={},ln=new WeakMap;let At;function Zc(e,t=!1,s=At){if(s){let n=ln.get(s);n||ln.set(s,n=[]),n.push(e)}}function Wc(e,t,s=me){const{immediate:n,deep:r,once:i,scheduler:o,augmentJob:a,call:c}=s,u=C=>r?C:Ze(C)||r===!1||r===0?vt(C,1):vt(C);let f,l,d,h,g=!1,y=!1;if(Re(e)?(l=()=>e.value,g=Ze(e)):Jt(e)?(l=()=>u(e),g=!0):X(e)?(y=!0,g=e.some(C=>Jt(C)||Ze(C)),l=()=>e.map(C=>{if(Re(C))return C.value;if(Jt(C))return u(C);if(Y(C))return c?c(C,2):C()})):Y(e)?t?l=c?()=>c(e,2):e:l=()=>{if(d){ct();try{d()}finally{lt()}}const C=At;At=f;try{return c?c(e,3,[h]):e(h)}finally{At=C}}:l=Xe,t&&r){const C=l,k=r===!0?1/0:r;l=()=>vt(C(),k)}const x=vc(),b=()=>{f.stop(),x&&x.active&&Nr(x.effects,f)};if(i&&t){const C=t;t=(...k)=>{C(...k),b()}}let L=y?new Array(e.length).fill(Ys):Ys;const $=C=>{if(!(!(f.flags&1)||!f.dirty&&!C))if(t){const k=f.run();if(r||g||(y?k.some((_,D)=>xt(_,L[D])):xt(k,L))){d&&d();const _=At;At=f;try{const D=[k,L===Ys?void 0:y&&L[0]===Ys?[]:L,h];L=k,c?c(t,3,D):t(...D)}finally{At=_}}}else f.run()};return a&&a($),f=new an(l),f.scheduler=o?()=>o($,!1):$,h=C=>Zc(C,!1,f),d=f.onStop=()=>{const C=ln.get(f);if(C){if(c)c(C,4);else for(const k of C)k();ln.delete(f)}},t?n?$(!0):L=f.run():o?o($.bind(null,!0),!0):f.run(),b.pause=f.pause.bind(f),b.resume=f.resume.bind(f),b.stop=b,b}function vt(e,t=1/0,s){if(t<=0||!ge(e)||e.__v_skip||(s=s||new Map,(s.get(e)||0)>=t))return e;if(s.set(e,t),t--,Re(e))vt(e.value,t,s);else if(X(e))for(let n=0;n{vt(n,t,s)});else if(ic(e)){for(const n in e)vt(e[n],t,s);for(const n of Object.getOwnPropertySymbols(e))Object.prototype.propertyIsEnumerable.call(e,n)&&vt(e[n],t,s)}return e}/** +* @vue/runtime-core v3.5.25 +* (c) 2018-present Yuxi (Evan) You and Vue contributors +* @license MIT +**/function Zs(e,t,s,n){try{return n?e(...n):e()}catch(r){Ws(r,t,s)}}function tt(e,t,s,n){if(Y(e)){const r=Zs(e,t,s,n);return r&&Oo(r)&&r.catch(i=>{Ws(i,t,s)}),r}if(X(e)){const r=[];for(let i=0;i>>1,r=ke[n],i=As(r);i=As(s)?ke.push(e):ke.splice(Kc(t),0,e),e.flags|=1,Qo()}}function Qo(){un||(un=Xo.then(ta))}function mr(e){X(e)?Yt.push(...e):pt&&e.id===-1?pt.splice(Kt+1,0,e):e.flags&1||(Yt.push(e),e.flags|=1),Qo()}function ki(e,t,s=Je+1){for(;sAs(s)-As(n));if(Yt.length=0,pt){pt.push(...t);return}for(pt=t,Kt=0;Kte.id==null?e.flags&2?-1:1/0:e.id;function ta(e){try{for(Je=0;Je{n._d&&pn(-1);const i=fn(t);let o;try{o=e(...r)}finally{fn(i),n._d&&pn(1)}return o};return n._n=!0,n._c=!0,n._d=!0,n}function Et(e,t,s,n){const r=e.dirs,i=t&&t.dirs;for(let o=0;oe.__isTeleport,Yc=Symbol("_leaveCb");function Gr(e,t){e.shapeFlag&6&&e.component?(e.transition=t,Gr(e.component.subTree,t)):e.shapeFlag&128?(e.ssContent.transition=t.clone(e.ssContent),e.ssFallback.transition=t.clone(e.ssFallback)):e.transition=t}function ve(e,t){return Y(e)?be({name:e.name},t,{setup:e}):e}function na(e){e.ids=[e.ids[0]+e.ids[2]+++"-",0,0]}const dn=new WeakMap;function Rs(e,t,s,n,r=!1){if(X(e)){e.forEach((g,y)=>Rs(g,t&&(X(t)?t[y]:t),s,n,r));return}if(Cs(n)&&!r){n.shapeFlag&512&&n.type.__asyncResolved&&n.component.subTree.component&&Rs(e,t,s,n.component.subTree);return}const i=n.shapeFlag&4?ii(n.component):n.el,o=r?null:i,{i:a,r:c}=e,u=t&&t.r,f=a.refs===me?a.refs={}:a.refs,l=a.setupState,d=ae(l),h=l===me?Eo:g=>le(d,g);if(u!=null&&u!==c){if(Ti(t),xe(u))f[u]=null,h(u)&&(l[u]=null);else if(Re(u)){u.value=null;const g=t;g.k&&(f[g.k]=null)}}if(Y(c))Zs(c,a,12,[o,f]);else{const g=xe(c),y=Re(c);if(g||y){const x=()=>{if(e.f){const b=g?h(c)?l[c]:f[c]:c.value;if(r)X(b)&&Nr(b,i);else if(X(b))b.includes(i)||b.push(i);else if(g)f[c]=[i],h(c)&&(l[c]=f[c]);else{const L=[i];c.value=L,e.k&&(f[e.k]=L)}}else g?(f[c]=o,h(c)&&(l[c]=o)):y&&(c.value=o,e.k&&(f[e.k]=o))};if(o){const b=()=>{x(),dn.delete(e)};b.id=-1,dn.set(e,b),Me(b,s)}else Ti(e),x()}}}function Ti(e){const t=dn.get(e);t&&(t.flags|=8,dn.delete(e))}En().requestIdleCallback;En().cancelIdleCallback;const Cs=e=>!!e.type.__asyncLoader,ra=e=>e.type.__isKeepAlive;function Xc(e,t){ia(e,"a",t)}function Qc(e,t){ia(e,"da",t)}function ia(e,t,s=Te){const n=e.__wdc||(e.__wdc=()=>{let r=s;for(;r;){if(r.isDeactivated)return;r=r.parent}return e()});if(On(t,n,s),s){let r=s.parent;for(;r&&r.parent;)ra(r.parent.vnode)&&el(n,t,s,r),r=r.parent}}function el(e,t,s,n){const r=On(t,e,n,!0);Jr(()=>{Nr(n[t],r)},s)}function On(e,t,s=Te,n=!1){if(s){const r=s[e]||(s[e]=[]),i=t.__weh||(t.__weh=(...o)=>{ct();const a=zs(s),c=tt(t,s,e,o);return a(),lt(),c});return n?r.unshift(i):r.push(i),i}}const dt=e=>(t,s=Te)=>{(!$s||e==="sp")&&On(e,(...n)=>t(...n),s)},tl=dt("bm"),at=dt("m"),sl=dt("bu"),nl=dt("u"),rl=dt("bum"),Jr=dt("um"),il=dt("sp"),ol=dt("rtg"),al=dt("rtc");function oa(e,t=Te){On("ec",e,t)}const cl=Symbol.for("v-ndc"),gr=e=>e?Ca(e)?ii(e):gr(e.parent):null,Ps=be(Object.create(null),{$:e=>e,$el:e=>e.vnode.el,$data:e=>e.data,$props:e=>e.props,$attrs:e=>e.attrs,$slots:e=>e.slots,$refs:e=>e.refs,$parent:e=>gr(e.parent),$root:e=>gr(e.root),$host:e=>e.ce,$emit:e=>e.emit,$options:e=>Yr(e),$forceUpdate:e=>e.f||(e.f=()=>{qr(e.update)}),$nextTick:e=>e.n||(e.n=pr.bind(e.proxy)),$watch:e=>_l.bind(e)}),Kn=(e,t)=>e!==me&&!e.__isScriptSetup&&le(e,t),ll={get({_:e},t){if(t==="__v_skip")return!0;const{ctx:s,setupState:n,data:r,props:i,accessCache:o,type:a,appContext:c}=e;if(t[0]!=="$"){const d=o[t];if(d!==void 0)switch(d){case 1:return n[t];case 2:return r[t];case 4:return s[t];case 3:return i[t]}else{if(Kn(n,t))return o[t]=1,n[t];if(r!==me&&le(r,t))return o[t]=2,r[t];if(le(i,t))return o[t]=3,i[t];if(s!==me&&le(s,t))return o[t]=4,s[t];vr&&(o[t]=0)}}const u=Ps[t];let f,l;if(u)return t==="$attrs"&&Se(e.attrs,"get",""),u(e);if((f=a.__cssModules)&&(f=f[t]))return f;if(s!==me&&le(s,t))return o[t]=4,s[t];if(l=c.config.globalProperties,le(l,t))return l[t]},set({_:e},t,s){const{data:n,setupState:r,ctx:i}=e;return Kn(r,t)?(r[t]=s,!0):n!==me&&le(n,t)?(n[t]=s,!0):le(e.props,t)||t[0]==="$"&&t.slice(1)in e?!1:(i[t]=s,!0)},has({_:{data:e,setupState:t,accessCache:s,ctx:n,appContext:r,props:i,type:o}},a){let c;return!!(s[a]||e!==me&&a[0]!=="$"&&le(e,a)||Kn(t,a)||le(i,a)||le(n,a)||le(Ps,a)||le(r.config.globalProperties,a)||(c=o.__cssModules)&&c[a])},defineProperty(e,t,s){return s.get!=null?e._.accessCache[t]=0:le(s,"value")&&this.set(e,t,s.value,null),Reflect.defineProperty(e,t,s)}};function Ii(e){return X(e)?e.reduce((t,s)=>(t[s]=null,t),{}):e}let vr=!0;function ul(e){const t=Yr(e),s=e.proxy,n=e.ctx;vr=!1,t.beforeCreate&&Li(t.beforeCreate,e,"bc");const{data:r,computed:i,methods:o,watch:a,provide:c,inject:u,created:f,beforeMount:l,mounted:d,beforeUpdate:h,updated:g,activated:y,deactivated:x,beforeDestroy:b,beforeUnmount:L,destroyed:$,unmounted:C,render:k,renderTracked:_,renderTriggered:D,errorCaptured:M,serverPrefetch:B,expose:W,inheritAttrs:J,components:de,directives:P,filters:H}=t;if(u&&fl(u,n,null),o)for(const ie in o){const oe=o[ie];Y(oe)&&(n[ie]=oe.bind(s))}if(r){const ie=r.call(s,s);ge(ie)&&(e.data=Wr(ie))}if(vr=!0,i)for(const ie in i){const oe=i[ie],nt=Y(oe)?oe.bind(s,s):Y(oe.get)?oe.get.bind(s,s):Xe,Ks=!Y(oe)&&Y(oe.set)?oe.set.bind(s):Xe,Mt=fe({get:nt,set:Ks});Object.defineProperty(n,ie,{enumerable:!0,configurable:!0,get:()=>Mt.value,set:We=>Mt.value=We})}if(a)for(const ie in a)aa(a[ie],n,s,ie);if(c){const ie=Y(c)?c.call(s):c;Reflect.ownKeys(ie).forEach(oe=>{An(oe,ie[oe])})}f&&Li(f,e,"c");function Q(ie,oe){X(oe)?oe.forEach(nt=>ie(nt.bind(s))):oe&&ie(oe.bind(s))}if(Q(tl,l),Q(at,d),Q(sl,h),Q(nl,g),Q(Xc,y),Q(Qc,x),Q(oa,M),Q(al,_),Q(ol,D),Q(rl,L),Q(Jr,C),Q(il,B),X(W))if(W.length){const ie=e.exposed||(e.exposed={});W.forEach(oe=>{Object.defineProperty(ie,oe,{get:()=>s[oe],set:nt=>s[oe]=nt,enumerable:!0})})}else e.exposed||(e.exposed={});k&&e.render===Xe&&(e.render=k),J!=null&&(e.inheritAttrs=J),de&&(e.components=de),P&&(e.directives=P),B&&na(e)}function fl(e,t,s=Xe){X(e)&&(e=yr(e));for(const n in e){const r=e[n];let i;ge(r)?"default"in r?i=wt(r.from||n,r.default,!0):i=wt(r.from||n):i=wt(r),Re(i)?Object.defineProperty(t,n,{enumerable:!0,configurable:!0,get:()=>i.value,set:o=>i.value=o}):t[n]=i}}function Li(e,t,s){tt(X(e)?e.map(n=>n.bind(t.proxy)):e.bind(t.proxy),t,s)}function aa(e,t,s,n){let r=n.includes(".")?ua(s,n):()=>s[n];if(xe(e)){const i=t[e];Y(i)&&Qe(r,i)}else if(Y(e))Qe(r,e.bind(s));else if(ge(e))if(X(e))e.forEach(i=>aa(i,t,s,n));else{const i=Y(e.handler)?e.handler.bind(s):t[e.handler];Y(i)&&Qe(r,i,e)}}function Yr(e){const t=e.type,{mixins:s,extends:n}=t,{mixins:r,optionsCache:i,config:{optionMergeStrategies:o}}=e.appContext,a=i.get(t);let c;return a?c=a:!r.length&&!s&&!n?c=t:(c={},r.length&&r.forEach(u=>hn(c,u,o,!0)),hn(c,t,o)),ge(t)&&i.set(t,c),c}function hn(e,t,s,n=!1){const{mixins:r,extends:i}=t;i&&hn(e,i,s,!0),r&&r.forEach(o=>hn(e,o,s,!0));for(const o in t)if(!(n&&o==="expose")){const a=dl[o]||s&&s[o];e[o]=a?a(e[o],t[o]):t[o]}return e}const dl={data:Mi,props:Ei,emits:Ei,methods:gs,computed:gs,beforeCreate:Pe,created:Pe,beforeMount:Pe,mounted:Pe,beforeUpdate:Pe,updated:Pe,beforeDestroy:Pe,beforeUnmount:Pe,destroyed:Pe,unmounted:Pe,activated:Pe,deactivated:Pe,errorCaptured:Pe,serverPrefetch:Pe,components:gs,directives:gs,watch:pl,provide:Mi,inject:hl};function Mi(e,t){return t?e?function(){return be(Y(e)?e.call(this,this):e,Y(t)?t.call(this,this):t)}:t:e}function hl(e,t){return gs(yr(e),yr(t))}function yr(e){if(X(e)){const t={};for(let s=0;s1)return s&&Y(t)?t.call(n&&n.proxy):t}}const vl=Symbol.for("v-scx"),yl=()=>wt(vl);function la(e,t){return Xr(e,null,t)}function Qe(e,t,s){return Xr(e,t,s)}function Xr(e,t,s=me){const{immediate:n,deep:r,flush:i,once:o}=s,a=be({},s),c=t&&n||!t&&i!=="post";let u;if($s){if(i==="sync"){const h=yl();u=h.__watcherHandles||(h.__watcherHandles=[])}else if(!c){const h=()=>{};return h.stop=Xe,h.resume=Xe,h.pause=Xe,h}}const f=Te;a.call=(h,g,y)=>tt(h,f,g,y);let l=!1;i==="post"?a.scheduler=h=>{Me(h,f&&f.suspense)}:i!=="sync"&&(l=!0,a.scheduler=(h,g)=>{g?h():qr(h)}),a.augmentJob=h=>{t&&(h.flags|=4),l&&(h.flags|=2,f&&(h.id=f.uid,h.i=f))};const d=Wc(e,t,a);return $s&&(u?u.push(d):c&&d()),d}function _l(e,t,s){const n=this.proxy,r=xe(e)?e.includes(".")?ua(n,e):()=>n[e]:e.bind(n,n);let i;Y(t)?i=t:(i=t.handler,s=t);const o=zs(this),a=Xr(r,i.bind(n),s);return o(),a}function ua(e,t){const s=t.split(".");return()=>{let n=e;for(let r=0;rt==="modelValue"||t==="model-value"?e.modelModifiers:e[`${t}Modifiers`]||e[`${Pt(t)}Modifiers`]||e[`${Zt(t)}Modifiers`];function xl(e,t,...s){if(e.isUnmounted)return;const n=e.vnode.props||me;let r=s;const i=t.startsWith("update:"),o=i&&bl(n,t.slice(7));o&&(o.trim&&(r=s.map(f=>xe(f)?f.trim():f)),o.number&&(r=s.map(cc)));let a,c=n[a=Un(t)]||n[a=Un(Pt(t))];!c&&i&&(c=n[a=Un(Zt(t))]),c&&tt(c,e,6,r);const u=n[a+"Once"];if(u){if(!e.emitted)e.emitted={};else if(e.emitted[a])return;e.emitted[a]=!0,tt(u,e,6,r)}}const wl=new WeakMap;function fa(e,t,s=!1){const n=s?wl:t.emitsCache,r=n.get(e);if(r!==void 0)return r;const i=e.emits;let o={},a=!1;if(!Y(e)){const c=u=>{const f=fa(u,t,!0);f&&(a=!0,be(o,f))};!s&&t.mixins.length&&t.mixins.forEach(c),e.extends&&c(e.extends),e.mixins&&e.mixins.forEach(c)}return!i&&!a?(ge(e)&&n.set(e,null),null):(X(i)?i.forEach(c=>o[c]=null):be(o,i),ge(e)&&n.set(e,o),o)}function Nn(e,t){return!e||!In(t)?!1:(t=t.slice(2).replace(/Once$/,""),le(e,t[0].toLowerCase()+t.slice(1))||le(e,Zt(t))||le(e,t))}function Oi(e){const{type:t,vnode:s,proxy:n,withProxy:r,propsOptions:[i],slots:o,attrs:a,emit:c,render:u,renderCache:f,props:l,data:d,setupState:h,ctx:g,inheritAttrs:y}=e,x=fn(e);let b,L;try{if(s.shapeFlag&4){const C=r||n,k=C;b=De(u.call(k,C,f,l,h,d,g)),L=a}else{const C=t;b=De(C.length>1?C(l,{attrs:a,slots:o,emit:c}):C(l,null)),L=t.props?a:Rl(a)}}catch(C){ks.length=0,Ws(C,e,1),b=ce(Tt)}let $=b;if(L&&y!==!1){const C=Object.keys(L),{shapeFlag:k}=$;C.length&&k&7&&(i&&C.some(Ar)&&(L=Cl(L,i)),$=es($,L,!1,!0))}return s.dirs&&($=es($,null,!1,!0),$.dirs=$.dirs?$.dirs.concat(s.dirs):s.dirs),s.transition&&Gr($,s.transition),b=$,fn(x),b}function Sl(e,t=!0){let s;for(let n=0;n{let t;for(const s in e)(s==="class"||s==="style"||In(s))&&((t||(t={}))[s]=e[s]);return t},Cl=(e,t)=>{const s={};for(const n in e)(!Ar(n)||!(n.slice(9)in t))&&(s[n]=e[n]);return s};function Pl(e,t,s){const{props:n,children:r,component:i}=e,{props:o,children:a,patchFlag:c}=t,u=i.emitsOptions;if(t.dirs||t.transition)return!0;if(s&&c>=0){if(c&1024)return!0;if(c&16)return n?Ai(n,o,u):!!o;if(c&8){const f=t.dynamicProps;for(let l=0;lObject.create(da),pa=e=>Object.getPrototypeOf(e)===da;function kl(e,t,s,n=!1){const r={},i=ha();e.propsDefaults=Object.create(null),ma(e,t,r,i);for(const o in e.propsOptions[0])o in r||(r[o]=void 0);s?e.props=n?r:$c(r):e.type.props?e.props=r:e.props=i,e.attrs=i}function Tl(e,t,s,n){const{props:r,attrs:i,vnode:{patchFlag:o}}=e,a=ae(r),[c]=e.propsOptions;let u=!1;if((n||o>0)&&!(o&16)){if(o&8){const f=e.vnode.dynamicProps;for(let l=0;l{c=!0;const[d,h]=ga(l,t,!0);be(o,d),h&&a.push(...h)};!s&&t.mixins.length&&t.mixins.forEach(f),e.extends&&f(e.extends),e.mixins&&e.mixins.forEach(f)}if(!i&&!c)return ge(e)&&n.set(e,_s),_s;if(X(i))for(let f=0;fe==="_"||e==="_ctx"||e==="$stable",ti=e=>X(e)?e.map(De):[De(e)],Ll=(e,t,s)=>{if(t._n)return t;const n=qc((...r)=>ti(t(...r)),s);return n._c=!1,n},va=(e,t,s)=>{const n=e._ctx;for(const r in e){if(ei(r))continue;const i=e[r];if(Y(i))t[r]=Ll(r,i,n);else if(i!=null){const o=ti(i);t[r]=()=>o}}},ya=(e,t)=>{const s=ti(t);e.slots.default=()=>s},_a=(e,t,s)=>{for(const n in t)(s||!ei(n))&&(e[n]=t[n])},Ml=(e,t,s)=>{const n=e.slots=ha();if(e.vnode.shapeFlag&32){const r=t._;r?(_a(n,t,s),s&&No(n,"_",r,!0)):va(t,n)}else t&&ya(e,t)},El=(e,t,s)=>{const{vnode:n,slots:r}=e;let i=!0,o=me;if(n.shapeFlag&32){const a=t._;a?s&&a===1?i=!1:_a(r,t,s):(i=!t.$stable,va(t,r)),o=t}else t&&(ya(e,t),o={default:1});if(i)for(const a in r)!ei(a)&&o[a]==null&&delete r[a]},Me=Ul;function Ol(e){return Al(e)}function Al(e,t){const s=En();s.__VUE__=!0;const{insert:n,remove:r,patchProp:i,createElement:o,createText:a,createComment:c,setText:u,setElementText:f,parentNode:l,nextSibling:d,setScopeId:h=Xe,insertStaticContent:g}=e,y=(p,m,v,T=null,w=null,S=null,A=void 0,O=null,E=!!m.dynamicChildren)=>{if(p===m)return;p&&!yt(p,m)&&(T=qs(p),We(p,w,S,!0),p=null),m.patchFlag===-2&&(E=!1,m.dynamicChildren=null);const{type:R,ref:z,shapeFlag:F}=m;switch(R){case Fn:x(p,m,v,T);break;case Tt:b(p,m,v,T);break;case Gn:p==null&&L(m,v,T,A);break;case Fe:de(p,m,v,T,w,S,A,O,E);break;default:F&1?k(p,m,v,T,w,S,A,O,E):F&6?P(p,m,v,T,w,S,A,O,E):(F&64||F&128)&&R.process(p,m,v,T,w,S,A,O,E,fs)}z!=null&&w?Rs(z,p&&p.ref,S,m||p,!m):z==null&&p&&p.ref!=null&&Rs(p.ref,null,S,p,!0)},x=(p,m,v,T)=>{if(p==null)n(m.el=a(m.children),v,T);else{const w=m.el=p.el;m.children!==p.children&&u(w,m.children)}},b=(p,m,v,T)=>{p==null?n(m.el=c(m.children||""),v,T):m.el=p.el},L=(p,m,v,T)=>{[p.el,p.anchor]=g(p.children,m,v,T,p.el,p.anchor)},$=({el:p,anchor:m},v,T)=>{let w;for(;p&&p!==m;)w=d(p),n(p,v,T),p=w;n(m,v,T)},C=({el:p,anchor:m})=>{let v;for(;p&&p!==m;)v=d(p),r(p),p=v;r(m)},k=(p,m,v,T,w,S,A,O,E)=>{if(m.type==="svg"?A="svg":m.type==="math"&&(A="mathml"),p==null)_(m,v,T,w,S,A,O,E);else{const R=p.el&&p.el._isVueCE?p.el:null;try{R&&R._beginPatch(),B(p,m,w,S,A,O,E)}finally{R&&R._endPatch()}}},_=(p,m,v,T,w,S,A,O)=>{let E,R;const{props:z,shapeFlag:F,transition:Z,dirs:K}=p;if(E=p.el=o(p.type,S,z&&z.is,z),F&8?f(E,p.children):F&16&&M(p.children,E,null,T,w,qn(p,S),A,O),K&&Et(p,null,T,"created"),D(E,p,p.scopeId,A,T),z){for(const he in z)he!=="value"&&!xs(he)&&i(E,he,null,z[he],S,T);"value"in z&&i(E,"value",null,z.value,S),(R=z.onVnodeBeforeMount)&&Ge(R,T,p)}K&&Et(p,null,T,"beforeMount");const se=Nl(w,Z);se&&Z.beforeEnter(E),n(E,m,v),((R=z&&z.onVnodeMounted)||se||K)&&Me(()=>{R&&Ge(R,T,p),se&&Z.enter(E),K&&Et(p,null,T,"mounted")},w)},D=(p,m,v,T,w)=>{if(v&&h(p,v),T)for(let S=0;S{for(let R=E;R{const O=m.el=p.el;let{patchFlag:E,dynamicChildren:R,dirs:z}=m;E|=p.patchFlag&16;const F=p.props||me,Z=m.props||me;let K;if(v&&Ot(v,!1),(K=Z.onVnodeBeforeUpdate)&&Ge(K,v,m,p),z&&Et(m,p,v,"beforeUpdate"),v&&Ot(v,!0),(F.innerHTML&&Z.innerHTML==null||F.textContent&&Z.textContent==null)&&f(O,""),R?W(p.dynamicChildren,R,O,v,T,qn(m,w),S):A||oe(p,m,O,null,v,T,qn(m,w),S,!1),E>0){if(E&16)J(O,F,Z,v,w);else if(E&2&&F.class!==Z.class&&i(O,"class",null,Z.class,w),E&4&&i(O,"style",F.style,Z.style,w),E&8){const se=m.dynamicProps;for(let he=0;he{K&&Ge(K,v,m,p),z&&Et(m,p,v,"updated")},T)},W=(p,m,v,T,w,S,A)=>{for(let O=0;O{if(m!==v){if(m!==me)for(const S in m)!xs(S)&&!(S in v)&&i(p,S,m[S],null,w,T);for(const S in v){if(xs(S))continue;const A=v[S],O=m[S];A!==O&&S!=="value"&&i(p,S,O,A,w,T)}"value"in v&&i(p,"value",m.value,v.value,w)}},de=(p,m,v,T,w,S,A,O,E)=>{const R=m.el=p?p.el:a(""),z=m.anchor=p?p.anchor:a("");let{patchFlag:F,dynamicChildren:Z,slotScopeIds:K}=m;K&&(O=O?O.concat(K):K),p==null?(n(R,v,T),n(z,v,T),M(m.children||[],v,z,w,S,A,O,E)):F>0&&F&64&&Z&&p.dynamicChildren?(W(p.dynamicChildren,Z,v,w,S,A,O),(m.key!=null||w&&m===w.subTree)&&ba(p,m,!0)):oe(p,m,v,z,w,S,A,O,E)},P=(p,m,v,T,w,S,A,O,E)=>{m.slotScopeIds=O,p==null?m.shapeFlag&512?w.ctx.activate(m,v,T,A,E):H(m,v,T,w,S,A,E):te(p,m,E)},H=(p,m,v,T,w,S,A)=>{const O=p.component=Yl(p,T,w);if(ra(p)&&(O.ctx.renderer=fs),Ql(O,!1,A),O.asyncDep){if(w&&w.registerDep(O,Q,A),!p.el){const E=O.subTree=ce(Tt);b(null,E,m,v),p.placeholder=E.el}}else Q(O,p,m,v,w,S,A)},te=(p,m,v)=>{const T=m.component=p.component;if(Pl(p,m,v))if(T.asyncDep&&!T.asyncResolved){ie(T,m,v);return}else T.next=m,T.update();else m.el=p.el,T.vnode=m},Q=(p,m,v,T,w,S,A)=>{const O=()=>{if(p.isMounted){let{next:F,bu:Z,u:K,parent:se,vnode:he}=p;{const Ke=xa(p);if(Ke){F&&(F.el=he.el,ie(p,F,A)),Ke.asyncDep.then(()=>{p.isUnmounted||O()});return}}let ue=F,Ie;Ot(p,!1),F?(F.el=he.el,ie(p,F,A)):F=he,Z&&Hn(Z),(Ie=F.props&&F.props.onVnodeBeforeUpdate)&&Ge(Ie,se,F,he),Ot(p,!0);const Le=Oi(p),ze=p.subTree;p.subTree=Le,y(ze,Le,l(ze.el),qs(ze),p,w,S),F.el=Le.el,ue===null&&Qr(p,Le.el),K&&Me(K,w),(Ie=F.props&&F.props.onVnodeUpdated)&&Me(()=>Ge(Ie,se,F,he),w)}else{let F;const{el:Z,props:K}=m,{bm:se,m:he,parent:ue,root:Ie,type:Le}=p,ze=Cs(m);Ot(p,!1),se&&Hn(se),!ze&&(F=K&&K.onVnodeBeforeMount)&&Ge(F,ue,m),Ot(p,!0);{Ie.ce&&Ie.ce._def.shadowRoot!==!1&&Ie.ce._injectChildStyle(Le);const Ke=p.subTree=Oi(p);y(null,Ke,v,T,p,w,S),m.el=Ke.el}if(he&&Me(he,w),!ze&&(F=K&&K.onVnodeMounted)){const Ke=m;Me(()=>Ge(F,ue,Ke),w)}(m.shapeFlag&256||ue&&Cs(ue.vnode)&&ue.vnode.shapeFlag&256)&&p.a&&Me(p.a,w),p.isMounted=!0,m=v=T=null}};p.scope.on();const E=p.effect=new an(O);p.scope.off();const R=p.update=E.run.bind(E),z=p.job=E.runIfDirty.bind(E);z.i=p,z.id=p.uid,E.scheduler=()=>qr(z),Ot(p,!0),R()},ie=(p,m,v)=>{m.component=p;const T=p.vnode.props;p.vnode=m,p.next=null,Tl(p,m.props,T,v),El(p,m.children,v),ct(),ki(p),lt()},oe=(p,m,v,T,w,S,A,O,E=!1)=>{const R=p&&p.children,z=p?p.shapeFlag:0,F=m.children,{patchFlag:Z,shapeFlag:K}=m;if(Z>0){if(Z&128){Ks(R,F,v,T,w,S,A,O,E);return}else if(Z&256){nt(R,F,v,T,w,S,A,O,E);return}}K&8?(z&16&&us(R,w,S),F!==R&&f(v,F)):z&16?K&16?Ks(R,F,v,T,w,S,A,O,E):us(R,w,S,!0):(z&8&&f(v,""),K&16&&M(F,v,T,w,S,A,O,E))},nt=(p,m,v,T,w,S,A,O,E)=>{p=p||_s,m=m||_s;const R=p.length,z=m.length,F=Math.min(R,z);let Z;for(Z=0;Zz?us(p,w,S,!0,!1,F):M(m,v,T,w,S,A,O,E,F)},Ks=(p,m,v,T,w,S,A,O,E)=>{let R=0;const z=m.length;let F=p.length-1,Z=z-1;for(;R<=F&&R<=Z;){const K=p[R],se=m[R]=E?mt(m[R]):De(m[R]);if(yt(K,se))y(K,se,v,null,w,S,A,O,E);else break;R++}for(;R<=F&&R<=Z;){const K=p[F],se=m[Z]=E?mt(m[Z]):De(m[Z]);if(yt(K,se))y(K,se,v,null,w,S,A,O,E);else break;F--,Z--}if(R>F){if(R<=Z){const K=Z+1,se=KZ)for(;R<=F;)We(p[R],w,S,!0),R++;else{const K=R,se=R,he=new Map;for(R=se;R<=Z;R++){const Oe=m[R]=E?mt(m[R]):De(m[R]);Oe.key!=null&&he.set(Oe.key,R)}let ue,Ie=0;const Le=Z-se+1;let ze=!1,Ke=0;const ds=new Array(Le);for(R=0;R=Le){We(Oe,w,S,!0);continue}let qe;if(Oe.key!=null)qe=he.get(Oe.key);else for(ue=se;ue<=Z;ue++)if(ds[ue-se]===0&&yt(Oe,m[ue])){qe=ue;break}qe===void 0?We(Oe,w,S,!0):(ds[qe-se]=R+1,qe>=Ke?Ke=qe:ze=!0,y(Oe,m[qe],v,null,w,S,A,O,E),Ie++)}const xi=ze?Fl(ds):_s;for(ue=xi.length-1,R=Le-1;R>=0;R--){const Oe=se+R,qe=m[Oe],wi=m[Oe+1],Si=Oe+1{const{el:S,type:A,transition:O,children:E,shapeFlag:R}=p;if(R&6){Mt(p.component.subTree,m,v,T);return}if(R&128){p.suspense.move(m,v,T);return}if(R&64){A.move(p,m,v,fs);return}if(A===Fe){n(S,m,v);for(let F=0;FO.enter(S),w);else{const{leave:F,delayLeave:Z,afterLeave:K}=O,se=()=>{p.ctx.isUnmounted?r(S):n(S,m,v)},he=()=>{S._isLeaving&&S[Yc](!0),F(S,()=>{se(),K&&K()})};Z?Z(S,se,he):he()}else n(S,m,v)},We=(p,m,v,T=!1,w=!1)=>{const{type:S,props:A,ref:O,children:E,dynamicChildren:R,shapeFlag:z,patchFlag:F,dirs:Z,cacheIndex:K}=p;if(F===-2&&(w=!1),O!=null&&(ct(),Rs(O,null,v,p,!0),lt()),K!=null&&(m.renderCache[K]=void 0),z&256){m.ctx.deactivate(p);return}const se=z&1&&Z,he=!Cs(p);let ue;if(he&&(ue=A&&A.onVnodeBeforeUnmount)&&Ge(ue,m,p),z&6)ec(p.component,v,T);else{if(z&128){p.suspense.unmount(v,T);return}se&&Et(p,null,m,"beforeUnmount"),z&64?p.type.remove(p,m,v,fs,T):R&&!R.hasOnce&&(S!==Fe||F>0&&F&64)?us(R,m,v,!1,!0):(S===Fe&&F&384||!w&&z&16)&&us(E,m,v),T&&_i(p)}(he&&(ue=A&&A.onVnodeUnmounted)||se)&&Me(()=>{ue&&Ge(ue,m,p),se&&Et(p,null,m,"unmounted")},v)},_i=p=>{const{type:m,el:v,anchor:T,transition:w}=p;if(m===Fe){Qa(v,T);return}if(m===Gn){C(p);return}const S=()=>{r(v),w&&!w.persisted&&w.afterLeave&&w.afterLeave()};if(p.shapeFlag&1&&w&&!w.persisted){const{leave:A,delayLeave:O}=w,E=()=>A(v,S);O?O(p.el,S,E):E()}else S()},Qa=(p,m)=>{let v;for(;p!==m;)v=d(p),r(p),p=v;r(m)},ec=(p,m,v)=>{const{bum:T,scope:w,job:S,subTree:A,um:O,m:E,a:R}=p;Fi(E),Fi(R),T&&Hn(T),w.stop(),S&&(S.flags|=8,We(A,p,m,v)),O&&Me(O,m),Me(()=>{p.isUnmounted=!0},m)},us=(p,m,v,T=!1,w=!1,S=0)=>{for(let A=S;A{if(p.shapeFlag&6)return qs(p.component.subTree);if(p.shapeFlag&128)return p.suspense.next();const m=d(p.anchor||p.el),v=m&&m[Gc];return v?d(v):m};let Vn=!1;const bi=(p,m,v)=>{p==null?m._vnode&&We(m._vnode,null,null,!0):y(m._vnode||null,p,m,null,null,null,v),m._vnode=p,Vn||(Vn=!0,ki(),ea(),Vn=!1)},fs={p:y,um:We,m:Mt,r:_i,mt:H,mc:M,pc:oe,pbc:W,n:qs,o:e};return{render:bi,hydrate:void 0,createApp:gl(bi)}}function qn({type:e,props:t},s){return s==="svg"&&e==="foreignObject"||s==="mathml"&&e==="annotation-xml"&&t&&t.encoding&&t.encoding.includes("html")?void 0:s}function Ot({effect:e,job:t},s){s?(e.flags|=32,t.flags|=4):(e.flags&=-33,t.flags&=-5)}function Nl(e,t){return(!e||e&&!e.pendingBranch)&&t&&!t.persisted}function ba(e,t,s=!1){const n=e.children,r=t.children;if(X(n)&&X(r))for(let i=0;i>1,e[s[a]]0&&(t[n]=s[i-1]),s[i]=n)}}for(i=s.length,o=s[i-1];i-- >0;)s[i]=o,o=t[o];return s}function xa(e){const t=e.subTree.component;if(t)return t.asyncDep&&!t.asyncResolved?t:xa(t)}function Fi(e){if(e)for(let t=0;te.__isSuspense;let br=0;const $l={name:"Suspense",__isSuspense:!0,process(e,t,s,n,r,i,o,a,c,u){if(e==null)Bl(t,s,n,r,i,o,a,c,u);else{if(i&&i.deps>0&&!e.suspense.isInFallback){t.suspense=e.suspense,t.suspense.vnode=t,t.el=e.el;return}jl(e,t,s,n,r,o,a,c,u)}},hydrate:Dl,normalize:Vl},si=$l;function Ns(e,t){const s=e.props&&e.props[t];Y(s)&&s()}function Bl(e,t,s,n,r,i,o,a,c){const{p:u,o:{createElement:f}}=c,l=f("div"),d=e.suspense=Sa(e,r,n,t,l,s,i,o,a,c);u(null,d.pendingBranch=e.ssContent,l,null,n,d,i,o),d.deps>0?(Ns(e,"onPending"),Ns(e,"onFallback"),u(null,e.ssFallback,t,s,n,null,i,o),Qt(d,e.ssFallback)):d.resolve(!1,!0)}function jl(e,t,s,n,r,i,o,a,{p:c,um:u,o:{createElement:f}}){const l=t.suspense=e.suspense;l.vnode=t,t.el=e.el;const d=t.ssContent,h=t.ssFallback,{activeBranch:g,pendingBranch:y,isInFallback:x,isHydrating:b}=l;if(y)l.pendingBranch=d,yt(y,d)?(c(y,d,l.hiddenContainer,null,r,l,i,o,a),l.deps<=0?l.resolve():x&&(b||(c(g,h,s,n,r,null,i,o,a),Qt(l,h)))):(l.pendingId=br++,b?(l.isHydrating=!1,l.activeBranch=y):u(y,r,l),l.deps=0,l.effects.length=0,l.hiddenContainer=f("div"),x?(c(null,d,l.hiddenContainer,null,r,l,i,o,a),l.deps<=0?l.resolve():(c(g,h,s,n,r,null,i,o,a),Qt(l,h))):g&&yt(g,d)?(c(g,d,s,n,r,l,i,o,a),l.resolve(!0)):(c(null,d,l.hiddenContainer,null,r,l,i,o,a),l.deps<=0&&l.resolve()));else if(g&&yt(g,d))c(g,d,s,n,r,l,i,o,a),Qt(l,d);else if(Ns(t,"onPending"),l.pendingBranch=d,d.shapeFlag&512?l.pendingId=d.component.suspenseId:l.pendingId=br++,c(null,d,l.hiddenContainer,null,r,l,i,o,a),l.deps<=0)l.resolve();else{const{timeout:L,pendingId:$}=l;L>0?setTimeout(()=>{l.pendingId===$&&l.fallback(h)},L):L===0&&l.fallback(h)}}function Sa(e,t,s,n,r,i,o,a,c,u,f=!1){const{p:l,m:d,um:h,n:g,o:{parentNode:y,remove:x}}=u;let b;const L=Hl(e);L&&t&&t.pendingBranch&&(b=t.pendingId,t.deps++);const $=e.props?lc(e.props.timeout):void 0,C=i,k={vnode:e,parent:t,parentComponent:s,namespace:o,container:n,hiddenContainer:r,deps:0,pendingId:br++,timeout:typeof $=="number"?$:-1,activeBranch:null,pendingBranch:null,isInFallback:!f,isHydrating:f,isUnmounted:!1,effects:[],resolve(_=!1,D=!1){const{vnode:M,activeBranch:B,pendingBranch:W,pendingId:J,effects:de,parentComponent:P,container:H,isInFallback:te}=k;let Q=!1;k.isHydrating?k.isHydrating=!1:_||(Q=B&&W.transition&&W.transition.mode==="out-in",Q&&(B.transition.afterLeave=()=>{J===k.pendingId&&(d(W,H,i===C?g(B):i,0),mr(de),te&&M.ssFallback&&(M.ssFallback.el=null))}),B&&(y(B.el)===H&&(i=g(B)),h(B,P,k,!0),!Q&&te&&M.ssFallback&&Me(()=>M.ssFallback.el=null,k)),Q||d(W,H,i,0)),Qt(k,W),k.pendingBranch=null,k.isInFallback=!1;let ie=k.parent,oe=!1;for(;ie;){if(ie.pendingBranch){ie.effects.push(...de),oe=!0;break}ie=ie.parent}!oe&&!Q&&mr(de),k.effects=[],L&&t&&t.pendingBranch&&b===t.pendingId&&(t.deps--,t.deps===0&&!D&&t.resolve()),Ns(M,"onResolve")},fallback(_){if(!k.pendingBranch)return;const{vnode:D,activeBranch:M,parentComponent:B,container:W,namespace:J}=k;Ns(D,"onFallback");const de=g(M),P=()=>{k.isInFallback&&(l(null,_,W,de,B,null,J,a,c),Qt(k,_))},H=_.transition&&_.transition.mode==="out-in";H&&(M.transition.afterLeave=P),k.isInFallback=!0,h(M,B,null,!0),H||P()},move(_,D,M){k.activeBranch&&d(k.activeBranch,_,D,M),k.container=_},next(){return k.activeBranch&&g(k.activeBranch)},registerDep(_,D,M){const B=!!k.pendingBranch;B&&k.deps++;const W=_.vnode.el;_.asyncDep.catch(J=>{Ws(J,_,0)}).then(J=>{if(_.isUnmounted||k.isUnmounted||k.pendingId!==_.suspenseId)return;_.asyncResolved=!0;const{vnode:de}=_;Sr(_,J,!1),W&&(de.el=W);const P=!W&&_.subTree.el;D(_,de,y(W||_.subTree.el),W?null:g(_.subTree),k,o,M),P&&(de.placeholder=null,x(P)),Qr(_,de.el),B&&--k.deps===0&&k.resolve()})},unmount(_,D){k.isUnmounted=!0,k.activeBranch&&h(k.activeBranch,s,_,D),k.pendingBranch&&h(k.pendingBranch,s,_,D)}};return k}function Dl(e,t,s,n,r,i,o,a,c){const u=t.suspense=Sa(t,n,s,e.parentNode,document.createElement("div"),null,r,i,o,a,!0),f=c(e,u.pendingBranch=t.ssContent,s,u,i,o);return u.deps===0&&u.resolve(!1,!0),f}function Vl(e){const{shapeFlag:t,children:s}=e,n=t&32;e.ssContent=$i(n?s.default:s),e.ssFallback=n?$i(s.fallback):ce(Tt)}function $i(e){let t;if(Y(e)){const s=$n&&e._c;s&&(e._d=!1,Zl()),e=e(),s&&(e._d=!0,t=Ve,Wl())}return X(e)&&(e=Sl(e)),e=De(e),t&&!e.dynamicChildren&&(e.dynamicChildren=t.filter(s=>s!==e)),e}function Ul(e,t){t&&t.pendingBranch?X(e)?t.effects.push(...e):t.effects.push(e):mr(e)}function Qt(e,t){e.activeBranch=t;const{vnode:s,parentComponent:n}=e;let r=t.el;for(;!r&&t.component;)t=t.component.subTree,r=t.el;s.el=r,n&&n.subTree===s&&(n.vnode.el=r,Qr(n,r))}function Hl(e){const t=e.props&&e.props.suspensible;return t!=null&&t!==!1}const Fe=Symbol.for("v-fgt"),Fn=Symbol.for("v-txt"),Tt=Symbol.for("v-cmt"),Gn=Symbol.for("v-stc"),ks=[];let Ve=null;function Zl(e=!1){ks.push(Ve=e?null:[])}function Wl(){ks.pop(),Ve=ks[ks.length-1]||null}let $n=1;function pn(e,t=!1){$n+=e,e<0&&Ve&&t&&(Ve.hasOnce=!0)}function Fs(e){return e?e.__v_isVNode===!0:!1}function yt(e,t){return e.type===t.type&&e.key===t.key}const Ra=({key:e})=>e??null,sn=({ref:e,ref_key:t,ref_for:s})=>(typeof e=="number"&&(e=""+e),e!=null?xe(e)||Re(e)||Y(e)?{i:Ye,r:e,k:t,f:!!s}:e:null);function zl(e,t=null,s=null,n=0,r=null,i=e===Fe?0:1,o=!1,a=!1){const c={__v_isVNode:!0,__v_skip:!0,type:e,props:t,key:t&&Ra(t),ref:t&&sn(t),scopeId:sa,slotScopeIds:null,children:s,component:null,suspense:null,ssContent:null,ssFallback:null,dirs:null,transition:null,el:null,anchor:null,target:null,targetStart:null,targetAnchor:null,staticCount:0,shapeFlag:i,patchFlag:n,dynamicProps:r,dynamicChildren:null,appContext:null,ctx:Ye};return a?(ni(c,s),i&128&&e.normalize(c)):s&&(c.shapeFlag|=xe(s)?8:16),$n>0&&!o&&Ve&&(c.patchFlag>0||i&6)&&c.patchFlag!==32&&Ve.push(c),c}const ce=Kl;function Kl(e,t=null,s=null,n=0,r=null,i=!1){if((!e||e===cl)&&(e=Tt),Fs(e)){const a=es(e,t,!0);return s&&ni(a,s),$n>0&&!i&&Ve&&(a.shapeFlag&6?Ve[Ve.indexOf(e)]=a:Ve.push(a)),a.patchFlag=-2,a}if(nu(e)&&(e=e.__vccOpts),t){t=ql(t);let{class:a,style:c}=t;a&&!xe(a)&&(t.class=Br(a)),ge(c)&&(Kr(c)&&!X(c)&&(c=be({},c)),t.style=$r(c))}const o=xe(e)?1:wa(e)?128:Jc(e)?64:ge(e)?4:Y(e)?2:0;return zl(e,t,s,n,r,o,i,!0)}function ql(e){return e?Kr(e)||pa(e)?be({},e):e:null}function es(e,t,s=!1,n=!1){const{props:r,ref:i,patchFlag:o,children:a,transition:c}=e,u=t?ri(r||{},t):r,f={__v_isVNode:!0,__v_skip:!0,type:e.type,props:u,key:u&&Ra(u),ref:t&&t.ref?s&&i?X(i)?i.concat(sn(t)):[i,sn(t)]:sn(t):i,scopeId:e.scopeId,slotScopeIds:e.slotScopeIds,children:a,target:e.target,targetStart:e.targetStart,targetAnchor:e.targetAnchor,staticCount:e.staticCount,shapeFlag:e.shapeFlag,patchFlag:t&&e.type!==Fe?o===-1?16:o|16:o,dynamicProps:e.dynamicProps,dynamicChildren:e.dynamicChildren,appContext:e.appContext,dirs:e.dirs,transition:c,component:e.component,suspense:e.suspense,ssContent:e.ssContent&&es(e.ssContent),ssFallback:e.ssFallback&&es(e.ssFallback),placeholder:e.placeholder,el:e.el,anchor:e.anchor,ctx:e.ctx,ce:e.ce};return c&&n&&Gr(f,c.clone(f)),f}function xr(e=" ",t=0){return ce(Fn,null,e,t)}function De(e){return e==null||typeof e=="boolean"?ce(Tt):X(e)?ce(Fe,null,e.slice()):Fs(e)?mt(e):ce(Fn,null,String(e))}function mt(e){return e.el===null&&e.patchFlag!==-1||e.memo?e:es(e)}function ni(e,t){let s=0;const{shapeFlag:n}=e;if(t==null)t=null;else if(X(t))s=16;else if(typeof t=="object")if(n&65){const r=t.default;r&&(r._c&&(r._d=!1),ni(e,r()),r._c&&(r._d=!0));return}else{s=32;const r=t._;!r&&!pa(t)?t._ctx=Ye:r===3&&Ye&&(Ye.slots._===1?t._=1:(t._=2,e.patchFlag|=1024))}else Y(t)?(t={default:t,_ctx:Ye},s=32):(t=String(t),n&64?(s=16,t=[xr(t)]):s=8);e.children=t,e.shapeFlag|=s}function ri(...e){const t={};for(let s=0;sTe||Ye;let mn,wr;{const e=En(),t=(s,n)=>{let r;return(r=e[s])||(r=e[s]=[]),r.push(n),i=>{r.length>1?r.forEach(o=>o(i)):r[0](i)}};mn=t("__VUE_INSTANCE_SETTERS__",s=>Te=s),wr=t("__VUE_SSR_SETTERS__",s=>$s=s)}const zs=e=>{const t=Te;return mn(e),e.scope.on(),()=>{e.scope.off(),mn(t)}},Bi=()=>{Te&&Te.scope.off(),mn(null)};function Ca(e){return e.vnode.shapeFlag&4}let $s=!1;function Ql(e,t=!1,s=!1){t&&wr(t);const{props:n,children:r}=e.vnode,i=Ca(e);kl(e,n,i,t),Ml(e,r,s||t);const o=i?eu(e,t):void 0;return t&&wr(!1),o}function eu(e,t){const s=e.type;e.accessCache=Object.create(null),e.proxy=new Proxy(e.ctx,ll);const{setup:n}=s;if(n){ct();const r=e.setupContext=n.length>1?su(e):null,i=zs(e),o=Zs(n,e,0,[e.props,r]),a=Oo(o);if(lt(),i(),(a||e.sp)&&!Cs(e)&&na(e),a){if(o.then(Bi,Bi),t)return o.then(c=>{Sr(e,c,t)}).catch(c=>{Ws(c,e,0)});e.asyncDep=o}else Sr(e,o,t)}else Pa(e,t)}function Sr(e,t,s){Y(t)?e.type.__ssrInlineRender?e.ssrRender=t:e.render=t:ge(t)&&(e.setupState=Yo(t)),Pa(e,s)}let ji;function Pa(e,t,s){const n=e.type;if(!e.render){if(!t&&ji&&!n.render){const r=n.template||Yr(e).template;if(r){const{isCustomElement:i,compilerOptions:o}=e.appContext.config,{delimiters:a,compilerOptions:c}=n,u=be(be({isCustomElement:i,delimiters:a},o),c);n.render=ji(r,u)}}e.render=n.render||Xe}{const r=zs(e);ct();try{ul(e)}finally{lt(),r()}}}const tu={get(e,t){return Se(e,"get",""),e[t]}};function su(e){const t=s=>{e.exposed=s||{}};return{attrs:new Proxy(e.attrs,tu),slots:e.slots,emit:e.emit,expose:t}}function ii(e){return e.exposed?e.exposeProxy||(e.exposeProxy=new Proxy(Yo(hr(e.exposed)),{get(t,s){if(s in t)return t[s];if(s in Ps)return Ps[s](e)},has(t,s){return s in t||s in Ps}})):e.proxy}function nu(e){return Y(e)&&"__vccOpts"in e}const fe=(e,t)=>Hc(e,t,$s);function j(e,t,s){try{pn(-1);const n=arguments.length;return n===2?ge(t)&&!X(t)?Fs(t)?ce(e,null,[t]):ce(e,t):ce(e,null,t):(n>3?s=Array.prototype.slice.call(arguments,2):n===3&&Fs(s)&&(s=[s]),ce(e,t,s))}finally{pn(1)}}const ru="3.5.25";/** +* @vue/runtime-dom v3.5.25 +* (c) 2018-present Yuxi (Evan) You and Vue contributors +* @license MIT +**/let Rr;const Di=typeof window<"u"&&window.trustedTypes;if(Di)try{Rr=Di.createPolicy("vue",{createHTML:e=>e})}catch{}const ka=Rr?e=>Rr.createHTML(e):e=>e,iu="http://www.w3.org/2000/svg",ou="http://www.w3.org/1998/Math/MathML",it=typeof document<"u"?document:null,Vi=it&&it.createElement("template"),au={insert:(e,t,s)=>{t.insertBefore(e,s||null)},remove:e=>{const t=e.parentNode;t&&t.removeChild(e)},createElement:(e,t,s,n)=>{const r=t==="svg"?it.createElementNS(iu,e):t==="mathml"?it.createElementNS(ou,e):s?it.createElement(e,{is:s}):it.createElement(e);return e==="select"&&n&&n.multiple!=null&&r.setAttribute("multiple",n.multiple),r},createText:e=>it.createTextNode(e),createComment:e=>it.createComment(e),setText:(e,t)=>{e.nodeValue=t},setElementText:(e,t)=>{e.textContent=t},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>it.querySelector(e),setScopeId(e,t){e.setAttribute(t,"")},insertStaticContent(e,t,s,n,r,i){const o=s?s.previousSibling:t.lastChild;if(r&&(r===i||r.nextSibling))for(;t.insertBefore(r.cloneNode(!0),s),!(r===i||!(r=r.nextSibling)););else{Vi.innerHTML=ka(n==="svg"?`${e}`:n==="mathml"?`${e}`:e);const a=Vi.content;if(n==="svg"||n==="mathml"){const c=a.firstChild;for(;c.firstChild;)a.appendChild(c.firstChild);a.removeChild(c)}t.insertBefore(a,s)}return[o?o.nextSibling:t.firstChild,s?s.previousSibling:t.lastChild]}},cu=Symbol("_vtc");function lu(e,t,s){const n=e[cu];n&&(t=(t?[t,...n]:[...n]).join(" ")),t==null?e.removeAttribute("class"):s?e.setAttribute("class",t):e.className=t}const Ui=Symbol("_vod"),uu=Symbol("_vsh"),fu=Symbol(""),du=/(?:^|;)\s*display\s*:/;function hu(e,t,s){const n=e.style,r=xe(s);let i=!1;if(s&&!r){if(t)if(xe(t))for(const o of t.split(";")){const a=o.slice(0,o.indexOf(":")).trim();s[a]==null&&nn(n,a,"")}else for(const o in t)s[o]==null&&nn(n,o,"");for(const o in s)o==="display"&&(i=!0),nn(n,o,s[o])}else if(r){if(t!==s){const o=n[fu];o&&(s+=";"+o),n.cssText=s,i=du.test(s)}}else t&&e.removeAttribute("style");Ui in e&&(e[Ui]=i?n.display:"",e[uu]&&(n.display="none"))}const Hi=/\s*!important$/;function nn(e,t,s){if(X(s))s.forEach(n=>nn(e,t,n));else if(s==null&&(s=""),t.startsWith("--"))e.setProperty(t,s);else{const n=pu(e,t);Hi.test(s)?e.setProperty(Zt(n),s.replace(Hi,""),"important"):e[n]=s}}const Zi=["Webkit","Moz","ms"],Jn={};function pu(e,t){const s=Jn[t];if(s)return s;let n=Pt(t);if(n!=="filter"&&n in e)return Jn[t]=n;n=Ao(n);for(let r=0;rYn||(_u.then(()=>Yn=0),Yn=Date.now());function xu(e,t){const s=n=>{if(!n._vts)n._vts=Date.now();else if(n._vts<=s.attached)return;tt(wu(n,s.value),t,5,[n])};return s.value=e,s.attached=bu(),s}function wu(e,t){if(X(t)){const s=e.stopImmediatePropagation;return e.stopImmediatePropagation=()=>{s.call(e),e._stopped=!0},t.map(n=>r=>!r._stopped&&n&&n(r))}else return t}const Ji=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&e.charCodeAt(2)>96&&e.charCodeAt(2)<123,Su=(e,t,s,n,r,i)=>{const o=r==="svg";t==="class"?lu(e,n,o):t==="style"?hu(e,s,n):In(t)?Ar(t)||vu(e,t,s,n,i):(t[0]==="."?(t=t.slice(1),!0):t[0]==="^"?(t=t.slice(1),!1):Ru(e,t,n,o))?(Ki(e,t,n),!e.tagName.includes("-")&&(t==="value"||t==="checked"||t==="selected")&&zi(e,t,n,o,i,t!=="value")):e._isVueCE&&(/[A-Z]/.test(t)||!xe(n))?Ki(e,Pt(t),n,i,t):(t==="true-value"?e._trueValue=n:t==="false-value"&&(e._falseValue=n),zi(e,t,n,o))};function Ru(e,t,s,n){if(n)return!!(t==="innerHTML"||t==="textContent"||t in e&&Ji(t)&&Y(s));if(t==="spellcheck"||t==="draggable"||t==="translate"||t==="autocorrect"||t==="sandbox"&&e.tagName==="IFRAME"||t==="form"||t==="list"&&e.tagName==="INPUT"||t==="type"&&e.tagName==="TEXTAREA")return!1;if(t==="width"||t==="height"){const r=e.tagName;if(r==="IMG"||r==="VIDEO"||r==="CANVAS"||r==="SOURCE")return!1}return Ji(t)&&xe(s)?!1:t in e}const Cu=be({patchProp:Su},au);let Yi;function Pu(){return Yi||(Yi=Ol(Cu))}const ku=((...e)=>{const t=Pu().createApp(...e),{mount:s}=t;return t.mount=n=>{const r=Iu(n);if(!r)return;const i=t._component;!Y(i)&&!i.render&&!i.template&&(i.template=r.innerHTML),r.nodeType===1&&(r.textContent="");const o=s(r,!1,Tu(r));return r instanceof Element&&(r.removeAttribute("v-cloak"),r.setAttribute("data-v-app","")),o},t});function Tu(e){if(e instanceof SVGElement)return"svg";if(typeof MathMLElement=="function"&&e instanceof MathMLElement)return"mathml"}function Iu(e){return xe(e)?document.querySelector(e):e}const Cr=new WeakMap,Lu=new WeakMap,gn={current:[]};let Xn=!1,Ts=0;const vs=new Set,Xs=new Map;function Ta(e){for(const t of e){if(gn.current.includes(t))continue;gn.current.push(t),t.recompute();const s=Lu.get(t);if(s)for(const n of s){const r=Cr.get(n);r?.length&&Ta(r)}}}function Mu(e){const t={prevVal:e.prevState,currentVal:e.state};for(const s of e.listeners)s(t)}function Eu(e){const t={prevVal:e.prevState,currentVal:e.state};for(const s of e.listeners)s(t)}function Ia(e){if(Ts>0&&!Xs.has(e)&&Xs.set(e,e.prevState),vs.add(e),!(Ts>0)&&!Xn)try{for(Xn=!0;vs.size>0;){const t=Array.from(vs);vs.clear();for(const s of t){const n=Xs.get(s)??s.prevState;s.prevState=n,Mu(s)}for(const s of t){const n=Cr.get(s);n&&(gn.current.push(s),Ta(n))}for(const s of t){const n=Cr.get(s);if(n)for(const r of n)Eu(r)}}}finally{Xn=!1,gn.current=[],Xs.clear()}}function Is(e){Ts++;try{e()}finally{if(Ts--,Ts===0){const t=vs.values().next().value;t&&Ia(t)}}}function Ou(e){return typeof e=="function"}class Au{constructor(t,s){this.listeners=new Set,this.subscribe=n=>{var r,i;this.listeners.add(n);const o=(i=(r=this.options)==null?void 0:r.onSubscribe)==null?void 0:i.call(r,n,this);return()=>{this.listeners.delete(n),o?.()}},this.prevState=t,this.state=t,this.options=s}setState(t){var s,n,r;this.prevState=this.state,(s=this.options)!=null&&s.updateFn?this.state=this.options.updateFn(this.prevState)(t):Ou(t)?this.state=t(this.prevState):this.state=t,(r=(n=this.options)==null?void 0:n.onUpdate)==null||r.call(n),Ia(this)}}const St="__TSR_index",Xi="popstate",Qi="beforeunload";function Nu(e){let t=e.getLocation();const s=new Set,n=o=>{t=e.getLocation(),s.forEach(a=>a({location:t,action:o}))},r=o=>{e.notifyOnIndexChange??!0?n(o):t=e.getLocation()},i=async({task:o,navigateOpts:a,...c})=>{if(a?.ignoreBlocker??!1){o();return}const f=e.getBlockers?.()??[],l=c.type==="PUSH"||c.type==="REPLACE";if(typeof document<"u"&&f.length&&l)for(const d of f){const h=Bs(c.path,c.state);if(await d.blockerFn({currentLocation:t,nextLocation:h,action:c.type})){e.onBlocked?.();return}}o()};return{get location(){return t},get length(){return e.getLength()},subscribers:s,subscribe:o=>(s.add(o),()=>{s.delete(o)}),push:(o,a,c)=>{const u=t.state[St];a=eo(u+1,a),i({task:()=>{e.pushState(o,a),n({type:"PUSH"})},navigateOpts:c,type:"PUSH",path:o,state:a})},replace:(o,a,c)=>{const u=t.state[St];a=eo(u,a),i({task:()=>{e.replaceState(o,a),n({type:"REPLACE"})},navigateOpts:c,type:"REPLACE",path:o,state:a})},go:(o,a)=>{i({task:()=>{e.go(o),r({type:"GO",index:o})},navigateOpts:a,type:"GO"})},back:o=>{i({task:()=>{e.back(o?.ignoreBlocker??!1),r({type:"BACK"})},navigateOpts:o,type:"BACK"})},forward:o=>{i({task:()=>{e.forward(o?.ignoreBlocker??!1),r({type:"FORWARD"})},navigateOpts:o,type:"FORWARD"})},canGoBack:()=>t.state[St]!==0,createHref:o=>e.createHref(o),block:o=>{if(!e.setBlockers)return()=>{};const a=e.getBlockers?.()??[];return e.setBlockers([...a,o]),()=>{const c=e.getBlockers?.()??[];e.setBlockers?.(c.filter(u=>u!==o))}},flush:()=>e.flush?.(),destroy:()=>e.destroy?.(),notify:n}}function eo(e,t){t||(t={});const s=oi();return{...t,key:s,__TSR_key:s,[St]:e}}function La(e){const t=e?.window??(typeof document<"u"?window:void 0),s=t.history.pushState,n=t.history.replaceState;let r=[];const i=()=>r,o=M=>r=M,a=e?.createHref??(M=>M),c=e?.parseLocation??(()=>Bs(`${t.location.pathname}${t.location.search}${t.location.hash}`,t.history.state));if(!t.history.state?.__TSR_key&&!t.history.state?.key){const M=oi();t.history.replaceState({[St]:0,key:M,__TSR_key:M},"")}let u=c(),f,l=!1,d=!1,h=!1,g=!1;const y=()=>u;let x,b;const L=()=>{x&&(D._ignoreSubscribers=!0,(x.isPush?t.history.pushState:t.history.replaceState)(x.state,"",x.href),D._ignoreSubscribers=!1,x=void 0,b=void 0,f=void 0)},$=(M,B,W)=>{const J=a(B);b||(f=u),u=Bs(B,W),x={href:J,state:W,isPush:x?.isPush||M==="push"},b||(b=Promise.resolve().then(()=>L()))},C=M=>{u=c(),D.notify({type:M})},k=async()=>{if(d){d=!1;return}const M=c(),B=M.state[St]-u.state[St],W=B===1,J=B===-1,de=!W&&!J||l;l=!1;const P=de?"GO":J?"BACK":"FORWARD",H=de?{type:"GO",index:B}:{type:J?"BACK":"FORWARD"};if(h)h=!1;else{const te=i();if(typeof document<"u"&&te.length){for(const Q of te)if(await Q.blockerFn({currentLocation:u,nextLocation:M,action:P})){d=!0,t.history.go(1),D.notify(H);return}}}u=c(),D.notify(H)},_=M=>{if(g){g=!1;return}let B=!1;const W=i();if(typeof document<"u"&&W.length)for(const J of W){const de=J.enableBeforeUnload??!0;if(de===!0){B=!0;break}if(typeof de=="function"&&de()===!0){B=!0;break}}if(B)return M.preventDefault(),M.returnValue=""},D=Nu({getLocation:y,getLength:()=>t.history.length,pushState:(M,B)=>$("push",M,B),replaceState:(M,B)=>$("replace",M,B),back:M=>(M&&(h=!0),g=!0,t.history.back()),forward:M=>{M&&(h=!0),g=!0,t.history.forward()},go:M=>{l=!0,t.history.go(M)},createHref:M=>a(M),flush:L,destroy:()=>{t.history.pushState=s,t.history.replaceState=n,t.removeEventListener(Qi,_,{capture:!0}),t.removeEventListener(Xi,k)},onBlocked:()=>{f&&u!==f&&(u=f)},getBlockers:i,setBlockers:o,notifyOnIndexChange:!1});return t.addEventListener(Qi,_,{capture:!0}),t.addEventListener(Xi,k),t.history.pushState=function(...M){const B=s.apply(t.history,M);return D._ignoreSubscribers||C("PUSH"),B},t.history.replaceState=function(...M){const B=n.apply(t.history,M);return D._ignoreSubscribers||C("REPLACE"),B},D}function Fu(e){const t=typeof document<"u"?window:void 0;return La({window:t,parseLocation:()=>{const s=t.location.hash.split("#").slice(1),n=s[0]??"/",r=t.location.search,i=s.slice(1),o=i.length===0?"":`#${i.join("#")}`,a=`${n}${r}${o}`;return Bs(a,t.history.state)},createHref:s=>`${t.location.pathname}${t.location.search}#${s}`})}function Bs(e,t){const s=e.indexOf("#"),n=e.indexOf("?"),r=oi();return{href:e,pathname:e.substring(0,s>0?n>0?Math.min(s,n):s:n>0?n:e.length),hash:s>-1?e.substring(s):"",search:n>-1?e.slice(n,s===-1?void 0:s):"",state:t||{[St]:0,key:r,__TSR_key:r}}}function oi(){return(Math.random()+1).toString(36).substring(7)}function vn(e){return e[e.length-1]}function $u(e){return typeof e=="function"}function Gt(e,t){return $u(e)?e(t):e}const Bu=Object.prototype.hasOwnProperty;function je(e,t){if(e===t)return e;const s=t,n=no(e)&&no(s);if(!n&&!(yn(e)&&yn(s)))return s;const r=n?e:to(e);if(!r)return s;const i=n?s:to(s);if(!i)return s;const o=r.length,a=i.length,c=n?new Array(a):{};let u=0;for(let f=0;f"u")return!0;const s=t.prototype;return!(!so(s)||!s.hasOwnProperty("isPrototypeOf"))}function so(e){return Object.prototype.toString.call(e)==="[object Object]"}function no(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function $t(e,t,s){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0,r=e.length;nr||!$t(e[o],t[o],s)))return!1;return r===i}return!1}function ts(e){let t,s;const n=new Promise((r,i)=>{t=r,s=i});return n.status="pending",n.resolve=r=>{n.status="resolved",n.value=r,t(r),e?.(r)},n.reject=r=>{n.status="rejected",s(r)},n}function Rt(e){return!!(e&&typeof e=="object"&&typeof e.then=="function")}function ro(e){try{return decodeURI(e)}catch{return e.replaceAll(/%[0-9A-F]{2}/gi,t=>{try{return decodeURI(t)}catch{return t}})}}function io(e,t){if(!e)return e;const s=/%25|%5C/gi;let n=0,r="",i;for(;(i=s.exec(e))!==null;)r+=ro(e.slice(n,i.index))+i[0],n=s.lastIndex;return r+ro(n?e.slice(n):e)}var ju="Invariant failed";function Dt(e,t){if(!e)throw new Error(ju)}function _n(e){const t=new Map;let s,n;const r=i=>{i.next&&(i.prev?(i.prev.next=i.next,i.next.prev=i.prev,i.next=void 0,n&&(n.next=i,i.prev=n)):(i.next.prev=void 0,s=i.next,i.next=void 0,n&&(i.prev=n,n.next=i)),n=i)};return{get(i){const o=t.get(i);if(o)return r(o),o.value},set(i,o){if(t.size>=e&&s){const c=s;t.delete(c.key),c.next&&(s=c.next,c.next.prev=void 0),c===n&&(n=void 0)}const a=t.get(i);if(a)a.value=o,r(a);else{const c={key:i,value:o,prev:n};n&&(n.next=c),n=c,s||(s=c),t.set(i,c)}},clear(){t.clear(),s=void 0,n=void 0}}}const ss=0,Vt=1,Ut=2,js=3,Du=/^([^{]*)\{\$([a-zA-Z_$][a-zA-Z0-9_$]*)\}([^}]*)$/,Vu=/^([^{]*)\{-\$([a-zA-Z_$][a-zA-Z0-9_$]*)\}([^}]*)$/,Uu=/^([^{]*)\{\$\}([^}]*)$/;function ai(e,t,s=new Uint16Array(6)){const n=e.indexOf("/",t),r=n===-1?e.length:n,i=e.substring(t,r);if(!i||!i.includes("$"))return s[0]=ss,s[1]=t,s[2]=t,s[3]=r,s[4]=r,s[5]=r,s;if(i==="$"){const u=e.length;return s[0]=Ut,s[1]=t,s[2]=t,s[3]=u,s[4]=u,s[5]=u,s}if(i.charCodeAt(0)===36)return s[0]=Vt,s[1]=t,s[2]=t+1,s[3]=r,s[4]=r,s[5]=r,s;const o=i.match(Uu);if(o){const f=o[1].length;return s[0]=Ut,s[1]=t+f,s[2]=t+f+1,s[3]=t+f+2,s[4]=t+f+3,s[5]=e.length,s}const a=i.match(Vu);if(a){const u=a[1],f=a[2],l=a[3],d=u.length;return s[0]=js,s[1]=t+d,s[2]=t+d+3,s[3]=t+d+3+f.length,s[4]=r-l.length,s[5]=r,s}const c=i.match(Du);if(c){const u=c[1],f=c[2],l=c[3],d=u.length;return s[0]=Vt,s[1]=t+d,s[2]=t+d+2,s[3]=t+d+2+f.length,s[4]=r-l.length,s[5]=r,s}return s[0]=ss,s[1]=t,s[2]=t,s[3]=r,s[4]=r,s[5]=r,s}function Bn(e,t,s,n,r,i,o){o?.(s);let a=n;{const c=s.fullPath??s.from,u=c.length,f=s.options?.caseSensitive??e;for(;a_.caseSensitive===L&&_.prefix===$&&_.suffix===C);if(k)d=k;else{const _=er(Vt,s.fullPath??s.from,L,$,C);d=_,_.depth=i,_.parent=r,r.dynamic??=[],r.dynamic.push(_)}break}case js:{const x=c.substring(h,l[1]),b=c.substring(l[4],g),L=f&&!!(x||b),$=x?L?x:x.toLowerCase():void 0,C=b?L?b:b.toLowerCase():void 0,k=r.optional?.find(_=>_.caseSensitive===L&&_.prefix===$&&_.suffix===C);if(k)d=k;else{const _=er(js,s.fullPath??s.from,L,$,C);d=_,_.parent=r,_.depth=i,r.optional??=[],r.optional.push(_)}break}case Ut:{const x=c.substring(h,l[1]),b=c.substring(l[4],g),L=f&&!!(x||b),$=x?L?x:x.toLowerCase():void 0,C=b?L?b:b.toLowerCase():void 0,k=er(Ut,s.fullPath??s.from,L,$,C);d=k,k.parent=r,k.depth=i,r.wildcard??=[],r.wildcard.push(k)}}r=d}if((s.path||!s.children)&&!s.isRoot){const l=c.endsWith("/");l||(r.notFound=s),(!r.route||!r.isIndex&&l)&&(r.route=s,r.fullPath=s.fullPath??s.from),r.isIndex||=l}}if(s.children)for(const c of s.children)Bn(e,t,c,a,r,i,o)}function Qn(e,t){if(e.prefix&&t.prefix&&e.prefix!==t.prefix){if(e.prefix.startsWith(t.prefix))return-1;if(t.prefix.startsWith(e.prefix))return 1}if(e.suffix&&t.suffix&&e.suffix!==t.suffix){if(e.suffix.endsWith(t.suffix))return-1;if(t.suffix.endsWith(e.suffix))return 1}return e.prefix&&!t.prefix?-1:!e.prefix&&t.prefix?1:e.suffix&&!t.suffix?-1:!e.suffix&&t.suffix?1:e.caseSensitive&&!t.caseSensitive?-1:!e.caseSensitive&&t.caseSensitive?1:0}function Nt(e){if(e.static)for(const t of e.static.values())Nt(t);if(e.staticInsensitive)for(const t of e.staticInsensitive.values())Nt(t);if(e.dynamic?.length){e.dynamic.sort(Qn);for(const t of e.dynamic)Nt(t)}if(e.optional?.length){e.optional.sort(Qn);for(const t of e.optional)Nt(t)}if(e.wildcard?.length){e.wildcard.sort(Qn);for(const t of e.wildcard)Nt(t)}}function Ds(e){return{kind:ss,depth:0,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:e,parent:null,isIndex:!1,notFound:null}}function er(e,t,s,n,r){return{kind:e,depth:0,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:t,parent:null,isIndex:!1,notFound:null,caseSensitive:s,prefix:n,suffix:r}}function Hu(e,t){const s=Ds("/"),n=new Uint16Array(6);for(const r of e)Bn(!1,n,r,1,s,0);Nt(s),t.masksTree=s,t.flatCache=_n(1e3)}function Zu(e,t){e||="/";const s=t.flatCache.get(e);if(s)return s;const n=ci(e,t.masksTree);return t.flatCache.set(e,n),n}function Wu(e,t,s,n,r){e||="/",n||="/";const i=t?`case\0${e}`:e;let o=r.singleCache.get(i);if(!o){o=Ds("/");const a=new Uint16Array(6);Bn(t,a,{from:e},1,o,0),r.singleCache.set(i,o)}return ci(n,o,s)}function zu(e,t,s=!1){const n=s?e:`nofuzz\0${e}`,r=t.matchCache.get(n);if(r!==void 0)return r;e||="/";const i=ci(e,t.segmentTree,s);return i&&(i.branch=Ju(i.route)),t.matchCache.set(n,i),i}function Ku(e){return e==="/"?e:e.replace(/\/{1,}$/,"")}function qu(e,t=!1,s){const n=Ds(e.fullPath),r=new Uint16Array(6),i={},o={};let a=0;return Bn(t,r,e,1,n,0,u=>{if(s?.(u,a),Dt(!(u.id in i),`Duplicate routes found with id: ${String(u.id)}`),i[u.id]=u,a!==0&&u.path){const f=Ku(u.fullPath);(!o[f]||u.fullPath.endsWith("/"))&&(o[f]=u)}a++}),Nt(n),{processedTree:{segmentTree:n,singleCache:_n(1e3),matchCache:_n(1e3),flatCache:null,masksTree:null},routesById:i,routesByPath:o}}function ci(e,t,s=!1){const n=e.split("/"),r=Xu(e,n,t,s);if(!r)return null;const i=Gu(e,n,r),o="**"in r;return o&&(i["**"]=r["**"]),{route:o?r.node.notFound??r.node.route:r.node.route,params:i}}function Gu(e,t,s){const n=Yu(s.node);let r=null;const i={};for(let o=0,a=0,c=0;a=0;M--){const B=d.optional[M];a.push({node:B,index:h,skipped:_,depth:D,statics:x,dynamics:b,optionals:L})}if(!$)for(let M=d.optional.length-1;M>=0;M--){const B=d.optional[M],{prefix:W,suffix:J}=B;if(W||J){const de=B.caseSensitive?C:k??=C.toLowerCase();if(W&&!de.startsWith(W)||J&&!de.endsWith(J))continue}a.push({node:B,index:h+1,skipped:g,depth:D,statics:x,dynamics:b,optionals:L+1})}}if(!$&&d.dynamic&&C)for(let _=d.dynamic.length-1;_>=0;_--){const D=d.dynamic[_],{prefix:M,suffix:B}=D;if(M||B){const W=D.caseSensitive?C:k??=C.toLowerCase();if(M&&!W.startsWith(M)||B&&!W.endsWith(B))continue}a.push({node:D,index:h+1,skipped:g,depth:y+1,statics:x,dynamics:b+1,optionals:L})}if(!$&&d.staticInsensitive){const _=d.staticInsensitive.get(k??=C.toLowerCase());_&&a.push({node:_,index:h+1,skipped:g,depth:y+1,statics:x+1,dynamics:b,optionals:L})}if(!$&&d.static){const _=d.static.get(C);_&&a.push({node:_,index:h+1,skipped:g,depth:y+1,statics:x+1,dynamics:b,optionals:L})}}if(f&&c)return Qs(c,f)?f:c;if(f)return f;if(c)return c;if(n&&u){let l=u.index;for(let h=0;he.statics||t.statics===e.statics&&(t.dynamics>e.dynamics||t.dynamics===e.dynamics&&(t.optionals>e.optionals||t.optionals===e.optionals&&(t.node.isIndex>e.node.isIndex||t.node.isIndex===e.node.isIndex&&t.depth>e.depth))):!0}function rn(e){return li(e.filter(t=>t!==void 0).join("/"))}function li(e){return e.replace(/\/{2,}/g,"/")}function Ma(e){return e==="/"?e:e.replace(/^\/{1,}/,"")}function Bt(e){const t=e.length;return t>1&&e[t-1]==="/"?e.replace(/\/{1,}$/,""):e}function Ea(e){return Bt(Ma(e))}function bn(e,t){return e?.endsWith("/")&&e!=="/"&&e!==`${t}/`?e.slice(0,-1):e}function Qu(e,t,s){return bn(e,s)===bn(t,s)}function ef({base:e,to:t,trailingSlash:s="never",cache:n}){const r=t.startsWith("/"),i=!r&&t===".";let o;if(n){o=r?t:i?e:e+"\0"+t;const l=n.get(o);if(l)return l}let a;if(i)a=e.split("/");else if(r)a=t.split("/");else{for(a=e.split("/");a.length>1&&vn(a)==="";)a.pop();const l=t.split("/");for(let d=0,h=l.length;d1&&(vn(a)===""?s==="never"&&a.pop():s==="always"&&a.push(""));let c,u="";for(let l=0;l0&&(u+="/");const d=a[l];if(!d)continue;c=ai(d,0,c);const h=c[0];if(h===ss){u+=d;continue}const g=c[5],y=d.substring(0,c[1]),x=d.substring(c[4],g),b=d.substring(c[2],c[3]);h===Vt?u+=y||x?`${y}{$${b}}${x}`:`$${b}`:h===Ut?u+=y||x?`${y}{$}${x}`:"$":u+=`${y}{-$${b}}${x}`}u=li(u);const f=u||"/";return o&&n&&n.set(o,f),f}function tr(e,t,s){const n=t[e];return typeof n!="string"?n:e==="_splat"?encodeURI(n):tf(n,s)}function sr({path:e,params:t,decodeCharMap:s}){let n=!1;const r={};if(!e||e==="/")return{interpolatedPath:"/",usedParams:r,isMissingParams:n};if(!e.includes("$"))return{interpolatedPath:e,usedParams:r,isMissingParams:n};const i=e.length;let o=0,a,c="";for(;o{let s;return(...n)=>{s||(s=setTimeout(()=>{e(...n),s=null},t))}};function rf(){const e=sf();if(!e)return null;const t=e.getItem(xn);let s=t?JSON.parse(t):{};return{state:s,set:n=>(s=Gt(n,s)||s,e.setItem(xn,JSON.stringify(s)))}}const en=rf(),Pr=e=>e.state.__TSR_key||e.href;function of(e){const t=[];let s;for(;s=e.parentNode;)t.push(`${e.tagName}:nth-child(${Array.prototype.indexOf.call(s.children,e)+1})`),e=s;return`${t.reverse().join(" > ")}`.toLowerCase()}let wn=!1;function Oa({storageKey:e,key:t,behavior:s,shouldScrollRestoration:n,scrollToTopSelectors:r,location:i}){let o;try{o=JSON.parse(sessionStorage.getItem(e)||"{}")}catch(u){console.error(u);return}const a=t||window.history.state?.__TSR_key,c=o[a];wn=!0;e:{if(n&&c&&Object.keys(c).length>0){for(const l in c){const d=c[l];if(l==="window")window.scrollTo({top:d.scrollY,left:d.scrollX,behavior:s});else if(l){const h=document.querySelector(l);h&&(h.scrollLeft=d.scrollX,h.scrollTop=d.scrollY)}}break e}const u=(i??window.location).hash.split("#",2)[1];if(u){const l=window.history.state?.__hashScrollIntoViewOptions??!0;if(l){const d=document.getElementById(u);d&&d.scrollIntoView(l)}break e}const f={top:0,left:0,behavior:s};if(window.scrollTo(f),r)for(const l of r){if(l==="window")continue;const d=typeof l=="function"?l():document.querySelector(l);d&&d.scrollTo(f)}}wn=!1}function af(e,t){if(!en&&!e.isServer||((e.options.scrollRestoration??!1)&&(e.isScrollRestoring=!0),e.isServer||e.isScrollRestorationSetup||!en))return;e.isScrollRestorationSetup=!0,wn=!1;const n=e.options.getScrollRestorationKey||Pr;window.history.scrollRestoration="manual";const r=i=>{if(wn||!e.isScrollRestoring)return;let o="";if(i.target===document||i.target===window)o="window";else{const c=i.target.getAttribute("data-scroll-restoration-id");c?o=`[data-scroll-restoration-id="${c}"]`:o=of(i.target)}const a=n(e.state.location);en.set(c=>{const u=c[a]||={},f=u[o]||={};if(o==="window")f.scrollX=window.scrollX||0,f.scrollY=window.scrollY||0;else if(o){const l=document.querySelector(o);l&&(f.scrollX=l.scrollLeft||0,f.scrollY=l.scrollTop||0)}return c})};typeof document<"u"&&document.addEventListener("scroll",nf(r,100),!0),e.subscribe("onRendered",i=>{const o=n(i.toLocation);if(!e.resetNextScroll){e.resetNextScroll=!0;return}typeof e.options.scrollRestoration=="function"&&!e.options.scrollRestoration({location:e.latestLocation})||(Oa({storageKey:xn,key:o,behavior:e.options.scrollRestorationBehavior,shouldScrollRestoration:e.isScrollRestoring,scrollToTopSelectors:e.options.scrollToTopSelectors,location:e.history.location}),e.isScrollRestoring&&en.set(a=>(a[o]||={},a)))})}function cf(e){if(typeof document<"u"&&document.querySelector){const t=e.state.location.state.__hashScrollIntoViewOptions??!0;if(t&&e.state.location.hash!==""){const s=document.getElementById(e.state.location.hash);s&&s.scrollIntoView(t)}}}function lf(e,t=String){const s=new URLSearchParams;for(const n in e){const r=e[n];r!==void 0&&s.set(n,t(r))}return s.toString()}function nr(e){return e?e==="false"?!1:e==="true"?!0:+e*0===0&&+e+""===e?+e:e:""}function uf(e){const t=new URLSearchParams(e),s={};for(const[n,r]of t.entries()){const i=s[n];i==null?s[n]=nr(r):Array.isArray(i)?i.push(nr(r)):s[n]=[i,nr(r)]}return s}const ff=hf(JSON.parse),df=pf(JSON.stringify,JSON.parse);function hf(e){return t=>{t[0]==="?"&&(t=t.substring(1));const s=uf(t);for(const n in s){const r=s[n];if(typeof r=="string")try{s[n]=e(r)}catch{}}return s}}function pf(e,t){const s=typeof t=="function";function n(r){if(typeof r=="object"&&r!==null)try{return e(r)}catch{}else if(s&&typeof r=="string")try{return t(r),e(r)}catch{}return r}return r=>{const i=lf(r,n);return i?`?${i}`:""}}const Ne="__root__";function mf(e){if(e.statusCode=e.statusCode||e.code||307,!e.reloadDocument&&typeof e.href=="string")try{new URL(e.href),e.reloadDocument=!0}catch{}const t=new Headers(e.headers);e.href&&t.get("Location")===null&&t.set("Location",e.href);const s=new Response(null,{status:e.statusCode,headers:t});if(s.options=e,e.throw)throw s;return s}function Ue(e){return e instanceof Response&&!!e.options}const on=e=>{if(!e.rendered)return e.rendered=!0,e.onReady?.()},jn=(e,t)=>!!(e.preload&&!e.router.state.matches.some(s=>s.id===t)),ui=(e,t,s=!0)=>{const n={...e.router.options.context??{}},r=s?t:t-1;for(let i=0;i<=r;i++){const o=e.matches[i];if(!o)continue;const a=e.router.getMatch(o.id);a&&Object.assign(n,a.__routeContext,a.__beforeLoadContext)}return n},Aa=(e,t)=>{const s=e.router.routesById[t.routeId??""]??e.router.routeTree;!s.options.notFoundComponent&&e.router.options?.defaultNotFoundComponent&&(s.options.notFoundComponent=e.router.options.defaultNotFoundComponent),Dt(s.options.notFoundComponent);const n=e.matches.find(r=>r.routeId===s.id);Dt(n,"Could not find match for route: "+s.id),e.updateMatch(n.id,r=>({...r,status:"notFound",error:t,isFetching:!1})),t.routerCode==="BEFORE_LOAD"&&s.parentRoute&&(t.routeId=s.parentRoute.id,Aa(e,t))},_t=(e,t,s)=>{if(!(!Ue(s)&&!$e(s))){if(Ue(s)&&s.redirectHandled&&!s.options.reloadDocument)throw s;if(t){t._nonReactive.beforeLoadPromise?.resolve(),t._nonReactive.loaderPromise?.resolve(),t._nonReactive.beforeLoadPromise=void 0,t._nonReactive.loaderPromise=void 0;const n=Ue(s)?"redirected":"notFound";t._nonReactive.error=s,e.updateMatch(t.id,r=>({...r,status:n,isFetching:!1,error:s})),$e(s)&&!s.routeId&&(s.routeId=t.routeId),t._nonReactive.loadPromise?.resolve()}throw Ue(s)?(e.rendered=!0,s.options._fromLocation=e.location,s.redirectHandled=!0,s=e.router.resolveRedirect(s),s):(Aa(e,s),s)}},Na=(e,t)=>{const s=e.router.getMatch(t);return!!(!e.router.isServer&&s._nonReactive.dehydrated||e.router.isServer&&s.ssr===!1)},ps=(e,t,s,n)=>{const{id:r,routeId:i}=e.matches[t],o=e.router.looseRoutesById[i];if(s instanceof Promise)throw s;s.routerCode=n,e.firstBadMatchIndex??=t,_t(e,e.router.getMatch(r),s);try{o.options.onError?.(s)}catch(a){s=a,_t(e,e.router.getMatch(r),s)}e.updateMatch(r,a=>(a._nonReactive.beforeLoadPromise?.resolve(),a._nonReactive.beforeLoadPromise=void 0,a._nonReactive.loadPromise?.resolve(),{...a,error:s,status:"error",isFetching:!1,updatedAt:Date.now(),abortController:new AbortController}))},gf=(e,t,s,n)=>{const r=e.router.getMatch(t),i=e.matches[s-1]?.id,o=i?e.router.getMatch(i):void 0;if(e.router.isShell()){r.ssr=n.id===Ne;return}if(o?.ssr===!1){r.ssr=!1;return}const a=h=>h===!0&&o?.ssr==="data-only"?"data-only":h,c=e.router.options.defaultSsr??!0;if(n.options.ssr===void 0){r.ssr=a(c);return}if(typeof n.options.ssr!="function"){r.ssr=a(n.options.ssr);return}const{search:u,params:f}=r,l={search:tn(u,r.searchError),params:tn(f,r.paramsError),location:e.location,matches:e.matches.map(h=>({index:h.index,pathname:h.pathname,fullPath:h.fullPath,staticData:h.staticData,id:h.id,routeId:h.routeId,search:tn(h.search,h.searchError),params:tn(h.params,h.paramsError),ssr:h.ssr}))},d=n.options.ssr(l);if(Rt(d))return d.then(h=>{r.ssr=a(h??c)});r.ssr=a(d??c)},Fa=(e,t,s,n)=>{if(n._nonReactive.pendingTimeout!==void 0)return;const r=s.options.pendingMs??e.router.options.defaultPendingMs;if(!!(e.onReady&&!e.router.isServer&&!jn(e,t)&&(s.options.loader||s.options.beforeLoad||ja(s))&&typeof r=="number"&&r!==1/0&&(s.options.pendingComponent??e.router.options?.defaultPendingComponent))){const o=setTimeout(()=>{on(e)},r);n._nonReactive.pendingTimeout=o}},vf=(e,t,s)=>{const n=e.router.getMatch(t);if(!n._nonReactive.beforeLoadPromise&&!n._nonReactive.loaderPromise)return;Fa(e,t,s,n);const r=()=>{const i=e.router.getMatch(t);i.preload&&(i.status==="redirected"||i.status==="notFound")&&_t(e,i,i.error)};return n._nonReactive.beforeLoadPromise?n._nonReactive.beforeLoadPromise.then(r):r()},yf=(e,t,s,n)=>{const r=e.router.getMatch(t),i=r._nonReactive.loadPromise;r._nonReactive.loadPromise=ts(()=>{i?.resolve()});const{paramsError:o,searchError:a}=r;o&&ps(e,s,o,"PARSE_PARAMS"),a&&ps(e,s,a,"VALIDATE_SEARCH"),Fa(e,t,n,r);const c=new AbortController,u=e.matches[s-1]?.id;(u?e.router.getMatch(u):void 0)?.context??e.router.options.context;let l=!1;const d=()=>{l||(l=!0,e.updateMatch(t,_=>({..._,isFetching:"beforeLoad",fetchCount:_.fetchCount+1,abortController:c})))},h=()=>{r._nonReactive.beforeLoadPromise?.resolve(),r._nonReactive.beforeLoadPromise=void 0,e.updateMatch(t,_=>({..._,isFetching:!1}))};if(!n.options.beforeLoad){Is(()=>{d(),h()});return}r._nonReactive.beforeLoadPromise=ts();const g={...ui(e,s,!1),...r.__routeContext},{search:y,params:x,cause:b}=r,L=jn(e,t),$={search:y,abortController:c,params:x,preload:L,context:g,location:e.location,navigate:_=>e.router.navigate({..._,_fromLocation:e.location}),buildLocation:e.router.buildLocation,cause:L?"preload":b,matches:e.matches,...e.router.options.additionalContext},C=_=>{if(_===void 0){Is(()=>{d(),h()});return}(Ue(_)||$e(_))&&(d(),ps(e,s,_,"BEFORE_LOAD")),Is(()=>{d(),e.updateMatch(t,D=>({...D,__beforeLoadContext:_})),h()})};let k;try{if(k=n.options.beforeLoad($),Rt(k))return d(),k.catch(_=>{ps(e,s,_,"BEFORE_LOAD")}).then(C)}catch(_){d(),ps(e,s,_,"BEFORE_LOAD")}C(k)},_f=(e,t)=>{const{id:s,routeId:n}=e.matches[t],r=e.router.looseRoutesById[n],i=()=>{if(e.router.isServer){const c=gf(e,s,t,r);if(Rt(c))return c.then(a)}return a()},o=()=>yf(e,s,t,r),a=()=>{if(Na(e,s))return;const c=vf(e,s,r);return Rt(c)?c.then(o):o()};return i()},Ls=(e,t,s)=>{const n=e.router.getMatch(t);if(!n||!s.options.head&&!s.options.scripts&&!s.options.headers)return;const r={matches:e.matches,match:n,params:n.params,loaderData:n.loaderData};return Promise.all([s.options.head?.(r),s.options.scripts?.(r),s.options.headers?.(r)]).then(([i,o,a])=>{const c=i?.meta,u=i?.links,f=i?.scripts,l=i?.styles;return{meta:c,links:u,headScripts:f,headers:a,scripts:o,styles:l}})},$a=(e,t,s,n)=>{const r=e.matchPromises[s-1],{params:i,loaderDeps:o,abortController:a,cause:c}=e.router.getMatch(t),u=ui(e,s),f=jn(e,t);return{params:i,deps:o,preload:!!f,parentMatchPromise:r,abortController:a,context:u,location:e.location,navigate:l=>e.router.navigate({...l,_fromLocation:e.location}),cause:f?"preload":c,route:n,...e.router.options.additionalContext}},oo=async(e,t,s,n)=>{try{const r=e.router.getMatch(t);try{(!e.router.isServer||r.ssr===!0)&&Ba(n);const i=n.options.loader?.($a(e,t,s,n)),o=n.options.loader&&Rt(i);if(!!(o||n._lazyPromise||n._componentsPromise||n.options.head||n.options.scripts||n.options.headers||r._nonReactive.minPendingPromise)&&e.updateMatch(t,l=>({...l,isFetching:"loader"})),n.options.loader){const l=o?await i:i;_t(e,e.router.getMatch(t),l),l!==void 0&&e.updateMatch(t,d=>({...d,loaderData:l}))}n._lazyPromise&&await n._lazyPromise;const c=Ls(e,t,n),u=c?await c:void 0,f=r._nonReactive.minPendingPromise;f&&await f,n._componentsPromise&&await n._componentsPromise,e.updateMatch(t,l=>({...l,error:void 0,status:"success",isFetching:!1,updatedAt:Date.now(),...u}))}catch(i){let o=i;const a=r._nonReactive.minPendingPromise;a&&await a,$e(i)&&await n.options.notFoundComponent?.preload?.(),_t(e,e.router.getMatch(t),i);try{n.options.onError?.(i)}catch(f){o=f,_t(e,e.router.getMatch(t),f)}const c=Ls(e,t,n),u=c?await c:void 0;e.updateMatch(t,f=>({...f,error:o,status:"error",isFetching:!1,...u}))}}catch(r){const i=e.router.getMatch(t);if(i){const o=Ls(e,t,n);if(o){const a=await o;e.updateMatch(t,c=>({...c,...a}))}i._nonReactive.loaderPromise=void 0}_t(e,i,r)}},bf=async(e,t)=>{const{id:s,routeId:n}=e.matches[t];let r=!1,i=!1;const o=e.router.looseRoutesById[n],a=()=>{e.updateMatch(s,f=>({...f,context:ui(e,t)}))};if(Na(e,s)){if(e.router.isServer){const f=Ls(e,s,o);if(f){const l=await f;e.updateMatch(s,d=>({...d,...l}))}return e.router.getMatch(s)}}else{const f=e.router.getMatch(s);if(f._nonReactive.loaderPromise){if(f.status==="success"&&!e.sync&&!f.preload)return f;await f._nonReactive.loaderPromise;const l=e.router.getMatch(s),d=l._nonReactive.error||l.error;d&&_t(e,l,d)}else{const l=Date.now()-f.updatedAt,d=jn(e,s),h=d?o.options.preloadStaleTime??e.router.options.defaultPreloadStaleTime??3e4:o.options.staleTime??e.router.options.defaultStaleTime??0,g=o.options.shouldReload,y=typeof g=="function"?g($a(e,s,t,o)):g,x=!!d&&!e.router.state.matches.some(C=>C.id===s),b=e.router.getMatch(s);b._nonReactive.loaderPromise=ts(),x!==b.preload&&e.updateMatch(s,C=>({...C,preload:x}));const{status:L,invalid:$}=b;if(r=L==="success"&&($||(y??l>h)),!(d&&o.options.preload===!1))if(r&&!e.sync)i=!0,(async()=>{try{await oo(e,s,t,o),a();const C=e.router.getMatch(s);C._nonReactive.loaderPromise?.resolve(),C._nonReactive.loadPromise?.resolve(),C._nonReactive.loaderPromise=void 0}catch(C){Ue(C)&&await e.router.navigate(C.options)}})();else if(L!=="success"||r&&e.sync)await oo(e,s,t,o);else{const C=Ls(e,s,o);if(C){const k=await C;e.updateMatch(s,_=>({..._,...k}))}}}}const c=e.router.getMatch(s);i||(c._nonReactive.loaderPromise?.resolve(),c._nonReactive.loadPromise?.resolve()),clearTimeout(c._nonReactive.pendingTimeout),c._nonReactive.pendingTimeout=void 0,i||(c._nonReactive.loaderPromise=void 0),c._nonReactive.dehydrated=void 0,i||a();const u=i?c.isFetching:!1;return u!==c.isFetching||c.invalid!==!1?(e.updateMatch(s,f=>({...f,isFetching:u,invalid:!1})),e.router.getMatch(s)):c};async function ao(e){const t=Object.assign(e,{matchPromises:[]});!t.router.isServer&&t.router.state.matches.some(s=>s._forcePending)&&on(t);try{for(let r=0;r{const{id:s,...n}=t.options;Object.assign(e.options,n),e._lazyLoaded=!0,e._lazyPromise=void 0}):e._lazyLoaded=!0),!e._componentsLoaded&&e._componentsPromise===void 0){const t=()=>{const s=[];for(const n of Da){const r=e.options[n]?.preload;r&&s.push(r())}if(s.length)return Promise.all(s).then(()=>{e._componentsLoaded=!0,e._componentsPromise=void 0});e._componentsLoaded=!0,e._componentsPromise=void 0};e._componentsPromise=e._lazyPromise?e._lazyPromise.then(t):t()}return e._componentsPromise}function tn(e,t){return t?{status:"error",error:t}:{status:"success",value:e}}function ja(e){for(const t of Da)if(e.options[t]?.preload)return!0;return!1}const Da=["component","errorComponent","pendingComponent","notFoundComponent"];function xf(e){return{input:({url:t})=>{for(const s of e)t=Va(s,t);return t},output:({url:t})=>{for(let s=e.length-1;s>=0;s--)t=Ua(e[s],t);return t}}}function wf(e){const t=Ea(e.basepath),s=`/${t}`,n=`${s}/`,r=e.caseSensitive?s:s.toLowerCase(),i=e.caseSensitive?n:n.toLowerCase();return{input:({url:o})=>{const a=e.caseSensitive?o.pathname:o.pathname.toLowerCase();return a===r?o.pathname="/":a.startsWith(i)&&(o.pathname=o.pathname.slice(s.length)),o},output:({url:o})=>(o.pathname=rn(["/",t,o.pathname]),o)}}function Va(e,t){const s=e?.input?.({url:t});if(s){if(typeof s=="string")return new URL(s);if(s instanceof URL)return s}return t}function Ua(e,t){const s=e?.output?.({url:t});if(s){if(typeof s=="string")return new URL(s);if(s instanceof URL)return s}return t}function jt(e){const t=e.resolvedLocation,s=e.location,n=t?.pathname!==s.pathname,r=t?.href!==s.href,i=t?.hash!==s.hash;return{fromLocation:t,toLocation:s,pathChanged:n,hrefChanged:r,hashChanged:i}}class Sf{constructor(t){this.tempLocationKey=`${Math.round(Math.random()*1e7)}`,this.resetNextScroll=!0,this.shouldViewTransition=void 0,this.isViewTransitionTypesSupported=void 0,this.subscribers=new Set,this.isScrollRestoring=!1,this.isScrollRestorationSetup=!1,this.startTransition=s=>s(),this.update=s=>{s.notFoundRoute&&console.warn("The notFoundRoute API is deprecated and will be removed in the next major version. See https://tanstack.com/router/v1/docs/framework/react/guide/not-found-errors#migrating-from-notfoundroute for more info.");const n=this.options,r=this.basepath??n?.basepath??"/",i=this.basepath===void 0,o=n?.rewrite;this.options={...n,...s},this.isServer=this.options.isServer??typeof document>"u",this.pathParamsDecodeCharMap=this.options.pathParamsAllowedCharacters?new Map(this.options.pathParamsAllowedCharacters.map(d=>[encodeURIComponent(d),d])):void 0,(!this.history||this.options.history&&this.options.history!==this.history)&&(this.options.history?this.history=this.options.history:this.isServer||(this.history=La())),this.origin=this.options.origin,this.origin||(!this.isServer&&window?.origin&&window.origin!=="null"?this.origin=window.origin:this.origin="http://localhost"),this.history&&this.updateLatestLocation(),this.options.routeTree!==this.routeTree&&(this.routeTree=this.options.routeTree,this.buildRouteTree()),!this.__store&&this.latestLocation&&(this.__store=new Au(Cf(this.latestLocation),{onUpdate:()=>{this.__store.state={...this.state,cachedMatches:this.state.cachedMatches.filter(d=>!["redirected"].includes(d.status))}}}),af(this));let a=!1;const c=this.options.basepath??"/",u=this.options.rewrite;if(i||r!==c||o!==u){this.basepath=c;const d=[];Ea(c)!==""&&d.push(wf({basepath:c})),u&&d.push(u),this.rewrite=d.length===0?void 0:d.length===1?d[0]:xf(d),this.history&&this.updateLatestLocation(),a=!0}a&&this.__store&&(this.__store.state={...this.state,location:this.latestLocation}),typeof window<"u"&&"CSS"in window&&typeof window.CSS?.supports=="function"&&(this.isViewTransitionTypesSupported=window.CSS.supports("selector(:active-view-transition-type(a)"))},this.updateLatestLocation=()=>{this.latestLocation=this.parseLocation(this.history.location,this.latestLocation)},this.buildRouteTree=()=>{const{routesById:s,routesByPath:n,processedTree:r}=qu(this.routeTree,this.options.caseSensitive,(o,a)=>{o.init({originalIndex:a})});this.options.routeMasks&&Hu(this.options.routeMasks,r),this.routesById=s,this.routesByPath=n,this.processedTree=r;const i=this.options.notFoundRoute;i&&(i.init({originalIndex:99999999999}),this.routesById[i.id]=i)},this.subscribe=(s,n)=>{const r={eventType:s,fn:n};return this.subscribers.add(r),()=>{this.subscribers.delete(r)}},this.emit=s=>{this.subscribers.forEach(n=>{n.eventType===s.type&&n.fn(s)})},this.parseLocation=(s,n)=>{const r=({href:c,state:u})=>{const f=new URL(c,this.origin),l=Va(this.rewrite,f),d=this.options.parseSearch(l.search),h=this.options.stringifySearch(d);return l.search=h,{href:l.href.replace(l.origin,""),publicHref:c,url:l,pathname:io(l.pathname),searchStr:h,search:je(n?.search,d),hash:l.hash.split("#").reverse()[0]??"",state:je(n?.state,u)}},i=r(s),{__tempLocation:o,__tempKey:a}=i.state;if(o&&(!a||a===this.tempLocationKey)){const c=r(o);return c.state.key=i.state.key,c.state.__TSR_key=i.state.__TSR_key,delete c.state.__tempLocation,{...c,maskedLocation:i}}return i},this.resolvePathCache=_n(1e3),this.resolvePathWithBase=(s,n)=>ef({base:s,to:li(n),trailingSlash:this.options.trailingSlash,cache:this.resolvePathCache}),this.matchRoutes=(s,n,r)=>typeof s=="string"?this.matchRoutesInternal({pathname:s,search:n},r):this.matchRoutesInternal(s,n),this.getMatchedRoutes=s=>Pf({pathname:s,routesById:this.routesById,processedTree:this.processedTree}),this.cancelMatch=s=>{const n=this.getMatch(s);n&&(n.abortController.abort(),clearTimeout(n._nonReactive.pendingTimeout),n._nonReactive.pendingTimeout=void 0)},this.cancelMatches=()=>{const s=this.state.matches.filter(i=>i.status==="pending"),n=this.state.matches.filter(i=>i.isFetching==="loader");new Set([...this.state.pendingMatches??[],...s,...n]).forEach(i=>{this.cancelMatch(i.id)})},this.buildLocation=s=>{const n=(i={})=>{const o=i._fromLocation||this.pendingBuiltLocation||this.latestLocation,a=this.matchRoutes(o,{_buildLocation:!0}),c=vn(a);i.from;const u=i.unsafeRelative==="path"?o.pathname:i.from??c.fullPath,f=this.resolvePathWithBase(u,"."),l=c.search,d={...c.params},h=i.to?this.resolvePathWithBase(f,`${i.to}`):this.resolvePathWithBase(f,"."),g=i.params===!1||i.params===null?{}:(i.params??!0)===!0?d:Object.assign(d,Gt(i.params,d)),y=sr({path:h,params:g}).interpolatedPath,x=this.matchRoutes(y,void 0,{_buildLocation:!0}).map(W=>this.looseRoutesById[W.routeId]);if(Object.keys(g).length>0)for(const W of x){const J=W.options.params?.stringify??W.options.stringifyParams;J&&Object.assign(g,J(g))}const b=s.leaveParams?h:io(sr({path:h,params:g,decodeCharMap:this.pathParamsDecodeCharMap}).interpolatedPath);let L=l;if(s._includeValidateSearch&&this.options.search?.strict){const W={};x.forEach(J=>{if(J.options.validateSearch)try{Object.assign(W,kr(J.options.validateSearch,{...W,...L}))}catch{}}),L=W}L=kf({search:L,dest:i,destRoutes:x,_includeValidateSearch:s._includeValidateSearch}),L=je(l,L);const $=this.options.stringifySearch(L),C=i.hash===!0?o.hash:i.hash?Gt(i.hash,o.hash):void 0,k=C?`#${C}`:"";let _=i.state===!0?o.state:i.state?Gt(i.state,o.state):{};_=je(o.state,_);const D=`${b}${$}${k}`,M=new URL(D,this.origin),B=Ua(this.rewrite,M);return{publicHref:B.pathname+B.search+B.hash,href:D,url:B,pathname:b,search:L,searchStr:$,state:_,hash:C??"",unmaskOnReload:i.unmaskOnReload}},r=(i={},o)=>{const a=n(i);let c=o?n(o):void 0;if(!c){const u={};if(this.options.routeMasks){const f=Zu(a.pathname,this.processedTree);if(f){Object.assign(u,f.params);const{from:l,params:d,...h}=f.route,g=d===!1||d===null?{}:(d??!0)===!0?u:Object.assign(u,Gt(d,u));o={from:s.from,...h,params:g},c=n(o)}}}return c&&(a.maskedLocation=c),a};return s.mask?r(s,{from:s.from,...s.mask}):r(s)},this.commitLocation=({viewTransition:s,ignoreBlocker:n,...r})=>{const i=()=>{const c=["key","__TSR_key","__TSR_index","__hashScrollIntoViewOptions"];c.forEach(f=>{r.state[f]=this.latestLocation.state[f]});const u=$t(r.state,this.latestLocation.state);return c.forEach(f=>{delete r.state[f]}),u},o=Bt(this.latestLocation.href)===Bt(r.href),a=this.commitLocationPromise;if(this.commitLocationPromise=ts(()=>{a?.resolve()}),o&&i())this.load();else{let{maskedLocation:c,hashScrollIntoView:u,url:f,...l}=r;c&&(l={...c,state:{...c.state,__tempKey:void 0,__tempLocation:{...l,search:l.searchStr,state:{...l.state,__tempKey:void 0,__tempLocation:void 0,__TSR_key:void 0,key:void 0}}}},(l.unmaskOnReload??this.options.unmaskOnReload??!1)&&(l.state.__tempKey=this.tempLocationKey)),l.state.__hashScrollIntoViewOptions=u??this.options.defaultHashScrollIntoView??!0,this.shouldViewTransition=s,this.history[r.replace?"replace":"push"](l.publicHref,l.state,{ignoreBlocker:n})}return this.resetNextScroll=r.resetScroll??!0,this.history.subscribers.size||this.load(),this.commitLocationPromise},this.buildAndCommitLocation=({replace:s,resetScroll:n,hashScrollIntoView:r,viewTransition:i,ignoreBlocker:o,href:a,...c}={})=>{if(a){const l=this.history.location.state.__TSR_index,d=Bs(a,{__TSR_index:s?l:l+1});c.to=d.pathname,c.search=this.options.parseSearch(d.search),c.hash=d.hash.slice(1)}const u=this.buildLocation({...c,_includeValidateSearch:!0});this.pendingBuiltLocation=u;const f=this.commitLocation({...u,viewTransition:i,replace:s,resetScroll:n,hashScrollIntoView:r,ignoreBlocker:o});return Promise.resolve().then(()=>{this.pendingBuiltLocation===u&&(this.pendingBuiltLocation=void 0)}),f},this.navigate=async({to:s,reloadDocument:n,href:r,...i})=>{if(!n&&r)try{new URL(`${r}`),n=!0}catch{}if(n){if(r||(r=this.buildLocation({to:s,...i}).url.href),!i.ignoreBlocker){const a=this.history.getBlockers?.()??[];for(const c of a)if(c?.blockerFn&&await c.blockerFn({currentLocation:this.latestLocation,nextLocation:this.latestLocation,action:"PUSH"}))return Promise.resolve()}return i.replace?window.location.replace(r):window.location.href=r,Promise.resolve()}return this.buildAndCommitLocation({...i,href:r,to:s,_isNavigate:!0})},this.beforeLoad=()=>{if(this.cancelMatches(),this.updateLatestLocation(),this.isServer){const n=this.buildLocation({to:this.latestLocation.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});if(this.latestLocation.publicHref!==n.publicHref||n.url.origin!==this.origin){const r=this.getParsedLocationHref(n);throw mf({href:r})}}const s=this.matchRoutes(this.latestLocation);this.__store.setState(n=>({...n,status:"pending",statusCode:200,isLoading:!0,location:this.latestLocation,pendingMatches:s,cachedMatches:n.cachedMatches.filter(r=>!s.some(i=>i.id===r.id))}))},this.load=async s=>{let n,r,i;for(i=new Promise(a=>{this.startTransition(async()=>{try{this.beforeLoad();const c=this.latestLocation,u=this.state.resolvedLocation;this.state.redirect||this.emit({type:"onBeforeNavigate",...jt({resolvedLocation:u,location:c})}),this.emit({type:"onBeforeLoad",...jt({resolvedLocation:u,location:c})}),await ao({router:this,sync:s?.sync,matches:this.state.pendingMatches,location:c,updateMatch:this.updateMatch,onReady:async()=>{this.startTransition(()=>{this.startViewTransition(async()=>{let f=[],l=[],d=[];Is(()=>{this.__store.setState(h=>{const g=h.matches,y=h.pendingMatches||h.matches;return f=g.filter(x=>!y.some(b=>b.id===x.id)),l=y.filter(x=>!g.some(b=>b.id===x.id)),d=y.filter(x=>g.some(b=>b.id===x.id)),{...h,isLoading:!1,loadedAt:Date.now(),matches:y,pendingMatches:void 0,cachedMatches:[...h.cachedMatches,...f.filter(x=>x.status!=="error"&&x.status!=="notFound")]}}),this.clearExpiredCache()}),[[f,"onLeave"],[l,"onEnter"],[d,"onStay"]].forEach(([h,g])=>{h.forEach(y=>{this.looseRoutesById[y.routeId].options[g]?.(y)})})})})}})}catch(c){Ue(c)?(n=c,this.isServer||this.navigate({...n.options,replace:!0,ignoreBlocker:!0})):$e(c)&&(r=c),this.__store.setState(u=>({...u,statusCode:n?n.status:r?404:u.matches.some(f=>f.status==="error")?500:200,redirect:n}))}this.latestLoadPromise===i&&(this.commitLocationPromise?.resolve(),this.latestLoadPromise=void 0,this.commitLocationPromise=void 0),a()})}),this.latestLoadPromise=i,await i;this.latestLoadPromise&&i!==this.latestLoadPromise;)await this.latestLoadPromise;let o;this.hasNotFoundMatch()?o=404:this.__store.state.matches.some(a=>a.status==="error")&&(o=500),o!==void 0&&this.__store.setState(a=>({...a,statusCode:o}))},this.startViewTransition=s=>{const n=this.shouldViewTransition??this.options.defaultViewTransition;if(delete this.shouldViewTransition,n&&typeof document<"u"&&"startViewTransition"in document&&typeof document.startViewTransition=="function"){let r;if(typeof n=="object"&&this.isViewTransitionTypesSupported){const i=this.latestLocation,o=this.state.resolvedLocation,a=typeof n.types=="function"?n.types(jt({resolvedLocation:o,location:i})):n.types;if(a===!1){s();return}r={update:s,types:a}}else r=s;document.startViewTransition(r)}else s()},this.updateMatch=(s,n)=>{this.startTransition(()=>{const r=this.state.pendingMatches?.some(i=>i.id===s)?"pendingMatches":this.state.matches.some(i=>i.id===s)?"matches":this.state.cachedMatches.some(i=>i.id===s)?"cachedMatches":"";r&&this.__store.setState(i=>({...i,[r]:i[r]?.map(o=>o.id===s?n(o):o)}))})},this.getMatch=s=>{const n=r=>r.id===s;return this.state.cachedMatches.find(n)??this.state.pendingMatches?.find(n)??this.state.matches.find(n)},this.invalidate=s=>{const n=r=>s?.filter?.(r)??!0?{...r,invalid:!0,...s?.forcePending||r.status==="error"||r.status==="notFound"?{status:"pending",error:void 0}:void 0}:r;return this.__store.setState(r=>({...r,matches:r.matches.map(n),cachedMatches:r.cachedMatches.map(n),pendingMatches:r.pendingMatches?.map(n)})),this.shouldViewTransition=!1,this.load({sync:s?.sync})},this.getParsedLocationHref=s=>{let n=s.url.href;return this.origin&&s.url.origin===this.origin&&(n=n.replace(this.origin,"")||"/"),n},this.resolveRedirect=s=>{if(!s.options.href){const n=this.buildLocation(s.options),r=this.getParsedLocationHref(n);s.options.href=n.href,s.headers.set("Location",r)}return s.headers.get("Location")||s.headers.set("Location",s.options.href),s},this.clearCache=s=>{const n=s?.filter;n!==void 0?this.__store.setState(r=>({...r,cachedMatches:r.cachedMatches.filter(i=>!n(i))})):this.__store.setState(r=>({...r,cachedMatches:[]}))},this.clearExpiredCache=()=>{const s=n=>{const r=this.looseRoutesById[n.routeId];if(!r.options.loader)return!0;const i=(n.preload?r.options.preloadGcTime??this.options.defaultPreloadGcTime:r.options.gcTime??this.options.defaultGcTime)??300*1e3;return n.status==="error"?!0:Date.now()-n.updatedAt>=i};this.clearCache({filter:s})},this.loadRouteChunk=Ba,this.preloadRoute=async s=>{const n=this.buildLocation(s);let r=this.matchRoutes(n,{throwOnError:!0,preload:!0,dest:s});const i=new Set([...this.state.matches,...this.state.pendingMatches??[]].map(a=>a.id)),o=new Set([...i,...this.state.cachedMatches.map(a=>a.id)]);Is(()=>{r.forEach(a=>{o.has(a.id)||this.__store.setState(c=>({...c,cachedMatches:[...c.cachedMatches,a]}))})});try{return r=await ao({router:this,matches:r,location:n,preload:!0,updateMatch:(a,c)=>{i.has(a)?r=r.map(u=>u.id===a?c(u):u):this.updateMatch(a,c)}}),r}catch(a){if(Ue(a))return a.options.reloadDocument?void 0:await this.preloadRoute({...a.options,_fromLocation:n});$e(a)||console.error(a);return}},this.matchRoute=(s,n)=>{const r={...s,to:s.to?this.resolvePathWithBase(s.from||"",s.to):void 0,params:s.params||{},leaveParams:!0},i=this.buildLocation(r);if(n?.pending&&this.state.status!=="pending")return!1;const a=(n?.pending===void 0?!this.state.isLoading:n.pending)?this.latestLocation:this.state.resolvedLocation||this.state.location,c=Wu(i.pathname,n?.caseSensitive??!1,n?.fuzzy??!1,a.pathname,this.processedTree);return!c||s.params&&!$t(c.params,s.params,{partial:!0})?!1:n?.includeSearch??!0?$t(a.search,i.search,{partial:!0})?c.params:!1:c.params},this.hasNotFoundMatch=()=>this.__store.state.matches.some(s=>s.status==="notFound"||s.globalNotFound),this.update({defaultPreloadDelay:50,defaultPendingMs:1e3,defaultPendingMinMs:500,context:void 0,...t,caseSensitive:t.caseSensitive??!1,notFoundMode:t.notFoundMode??"fuzzy",stringifySearch:t.stringifySearch??df,parseSearch:t.parseSearch??ff}),typeof document<"u"&&(self.__TSR_ROUTER__=this)}isShell(){return!!this.options.isShell}isPrerendering(){return!!this.options.isPrerendering}get state(){return this.__store.state}get looseRoutesById(){return this.routesById}matchRoutesInternal(t,s){const n=this.getMatchedRoutes(t.pathname),{foundRoute:r,routeParams:i}=n;let{matchedRoutes:o}=n,a=!1;(r?r.path!=="/"&&i["**"]:Bt(t.pathname))&&(this.options.notFoundRoute?o=[...o,this.options.notFoundRoute]:a=!0);const c=(()=>{if(a){if(this.options.notFoundMode!=="root")for(let l=o.length-1;l>=0;l--){const d=o[l];if(d.children)return d.id}return Ne}})(),u=[],f=l=>l?.id?l.context??this.options.context??void 0:this.options.context??void 0;return o.forEach((l,d)=>{const h=u[d-1],[g,y,x]=(()=>{const P=h?.search??t.search,H=h?._strictSearch??void 0;try{const te=kr(l.options.validateSearch,{...P})??void 0;return[{...P,...te},{...H,...te},void 0]}catch(te){let Q=te;if(te instanceof Sn||(Q=new Sn(te.message,{cause:te})),s?.throwOnError)throw Q;return[P,{},Q]}})(),b=l.options.loaderDeps?.({search:g})??"",L=b?JSON.stringify(b):"",{interpolatedPath:$,usedParams:C}=sr({path:l.fullPath,params:i,decodeCharMap:this.pathParamsDecodeCharMap}),k=l.id+$+L,_=this.getMatch(k),D=this.state.matches.find(P=>P.routeId===l.id),M=_?._strictParams??C;let B;if(!_){const P=l.options.params?.parse??l.options.parseParams;if(P)try{Object.assign(M,P(M))}catch(H){if($e(H)||Ue(H)?B=H:B=new Rf(H.message,{cause:H}),s?.throwOnError)throw B}}Object.assign(i,M);const W=D?"stay":"enter";let J;if(_)J={..._,cause:W,params:D?je(D.params,i):i,_strictParams:M,search:je(D?D.search:_.search,g),_strictSearch:y};else{const P=l.options.loader||l.options.beforeLoad||l.lazyFn||ja(l)?"pending":"success";J={id:k,ssr:this.isServer?void 0:l.options.ssr,index:d,routeId:l.id,params:D?je(D.params,i):i,_strictParams:M,pathname:$,updatedAt:Date.now(),search:D?je(D.search,g):g,_strictSearch:y,searchError:void 0,status:P,isFetching:!1,error:void 0,paramsError:B,__routeContext:void 0,_nonReactive:{loadPromise:ts()},__beforeLoadContext:void 0,context:{},abortController:new AbortController,fetchCount:0,cause:W,loaderDeps:D?je(D.loaderDeps,b):b,invalid:!1,preload:!1,links:void 0,scripts:void 0,headScripts:void 0,meta:void 0,staticData:l.options.staticData||{},fullPath:l.fullPath}}s?.preload||(J.globalNotFound=c===l.id),J.searchError=x;const de=f(h);J.context={...de,...J.__routeContext,...J.__beforeLoadContext},u.push(J)}),u.forEach((l,d)=>{const h=this.looseRoutesById[l.routeId];if(!this.getMatch(l.id)&&s?._buildLocation!==!0){const y=u[d-1],x=f(y);if(h.options.context){const b={deps:l.loaderDeps,params:l.params,context:x??{},location:t,navigate:L=>this.navigate({...L,_fromLocation:t}),buildLocation:this.buildLocation,cause:l.cause,abortController:l.abortController,preload:!!l.preload,matches:u};l.__routeContext=h.options.context(b)??void 0}l.context={...x,...l.__routeContext,...l.__beforeLoadContext}}}),u}}class Sn extends Error{}class Rf extends Error{}function Cf(e){return{loadedAt:0,isLoading:!1,isTransitioning:!1,status:"idle",resolvedLocation:void 0,location:e,matches:[],pendingMatches:[],cachedMatches:[],statusCode:200}}function kr(e,t){if(e==null)return{};if("~standard"in e){const s=e["~standard"].validate(t);if(s instanceof Promise)throw new Sn("Async validation not supported");if(s.issues)throw new Sn(JSON.stringify(s.issues,void 0,2),{cause:s});return s.value}return"parse"in e?e.parse(t):typeof e=="function"?e(t):{}}function Pf({pathname:e,routesById:t,processedTree:s}){const n={},r=Bt(e);let i;const o=zu(r,s,!0);return o&&(i=o.route,Object.assign(n,o.params)),{matchedRoutes:o?.branch||[t[Ne]],routeParams:n,foundRoute:i}}function kf({search:e,dest:t,destRoutes:s,_includeValidateSearch:n}){const r=s.reduce((a,c)=>{const u=[];if("search"in c.options)c.options.search?.middlewares&&u.push(...c.options.search.middlewares);else if(c.options.preSearchFilters||c.options.postSearchFilters){const f=({search:l,next:d})=>{let h=l;"preSearchFilters"in c.options&&c.options.preSearchFilters&&(h=c.options.preSearchFilters.reduce((y,x)=>x(y),l));const g=d(h);return"postSearchFilters"in c.options&&c.options.postSearchFilters?c.options.postSearchFilters.reduce((y,x)=>x(y),g):g};u.push(f)}if(n&&c.options.validateSearch){const f=({search:l,next:d})=>{const h=d(l);try{return{...h,...kr(c.options.validateSearch,h)??void 0}}catch{return h}};u.push(f)}return a.concat(u)},[])??[],i=({search:a})=>t.search?t.search===!0?a:Gt(t.search,a):{};r.push(i);const o=(a,c)=>{if(a>=r.length)return c;const u=r[a];return u({search:c,next:l=>o(a+1,l)})};return o(0,e)}const Tf="Error preloading route! ☝️";class Ha{constructor(t){if(this.init=s=>{this.originalIndex=s.originalIndex;const n=this.options,r=!n?.path&&!n?.id;this.parentRoute=this.options.getParentRoute?.(),r?this._path=Ne:this.parentRoute||Dt(!1);let i=r?Ne:n?.path;i&&i!=="/"&&(i=Ma(i));const o=n?.id||i;let a=r?Ne:rn([this.parentRoute.id===Ne?"":this.parentRoute.id,o]);i===Ne&&(i="/"),a!==Ne&&(a=rn(["/",a]));const c=a===Ne?"/":rn([this.parentRoute.fullPath,i]);this._path=i,this._id=a,this._fullPath=c,this._to=c},this.addChildren=s=>this._addFileChildren(s),this._addFileChildren=s=>(Array.isArray(s)&&(this.children=s),typeof s=="object"&&s!==null&&(this.children=Object.values(s)),this),this._addFileTypes=()=>this,this.updateLoader=s=>(Object.assign(this.options,s),this),this.update=s=>(Object.assign(this.options,s),this),this.lazy=s=>(this.lazyFn=s,this),this.options=t||{},this.isRoot=!t?.getParentRoute,t?.id&&t?.path)throw new Error("Route cannot have both an 'id' and a 'path' option.")}get to(){return this._to}get id(){return this._id}get path(){return this._path}get fullPath(){return this._fullPath}}class If extends Ha{constructor(t){super(t)}}const Lf=ve({name:"VueErrorBoundary",props:{onError:Function,resetKey:[String,Number]},emits:["catch"],setup(e,{slots:t}){const s=we(null),n=we(null),r=()=>{s.value=null};return Qe(()=>e.resetKey,(i,o)=>{i!==o&&s.value&&r()}),oa(i=>(i instanceof Promise||i&&typeof i.then=="function"||(s.value=i,n.value=r,e.onError&&e.onError(i)),!1)),()=>{if(s.value&&t.fallback){const o=t.fallback({error:s.value,reset:r});return Array.isArray(o)&&o.length===1?o[0]:o}const i=t.default&&t.default();return Array.isArray(i)&&i.length===1?i[0]:i}}}),Mf=ve({name:"CatchBoundary",inheritAttrs:!1,props:["getResetKey","children","errorComponent","onCatch"],setup(e){const t=fe(()=>e.getResetKey());return()=>j(Lf,{resetKey:t.value,onError:e.onCatch},{default:()=>e.children,fallback:({error:s,reset:n})=>e.errorComponent?j(e.errorComponent,{error:s,reset:n}):j(Za,{error:s,reset:n})})}});function fi(e){return j(Mf,e)}const Za=ve({name:"ErrorComponent",props:{error:Object,reset:Function},setup(e){const t=we(!1),s=()=>{t.value=!t.value};return()=>j("div",{style:{padding:".5rem",maxWidth:"100%"}},[j("div",{style:{display:"flex",alignItems:"center",gap:".5rem"}},[j("strong",{style:{fontSize:"1rem"}},"Something went wrong!"),j("button",{style:{appearance:"none",fontSize:".6em",border:"1px solid currentColor",padding:".1rem .2rem",fontWeight:"bold",borderRadius:".25rem"},onClick:s},t.value?"Hide Error":"Show Error")]),j("div",{style:{height:".25rem"}}),t.value?j("div",{},[j("pre",{style:{fontSize:".7em",border:"1px solid red",borderRadius:".25rem",padding:".3rem",color:"red",overflow:"auto"}},[e.error?.message?j("code",{},e.error.message):null])]):null])}});function Ef(e,t=n=>n,s={}){const n=we(t(e.state)),r=s.equal??Of;return Qe(()=>e,(i,o,a)=>{const c=i.subscribe(()=>{const u=t(i.state);r(ae(n.value),u)||(n.value=u)});a(()=>{c()})},{immediate:!0}),cn(n)}function Of(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[n,r]of e)if(!t.has(n)||!Object.is(r,t.get(n)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const s=Object.keys(e);if(s.length!==Object.keys(t).length)return!1;for(let n=0;n"u"?rr:window.__TSR_ROUTER_CONTEXT__?window.__TSR_ROUTER_CONTEXT__:(window.__TSR_ROUTER_CONTEXT__=rr,rr)}function Af(e){An(Wa(),e)}function Ce(e){const t=wt(Wa(),null);return e?.warn,t}function _e(e){const t=Ce({warn:e?.router===void 0}),s=e?.router||t;return!s||!s.__store?we(void 0):Ef(s.__store,n=>e?.select?e.select(n):n)}const Dn=Symbol("TanStackRouterMatch"),Nf=Symbol("TanStackRouterDummyMatch");function Ff(){return wt(Dn,we(void 0))}function $f(){return wt(Nf,we(void 0))}function st(e){const t=e.from?$f():Ff(),s=we(null),n=_e({select:i=>{const o=i.matches.find(a=>e.from?e.from===a.routeId:a.id===t.value);if(o===void 0){if(i.pendingMatches?.find(c=>e.from?e.from===c.routeId:c.id===t.value)||i.isTransitioning){s.value=null;return}(e.shouldThrow??!0)&&(s.value=new Error(`Invariant failed: Could not find ${e.from?`an active match from "${e.from}"`:"a nearest match!"}`));return}return s.value=null,e.select?e.select(o):o}}),r=fe(()=>{if(s.value)throw s.value;return n.value});if(s.value)throw s.value;return r}function di(e){return st({from:e.from,strict:e.strict,select:t=>e.select?e.select(t.loaderData):t.loaderData})}function hi(e){const{select:t,...s}=e;return st({...s,select:n=>t?t(n.loaderDeps):n.loaderDeps})}function pi(e){return st({from:e.from,strict:e.strict,shouldThrow:e.shouldThrow,select:t=>e.select?e.select(t.params):t.params})}function mi(e){return st({from:e.from,strict:e.strict,shouldThrow:e.shouldThrow,select:t=>e.select?e.select(t.search):t.search})}function gi(e){const{navigate:t}=Ce();return s=>t({from:e?.from,...s})}let Bf=class extends Ha{constructor(t){super(t),this.useMatch=s=>st({select:s?.select,from:this.id}),this.useRouteContext=s=>st({...s,from:this.id,select:n=>s?.select?s.select(n.context):n.context}),this.useSearch=s=>mi({select:s?.select,from:this.id}),this.useParams=s=>pi({select:s?.select,from:this.id}),this.useLoaderDeps=s=>hi({...s,from:this.id}),this.useLoaderData=s=>di({...s,from:this.id}),this.useNavigate=()=>gi({from:this.fullPath})}};function jf(e){return new Bf(e)}class Df extends If{constructor(t){super(t),this.useMatch=s=>st({select:s?.select,from:this.id}),this.useRouteContext=s=>st({...s,from:this.id,select:n=>s?.select?s.select(n.context):n.context}),this.useSearch=s=>mi({select:s?.select,from:this.id}),this.useParams=s=>pi({select:s?.select,from:this.id}),this.useLoaderDeps=s=>hi({...s,from:this.id}),this.useLoaderData=s=>di({...s,from:this.id}),this.useNavigate=()=>gi({from:this.fullPath})}}function Vf(e){return new Df(e)}function cs(e){return typeof e=="object"?new co(e,{silent:!0}).createRoute(e):new co(e,{silent:!0}).createRoute}class co{constructor(t,s){this.path=t,this.createRoute=n=>{this.silent;const r=jf(n);return r.isRoot=!1,r},this.silent=s?.silent}}class lo{constructor(t){this.useMatch=s=>st({select:s?.select,from:this.options.id}),this.useRouteContext=s=>st({from:this.options.id,select:n=>s?.select?s.select(n.context):n.context}),this.useSearch=s=>mi({select:s?.select,from:this.options.id}),this.useParams=s=>pi({select:s?.select,from:this.options.id}),this.useLoaderDeps=s=>hi({...s,from:this.options.id}),this.useLoaderData=s=>di({...s,from:this.options.id}),this.useNavigate=()=>{const s=Ce();return gi({from:s.routesById[this.options.id].fullPath})},this.options=t}}function mh(e){return typeof e=="object"?new lo(e):t=>new lo({id:e,...t})}function Uf(e){const t=_e({select:n=>`not-found-${n.location.pathname}-${n.status}`});return j(fi,{getResetKey:()=>t.value,onCatch:n=>{if($e(n))e.onCatch&&e.onCatch(n);else throw n},errorComponent:n=>{const r=n.error;if($e(r))return e.fallback?e.fallback(r):j("p",null,"Not Found");throw r},children:e.children})}const Hf=ve({name:"DefaultGlobalNotFound",setup(){return()=>j("p",null,"Not Found")}});function za(e,t,s){return t.options.notFoundComponent?j(t.options.notFoundComponent,s):e.options.defaultNotFoundComponent?j(e.options.defaultNotFoundComponent,s):j(Hf)}const uo=ve({name:"ScriptOnce",props:{children:{type:String,required:!0}},setup(e){const t=Ce();if(t.isServer)return()=>ce("script",{nonce:t.options.ssr?.nonce,class:"$tsr",innerHTML:e.children},null);const s=we(!1);return at(()=>{s.value=!0}),()=>s.value?null:ce("script",{nonce:t.options.ssr?.nonce,class:"$tsr","data-allow-mismatch":!0,innerHTML:""},null)}}),Zf=ve({name:"ScrollRestoration",setup(){const e=Ce(),t=we(!1);return at(()=>{t.value=!0}),()=>{if(t.value||!e.isScrollRestoring||typeof e.options.scrollRestoration=="function"&&!e.options.scrollRestoration({location:e.latestLocation}))return null;const n=(e.options.getScrollRestorationKey||Pr)(e.latestLocation),r=n!==Pr(e.latestLocation)?n:void 0,i={storageKey:xn,shouldScrollRestoration:!0};return r&&(i.key=r),e.isServer?ce(uo,{children:`(${Oa.toString()})(${JSON.stringify(i)})`},null):ce(uo,{children:""},null)}}}),Ka=ve({name:"Match",props:{matchId:{type:String,required:!0}},setup(e){const t=Ce();let s=null;const n=_e({select:f=>{let l=f.matches.find(y=>y.id===e.matchId),d=l?f.matches.findIndex(y=>y.id===e.matchId):-1;if(l?s=l.routeId:s&&(l=f.matches.find(y=>y.routeId===s),d=l?f.matches.findIndex(y=>y.routeId===s):-1),!l)return null;const h=l.routeId,g=d>0?f.matches[d-1]?.routeId:null;return{matchId:l.id,routeId:h,parentRouteId:g,loadedAt:f.loadedAt}}});Dt(n.value,`Could not find routeId for matchId "${e.matchId}". Please file an issue!`);const r=fe(()=>n.value?t.routesById[n.value.routeId]:null),i=fe(()=>r.value?.options?.pendingComponent??t?.options?.defaultPendingComponent),o=fe(()=>r.value?.options?.errorComponent??t?.options?.defaultErrorComponent),a=fe(()=>r.value?.options?.onCatch??t?.options?.defaultOnCatch),c=fe(()=>r.value?.isRoot?r.value?.options?.notFoundComponent??t?.options?.notFoundRoute?.options?.component:r.value?.options?.notFoundComponent),u=we(n.value?.matchId??e.matchId);return Qe([()=>e.matchId,()=>n.value?.matchId],([f,l])=>{u.value=l??f},{immediate:!0}),An(Dn,u),()=>{const f=n.value?.matchId??e.matchId;let l=j(zf,{matchId:f});c.value&&(l=j(Uf,{fallback:g=>{if(!c.value||g.routeId&&g.routeId!==n.value?.routeId||!g.routeId&&r.value&&!r.value.isRoot)throw g;return j(c.value,g)},children:l})),o.value&&(l=fi({getResetKey:()=>n.value?.loadedAt??0,errorComponent:o.value||Za,onCatch:g=>{if($e(g))throw g;a.value?.(g)},children:l})),r.value&&(r.value?.options?.wrapInSuspense??i.value??!1)&&(l=j(si,{fallback:i.value?j(i.value):null},{default:()=>l}));const h=[l,n.value?.parentRouteId===Ne&&t.options.scrollRestoration?j(Fe,null,[j(Wf),j(Zf)]):null].filter(Boolean);return h.length===1?h[0]:j(Fe,null,h)}}}),Wf=ve({name:"OnRendered",setup(){const e=Ce(),t=_e({select:s=>s.resolvedLocation?.state.key});return la(()=>{t.value&&e.emit({type:"onRendered",...jt(e.state)})}),()=>null}}),zf=ve({name:"MatchInner",props:{matchId:{type:String,required:!0}},setup(e){const t=Ce();let s=null;const n=_e({select:a=>{let c=a.matches.find(d=>d.id===e.matchId);if(c)s=c.routeId;else if(s){const d=a.matches.find(h=>h.routeId===s);d&&(c=d)}if(!c)return null;const u=c.routeId,f=t.routesById[u].options.remountDeps??t.options.defaultRemountDeps;let l;if(f){const d=f({routeId:u,loaderDeps:c.loaderDeps,params:c._strictParams,search:c._strictSearch});l=d?JSON.stringify(d):void 0}return{routeId:u,match:{id:c.id,status:c.status,error:c.error},remountKey:l}}}),r=fe(()=>n.value?t.routesById[n.value.routeId]:null),i=fe(()=>n.value?.match),o=fe(()=>n.value?.remountKey);return()=>{if(!n.value||!i.value||!r.value)return null;if(i.value.status==="notFound")return Dt($e(i.value.error)),za(t,r.value,i.value.error);if(i.value.status==="redirected")throw Dt(Ue(i.value.error)),t.getMatch(i.value.id)?._nonReactive.loadPromise;if(i.value.status==="error"){const u=r.value.options.errorComponent??t.options.defaultErrorComponent;if(u)return j(u,{error:i.value.error,reset:()=>{t.invalidate()},info:{componentStack:""}});throw i.value.error}if(i.value.status==="pending"){const u=r.value.options.pendingMinMs??t.options.defaultPendingMinMs,f=t.getMatch(i.value.id);if(u&&f&&!f._nonReactive.minPendingPromise&&!t.isServer){const d=ts();f._nonReactive.minPendingPromise=d,setTimeout(()=>{d.resolve(),f._nonReactive.minPendingPromise=void 0},u)}const l=r.value.options.pendingComponent??t.options.defaultPendingComponent;return l?j(l):null}const a=r.value.options.component??t.options.defaultComponent,c=o.value;return a?j(a,c!==void 0?{key:c}:void 0):j(qa,c!==void 0?{key:c}:void 0)}}}),qa=ve({name:"Outlet",setup(){const e=Ce(),t=wt(Dn),s=fe(()=>t?.value||""),n=_e({select:a=>a.matches.find(c=>c.id===s.value)?.routeId}),r=fe(()=>e.routesById[n.value]),i=_e({select:a=>{const u=a.matches.find(f=>f.id===s.value);return u?u.globalNotFound:!1}}),o=_e({select:a=>{const c=a.matches,u=c.findIndex(l=>l.id===s.value),f=c[u+1];return f?{id:f.id,paramsKey:f.routeId+JSON.stringify(f._strictParams)}:null}});return()=>{if(i.value)return za(e,r.value,void 0);if(!o.value)return null;const a=j(Ka,{matchId:o.value.id,key:o.value.paramsKey});return s.value===Ne?j(si,{fallback:e.options.defaultPendingComponent?j(e.options.defaultPendingComponent):null},{default:()=>a}):a}}});function ir(e){return typeof e?.message!="string"?!1:e.message.startsWith("Failed to fetch dynamically imported module")||e.message.startsWith("error loading dynamically imported module")||e.message.startsWith("Importing a module script failed")}function vi(e,t,s){let n,r=null,i=null,o=!1;const a=()=>(n||(n=e().then(u=>(n=void 0,r=u[t],r)).catch(u=>{if(i=u,n=void 0,ir(i))return null;throw u})),n),c=ve({name:"LazyRouteComponent",setup(u){const f=Bc(r&&hr(r)),l=we(i),d=we(!f.value&&!l.value);if(at(()=>{!f.value&&!l.value&&(d.value=!0,a().then(h=>{f.value=h&&hr(h),d.value=!1}).catch(h=>{l.value=h,d.value=!1}))}),l.value&&ir(l.value)&&!o&&typeof window<"u"&&typeof sessionStorage<"u"){const h=`tanstack_router_reload:${l.value.message}`;if(!sessionStorage.getItem(h))return sessionStorage.setItem(h,"1"),o=!0,window.location.reload(),()=>null}if(l.value&&!ir(l.value))throw l.value;return()=>d.value||!f.value?j("div",null):j(f.value,u)}});return c.preload=a,c}const or=e=>fe((t={current:null,previous:null})=>{const s=e();return t.current!==s&&(t.previous=t.current,t.current=s),t});function Kf(e,t,s={},n={}){const r=typeof IntersectionObserver=="function",i=we(null);return la(o=>{const a=e.value,c=typeof n.disabled=="function"?n.disabled():n.disabled;if(!a||!r||c)return;const u=new IntersectionObserver(([f])=>{t(f)},s);i.value=u,u.observe(a),o(()=>{u.disconnect(),i.value=null})}),i}let ar={router:null,mounted:!1};function qf(){const e=Ce();if(e.isServer)return;const t=_e({select:({isLoading:d})=>d}),s=we(!1),n=_e({select:d=>d.matches.some(h=>h.status==="pending")}),r=or(()=>t.value),i=fe(()=>t.value||s.value||n.value),o=or(()=>i.value),a=fe(()=>t.value||n.value),c=or(()=>a.value);e.startTransition=d=>{s.value=!0;try{e.__store.setState(g=>({...g,isTransitioning:!0}))}catch{}const h=()=>{pr(()=>{try{s.value=!1,e.__store.setState(g=>({...g,isTransitioning:!1}))}catch{}})};d(),h()};const u=e.__tsrOriginalStartViewTransition??e.startViewTransition;e.__tsrOriginalStartViewTransition=u,e.startViewTransition=d=>u?.(async()=>{await d(),await pr()});let f;at(()=>{f=e.history.subscribe(e.load);const d=e.buildLocation({to:e.latestLocation.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});Bt(e.latestLocation.href)!==Bt(d.href)&&e.commitLocation({...d,replace:!0})});const l=we(!1);at(()=>{l.value=!0}),Jr(()=>{l.value=!1,f&&f()}),at(()=>{if(typeof window<"u"&&e.ssr||ar.router===e&&ar.mounted)return;ar={router:e,mounted:!0},(async()=>{try{await e.load()}catch(h){console.error(h)}})()}),Qe(()=>t.value,d=>{if(l.value)try{r.value.previous&&!d&&e.emit({type:"onLoad",...jt(e.state)})}catch{}}),Qe(a,d=>{if(l.value)try{c.value.previous&&!d&&e.emit({type:"onBeforeRouteMount",...jt(e.state)})}catch{}}),Qe(i,d=>{if(l.value)try{if(o.value.previous&&!d){const h=jt(e.state);e.emit({type:"onResolved",...h}),e.__store.setState(g=>({...g,status:"idle",resolvedLocation:g.location})),h.hrefChanged&&cf(e)}}catch{}})}const fo=ve({name:"MatchesContent",setup(){return qf(),()=>j(Yf)}}),Gf=ve({name:"Matches",setup(){const e=Ce();return()=>{const t=e?.options?.defaultPendingComponent?j(e.options.defaultPendingComponent):null,s=e?.isServer||typeof document<"u"&&e?.ssr?j(fo):j(si,{fallback:t},{default:()=>j(fo)});return e?.options?.InnerWrap?j(e.options.InnerWrap,null,{default:()=>s}):s}}}),Jf=e=>j("div",{class:"error"},[j("h1",null,"Error"),j("p",null,e.error.message||String(e.error)),j("button",{onClick:e.reset},"Try Again")]),Yf=ve({name:"MatchesInner",setup(){const e=Ce(),t=_e({select:r=>r.matches[0]?.id}),s=_e({select:r=>r.loadedAt}),n=fe(()=>t.value);return An(Dn,n),()=>{const r=t.value?j(Ka,{matchId:t.value}):j("div");return e.options.disableGlobalCatchBoundary?r:j(fi,{getResetKey:()=>s.value,errorComponent:Jf,onCatch:i=>{i.message||i.toString()},children:r})}}});function Xf(e){return _e({select:t=>{const s=t?.matches||[];return e?.select?e.select(s):s}})}function Qf(e){const t=Ce(),s=we(!1);let n=!1;if(!t)return console.warn("useRouter must be used inside a component!"),{};const r=fe(()=>{try{return new URL(`${e.to}`),"external"}catch{return"internal"}}),i=_e({select:P=>P.location.searchStr}),o=Xf({select:P=>e.from??P[P.length-1]?.fullPath}),a=fe(()=>({...e,from:o.value})),c=fe(()=>(i.value,t.buildLocation(a.value))),u=fe(()=>a.value.reloadDocument?!1:e.preload??t.options.defaultPreload),f=fe(()=>e.preloadDelay??t.options.defaultPreloadDelay??0),l=_e({select:P=>{const H=e.activeOptions;if(H?.exact){if(!Qu(P.location.pathname,c.value.pathname,t.basepath))return!1}else{const te=bn(P.location.pathname,t.basepath).split("/");if(!bn(c.value?.pathname,t.basepath)?.split("/")?.every((oe,nt)=>oe===te[nt]))return!1}return(H?.includeSearch??!0)&&!$t(P.location.search,c.value.search,{partial:!H?.exact,ignoreUndefined:!H?.explicitUndefined})?!1:H?.includeHash?P.location.hash===c.value.hash:!0}}),d=()=>t.preloadRoute(a.value).catch(P=>{console.warn(P),console.warn(Tf)}),h=P=>{P?.isIntersecting&&d()},g=we(null);Kf(g,h,{rootMargin:"100px"},{disabled:()=>!!e.disabled||u.value!=="viewport"}),_c(()=>{n||!e.disabled&&u.value==="render"&&(d(),n=!0)});const y=()=>{const P={};for(const H in e)["activeProps","inactiveProps","activeOptions","to","preload","preloadDelay","hashScrollIntoView","replace","startTransition","resetScroll","viewTransition","children","target","disabled","style","class","onClick","onFocus","onMouseEnter","onMouseLeave","onMouseOver","onMouseOut","onTouchStart","ignoreBlocker","params","search","hash","state","mask","reloadDocument","_asChild","from","additionalProps"].includes(H)||(P[H]=e[H]);return P};if(r.value==="external"){const P={...y(),ref:g,href:e.to,target:e.target,disabled:e.disabled,style:e.style,class:e.class,onClick:e.onClick,onFocus:e.onFocus,onMouseEnter:e.onMouseEnter,onMouseLeave:e.onMouseLeave,onMouseOver:e.onMouseOver,onMouseOut:e.onMouseOut,onTouchStart:e.onTouchStart};return Object.keys(P).forEach(H=>{P[H]===void 0&&delete P[H]}),P}const x=P=>{const H=P.currentTarget?.getAttribute("target"),te=e.target!==void 0?e.target:H;if(!e.disabled&&!td(P)&&!P.defaultPrevented&&(!te||te==="_self")&&P.button===0){if(a.value.reloadDocument)return;P.preventDefault(),s.value=!0;const Q=t.subscribe("onResolved",()=>{Q(),s.value=!1});t.navigate({...a.value,replace:e.replace,resetScroll:e.resetScroll,hashScrollIntoView:e.hashScrollIntoView,startTransition:e.startTransition,viewTransition:e.viewTransition,ignoreBlocker:e.ignoreBlocker})}},b=P=>{e.disabled||u.value&&d()},L=P=>{e.disabled||u.value&&d()},$=P=>{if(e.disabled)return;const H=P.currentTarget||P.target||{};if(u.value){if(H.preloadTimeout)return;H.preloadTimeout=setTimeout(()=>{H.preloadTimeout=null,d()},f.value)}},C=P=>{if(e.disabled)return;const H=P.currentTarget||P.target||{};H.preloadTimeout&&(clearTimeout(H.preloadTimeout),H.preloadTimeout=null)};function k(P){return H=>{for(const te of P)te&&te(H)}}const _=fe(()=>{const P=e.activeProps||(()=>({class:"active"}));return(l.value?typeof P=="function"?P():P:{})||{class:void 0,style:void 0}}),D=fe(()=>{const P=e.inactiveProps||(()=>({}));return(l.value?{}:typeof P=="function"?P():P)||{class:void 0,style:void 0}}),M=fe(()=>{const P=[e.class,_.value?.class,D.value?.class].filter(Boolean);return P.length?P.join(" "):void 0}),B=fe(()=>{const P={};return e.style&&Object.assign(P,e.style),_.value?.style&&Object.assign(P,_.value.style),D.value?.style&&Object.assign(P,D.value.style),Object.keys(P).length>0?P:void 0}),W=fe(()=>{if(e.disabled)return;const P=c.value,H=P?.maskedLocation;let te;return H?te=H.url.href:te=P?.url.href,t.origin&&te?.startsWith(t.origin)&&(te=t.history.createHref(te.replace(t.origin,""))),te}),J={onClick:k([e.onClick,x]),onFocus:k([e.onFocus,b]),onMouseenter:k([e.onMouseEnter,$]),onMouseover:k([e.onMouseOver,$]),onMouseleave:k([e.onMouseLeave,C]),onMouseout:k([e.onMouseOut,C]),onTouchstart:k([e.onTouchStart,L])};return fe(()=>{const P={...y(),href:W.value,ref:g,...J,disabled:!!e.disabled,target:e.target};B.value&&(P.style=B.value),M.value&&(P.class=M.value),e.disabled&&(P.role="link",P["aria-disabled"]=!0),l.value&&(P["data-status"]="active",P["aria-current"]="page"),s.value&&(P["data-transitioning"]="transitioning");const H=_.value,te=D.value;for(const Q of Object.keys(H))Q!=="class"&&Q!=="style"&&(P[Q]=H[Q]);for(const Q of Object.keys(te))Q!=="class"&&Q!=="style"&&(P[Q]=te[Q]);return P})}const ed=ve({name:"Link",inheritAttrs:!1,props:["_asChild","to","preload","preloadDelay","activeProps","inactiveProps","activeOptions","from","search","params","hash","state","mask","reloadDocument","disabled","additionalProps","viewTransition","resetScroll","startTransition","hashScrollIntoView","replace","ignoreBlocker","target"],setup(e,{attrs:t,slots:s}){const n={...e,...t},r=Qf(n);return()=>{const i=e._asChild||"a",o=r.value,a=o["data-status"]==="active",c=o["data-transitioning"]==="transitioning",u=s.default?s.default({isActive:a,isTransitioning:c}):[];if(i==="svg"){const f={...o};return delete f.class,j("svg",{},[j("a",f,u)])}return typeof i!="string"?j(i,{...o,children:u},u):j(i,o,u)}}}),ho=ed;function td(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}const ms=e=>e,sd=e=>new nd(e);class nd extends Sf{constructor(t){super(t)}}const rd=ve({name:"RouterContextProvider",props:{router:{type:Object,required:!0}},setup(e,{attrs:t,slots:s}){const n=e.router,r=t;return n.update({...n.options,...r,context:{...n.options.context,...r.context||{}}}),Af(n),()=>{const i=s.default?.();if(n.options.Wrap){const o=n.options.Wrap;return j(o,null,()=>i)}return Array.isArray(i)&&i.length===1?i[0]:i}}}),id=ve({name:"RouterProvider",props:{router:{type:Object,required:!0}},setup(e,{attrs:t}){const s=t;return()=>j(rd,{router:e.router,...s},{default:()=>j(Gf)})}}),od=ve({name:"Title",props:{children:{type:String,default:""}},setup(e){return Ce().isServer||(at(()=>{e.children&&(document.title=e.children)}),Qe(()=>e.children,s=>{s&&(document.title=s)})),()=>j("title",{},e.children)}}),ad=ve({name:"Script",props:{attrs:{type:Object,default:()=>({})},children:{type:String,default:void 0}},setup(e){const t=Ce();return t.isServer||at(()=>{const s=e.attrs,n=e.children;if(s?.src){const r=(()=>{try{const a=document.baseURI||window.location.href;return new URL(s.src,a).href}catch{return s.src}})();if(Array.from(document.querySelectorAll("script[src]")).find(a=>a.src===r))return;const o=document.createElement("script");for(const[a,c]of Object.entries(s))c!==void 0&&c!==!1&&o.setAttribute(a,typeof c=="boolean"?"":String(c));document.head.appendChild(o)}else if(typeof n=="string"){const r=typeof s?.type=="string"?s.type:"text/javascript",i=typeof s?.nonce=="string"?s.nonce:void 0;if(Array.from(document.querySelectorAll("script:not([src])")).find(c=>{if(!(c instanceof HTMLScriptElement))return!1;const u=c.getAttribute("type")??"text/javascript",f=c.getAttribute("nonce")??void 0;return c.textContent===n&&u===r&&f===i}))return;const a=document.createElement("script");if(a.textContent=n,s)for(const[c,u]of Object.entries(s))u!==void 0&&u!==!1&&a.setAttribute(c,typeof u=="boolean"?"":String(u));document.head.appendChild(a)}}),()=>{if(!t.isServer){const{src:s,...n}=e.attrs||{};return j("script",{...n,"data-allow-mismatch":!0,innerHTML:""})}return e.attrs?.src&&typeof e.attrs.src=="string"?j("script",e.attrs):typeof e.children=="string"?j("script",{...e.attrs,innerHTML:e.children}):null}}});function cd({tag:e,attrs:t,children:s}){switch(e){case"title":return j(od,{children:s});case"meta":return ce("meta",t,null);case"link":return ce("link",t,null);case"style":return ce("style",ri(t,{innerHTML:s}),null);case"script":return j(ad,{attrs:t,children:s});default:return null}}const ld=()=>{const e=Ce(),t=_e({select:o=>o.matches.map(a=>a.meta).filter(Boolean)}),s=fe(()=>{const o=[],a={};let c;return[...t.value].reverse().forEach(u=>{[...u].reverse().forEach(f=>{if(f)if(f.title)c||(c={tag:"title",children:f.title});else{const l=f.name??f.property;if(l){if(a[l])return;a[l]=!0}o.push({tag:"meta",attrs:{...f}})}})}),c&&o.push(c),o.reverse(),o}),n=_e({select:o=>o.matches.map(a=>a.links).filter(Boolean).flat(1).map(a=>({tag:"link",attrs:{...a}}))}),r=_e({select:o=>{const a=[];return o.matches.map(c=>e.looseRoutesById[c.routeId]).forEach(c=>e.ssr?.manifest?.routes[c.id]?.preloads?.filter(Boolean).forEach(u=>{a.push({tag:"link",attrs:{rel:"modulepreload",href:u}})})),a}}),i=_e({select:o=>o.matches.map(a=>a.headScripts).flat(1).filter(Boolean).map(({children:a,...c})=>({tag:"script",attrs:{...c},children:a}))});return()=>fd([...s.value,...r.value,...n.value,...i.value],o=>JSON.stringify(o))},ud=ve({name:"HeadContent",setup(){const e=ld();return()=>e().map(t=>j(cd,{...t,key:`tsr-meta-${JSON.stringify(t)}`}))}});function fd(e,t){const s=new Set;return e.filter(n=>{const r=t(n);return s.has(r)?!1:(s.add(r),!0)})}const dd="modulepreload",hd=function(e){return"/"+e},po={},ls=function(t,s,n){let r=Promise.resolve();if(s&&s.length>0){let c=function(u){return Promise.all(u.map(f=>Promise.resolve(f).then(l=>({status:"fulfilled",value:l}),l=>({status:"rejected",reason:l}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),a=o?.nonce||o?.getAttribute("nonce");r=c(s.map(u=>{if(u=hd(u),u in po)return;po[u]=!0;const f=u.endsWith(".css"),l=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${l}`))return;const d=document.createElement("link");if(d.rel=f?"stylesheet":dd,f||(d.as="script"),d.crossOrigin="",d.href=u,a&&d.setAttribute("nonce",a),document.head.appendChild(d),f)return new Promise((h,g)=>{d.addEventListener("load",h),d.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return r.then(o=>{for(const a of o||[])a.status==="rejected"&&i(a.reason);return t().catch(i)})},pd=ve({name:"NullTanStackRouterDevtools",setup(){return()=>null}}),md=pd,Wt=Vf({component:gd});function gd(){return ce(Fe,null,[ce(ud,null,null),ce(mo,{type:"header"},null),ce("hr",null,null),ce(qa,null,null),ce("hr",null,null),ce(mo,{type:"footer"},null),ce(md,{position:"bottom-right"},null)])}function mo({type:e}){const t=e==="header"?"header":"footer",s=e==="header"?"Head":"Foot";return ce(t,{class:"p-2 flex gap-2 text-lg"},{default:()=>[ce(ho,{to:"/",activeProps:{class:"font-bold"},activeOptions:{exact:!0}},{default:()=>[s,xr("-/")]})," ",[ms({to:"/normal-page"}),ms({to:"/lazy-page"}),ms({to:"/virtual-page"}),ms({to:"/lazy-with-loader-page"}),ms({to:"/page-with-search",search:{where:e}})].map(n=>ce(ho,ri(n,{activeProps:{class:"font-bold"}}),{default:()=>[s,xr("-"),n.to]}))]})}const vd=()=>ls(()=>import("./index-rPfEOKs3.js"),[]),yd=cs("/")({component:vi(vd,"component")});var re;(function(e){e.assertEqual=r=>{};function t(r){}e.assertIs=t;function s(r){throw new Error}e.assertNever=s,e.arrayToEnum=r=>{const i={};for(const o of r)i[o]=o;return i},e.getValidEnumValues=r=>{const i=e.objectKeys(r).filter(a=>typeof r[r[a]]!="number"),o={};for(const a of i)o[a]=r[a];return e.objectValues(o)},e.objectValues=r=>e.objectKeys(r).map(function(i){return r[i]}),e.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{const i=[];for(const o in r)Object.prototype.hasOwnProperty.call(r,o)&&i.push(o);return i},e.find=(r,i)=>{for(const o of r)if(i(o))return o},e.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&Number.isFinite(r)&&Math.floor(r)===r;function n(r,i=" | "){return r.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}e.joinValues=n,e.jsonStringifyReplacer=(r,i)=>typeof i=="bigint"?i.toString():i})(re||(re={}));var go;(function(e){e.mergeShapes=(t,s)=>({...t,...s})})(go||(go={}));const V=re.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),gt=e=>{switch(typeof e){case"undefined":return V.undefined;case"string":return V.string;case"number":return Number.isNaN(e)?V.nan:V.number;case"boolean":return V.boolean;case"function":return V.function;case"bigint":return V.bigint;case"symbol":return V.symbol;case"object":return Array.isArray(e)?V.array:e===null?V.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?V.promise:typeof Map<"u"&&e instanceof Map?V.map:typeof Set<"u"&&e instanceof Set?V.set:typeof Date<"u"&&e instanceof Date?V.date:V.object;default:return V.unknown}},I=re.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ft extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const s=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,s):this.__proto__=s,this.name="ZodError",this.issues=t}format(t){const s=t||function(i){return i.message},n={_errors:[]},r=i=>{for(const o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(r);else if(o.code==="invalid_return_type")r(o.returnTypeError);else if(o.code==="invalid_arguments")r(o.argumentsError);else if(o.path.length===0)n._errors.push(s(o));else{let a=n,c=0;for(;cs.message){const s={},n=[];for(const r of this.issues)r.path.length>0?(s[r.path[0]]=s[r.path[0]]||[],s[r.path[0]].push(t(r))):n.push(t(r));return{formErrors:n,fieldErrors:s}}get formErrors(){return this.flatten()}}ft.create=e=>new ft(e);const Tr=(e,t)=>{let s;switch(e.code){case I.invalid_type:e.received===V.undefined?s="Required":s=`Expected ${e.expected}, received ${e.received}`;break;case I.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(e.expected,re.jsonStringifyReplacer)}`;break;case I.unrecognized_keys:s=`Unrecognized key(s) in object: ${re.joinValues(e.keys,", ")}`;break;case I.invalid_union:s="Invalid input";break;case I.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${re.joinValues(e.options)}`;break;case I.invalid_enum_value:s=`Invalid enum value. Expected ${re.joinValues(e.options)}, received '${e.received}'`;break;case I.invalid_arguments:s="Invalid function arguments";break;case I.invalid_return_type:s="Invalid function return type";break;case I.invalid_date:s="Invalid date";break;case I.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(s=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(s=`${s} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?s=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?s=`Invalid input: must end with "${e.validation.endsWith}"`:re.assertNever(e.validation):e.validation!=="regex"?s=`Invalid ${e.validation}`:s="Invalid";break;case I.too_small:e.type==="array"?s=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?s=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?s=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?s=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:s="Invalid input";break;case I.too_big:e.type==="array"?s=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?s=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?s=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?s=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?s=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:s="Invalid input";break;case I.custom:s="Invalid input";break;case I.invalid_intersection_types:s="Intersection results could not be merged";break;case I.not_multiple_of:s=`Number must be a multiple of ${e.multipleOf}`;break;case I.not_finite:s="Number must be finite";break;default:s=t.defaultError,re.assertNever(e)}return{message:s}};let _d=Tr;function bd(){return _d}const xd=e=>{const{data:t,path:s,errorMaps:n,issueData:r}=e,i=[...s,...r.path||[]],o={...r,path:i};if(r.message!==void 0)return{...r,path:i,message:r.message};let a="";const c=n.filter(u=>!!u).slice().reverse();for(const u of c)a=u(o,{data:t,defaultError:a}).message;return{...r,path:i,message:a}};function N(e,t){const s=bd(),n=xd({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,s,s===Tr?void 0:Tr].filter(r=>!!r)});e.common.issues.push(n)}class Ae{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,s){const n=[];for(const r of s){if(r.status==="aborted")return q;r.status==="dirty"&&t.dirty(),n.push(r.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,s){const n=[];for(const r of s){const i=await r.key,o=await r.value;n.push({key:i,value:o})}return Ae.mergeObjectSync(t,n)}static mergeObjectSync(t,s){const n={};for(const r of s){const{key:i,value:o}=r;if(i.status==="aborted"||o.status==="aborted")return q;i.status==="dirty"&&t.dirty(),o.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||r.alwaysSet)&&(n[i.value]=o.value)}return{status:t.value,value:n}}}const q=Object.freeze({status:"aborted"}),ys=e=>({status:"dirty",value:e}),Be=e=>({status:"valid",value:e}),vo=e=>e.status==="aborted",yo=e=>e.status==="dirty",ns=e=>e.status==="valid",Rn=e=>typeof Promise<"u"&&e instanceof Promise;var U;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(U||(U={}));class It{constructor(t,s,n,r){this._cachedPath=[],this.parent=t,this.data=s,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const _o=(e,t)=>{if(ns(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const s=new ft(e.common.issues);return this._error=s,this._error}}};function ee(e){if(!e)return{};const{errorMap:t,invalid_type_error:s,required_error:n,description:r}=e;if(t&&(s||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:r}:{errorMap:(o,a)=>{const{message:c}=e;return o.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:c??s??a.defaultError}},description:r}}class ne{get description(){return this._def.description}_getType(t){return gt(t.data)}_getOrReturnCtx(t,s){return s||{common:t.parent.common,data:t.data,parsedType:gt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Ae,ctx:{common:t.parent.common,data:t.data,parsedType:gt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const s=this._parse(t);if(Rn(s))throw new Error("Synchronous parse encountered promise.");return s}_parseAsync(t){const s=this._parse(t);return Promise.resolve(s)}parse(t,s){const n=this.safeParse(t,s);if(n.success)return n.data;throw n.error}safeParse(t,s){const n={common:{issues:[],async:s?.async??!1,contextualErrorMap:s?.errorMap},path:s?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:gt(t)},r=this._parseSync({data:t,path:n.path,parent:n});return _o(n,r)}"~validate"(t){const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:gt(t)};if(!this["~standard"].async)try{const n=this._parseSync({data:t,path:[],parent:s});return ns(n)?{value:n.value}:{issues:s.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),s.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:s}).then(n=>ns(n)?{value:n.value}:{issues:s.common.issues})}async parseAsync(t,s){const n=await this.safeParseAsync(t,s);if(n.success)return n.data;throw n.error}async safeParseAsync(t,s){const n={common:{issues:[],contextualErrorMap:s?.errorMap,async:!0},path:s?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:gt(t)},r=this._parse({data:t,path:n.path,parent:n}),i=await(Rn(r)?r:Promise.resolve(r));return _o(n,i)}refine(t,s){const n=r=>typeof s=="string"||typeof s>"u"?{message:s}:typeof s=="function"?s(r):s;return this._refinement((r,i)=>{const o=t(r),a=()=>i.addIssue({code:I.custom,...n(r)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(t,s){return this._refinement((n,r)=>t(n)?!0:(r.addIssue(typeof s=="function"?s(n,r):s),!1))}_refinement(t){return new is({schema:this,typeName:G.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:s=>this["~validate"](s)}}optional(){return Ct.create(this,this._def)}nullable(){return os.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return et.create(this)}promise(){return Tn.create(this,this._def)}or(t){return Pn.create([this,t],this._def)}and(t){return kn.create(this,t,this._def)}transform(t){return new is({...ee(this._def),schema:this,typeName:G.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const s=typeof t=="function"?t:()=>t;return new Lr({...ee(this._def),innerType:this,defaultValue:s,typeName:G.ZodDefault})}brand(){return new Zd({typeName:G.ZodBranded,type:this,...ee(this._def)})}catch(t){const s=typeof t=="function"?t:()=>t;return new Mr({...ee(this._def),innerType:this,catchValue:s,typeName:G.ZodCatch})}describe(t){const s=this.constructor;return new s({...this._def,description:t})}pipe(t){return yi.create(this,t)}readonly(){return Er.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const wd=/^c[^\s-]{8,}$/i,Sd=/^[0-9a-z]+$/,Rd=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Cd=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Pd=/^[a-z0-9_-]{21}$/i,kd=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Td=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Id=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ld="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let cr;const Md=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Ed=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Od=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Ad=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Nd=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Fd=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ga="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",$d=new RegExp(`^${Ga}$`);function Ja(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);const s=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${s}`}function Bd(e){return new RegExp(`^${Ja(e)}$`)}function jd(e){let t=`${Ga}T${Ja(e)}`;const s=[];return s.push(e.local?"Z?":"Z"),e.offset&&s.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${s.join("|")})`,new RegExp(`^${t}$`)}function Dd(e,t){return!!((t==="v4"||!t)&&Md.test(e)||(t==="v6"||!t)&&Od.test(e))}function Vd(e,t){if(!kd.test(e))return!1;try{const[s]=e.split("."),n=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(s.length+(4-s.length%4)%4,"="),r=JSON.parse(atob(n));return!(typeof r!="object"||r===null||"typ"in r&&r?.typ!=="JWT"||!r.alg||t&&r.alg!==t)}catch{return!1}}function Ud(e,t){return!!((t==="v4"||!t)&&Ed.test(e)||(t==="v6"||!t)&&Ad.test(e))}class bt extends ne{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==V.string){const i=this._getOrReturnCtx(t);return N(i,{code:I.invalid_type,expected:V.string,received:i.parsedType}),q}const n=new Ae;let r;for(const i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(r=this._getOrReturnCtx(t,r),N(r,{code:I.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){const o=t.data.length>i.value,a=t.data.lengtht.test(r),{validation:s,code:I.invalid_string,...U.errToObj(n)})}_addCheck(t){return new bt({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...U.errToObj(t)})}url(t){return this._addCheck({kind:"url",...U.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...U.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...U.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...U.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...U.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...U.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...U.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...U.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...U.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...U.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...U.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...U.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...U.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...U.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...U.errToObj(t)})}regex(t,s){return this._addCheck({kind:"regex",regex:t,...U.errToObj(s)})}includes(t,s){return this._addCheck({kind:"includes",value:t,position:s?.position,...U.errToObj(s?.message)})}startsWith(t,s){return this._addCheck({kind:"startsWith",value:t,...U.errToObj(s)})}endsWith(t,s){return this._addCheck({kind:"endsWith",value:t,...U.errToObj(s)})}min(t,s){return this._addCheck({kind:"min",value:t,...U.errToObj(s)})}max(t,s){return this._addCheck({kind:"max",value:t,...U.errToObj(s)})}length(t,s){return this._addCheck({kind:"length",value:t,...U.errToObj(s)})}nonempty(t){return this.min(1,U.errToObj(t))}trim(){return new bt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new bt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new bt({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const s of this._def.checks)s.kind==="min"&&(t===null||s.value>t)&&(t=s.value);return t}get maxLength(){let t=null;for(const s of this._def.checks)s.kind==="max"&&(t===null||s.valuenew bt({checks:[],typeName:G.ZodString,coerce:e?.coerce??!1,...ee(e)});function Hd(e,t){const s=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,r=s>n?s:n,i=Number.parseInt(e.toFixed(r).replace(".","")),o=Number.parseInt(t.toFixed(r).replace(".",""));return i%o/10**r}class Vs extends ne{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==V.number){const i=this._getOrReturnCtx(t);return N(i,{code:I.invalid_type,expected:V.number,received:i.parsedType}),q}let n;const r=new Ae;for(const i of this._def.checks)i.kind==="int"?re.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),N(n,{code:I.invalid_type,expected:"integer",received:"float",message:i.message}),r.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(n=this._getOrReturnCtx(t,n),N(n,{code:I.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="multipleOf"?Hd(t.data,i.value)!==0&&(n=this._getOrReturnCtx(t,n),N(n,{code:I.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),N(n,{code:I.not_finite,message:i.message}),r.dirty()):re.assertNever(i);return{status:r.value,value:t.data}}gte(t,s){return this.setLimit("min",t,!0,U.toString(s))}gt(t,s){return this.setLimit("min",t,!1,U.toString(s))}lte(t,s){return this.setLimit("max",t,!0,U.toString(s))}lt(t,s){return this.setLimit("max",t,!1,U.toString(s))}setLimit(t,s,n,r){return new Vs({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:n,message:U.toString(r)}]})}_addCheck(t){return new Vs({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:U.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:U.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:U.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:U.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:U.toString(t)})}multipleOf(t,s){return this._addCheck({kind:"multipleOf",value:t,message:U.toString(s)})}finite(t){return this._addCheck({kind:"finite",message:U.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:U.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:U.toString(t)})}get minValue(){let t=null;for(const s of this._def.checks)s.kind==="min"&&(t===null||s.value>t)&&(t=s.value);return t}get maxValue(){let t=null;for(const s of this._def.checks)s.kind==="max"&&(t===null||s.valuet.kind==="int"||t.kind==="multipleOf"&&re.isInteger(t.value))}get isFinite(){let t=null,s=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(s===null||n.value>s)&&(s=n.value):n.kind==="max"&&(t===null||n.valuenew Vs({checks:[],typeName:G.ZodNumber,coerce:e?.coerce||!1,...ee(e)});class Us extends ne{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==V.bigint)return this._getInvalidInput(t);let n;const r=new Ae;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(n=this._getOrReturnCtx(t,n),N(n,{code:I.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),N(n,{code:I.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):re.assertNever(i);return{status:r.value,value:t.data}}_getInvalidInput(t){const s=this._getOrReturnCtx(t);return N(s,{code:I.invalid_type,expected:V.bigint,received:s.parsedType}),q}gte(t,s){return this.setLimit("min",t,!0,U.toString(s))}gt(t,s){return this.setLimit("min",t,!1,U.toString(s))}lte(t,s){return this.setLimit("max",t,!0,U.toString(s))}lt(t,s){return this.setLimit("max",t,!1,U.toString(s))}setLimit(t,s,n,r){return new Us({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:n,message:U.toString(r)}]})}_addCheck(t){return new Us({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:U.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:U.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:U.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:U.toString(t)})}multipleOf(t,s){return this._addCheck({kind:"multipleOf",value:t,message:U.toString(s)})}get minValue(){let t=null;for(const s of this._def.checks)s.kind==="min"&&(t===null||s.value>t)&&(t=s.value);return t}get maxValue(){let t=null;for(const s of this._def.checks)s.kind==="max"&&(t===null||s.valuenew Us({checks:[],typeName:G.ZodBigInt,coerce:e?.coerce??!1,...ee(e)});class bo extends ne{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==V.boolean){const n=this._getOrReturnCtx(t);return N(n,{code:I.invalid_type,expected:V.boolean,received:n.parsedType}),q}return Be(t.data)}}bo.create=e=>new bo({typeName:G.ZodBoolean,coerce:e?.coerce||!1,...ee(e)});class Cn extends ne{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==V.date){const i=this._getOrReturnCtx(t);return N(i,{code:I.invalid_type,expected:V.date,received:i.parsedType}),q}if(Number.isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return N(i,{code:I.invalid_date}),q}const n=new Ae;let r;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(r=this._getOrReturnCtx(t,r),N(r,{code:I.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):re.assertNever(i);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Cn({...this._def,checks:[...this._def.checks,t]})}min(t,s){return this._addCheck({kind:"min",value:t.getTime(),message:U.toString(s)})}max(t,s){return this._addCheck({kind:"max",value:t.getTime(),message:U.toString(s)})}get minDate(){let t=null;for(const s of this._def.checks)s.kind==="min"&&(t===null||s.value>t)&&(t=s.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const s of this._def.checks)s.kind==="max"&&(t===null||s.valuenew Cn({checks:[],coerce:e?.coerce||!1,typeName:G.ZodDate,...ee(e)});class xo extends ne{_parse(t){if(this._getType(t)!==V.symbol){const n=this._getOrReturnCtx(t);return N(n,{code:I.invalid_type,expected:V.symbol,received:n.parsedType}),q}return Be(t.data)}}xo.create=e=>new xo({typeName:G.ZodSymbol,...ee(e)});class wo extends ne{_parse(t){if(this._getType(t)!==V.undefined){const n=this._getOrReturnCtx(t);return N(n,{code:I.invalid_type,expected:V.undefined,received:n.parsedType}),q}return Be(t.data)}}wo.create=e=>new wo({typeName:G.ZodUndefined,...ee(e)});class So extends ne{_parse(t){if(this._getType(t)!==V.null){const n=this._getOrReturnCtx(t);return N(n,{code:I.invalid_type,expected:V.null,received:n.parsedType}),q}return Be(t.data)}}So.create=e=>new So({typeName:G.ZodNull,...ee(e)});class Ro extends ne{constructor(){super(...arguments),this._any=!0}_parse(t){return Be(t.data)}}Ro.create=e=>new Ro({typeName:G.ZodAny,...ee(e)});class Co extends ne{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Be(t.data)}}Co.create=e=>new Co({typeName:G.ZodUnknown,...ee(e)});class Lt extends ne{_parse(t){const s=this._getOrReturnCtx(t);return N(s,{code:I.invalid_type,expected:V.never,received:s.parsedType}),q}}Lt.create=e=>new Lt({typeName:G.ZodNever,...ee(e)});class Po extends ne{_parse(t){if(this._getType(t)!==V.undefined){const n=this._getOrReturnCtx(t);return N(n,{code:I.invalid_type,expected:V.void,received:n.parsedType}),q}return Be(t.data)}}Po.create=e=>new Po({typeName:G.ZodVoid,...ee(e)});class et extends ne{_parse(t){const{ctx:s,status:n}=this._processInputParams(t),r=this._def;if(s.parsedType!==V.array)return N(s,{code:I.invalid_type,expected:V.array,received:s.parsedType}),q;if(r.exactLength!==null){const o=s.data.length>r.exactLength.value,a=s.data.lengthr.maxLength.value&&(N(s,{code:I.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),s.common.async)return Promise.all([...s.data].map((o,a)=>r.type._parseAsync(new It(s,o,s.path,a)))).then(o=>Ae.mergeArray(n,o));const i=[...s.data].map((o,a)=>r.type._parseSync(new It(s,o,s.path,a)));return Ae.mergeArray(n,i)}get element(){return this._def.type}min(t,s){return new et({...this._def,minLength:{value:t,message:U.toString(s)}})}max(t,s){return new et({...this._def,maxLength:{value:t,message:U.toString(s)}})}length(t,s){return new et({...this._def,exactLength:{value:t,message:U.toString(s)}})}nonempty(t){return this.min(1,t)}}et.create=(e,t)=>new et({type:e,minLength:null,maxLength:null,exactLength:null,typeName:G.ZodArray,...ee(t)});function qt(e){if(e instanceof ye){const t={};for(const s in e.shape){const n=e.shape[s];t[s]=Ct.create(qt(n))}return new ye({...e._def,shape:()=>t})}else return e instanceof et?new et({...e._def,type:qt(e.element)}):e instanceof Ct?Ct.create(qt(e.unwrap())):e instanceof os?os.create(qt(e.unwrap())):e instanceof Ht?Ht.create(e.items.map(t=>qt(t))):e}class ye extends ne{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),s=re.objectKeys(t);return this._cached={shape:t,keys:s},this._cached}_parse(t){if(this._getType(t)!==V.object){const u=this._getOrReturnCtx(t);return N(u,{code:I.invalid_type,expected:V.object,received:u.parsedType}),q}const{status:n,ctx:r}=this._processInputParams(t),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof Lt&&this._def.unknownKeys==="strip"))for(const u in r.data)o.includes(u)||a.push(u);const c=[];for(const u of o){const f=i[u],l=r.data[u];c.push({key:{status:"valid",value:u},value:f._parse(new It(r,l,r.path,u)),alwaysSet:u in r.data})}if(this._def.catchall instanceof Lt){const u=this._def.unknownKeys;if(u==="passthrough")for(const f of a)c.push({key:{status:"valid",value:f},value:{status:"valid",value:r.data[f]}});else if(u==="strict")a.length>0&&(N(r,{code:I.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const f of a){const l=r.data[f];c.push({key:{status:"valid",value:f},value:u._parse(new It(r,l,r.path,f)),alwaysSet:f in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const u=[];for(const f of c){const l=await f.key,d=await f.value;u.push({key:l,value:d,alwaysSet:f.alwaysSet})}return u}).then(u=>Ae.mergeObjectSync(n,u)):Ae.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return U.errToObj,new ye({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(s,n)=>{const r=this._def.errorMap?.(s,n).message??n.defaultError;return s.code==="unrecognized_keys"?{message:U.errToObj(t).message??r}:{message:r}}}:{}})}strip(){return new ye({...this._def,unknownKeys:"strip"})}passthrough(){return new ye({...this._def,unknownKeys:"passthrough"})}extend(t){return new ye({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new ye({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:G.ZodObject})}setKey(t,s){return this.augment({[t]:s})}catchall(t){return new ye({...this._def,catchall:t})}pick(t){const s={};for(const n of re.objectKeys(t))t[n]&&this.shape[n]&&(s[n]=this.shape[n]);return new ye({...this._def,shape:()=>s})}omit(t){const s={};for(const n of re.objectKeys(this.shape))t[n]||(s[n]=this.shape[n]);return new ye({...this._def,shape:()=>s})}deepPartial(){return qt(this)}partial(t){const s={};for(const n of re.objectKeys(this.shape)){const r=this.shape[n];t&&!t[n]?s[n]=r:s[n]=r.optional()}return new ye({...this._def,shape:()=>s})}required(t){const s={};for(const n of re.objectKeys(this.shape))if(t&&!t[n])s[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof Ct;)i=i._def.innerType;s[n]=i}return new ye({...this._def,shape:()=>s})}keyof(){return Ya(re.objectKeys(this.shape))}}ye.create=(e,t)=>new ye({shape:()=>e,unknownKeys:"strip",catchall:Lt.create(),typeName:G.ZodObject,...ee(t)});ye.strictCreate=(e,t)=>new ye({shape:()=>e,unknownKeys:"strict",catchall:Lt.create(),typeName:G.ZodObject,...ee(t)});ye.lazycreate=(e,t)=>new ye({shape:e,unknownKeys:"strip",catchall:Lt.create(),typeName:G.ZodObject,...ee(t)});class Pn extends ne{_parse(t){const{ctx:s}=this._processInputParams(t),n=this._def.options;function r(i){for(const a of i)if(a.result.status==="valid")return a.result;for(const a of i)if(a.result.status==="dirty")return s.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(a=>new ft(a.ctx.common.issues));return N(s,{code:I.invalid_union,unionErrors:o}),q}if(s.common.async)return Promise.all(n.map(async i=>{const o={...s,common:{...s.common,issues:[]},parent:null};return{result:await i._parseAsync({data:s.data,path:s.path,parent:o}),ctx:o}})).then(r);{let i;const o=[];for(const c of n){const u={...s,common:{...s.common,issues:[]},parent:null},f=c._parseSync({data:s.data,path:s.path,parent:u});if(f.status==="valid")return f;f.status==="dirty"&&!i&&(i={result:f,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(i)return s.common.issues.push(...i.ctx.common.issues),i.result;const a=o.map(c=>new ft(c));return N(s,{code:I.invalid_union,unionErrors:a}),q}}get options(){return this._def.options}}Pn.create=(e,t)=>new Pn({options:e,typeName:G.ZodUnion,...ee(t)});function Ir(e,t){const s=gt(e),n=gt(t);if(e===t)return{valid:!0,data:e};if(s===V.object&&n===V.object){const r=re.objectKeys(t),i=re.objectKeys(e).filter(a=>r.indexOf(a)!==-1),o={...e,...t};for(const a of i){const c=Ir(e[a],t[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(s===V.array&&n===V.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let i=0;i{if(vo(i)||vo(o))return q;const a=Ir(i.value,o.value);return a.valid?((yo(i)||yo(o))&&s.dirty(),{status:s.value,value:a.data}):(N(n,{code:I.invalid_intersection_types}),q)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,o])=>r(i,o)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}kn.create=(e,t,s)=>new kn({left:e,right:t,typeName:G.ZodIntersection,...ee(s)});class Ht extends ne{_parse(t){const{status:s,ctx:n}=this._processInputParams(t);if(n.parsedType!==V.array)return N(n,{code:I.invalid_type,expected:V.array,received:n.parsedType}),q;if(n.data.lengththis._def.items.length&&(N(n,{code:I.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),s.dirty());const i=[...n.data].map((o,a)=>{const c=this._def.items[a]||this._def.rest;return c?c._parse(new It(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(i).then(o=>Ae.mergeArray(s,o)):Ae.mergeArray(s,i)}get items(){return this._def.items}rest(t){return new Ht({...this._def,rest:t})}}Ht.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ht({items:e,typeName:G.ZodTuple,rest:null,...ee(t)})};class ko extends ne{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:s,ctx:n}=this._processInputParams(t);if(n.parsedType!==V.map)return N(n,{code:I.invalid_type,expected:V.map,received:n.parsedType}),q;const r=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([a,c],u)=>({key:r._parse(new It(n,a,n.path,[u,"key"])),value:i._parse(new It(n,c,n.path,[u,"value"]))}));if(n.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const c of o){const u=await c.key,f=await c.value;if(u.status==="aborted"||f.status==="aborted")return q;(u.status==="dirty"||f.status==="dirty")&&s.dirty(),a.set(u.value,f.value)}return{status:s.value,value:a}})}else{const a=new Map;for(const c of o){const u=c.key,f=c.value;if(u.status==="aborted"||f.status==="aborted")return q;(u.status==="dirty"||f.status==="dirty")&&s.dirty(),a.set(u.value,f.value)}return{status:s.value,value:a}}}}ko.create=(e,t,s)=>new ko({valueType:t,keyType:e,typeName:G.ZodMap,...ee(s)});class Hs extends ne{_parse(t){const{status:s,ctx:n}=this._processInputParams(t);if(n.parsedType!==V.set)return N(n,{code:I.invalid_type,expected:V.set,received:n.parsedType}),q;const r=this._def;r.minSize!==null&&n.data.sizer.maxSize.value&&(N(n,{code:I.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),s.dirty());const i=this._def.valueType;function o(c){const u=new Set;for(const f of c){if(f.status==="aborted")return q;f.status==="dirty"&&s.dirty(),u.add(f.value)}return{status:s.value,value:u}}const a=[...n.data.values()].map((c,u)=>i._parse(new It(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(t,s){return new Hs({...this._def,minSize:{value:t,message:U.toString(s)}})}max(t,s){return new Hs({...this._def,maxSize:{value:t,message:U.toString(s)}})}size(t,s){return this.min(t,s).max(t,s)}nonempty(t){return this.min(1,t)}}Hs.create=(e,t)=>new Hs({valueType:e,minSize:null,maxSize:null,typeName:G.ZodSet,...ee(t)});class To extends ne{get schema(){return this._def.getter()}_parse(t){const{ctx:s}=this._processInputParams(t);return this._def.getter()._parse({data:s.data,path:s.path,parent:s})}}To.create=(e,t)=>new To({getter:e,typeName:G.ZodLazy,...ee(t)});class Io extends ne{_parse(t){if(t.data!==this._def.value){const s=this._getOrReturnCtx(t);return N(s,{received:s.data,code:I.invalid_literal,expected:this._def.value}),q}return{status:"valid",value:t.data}}get value(){return this._def.value}}Io.create=(e,t)=>new Io({value:e,typeName:G.ZodLiteral,...ee(t)});function Ya(e,t){return new rs({values:e,typeName:G.ZodEnum,...ee(t)})}class rs extends ne{_parse(t){if(typeof t.data!="string"){const s=this._getOrReturnCtx(t),n=this._def.values;return N(s,{expected:re.joinValues(n),received:s.parsedType,code:I.invalid_type}),q}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const s=this._getOrReturnCtx(t),n=this._def.values;return N(s,{received:s.data,code:I.invalid_enum_value,options:n}),q}return Be(t.data)}get options(){return this._def.values}get enum(){const t={};for(const s of this._def.values)t[s]=s;return t}get Values(){const t={};for(const s of this._def.values)t[s]=s;return t}get Enum(){const t={};for(const s of this._def.values)t[s]=s;return t}extract(t,s=this._def){return rs.create(t,{...this._def,...s})}exclude(t,s=this._def){return rs.create(this.options.filter(n=>!t.includes(n)),{...this._def,...s})}}rs.create=Ya;class Lo extends ne{_parse(t){const s=re.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==V.string&&n.parsedType!==V.number){const r=re.objectValues(s);return N(n,{expected:re.joinValues(r),received:n.parsedType,code:I.invalid_type}),q}if(this._cache||(this._cache=new Set(re.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const r=re.objectValues(s);return N(n,{received:n.data,code:I.invalid_enum_value,options:r}),q}return Be(t.data)}get enum(){return this._def.values}}Lo.create=(e,t)=>new Lo({values:e,typeName:G.ZodNativeEnum,...ee(t)});class Tn extends ne{unwrap(){return this._def.type}_parse(t){const{ctx:s}=this._processInputParams(t);if(s.parsedType!==V.promise&&s.common.async===!1)return N(s,{code:I.invalid_type,expected:V.promise,received:s.parsedType}),q;const n=s.parsedType===V.promise?s.data:Promise.resolve(s.data);return Be(n.then(r=>this._def.type.parseAsync(r,{path:s.path,errorMap:s.common.contextualErrorMap})))}}Tn.create=(e,t)=>new Tn({type:e,typeName:G.ZodPromise,...ee(t)});class is extends ne{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===G.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:s,ctx:n}=this._processInputParams(t),r=this._def.effect||null,i={addIssue:o=>{N(n,o),o.fatal?s.abort():s.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type==="preprocess"){const o=r.transform(n.data,i);if(n.common.async)return Promise.resolve(o).then(async a=>{if(s.value==="aborted")return q;const c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?q:c.status==="dirty"||s.value==="dirty"?ys(c.value):c});{if(s.value==="aborted")return q;const a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?q:a.status==="dirty"||s.value==="dirty"?ys(a.value):a}}if(r.type==="refinement"){const o=a=>{const c=r.refinement(a,i);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?q:(a.status==="dirty"&&s.dirty(),o(a.value),{status:s.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?q:(a.status==="dirty"&&s.dirty(),o(a.value).then(()=>({status:s.value,value:a.value}))))}if(r.type==="transform")if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ns(o))return q;const a=r.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:s.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>ns(o)?Promise.resolve(r.transform(o.value,i)).then(a=>({status:s.value,value:a})):q);re.assertNever(r)}}is.create=(e,t,s)=>new is({schema:e,typeName:G.ZodEffects,effect:t,...ee(s)});is.createWithPreprocess=(e,t,s)=>new is({schema:t,effect:{type:"preprocess",transform:e},typeName:G.ZodEffects,...ee(s)});class Ct extends ne{_parse(t){return this._getType(t)===V.undefined?Be(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Ct.create=(e,t)=>new Ct({innerType:e,typeName:G.ZodOptional,...ee(t)});class os extends ne{_parse(t){return this._getType(t)===V.null?Be(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}os.create=(e,t)=>new os({innerType:e,typeName:G.ZodNullable,...ee(t)});class Lr extends ne{_parse(t){const{ctx:s}=this._processInputParams(t);let n=s.data;return s.parsedType===V.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:s.path,parent:s})}removeDefault(){return this._def.innerType}}Lr.create=(e,t)=>new Lr({innerType:e,typeName:G.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...ee(t)});class Mr extends ne{_parse(t){const{ctx:s}=this._processInputParams(t),n={...s,common:{...s.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Rn(r)?r.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ft(n.common.issues)},input:n.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new ft(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Mr.create=(e,t)=>new Mr({innerType:e,typeName:G.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...ee(t)});class Mo extends ne{_parse(t){if(this._getType(t)!==V.nan){const n=this._getOrReturnCtx(t);return N(n,{code:I.invalid_type,expected:V.nan,received:n.parsedType}),q}return{status:"valid",value:t.data}}}Mo.create=e=>new Mo({typeName:G.ZodNaN,...ee(e)});class Zd extends ne{_parse(t){const{ctx:s}=this._processInputParams(t),n=s.data;return this._def.type._parse({data:n,path:s.path,parent:s})}unwrap(){return this._def.type}}class yi extends ne{_parse(t){const{status:s,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?q:i.status==="dirty"?(s.dirty(),ys(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{const r=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return r.status==="aborted"?q:r.status==="dirty"?(s.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:n.path,parent:n})}}static create(t,s){return new yi({in:t,out:s,typeName:G.ZodPipeline})}}class Er extends ne{_parse(t){const s=this._def.innerType._parse(t),n=r=>(ns(r)&&(r.value=Object.freeze(r.value)),r);return Rn(s)?s.then(r=>n(r)):n(s)}unwrap(){return this._def.innerType}}Er.create=(e,t)=>new Er({innerType:e,typeName:G.ZodReadonly,...ee(t)});var G;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(G||(G={}));const Wd=bt.create;Lt.create;et.create;const zd=ye.create;Pn.create;kn.create;Ht.create;rs.create;Tn.create;Ct.create;os.create;const Kd=e=>{const t="input"in e?e.input:"input",s="output"in e?e.output:"output",n="schema"in e?e.schema._input:e._input,r="schema"in e?e.schema._output:e._output;return{types:{input:t==="output"?r:n,output:s==="input"?n:r},parse:i=>"schema"in e?e.schema.parse(i):e.parse(i)}},qd=()=>ls(()=>import("./page-with-search-BhJv4yJI.js"),__vite__mapDeps([0,1])),Gd=cs("/(tests)/page-with-search")({validateSearch:Kd(zd({where:Wd()})),component:vi(qd,"component")}),Jd=()=>ls(()=>import("./normal-page-BPOVyYTF.js"),__vite__mapDeps([2,1])),Yd=cs("/(tests)/normal-page")({component:vi(Jd,"component")});(function e(t){function s(r,i,o){var a,c={};if(Array.isArray(r))return r.concat(i);for(a in r)c[o?a.toLowerCase():a]=r[a];for(a in i){var u=o?a.toLowerCase():a,f=i[a];c[u]=u in c&&typeof f=="object"?s(c[u],f,u=="headers"):f}return c}function n(r,i,o,a,c){var u=typeof r!="string"?(i=r).url:r,f={config:i},l=s(t,i),d={};a=a||l.data,(l.transformRequest||[]).map(function(h){a=h(a,l.headers)||a}),l.auth&&(d.authorization=l.auth),a&&typeof a=="object"&&typeof a.append!="function"&&typeof a.text!="function"&&(a=JSON.stringify(a),d["content-type"]="application/json");try{d[l.xsrfHeaderName]=decodeURIComponent(document.cookie.match(RegExp("(^|; )"+l.xsrfCookieName+"=([^;]*)"))[2])}catch{}return l.baseURL&&(u=u.replace(/^(?!.*\/\/)\/?/,l.baseURL+"/")),l.params&&(u+=(~u.indexOf("?")?"&":"?")+(l.paramsSerializer?l.paramsSerializer(l.params):new URLSearchParams(l.params))),(l.fetch||fetch)(u,{method:(o||l.method||"get").toUpperCase(),body:a,headers:s(l.headers,d,!0),credentials:l.withCredentials?"include":c}).then(function(h){for(var g in h)typeof h[g]!="function"&&(f[g]=h[g]);return l.responseType=="stream"?(f.data=h.body,f):h[l.responseType||"text"]().then(function(y){f.data=y,f.data=JSON.parse(y)}).catch(Object).then(function(){return(l.validateStatus?l.validateStatus(h.status):h.ok)?f:Promise.reject(f)})})}return t=t||{},n.request=n,n.get=function(r,i){return n(r,i,"get")},n.delete=function(r,i){return n(r,i,"delete")},n.head=function(r,i){return n(r,i,"head")},n.options=function(r,i){return n(r,i,"options")},n.post=function(r,i,o){return n(r,o,"post",i)},n.put=function(r,i,o){return n(r,o,"put",i)},n.patch=function(r,i,o){return n(r,o,"patch",i)},n.all=Promise.all.bind(Promise),n.spread=function(r){return r.apply.bind(r,r)},n.CancelToken=typeof AbortController=="function"?AbortController:Object,n.defaults=t,n.create=e,n})();function Xd(e){return new Promise(t=>setTimeout(t,e))}const Qd=cs("/(tests)/lazy-with-loader-page")({loader:async()=>(await Xd(1e3),{foo:"bar"})}),eh=cs("/(tests)/lazy-page")({}),th=cs("/(tests)/virtual-page")(),sh=yd.update({id:"/",path:"/",getParentRoute:()=>Wt}),nh=th.update({id:"/(tests)/virtual-page",path:"/virtual-page",getParentRoute:()=>Wt}).lazy(()=>ls(()=>import("./virtual-page.lazy-BCqvdivF.js"),__vite__mapDeps([3,1])).then(e=>e.Route)),rh=Gd.update({id:"/(tests)/page-with-search",path:"/page-with-search",getParentRoute:()=>Wt}),ih=Yd.update({id:"/(tests)/normal-page",path:"/normal-page",getParentRoute:()=>Wt}),oh=Qd.update({id:"/(tests)/lazy-with-loader-page",path:"/lazy-with-loader-page",getParentRoute:()=>Wt}).lazy(()=>ls(()=>import("./lazy-with-loader-page.lazy-BzLmn584.js"),__vite__mapDeps([4,1])).then(e=>e.Route)),ah=eh.update({id:"/(tests)/lazy-page",path:"/lazy-page",getParentRoute:()=>Wt}).lazy(()=>ls(()=>import("./lazy-page.lazy-BzoMuhUY.js"),__vite__mapDeps([5,1])).then(e=>e.Route)),ch={IndexRoute:sh,testsLazyPageRoute:ah,testsLazyWithLoaderPageRoute:oh,testsNormalPageRoute:ih,testsPageWithSearchRoute:rh,testsVirtualPageLazyRoute:nh},lh=Wt._addFileChildren(ch)._addFileTypes();let Xa;Xa=Fu();const uh=sd({routeTree:lh,history:Xa,scrollRestoration:!0}),fh=document.getElementById("app");fh?.innerHTML||ku({setup(){return()=>ce(id,{router:uh},null)}}).mount("#app");export{Fe as F,ho as L,ce as a,xr as b,mh as c,ms as l,ri as m}; diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/index-ElfLiipA.css b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/index-ElfLiipA.css new file mode 100644 index 0000000000..b6e247a9c9 --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/index-ElfLiipA.css @@ -0,0 +1 @@ +/*! tailwindcss v4.1.15 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-border-style:solid;--tw-font-weight:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--color-gray-50:oklch(98.5% .002 247.839);--color-gray-200:oklch(92.8% .006 264.531);--color-gray-800:oklch(27.8% .033 256.848);--color-gray-900:oklch(21% .034 264.665);--color-gray-950:oklch(13% .028 261.692);--spacing:.25rem;--text-lg:1.125rem;--text-lg--line-height:calc(1.75/1.125);--font-weight-bold:700;--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}*,:after,:before,::backdrop{border-color:var(--color-gray-200,currentcolor)}::file-selector-button{border-color:var(--color-gray-200,currentcolor)}}@layer components;@layer utilities{.flex{display:flex}.grid{display:grid}.gap-2{gap:calc(var(--spacing)*2)}.border{border-style:var(--tw-border-style);border-width:1px}.p-2{padding:calc(var(--spacing)*2)}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}}html{color-scheme:light dark}*{border-color:var(--color-gray-200)}@media (prefers-color-scheme:dark){*{border-color:var(--color-gray-800)}}body{background-color:var(--color-gray-50);color:var(--color-gray-950)}@media (prefers-color-scheme:dark){body{background-color:var(--color-gray-900);color:var(--color-gray-200)}}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-font-weight{syntax:"*";inherits:false} diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/index-rPfEOKs3.js b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/index-rPfEOKs3.js new file mode 100644 index 0000000000..7dff2a5190 --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/index-rPfEOKs3.js @@ -0,0 +1 @@ +import{a as e,l as t,b as a,L as r,m as s}from"./index-BwsVWHwV.js";function i(){return e("div",{class:"p-2 grid gap-2"},[e("h3",null,[a("Welcome Home!")]),e("p",null,[a("The are the links to be tested when navigating away from the index page. Otherwise known as NOT first-load tests, rather known as navigation tests.")]),[t({to:"/normal-page"}),t({to:"/lazy-page"}),t({to:"/virtual-page"}),t({to:"/lazy-with-loader-page"}),t({to:"/page-with-search",search:{where:"footer"}})].map((o,n)=>e("div",{class:"border p-2"},[e("h4",null,[o.to,a(" tests")]),e("p",null,[e(r,s(o,{hash:"at-the-bottom"}),{default:()=>[o.to,a("#at-the-bottom")]})])]))])}export{i as component}; diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/lazy-page.lazy-BzoMuhUY.js b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/lazy-page.lazy-BzoMuhUY.js new file mode 100644 index 0000000000..b2ab5a4389 --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/lazy-page.lazy-BzoMuhUY.js @@ -0,0 +1 @@ +import{c as l,a as e,b as o}from"./index-BwsVWHwV.js";import{S as t}from"./scroll-block-BAas_Ct-.js";const c=l("/(tests)/lazy-page")({component:a});function a(){return e("div",{class:"p-2"},[e("h3",null,[o("lazy-page")]),e("hr",null,null),e(t,null,null)])}export{c as Route}; diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/lazy-with-loader-page.lazy-BzLmn584.js b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/lazy-with-loader-page.lazy-BzLmn584.js new file mode 100644 index 0000000000..ab267814ce --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/lazy-with-loader-page.lazy-BzLmn584.js @@ -0,0 +1 @@ +import{c as l,a as e,b as o}from"./index-BwsVWHwV.js";import{S as t}from"./scroll-block-BAas_Ct-.js";const c=l("/(tests)/lazy-with-loader-page")({component:a});function a(){return e("div",{class:"p-2"},[e("h3",null,[o("lazy-with-loader-page")]),e("hr",null,null),e(t,null,null)])}export{c as Route}; diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/normal-page-BPOVyYTF.js b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/normal-page-BPOVyYTF.js new file mode 100644 index 0000000000..ec26f71d98 --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/normal-page-BPOVyYTF.js @@ -0,0 +1 @@ +import{S as o}from"./scroll-block-BAas_Ct-.js";import{a as l,b as n}from"./index-BwsVWHwV.js";function a(){return l("div",{class:"p-2"},[l("h3",null,[n("normal-page")]),l("hr",null,null),l(o,null,null)])}export{a as component}; diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/page-with-search-BhJv4yJI.js b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/page-with-search-BhJv4yJI.js new file mode 100644 index 0000000000..67ce6cd937 --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/page-with-search-BhJv4yJI.js @@ -0,0 +1 @@ +import{S as o}from"./scroll-block-BAas_Ct-.js";import{a as l,b as e}from"./index-BwsVWHwV.js";function t(){return l("div",{class:"p-2"},[l("h3",null,[e("page-with-search")]),l("hr",null,null),l(o,null,null)])}export{t as component}; diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/scroll-block-BAas_Ct-.js b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/scroll-block-BAas_Ct-.js new file mode 100644 index 0000000000..89ed1c6988 --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/scroll-block-BAas_Ct-.js @@ -0,0 +1 @@ +import{a as t,b as r,F as l}from"./index-BwsVWHwV.js";const o="at-the-top",a="at-the-bottom";function m({number:e=100}){return t(l,null,[t("div",{id:o,"data-testid":o},null),Array.from({length:e}).map((n,d)=>t("div",null,[d])),t("div",{id:a,"data-testid":a},[r("At the bottom")])])}export{m as S}; diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/virtual-page.lazy-BCqvdivF.js b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/virtual-page.lazy-BCqvdivF.js new file mode 100644 index 0000000000..82d2cac67f --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/virtual-page.lazy-BCqvdivF.js @@ -0,0 +1 @@ +import{c as t,a as e,b as l}from"./index-BwsVWHwV.js";import{S as o}from"./scroll-block-BAas_Ct-.js";const u=t("/(tests)/virtual-page")({component:a});function a(){return e("div",{class:"p-2"},[e("h3",null,[l("virtual-page")]),e("hr",null,null),e(o,null,null)])}export{u as Route}; diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/index.html b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/index.html new file mode 100644 index 0000000000..2a9c6c3574 --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/index.html @@ -0,0 +1,12 @@ + + + + + + + + + +
+ + diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/package.json b/e2e/vue-router/scroll-restoration-sandbox-vite/package.json index d071ee546a..203f6a204f 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/package.json +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/package.json @@ -11,35 +11,26 @@ "start": "vite", "test:e2e:browser": "VITE_APP_HISTORY=browser playwright test --config=playwright.browser.config.ts --project=chromium", "test:e2e:hash": "VITE_APP_HISTORY=hash playwright test --config=playwright.hash.config.ts --project=chromium", - "test:e2e": "pnpm run test:e2e:browser && pnpm run test:e2e:hash" + "test:e2e": "rm -rf port*.txt; pnpm run test:e2e:browser && pnpm run test:e2e:hash" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", + "@tailwindcss/vite": "^4.1.18", "@tanstack/router-plugin": "workspace:^", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "catalog:", - "tailwindcss": "^4.2.2", + "@tanstack/zod-adapter": "workspace:^", + "redaxios": "^0.5.1", + "tailwindcss": "^4.1.18", "vue": "^3.5.16", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", - "@vitejs/plugin-vue": "^6.0.5", - "@vitejs/plugin-vue-jsx": "^5.1.5", + "@vitejs/plugin-vue": "^5.2.3", + "@vitejs/plugin-vue-jsx": "^4.1.2", "typescript": "~5.8.3", - "vite": "^8.0.14", - "vue-tsc": "^3.3.8" - }, - "nx": { - "targets": { - "test:e2e": { - "outputs": [ - "...", - "{projectRoot}/dist-hash" - ] - } - } + "vite": "^7.3.1", + "vue-tsc": "^3.1.5" } } diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts index e2681daea5..9d7691f0fd 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts @@ -1,7 +1,15 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, + resolveRuntimeSuffix, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort( + packageJson.name + `-${resolveRuntimeSuffix('browser')}`, +) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +20,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_APP_HISTORY=browser pnpm build && VITE_APP_HISTORY=browser pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=browser pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=browser pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts index 445616b9bd..80a340cef4 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts @@ -1,7 +1,15 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, + resolveRuntimeSuffix, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort( + packageJson.name + `-${resolveRuntimeSuffix('hash')}`, +) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +20,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_APP_HISTORY=hash vite build --outDir dist-hash && VITE_APP_HISTORY=hash pnpm preview --port ${PORT} --outDir dist-hash`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=hash vite build --outDir dist-hash && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=hash pnpm preview --port ${PORT} --outDir dist-hash`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/src/posts.tsx b/e2e/vue-router/scroll-restoration-sandbox-vite/src/posts.tsx index bc56dff904..c6cba486ab 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/src/posts.tsx +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/src/posts.tsx @@ -12,7 +12,11 @@ export type PostType = { export class PostNotFoundError extends Error {} -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts index e85be2bf37..69dda324fe 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts @@ -12,10 +12,10 @@ import { createFileRoute } from '@tanstack/vue-router' import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as testsLazyPageRouteImport } from './routes/(tests)/lazy-page' -import { Route as testsLazyWithLoaderPageRouteImport } from './routes/(tests)/lazy-with-loader-page' -import { Route as testsNormalPageRouteImport } from './routes/(tests)/normal-page' import { Route as testsPageWithSearchRouteImport } from './routes/(tests)/page-with-search' +import { Route as testsNormalPageRouteImport } from './routes/(tests)/normal-page' +import { Route as testsLazyWithLoaderPageRouteImport } from './routes/(tests)/lazy-with-loader-page' +import { Route as testsLazyPageRouteImport } from './routes/(tests)/lazy-page' const testsVirtualPageLazyRouteImport = createFileRoute( '/(tests)/virtual-page', @@ -26,13 +26,23 @@ const IndexRoute = IndexRouteImport.update({ path: '/', getParentRoute: () => rootRouteImport, } as any) -const testsLazyPageRoute = testsLazyPageRouteImport +const testsVirtualPageLazyRoute = testsVirtualPageLazyRouteImport .update({ - id: '/(tests)/lazy-page', - path: '/lazy-page', + id: '/(tests)/virtual-page', + path: '/virtual-page', getParentRoute: () => rootRouteImport, } as any) - .lazy(() => import('./routes/(tests)/lazy-page.lazy').then((d) => d.Route)) + .lazy(() => import('./routes/(tests)/virtual-page.lazy').then((d) => d.Route)) +const testsPageWithSearchRoute = testsPageWithSearchRouteImport.update({ + id: '/(tests)/page-with-search', + path: '/page-with-search', + getParentRoute: () => rootRouteImport, +} as any) +const testsNormalPageRoute = testsNormalPageRouteImport.update({ + id: '/(tests)/normal-page', + path: '/normal-page', + getParentRoute: () => rootRouteImport, +} as any) const testsLazyWithLoaderPageRoute = testsLazyWithLoaderPageRouteImport .update({ id: '/(tests)/lazy-with-loader-page', @@ -42,23 +52,13 @@ const testsLazyWithLoaderPageRoute = testsLazyWithLoaderPageRouteImport .lazy(() => import('./routes/(tests)/lazy-with-loader-page.lazy').then((d) => d.Route), ) -const testsNormalPageRoute = testsNormalPageRouteImport.update({ - id: '/(tests)/normal-page', - path: '/normal-page', - getParentRoute: () => rootRouteImport, -} as any) -const testsPageWithSearchRoute = testsPageWithSearchRouteImport.update({ - id: '/(tests)/page-with-search', - path: '/page-with-search', - getParentRoute: () => rootRouteImport, -} as any) -const testsVirtualPageLazyRoute = testsVirtualPageLazyRouteImport +const testsLazyPageRoute = testsLazyPageRouteImport .update({ - id: '/(tests)/virtual-page', - path: '/virtual-page', + id: '/(tests)/lazy-page', + path: '/lazy-page', getParentRoute: () => rootRouteImport, } as any) - .lazy(() => import('./routes/(tests)/virtual-page.lazy').then((d) => d.Route)) + .lazy(() => import('./routes/(tests)/lazy-page.lazy').then((d) => d.Route)) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -130,25 +130,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/(tests)/lazy-page': { - id: '/(tests)/lazy-page' - path: '/lazy-page' - fullPath: '/lazy-page' - preLoaderRoute: typeof testsLazyPageRouteImport - parentRoute: typeof rootRouteImport - } - '/(tests)/lazy-with-loader-page': { - id: '/(tests)/lazy-with-loader-page' - path: '/lazy-with-loader-page' - fullPath: '/lazy-with-loader-page' - preLoaderRoute: typeof testsLazyWithLoaderPageRouteImport - parentRoute: typeof rootRouteImport - } - '/(tests)/normal-page': { - id: '/(tests)/normal-page' - path: '/normal-page' - fullPath: '/normal-page' - preLoaderRoute: typeof testsNormalPageRouteImport + '/(tests)/virtual-page': { + id: '/(tests)/virtual-page' + path: '/virtual-page' + fullPath: '/virtual-page' + preLoaderRoute: typeof testsVirtualPageLazyRouteImport parentRoute: typeof rootRouteImport } '/(tests)/page-with-search': { @@ -158,11 +144,25 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof testsPageWithSearchRouteImport parentRoute: typeof rootRouteImport } - '/(tests)/virtual-page': { - id: '/(tests)/virtual-page' - path: '/virtual-page' - fullPath: '/virtual-page' - preLoaderRoute: typeof testsVirtualPageLazyRouteImport + '/(tests)/normal-page': { + id: '/(tests)/normal-page' + path: '/normal-page' + fullPath: '/normal-page' + preLoaderRoute: typeof testsNormalPageRouteImport + parentRoute: typeof rootRouteImport + } + '/(tests)/lazy-with-loader-page': { + id: '/(tests)/lazy-with-loader-page' + path: '/lazy-with-loader-page' + fullPath: '/lazy-with-loader-page' + preLoaderRoute: typeof testsLazyWithLoaderPageRouteImport + parentRoute: typeof rootRouteImport + } + '/(tests)/lazy-page': { + id: '/(tests)/lazy-page' + path: '/lazy-page' + fullPath: '/lazy-page' + preLoaderRoute: typeof testsLazyPageRouteImport parentRoute: typeof rootRouteImport } } diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/src/routes/(tests)/page-with-search.tsx b/e2e/vue-router/scroll-restoration-sandbox-vite/src/routes/(tests)/page-with-search.tsx index f608b9e379..3e1ec1eeba 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/src/routes/(tests)/page-with-search.tsx +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/src/routes/(tests)/page-with-search.tsx @@ -1,9 +1,10 @@ import { createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' +import { zodValidator } from '@tanstack/zod-adapter' import { ScrollBlock } from '../-components/scroll-block' export const Route = createFileRoute('/(tests)/page-with-search')({ - validateSearch: z.object({ where: z.string() }), + validateSearch: zodValidator(z.object({ where: z.string() })), component: Component, }) diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/src/vite-env.d.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/tests/app.spec.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/tests/app.spec.ts index 067f0341c4..5f226c6db3 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/tests/app.spec.ts +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import { toRuntimePath } from '@tanstack/router-e2e-utils' test('Smoke - Renders home', async ({ page }) => { diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/tsconfig.json b/e2e/vue-router/scroll-restoration-sandbox-vite/tsconfig.json index b47cca9589..3e5b04987f 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/tsconfig.json +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/tsconfig.json @@ -12,5 +12,5 @@ "allowJs": true, "types": ["vite/client", "node"] }, - "exclude": ["node_modules", "dist", "dist-hash"] + "exclude": ["node_modules", "dist"] } diff --git a/e2e/vue-router/sentry-integration/.devcontainer/devcontainer.json b/e2e/vue-router/sentry-integration/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-router/sentry-integration/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-router/sentry-integration/package.json b/e2e/vue-router/sentry-integration/package.json index 045ddd99be..1aaf6ec8fa 100644 --- a/e2e/vue-router/sentry-integration/package.json +++ b/e2e/vue-router/sentry-integration/package.json @@ -8,25 +8,25 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@sentry/vue": "^10.32.0", "@sentry/tracing": "^7.120.4", "@sentry/vite-plugin": "^4.6.1", - "@tailwindcss/vite": "^4.2.2", + "@tailwindcss/vite": "^4.1.18", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "catalog:", - "tailwindcss": "^4.2.2", + "redaxios": "^0.5.1", + "tailwindcss": "^4.1.18", "vue": "^3.5.16" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", - "@vitejs/plugin-vue-jsx": "^5.1.5", + "@vitejs/plugin-vue-jsx": "^4.1.2", "typescript": "~5.8.3", - "vite": "^8.0.14", - "vue-tsc": "^3.3.8" + "vite": "^7.3.1", + "vue-tsc": "^3.1.5" } } diff --git a/e2e/vue-router/sentry-integration/playwright.config.ts b/e2e/vue-router/sentry-integration/playwright.config.ts index 6a684ac89e..0c5cee43e4 100644 --- a/e2e/vue-router/sentry-integration/playwright.config.ts +++ b/e2e/vue-router/sentry-integration/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/sentry-integration/src/vite-env.d.ts b/e2e/vue-router/sentry-integration/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/vue-router/sentry-integration/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/vue-router/view-transitions/.devcontainer/devcontainer.json b/e2e/vue-router/view-transitions/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-router/view-transitions/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-router/view-transitions/package.json b/e2e/vue-router/view-transitions/package.json index 21a0f1d8a0..5f463b298f 100644 --- a/e2e/vue-router/view-transitions/package.json +++ b/e2e/vue-router/view-transitions/package.json @@ -8,26 +8,26 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", + "@tailwindcss/vite": "^4.1.18", "@tanstack/router-plugin": "workspace:^", "@tanstack/vue-query": "^5.90.0", "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "catalog:", - "tailwindcss": "^4.2.2", + "redaxios": "^0.5.1", + "tailwindcss": "^4.1.18", "vue": "^3.5.16" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:^", - "@vitejs/plugin-vue": "^6.0.5", - "@vitejs/plugin-vue-jsx": "^5.1.5", + "@vitejs/plugin-vue": "^5.2.3", + "@vitejs/plugin-vue-jsx": "^4.1.2", "typescript": "~5.8.3", - "vite": "^8.0.14", - "vue-tsc": "^3.3.8" + "vite": "^7.3.1", + "vue-tsc": "^3.1.5" } } diff --git a/e2e/vue-router/view-transitions/playwright.config.ts b/e2e/vue-router/view-transitions/playwright.config.ts index 4eead86444..c5de6b5611 100644 --- a/e2e/vue-router/view-transitions/playwright.config.ts +++ b/e2e/vue-router/view-transitions/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,10 +22,13 @@ export default defineConfig({ baseURL, }, + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && pnpm preview --port ${PORT}`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/view-transitions/src/routeTree.gen.ts b/e2e/vue-router/view-transitions/src/routeTree.gen.ts index 04708c29a8..465362a7a2 100644 --- a/e2e/vue-router/view-transitions/src/routeTree.gen.ts +++ b/e2e/vue-router/view-transitions/src/routeTree.gen.ts @@ -9,16 +9,16 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as ExploreRouteImport } from './routes/explore' import { Route as HowItWorksRouteImport } from './routes/how-it-works' +import { Route as ExploreRouteImport } from './routes/explore' import { Route as PostsRouteRouteImport } from './routes/posts.route' +import { Route as IndexRouteImport } from './routes/index' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const HowItWorksRoute = HowItWorksRouteImport.update({ + id: '/how-it-works', + path: '/how-it-works', getParentRoute: () => rootRouteImport, } as any) const ExploreRoute = ExploreRouteImport.update({ @@ -26,16 +26,16 @@ const ExploreRoute = ExploreRouteImport.update({ path: '/explore', getParentRoute: () => rootRouteImport, } as any) -const HowItWorksRoute = HowItWorksRouteImport.update({ - id: '/how-it-works', - path: '/how-it-works', - getParentRoute: () => rootRouteImport, -} as any) const PostsRouteRoute = PostsRouteRouteImport.update({ id: '/posts', path: '/posts', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -101,11 +101,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/how-it-works': { + id: '/how-it-works' + path: '/how-it-works' + fullPath: '/how-it-works' + preLoaderRoute: typeof HowItWorksRouteImport parentRoute: typeof rootRouteImport } '/explore': { @@ -115,13 +115,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ExploreRouteImport parentRoute: typeof rootRouteImport } - '/how-it-works': { - id: '/how-it-works' - path: '/how-it-works' - fullPath: '/how-it-works' - preLoaderRoute: typeof HowItWorksRouteImport - parentRoute: typeof rootRouteImport - } '/posts': { id: '/posts' path: '/posts' @@ -129,6 +122,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/posts/': { id: '/posts/' path: '/' diff --git a/e2e/vue-router/view-transitions/src/routes/posts.$postId.tsx b/e2e/vue-router/view-transitions/src/routes/posts.$postId.tsx index a86ea0762f..e271c139f5 100644 --- a/e2e/vue-router/view-transitions/src/routes/posts.$postId.tsx +++ b/e2e/vue-router/view-transitions/src/routes/posts.$postId.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -7,19 +6,6 @@ export function PostErrorComponent({ error }: ErrorComponentProps) { return } -const PostComponent = defineComponent({ - setup() { - const post = Route.useLoaderData() - - return () => ( -
-

{post.value.title}

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

{post.value.title}

+
{post.value.body}
+
+ ) +} diff --git a/e2e/vue-router/view-transitions/src/routes/posts.route.tsx b/e2e/vue-router/view-transitions/src/routes/posts.route.tsx index 6802b073f6..01d90b7ad6 100644 --- a/e2e/vue-router/view-transitions/src/routes/posts.route.tsx +++ b/e2e/vue-router/view-transitions/src/routes/posts.route.tsx @@ -1,46 +1,43 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../posts' -const PostsLayoutComponent = defineComponent({ - setup() { - const posts = Route.useLoaderData() - - return () => ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
-
-
- -
-
- ) - }, -}) - export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsLayoutComponent, }) + +function PostsLayoutComponent() { + const posts = Route.useLoaderData() + + return ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+
+
+ +
+
+ ) +} diff --git a/e2e/vue-router/view-transitions/src/vite-env.d.ts b/e2e/vue-router/view-transitions/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/e2e/vue-router/view-transitions/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/e2e/vue-router/view-transitions/tests/app.spec.ts b/e2e/vue-router/view-transitions/tests/app.spec.ts index 6c1ccf1a6e..472bd6ed0b 100644 --- a/e2e/vue-router/view-transitions/tests/app.spec.ts +++ b/e2e/vue-router/view-transitions/tests/app.spec.ts @@ -1,4 +1,4 @@ -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/view-transitions/tests/setup/global.setup.ts b/e2e/vue-router/view-transitions/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/view-transitions/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/view-transitions/tests/setup/global.teardown.ts b/e2e/vue-router/view-transitions/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/view-transitions/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-router/view-transitions/tests/view-transitions.spec.ts b/e2e/vue-router/view-transitions/tests/view-transitions.spec.ts index e62662a1d2..b827bf3e6e 100644 --- a/e2e/vue-router/view-transitions/tests/view-transitions.spec.ts +++ b/e2e/vue-router/view-transitions/tests/view-transitions.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.addInitScript(() => { @@ -32,12 +31,7 @@ test('navigation uses View Transitions API', async ({ page }) => { await page.getByRole('link', { name: 'Next Page ->' }).click() await expect(page).toHaveURL(/\/how-it-works$/) - await expect - .poll(async () => { - const calls = await page.evaluate( - () => (window as any).__viewTransitionCalls, - ) - return calls.length - }) - .toBeGreaterThan(0) + const calls = await page.evaluate(() => (window as any).__viewTransitionCalls) + expect(Array.isArray(calls)).toBe(true) + expect(calls.length).toBeGreaterThan(0) }) diff --git a/e2e/vue-start/basic-auth/.devcontainer/devcontainer.json b/e2e/vue-start/basic-auth/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-start/basic-auth/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-start/basic-auth/package.json b/e2e/vue-start/basic-auth/package.json index 7f6fb798da..4b536d56e4 100644 --- a/e2e/vue-start/basic-auth/package.json +++ b/e2e/vue-start/basic-auth/package.json @@ -10,7 +10,7 @@ "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", "prisma-generate": "prisma generate", - "test:e2e": "mkdir -p .tmp; rm -f .tmp/dev.db .tmp/dev.db-journal .tmp/dev.db-wal .tmp/dev.db-shm; export DATABASE_URL=file:./.tmp/dev.db; pnpm run prisma-generate && pnpm exec prisma migrate deploy && playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; mkdir -p .tmp; rm -f .tmp/dev.db .tmp/dev.db-journal .tmp/dev.db-wal .tmp/dev.db-shm; export DATABASE_URL=file:./.tmp/dev.db; pnpm run prisma-generate && pnpm exec prisma migrate deploy && playwright test --project=chromium" }, "dependencies": { "@libsql/client": "^0.15.15", @@ -19,35 +19,23 @@ "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", - "iron-session": "^9.0.1", - "redaxios": "catalog:", - "tailwind-merge": "^3.6.0", + "redaxios": "^0.5.1", + "tailwind-merge": "^2.6.0", + "vite": "^7.3.1", "vue": "^3.5.25" }, "devDependencies": { - "@playwright/test": "^1.61.0", - "@tailwindcss/vite": "^4.2.2", + "@playwright/test": "^1.50.1", + "@tailwindcss/vite": "^4.1.18", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", - "@vitejs/plugin-vue": "^6.0.5", - "@vitejs/plugin-vue-jsx": "^5.1.5", "dotenv": "^17.2.3", "prisma": "^7.0.0", - "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" - ] - } - } + "srvx": "^0.11.2", + "tailwindcss": "^4.1.18", + "typescript": "^5.7.2", + "@vitejs/plugin-vue": "^6.0.3", + "@vitejs/plugin-vue-jsx": "^5.1.2", + "vite-tsconfig-paths": "^5.1.4" } } diff --git a/e2e/vue-start/basic-auth/playwright.config.ts b/e2e/vue-start/basic-auth/playwright.config.ts index 82678ac00b..18b8905468 100644 --- a/e2e/vue-start/basic-auth/playwright.config.ts +++ b/e2e/vue-start/basic-auth/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/basic-auth/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/basic-auth/src/components/DefaultCatchBoundary.tsx index 0687372ae0..e11970b600 100644 --- a/e2e/vue-start/basic-auth/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/basic-auth/src/components/DefaultCatchBoundary.tsx @@ -1,61 +1,53 @@ -import { defineComponent } from 'vue' -import type { PropType } from 'vue' import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -export const DefaultCatchBoundary = defineComponent({ - props: { - error: { - type: Object as PropType, - required: true, - }, - }, - setup(props) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - return () => { - console.error(props.error) - return ( -
- -
- - {isRoot.value ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) - } - }, -}) +export function DefaultCatchBoundary({ error }: ErrorComponentProps) { + const router = useRouter() + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, + }) + + console.error(error) + + return ( +
+ +
+ + {isRoot.value ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
+
+ ) +} diff --git a/e2e/vue-start/basic-auth/src/routeTree.gen.ts b/e2e/vue-start/basic-auth/src/routeTree.gen.ts index 058f8674ac..6e06092779 100644 --- a/e2e/vue-start/basic-auth/src/routeTree.gen.ts +++ b/e2e/vue-start/basic-auth/src/routeTree.gen.ts @@ -9,27 +9,18 @@ // 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 AuthedRouteImport } from './routes/_authed' -import { Route as LoginRouteImport } from './routes/login' -import { Route as LogoutRouteImport } from './routes/logout' import { Route as SignupRouteImport } from './routes/signup' +import { Route as LogoutRouteImport } from './routes/logout' +import { Route as LoginRouteImport } from './routes/login' +import { Route as AuthedRouteImport } from './routes/_authed' +import { Route as IndexRouteImport } from './routes/index' import { Route as AuthedPostsRouteImport } from './routes/_authed/posts' import { Route as AuthedPostsIndexRouteImport } from './routes/_authed/posts.index' import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AuthedRoute = AuthedRouteImport.update({ - id: '/_authed', - getParentRoute: () => rootRouteImport, -} as any) -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', +const SignupRoute = SignupRouteImport.update({ + id: '/signup', + path: '/signup', getParentRoute: () => rootRouteImport, } as any) const LogoutRoute = LogoutRouteImport.update({ @@ -37,9 +28,18 @@ const LogoutRoute = LogoutRouteImport.update({ path: '/logout', getParentRoute: () => rootRouteImport, } as any) -const SignupRoute = SignupRouteImport.update({ - id: '/signup', - path: '/signup', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', + getParentRoute: () => rootRouteImport, +} as any) +const AuthedRoute = AuthedRouteImport.update({ + id: '/_authed', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AuthedPostsRoute = AuthedPostsRouteImport.update({ @@ -120,25 +120,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_authed': { - id: '/_authed' - path: '' - fullPath: '/' - preLoaderRoute: typeof AuthedRouteImport - parentRoute: typeof rootRouteImport - } - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport + '/signup': { + id: '/signup' + path: '/signup' + fullPath: '/signup' + preLoaderRoute: typeof SignupRouteImport parentRoute: typeof rootRouteImport } '/logout': { @@ -148,11 +134,25 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LogoutRouteImport parentRoute: typeof rootRouteImport } - '/signup': { - id: '/signup' - path: '/signup' - fullPath: '/signup' - preLoaderRoute: typeof SignupRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport + parentRoute: typeof rootRouteImport + } + '/_authed': { + id: '/_authed' + path: '' + fullPath: '' + preLoaderRoute: typeof AuthedRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_authed/posts': { diff --git a/e2e/vue-start/basic-auth/src/routes/__root.tsx b/e2e/vue-start/basic-auth/src/routes/__root.tsx index e5b6f6778f..89802cfd2f 100644 --- a/e2e/vue-start/basic-auth/src/routes/__root.tsx +++ b/e2e/vue-start/basic-auth/src/routes/__root.tsx @@ -1,5 +1,4 @@ /// -import { defineComponent } from 'vue' import { Body, HeadContent, @@ -16,69 +15,21 @@ import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary.js' import { NotFound } from '~/components/NotFound.js' import appCss from '~/styles/app.css?url' import { seo } from '~/utils/seo.js' -import { getAppSession } from '~/utils/session.js' +import { useAppSession } from '~/utils/session.js' const fetchUser = createServerFn({ method: 'GET' }).handler(async () => { // We need to auth on the server so we have access to secure cookies - const session = await getAppSession() + const session = await useAppSession() - if (!session.userEmail) { + if (!session.data.userEmail) { return null } return { - email: session.userEmail, + email: session.data.userEmail, } }) -const RootShell = defineComponent({ - setup(_, { slots }) { - const routeContext = Route.useRouteContext() - return () => ( - - - - - -
- - Home - {' '} - - Posts - -
- {routeContext.value.user ? ( - <> - {routeContext.value.user.email} - Logout - - ) : ( - Login - )} -
-
-
- {slots.default?.()} - - - - - ) - }, -}) - export const Route = createRootRoute({ beforeLoad: async () => { const user = await fetchUser() @@ -130,3 +81,50 @@ export const Route = createRootRoute({ notFoundComponent: () => , component: () => , }) + +function RootShell(_: unknown, { slots }: { slots: any }) { + const routeContext = Route.useRouteContext() + + return ( + + + + + +
+ + Home + {' '} + + Posts + +
+ {routeContext.value.user ? ( + <> + {routeContext.value.user.email} + Logout + + ) : ( + Login + )} +
+
+
+ {slots.default?.()} + + + + + ) +} diff --git a/e2e/vue-start/basic-auth/src/routes/_authed.tsx b/e2e/vue-start/basic-auth/src/routes/_authed.tsx index 606de3e487..53e16ebe33 100644 --- a/e2e/vue-start/basic-auth/src/routes/_authed.tsx +++ b/e2e/vue-start/basic-auth/src/routes/_authed.tsx @@ -3,12 +3,12 @@ import { createServerFn } from '@tanstack/vue-start' import { hashPassword, prismaClient } from '~/utils/prisma' import { Login } from '~/components/Login' -import { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' export const loginFn = createServerFn({ method: 'POST', }) - .validator((payload: { email: string; password: string }) => payload) + .inputValidator((payload: { email: string; password: string }) => payload) .handler(async ({ data }) => { // Find the user const user = await prismaClient.user.findUnique({ @@ -37,11 +37,12 @@ export const loginFn = createServerFn({ } // Create a session - const session = await getAppSession() + const session = await useAppSession() // Store the user's email in the session - session.userEmail = user.email - await session.save() + await session.update({ + userEmail: user.email, + }) }) export const Route = createFileRoute('/_authed')({ @@ -51,7 +52,7 @@ export const Route = createFileRoute('/_authed')({ } }, errorComponent: ({ error }) => { - if (error instanceof Error && error.message === 'Not authenticated') { + if (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 45d6bbab0d..da0c26f27f 100644 --- a/e2e/vue-start/basic-auth/src/routes/_authed/posts.$postId.tsx +++ b/e2e/vue-start/basic-auth/src/routes/_authed/posts.$postId.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -9,18 +8,6 @@ export function PostErrorComponent({ error }: ErrorComponentProps) { return } -const PostComponent = defineComponent({ - setup() { - const post = Route.useLoaderData() - return () => ( -
-

{post.value.title}

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

{post.value.title}

+
{post.value.body}
+
+ ) +} diff --git a/e2e/vue-start/basic-auth/src/routes/_authed/posts.tsx b/e2e/vue-start/basic-auth/src/routes/_authed/posts.tsx index 6b8b54c666..cfac133b51 100644 --- a/e2e/vue-start/basic-auth/src/routes/_authed/posts.tsx +++ b/e2e/vue-start/basic-auth/src/routes/_authed/posts.tsx @@ -1,38 +1,36 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '~/utils/posts.js' -const PostsComponent = defineComponent({ - setup() { - const posts = Route.useLoaderData() - return () => ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ))} -
-
- -
- ) - }, -}) +function PostsComponent() { + const posts = Route.useLoaderData() + + return ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ))} +
+
+ +
+ ) +} export const Route = createFileRoute('/_authed/posts')({ loader: () => fetchPosts(), diff --git a/e2e/vue-start/basic-auth/src/routes/logout.tsx b/e2e/vue-start/basic-auth/src/routes/logout.tsx index 8372b33608..f1d7b58e29 100644 --- a/e2e/vue-start/basic-auth/src/routes/logout.tsx +++ b/e2e/vue-start/basic-auth/src/routes/logout.tsx @@ -1,12 +1,12 @@ import { redirect, createFileRoute } from '@tanstack/vue-router' import { createServerFn } from '@tanstack/vue-start' -import { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await getAppSession() + const session = await useAppSession() - session.destroy() + session.clear() throw redirect({ href: '/', diff --git a/e2e/vue-start/basic-auth/src/routes/signup.tsx b/e2e/vue-start/basic-auth/src/routes/signup.tsx index 5f37f109c7..22fd7d4ca5 100644 --- a/e2e/vue-start/basic-auth/src/routes/signup.tsx +++ b/e2e/vue-start/basic-auth/src/routes/signup.tsx @@ -5,12 +5,12 @@ import { defineComponent } from 'vue' import { hashPassword, prismaClient } from '~/utils/prisma' import { useMutation } from '~/hooks/useMutation' import { Auth } from '~/components/Auth' -import { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' export const signupFn = createServerFn({ method: 'POST', }) - .validator( + .inputValidator( (data: { email: string; password: string; redirectUrl?: string }) => data, ) .handler(async ({ data: payload }) => { @@ -25,7 +25,7 @@ export const signupFn = createServerFn({ const password = await hashPassword(payload.password) // Create a session - const session = await getAppSession() + const session = await useAppSession() if (found) { if (found.password !== password) { @@ -37,8 +37,9 @@ export const signupFn = createServerFn({ } // Store the user's email in the session - session.userEmail = found.email - await session.save() + await session.update({ + userEmail: found.email, + }) // Redirect to the prev page stored in the "redirect" search param throw redirect({ @@ -55,8 +56,9 @@ export const signupFn = createServerFn({ }) // Store the user's email in the session - session.userEmail = user.email - await session.save() + await session.update({ + userEmail: user.email, + }) // Redirect to the prev page stored in the "redirect" search param throw redirect({ diff --git a/e2e/vue-start/basic-auth/src/utils/posts.ts b/e2e/vue-start/basic-auth/src/utils/posts.ts index 04dbccaa11..d72d7719a4 100644 --- a/e2e/vue-start/basic-auth/src/utils/posts.ts +++ b/e2e/vue-start/basic-auth/src/utils/posts.ts @@ -9,7 +9,7 @@ export type PostType = { } export const fetchPost = createServerFn({ method: 'GET' }) - .validator((postId: string) => postId) + .inputValidator((postId: string) => postId) .handler(async ({ data: postId }) => { console.info(`Fetching post with id ${postId}...`) const post = await axios diff --git a/e2e/vue-start/basic-auth/src/utils/session.ts b/e2e/vue-start/basic-auth/src/utils/session.ts index 7d078225a0..7cf2a41792 100644 --- a/e2e/vue-start/basic-auth/src/utils/session.ts +++ b/e2e/vue-start/basic-auth/src/utils/session.ts @@ -1,25 +1,13 @@ -import { getIronSession } from 'iron-session' -import { getCookie, setCookie } from '@tanstack/vue-start/server' +// src/services/session.server.ts +import { useSession } from '@tanstack/vue-start/server' import type { User } from '~/prisma-generated/client' type SessionUser = { userEmail: User['email'] } -export function getAppSession() { - return getIronSession( - { read: getCookie, write: setCookie }, - { - cookieName: 'test-auth-session', - // This fixture only runs locally with test credentials. - password: 'local-e2e-only-session-password-at-least-32-characters', - ttl: 60 * 60, - cookieOptions: { - httpOnly: true, - secure: false, - sameSite: 'lax', - path: '/', - }, - }, - ) +export function useAppSession() { + return useSession({ + password: 'ChangeThisBeforeShippingToProdOrYouWillBeFired', + }) } diff --git a/e2e/vue-start/basic-auth/tsconfig.json b/e2e/vue-start/basic-auth/tsconfig.json index 390dad84c0..f9f5aab3da 100644 --- a/e2e/vue-start/basic-auth/tsconfig.json +++ b/e2e/vue-start/basic-auth/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/basic-auth/vite.config.ts b/e2e/vue-start/basic-auth/vite.config.ts index 563e212077..e0b4a0e909 100644 --- a/e2e/vue-start/basic-auth/vite.config.ts +++ b/e2e/vue-start/basic-auth/vite.config.ts @@ -1,13 +1,21 @@ import { defineConfig } from 'vite' +import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import tailwindcss from '@tailwindcss/vite' export default defineConfig({ - resolve: { tsconfigPaths: true }, server: { port: 3000, }, - plugins: [tailwindcss(), tanstackStart(), vue(), vueJsx()], + plugins: [ + tailwindcss(), + tsConfigPaths({ + projects: ['./tsconfig.json'], + }), + tanstackStart(), + vue(), + vueJsx(), + ], }) diff --git a/e2e/vue-start/basic-cloudflare/.devcontainer/devcontainer.json b/e2e/vue-start/basic-cloudflare/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-start/basic-cloudflare/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-start/basic-cloudflare/package.json b/e2e/vue-start/basic-cloudflare/package.json index 5ab77db8fc..da3e8badcd 100644 --- a/e2e/vue-start/basic-cloudflare/package.json +++ b/e2e/vue-start/basic-cloudflare/package.json @@ -9,8 +9,8 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "cf-typegen": "wrangler types", - "postinstall": "WRANGLER_LOG=warn npm run --silent cf-typegen", - "test:e2e": "playwright test --project=chromium" + "postinstall": "npm run cf-typegen", + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -19,27 +19,17 @@ "vue": "^3.5.25" }, "devDependencies": { - "@cloudflare/vite-plugin": "^1.29.0", - "@playwright/test": "^1.61.0", - "@tailwindcss/vite": "^4.2.2", + "@cloudflare/vite-plugin": "^1.15.1", + "@playwright/test": "^1.50.1", + "@tailwindcss/vite": "^4.1.18", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", - "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "@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" - ] - } - } + "tailwindcss": "^4.1.18", + "typescript": "^5.7.2", + "vite": "^7.3.1", + "@vitejs/plugin-vue": "^6.0.3", + "@vitejs/plugin-vue-jsx": "^5.1.2", + "vite-tsconfig-paths": "^5.1.4", + "wrangler": "^4.49.1" } } diff --git a/e2e/vue-start/basic-cloudflare/playwright.config.ts b/e2e/vue-start/basic-cloudflare/playwright.config.ts index 0925936d55..a545dff891 100644 --- a/e2e/vue-start/basic-cloudflare/playwright.config.ts +++ b/e2e/vue-start/basic-cloudflare/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,6 +14,9 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, @@ -20,8 +24,8 @@ export default defineConfig({ webServer: { command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx index 0687372ae0..e11970b600 100644 --- a/e2e/vue-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx @@ -1,61 +1,53 @@ -import { defineComponent } from 'vue' -import type { PropType } from 'vue' import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -export const DefaultCatchBoundary = defineComponent({ - props: { - error: { - type: Object as PropType, - required: true, - }, - }, - setup(props) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - return () => { - console.error(props.error) - return ( -
- -
- - {isRoot.value ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) - } - }, -}) +export function DefaultCatchBoundary({ error }: ErrorComponentProps) { + const router = useRouter() + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, + }) + + console.error(error) + + return ( +
+ +
+ + {isRoot.value ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
+
+ ) +} diff --git a/e2e/vue-start/basic-cloudflare/src/routeTree.gen.ts b/e2e/vue-start/basic-cloudflare/src/routeTree.gen.ts index c52a88360b..30451e7ab7 100644 --- a/e2e/vue-start/basic-cloudflare/src/routeTree.gen.ts +++ b/e2e/vue-start/basic-cloudflare/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 IndexRouteImport } from './routes/index' import { Route as StaticRouteImport } from './routes/static' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const StaticRoute = StaticRouteImport.update({ id: '/static', path: '/static', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/static': { id: '/static' path: '/static' @@ -65,6 +58,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof StaticRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/e2e/vue-start/basic-cloudflare/src/routes/index.tsx b/e2e/vue-start/basic-cloudflare/src/routes/index.tsx index d3a020c7ad..1c708a7ec6 100644 --- a/e2e/vue-start/basic-cloudflare/src/routes/index.tsx +++ b/e2e/vue-start/basic-cloudflare/src/routes/index.tsx @@ -1,21 +1,7 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { createServerFn } from '@tanstack/vue-start' import { env } from 'cloudflare:workers' -const Home = defineComponent({ - setup() { - const data = Route.useLoaderData() - return () => ( -
-

Welcome Home!!!

-

{data.value.message}

-

{data.value.myVar}

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

Welcome Home!!!

+

{data.value.message}

+

{data.value.myVar}

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

Static Page

-

The value is {data.value.myVar}

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

Static Page

+

The value is {data.value.myVar}

+
+ ) +} diff --git a/e2e/vue-start/basic-cloudflare/tests/setup/global.setup.ts b/e2e/vue-start/basic-cloudflare/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-start/basic-cloudflare/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/basic-cloudflare/tests/setup/global.teardown.ts b/e2e/vue-start/basic-cloudflare/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-start/basic-cloudflare/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/basic-cloudflare/tsconfig.json b/e2e/vue-start/basic-cloudflare/tsconfig.json index 572d840872..8bf3d33789 100644 --- a/e2e/vue-start/basic-cloudflare/tsconfig.json +++ b/e2e/vue-start/basic-cloudflare/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/basic-cloudflare/vite.config.ts b/e2e/vue-start/basic-cloudflare/vite.config.ts index 1ee9e68614..fa484701ec 100644 --- a/e2e/vue-start/basic-cloudflare/vite.config.ts +++ b/e2e/vue-start/basic-cloudflare/vite.config.ts @@ -1,4 +1,5 @@ import { defineConfig } from 'vite' +import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' @@ -6,12 +7,14 @@ import { cloudflare } from '@cloudflare/vite-plugin' import tailwindcss from '@tailwindcss/vite' export default defineConfig({ - resolve: { tsconfigPaths: true }, server: { port: 3000, }, plugins: [ tailwindcss(), + tsConfigPaths({ + projects: ['./tsconfig.json'], + }), cloudflare({ viteEnvironment: { name: 'ssr' }, inspectorPort: false }), tanstackStart({ prerender: { diff --git a/e2e/vue-start/basic-cloudflare/worker-configuration.d.ts b/e2e/vue-start/basic-cloudflare/worker-configuration.d.ts index f7a8f16397..b0b47f3946 100644 --- a/e2e/vue-start/basic-cloudflare/worker-configuration.d.ts +++ b/e2e/vue-start/basic-cloudflare/worker-configuration.d.ts @@ -1,6 +1,6 @@ /* eslint-disable */ // Generated by Wrangler by running `wrangler types` (hash: b11df627d8b3c51b1bf3230a546b0f20) -// Runtime types generated with workerd@1.20260317.1 2025-09-24 nodejs_compat +// Runtime types generated with workerd@1.20251118.0 2025-09-24 nodejs_compat declare namespace Cloudflare { interface Env { MY_VAR: "Hello from Cloudflare"; @@ -31,70 +31,70 @@ and limitations under the License. ***************************************************************************** */ /* eslint-disable */ // noinspection JSUnusedGlobalSymbols -declare var onmessage: never; +declare var onmessage: never /** * The **`DOMException`** interface represents an abnormal event (called an **exception**) that occurs as a result of calling a method or accessing a property of a web API. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException) */ declare class DOMException extends Error { - constructor(message?: string, name?: string); - /** - * The **`message`** read-only property of the a message or description associated with the given error name. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) - */ - readonly message: string; - /** - * The **`name`** read-only property of the one of the strings associated with an error name. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) - */ - readonly name: string; - /** - * The **`code`** read-only property of the DOMException interface returns one of the legacy error code constants, or `0` if none match. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) - */ - readonly code: number; - static readonly INDEX_SIZE_ERR: number; - static readonly DOMSTRING_SIZE_ERR: number; - static readonly HIERARCHY_REQUEST_ERR: number; - static readonly WRONG_DOCUMENT_ERR: number; - static readonly INVALID_CHARACTER_ERR: number; - static readonly NO_DATA_ALLOWED_ERR: number; - static readonly NO_MODIFICATION_ALLOWED_ERR: number; - static readonly NOT_FOUND_ERR: number; - static readonly NOT_SUPPORTED_ERR: number; - static readonly INUSE_ATTRIBUTE_ERR: number; - static readonly INVALID_STATE_ERR: number; - static readonly SYNTAX_ERR: number; - static readonly INVALID_MODIFICATION_ERR: number; - static readonly NAMESPACE_ERR: number; - static readonly INVALID_ACCESS_ERR: number; - static readonly VALIDATION_ERR: number; - static readonly TYPE_MISMATCH_ERR: number; - static readonly SECURITY_ERR: number; - static readonly NETWORK_ERR: number; - static readonly ABORT_ERR: number; - static readonly URL_MISMATCH_ERR: number; - static readonly QUOTA_EXCEEDED_ERR: number; - static readonly TIMEOUT_ERR: number; - static readonly INVALID_NODE_TYPE_ERR: number; - static readonly DATA_CLONE_ERR: number; - get stack(): any; - set stack(value: any); + constructor(message?: string, name?: string) + /** + * The **`message`** read-only property of the a message or description associated with the given error name. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) + */ + readonly message: string + /** + * The **`name`** read-only property of the one of the strings associated with an error name. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) + */ + readonly name: string + /** + * The **`code`** read-only property of the DOMException interface returns one of the legacy error code constants, or `0` if none match. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number + static readonly INDEX_SIZE_ERR: number + static readonly DOMSTRING_SIZE_ERR: number + static readonly HIERARCHY_REQUEST_ERR: number + static readonly WRONG_DOCUMENT_ERR: number + static readonly INVALID_CHARACTER_ERR: number + static readonly NO_DATA_ALLOWED_ERR: number + static readonly NO_MODIFICATION_ALLOWED_ERR: number + static readonly NOT_FOUND_ERR: number + static readonly NOT_SUPPORTED_ERR: number + static readonly INUSE_ATTRIBUTE_ERR: number + static readonly INVALID_STATE_ERR: number + static readonly SYNTAX_ERR: number + static readonly INVALID_MODIFICATION_ERR: number + static readonly NAMESPACE_ERR: number + static readonly INVALID_ACCESS_ERR: number + static readonly VALIDATION_ERR: number + static readonly TYPE_MISMATCH_ERR: number + static readonly SECURITY_ERR: number + static readonly NETWORK_ERR: number + static readonly ABORT_ERR: number + static readonly URL_MISMATCH_ERR: number + static readonly QUOTA_EXCEEDED_ERR: number + static readonly TIMEOUT_ERR: number + static readonly INVALID_NODE_TYPE_ERR: number + static readonly DATA_CLONE_ERR: number + get stack(): any + set stack(value: any) } type WorkerGlobalScopeEventMap = { - fetch: FetchEvent; - scheduled: ScheduledEvent; - queue: QueueEvent; - unhandledrejection: PromiseRejectionEvent; - rejectionhandled: PromiseRejectionEvent; -}; + fetch: FetchEvent + scheduled: ScheduledEvent + queue: QueueEvent + unhandledrejection: PromiseRejectionEvent + rejectionhandled: PromiseRejectionEvent +} declare abstract class WorkerGlobalScope extends EventTarget { - EventTarget: typeof EventTarget; + EventTarget: typeof EventTarget } /* The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). * * The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). @@ -102,186 +102,204 @@ declare abstract class WorkerGlobalScope extends EventTarget; - type Imports = Record; - type ExportValue = Function | Global | Memory | Table; - type Exports = Record; - class Instance { - constructor(module: Module, imports?: Imports); - readonly exports: Exports; - } - interface MemoryDescriptor { - initial: number; - maximum?: number; - shared?: boolean; - } - class Memory { - constructor(descriptor: MemoryDescriptor); - readonly buffer: ArrayBuffer; - grow(delta: number): number; - } - type ImportExportKind = "function" | "global" | "memory" | "table"; - interface ModuleExportDescriptor { - kind: ImportExportKind; - name: string; - } - interface ModuleImportDescriptor { - kind: ImportExportKind; - module: string; - name: string; - } - abstract class Module { - static customSections(module: Module, sectionName: string): ArrayBuffer[]; - static exports(module: Module): ModuleExportDescriptor[]; - static imports(module: Module): ModuleImportDescriptor[]; - } - type TableKind = "anyfunc" | "externref"; - interface TableDescriptor { - element: TableKind; - initial: number; - maximum?: number; - } - class Table { - constructor(descriptor: TableDescriptor, value?: any); - readonly length: number; - get(index: number): any; - grow(delta: number, value?: any): number; - set(index: number, value?: any): void; - } - function instantiate(module: Module, imports?: Imports): Promise; - function validate(bytes: BufferSource): boolean; + class CompileError extends Error { + constructor(message?: string) + } + class RuntimeError extends Error { + constructor(message?: string) + } + type ValueType = + | 'anyfunc' + | 'externref' + | 'f32' + | 'f64' + | 'i32' + | 'i64' + | 'v128' + interface GlobalDescriptor { + value: ValueType + mutable?: boolean + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any) + value: any + valueOf(): any + } + type ImportValue = ExportValue | number + type ModuleImports = Record + type Imports = Record + type ExportValue = Function | Global | Memory | Table + type Exports = Record + class Instance { + constructor(module: Module, imports?: Imports) + readonly exports: Exports + } + interface MemoryDescriptor { + initial: number + maximum?: number + shared?: boolean + } + class Memory { + constructor(descriptor: MemoryDescriptor) + readonly buffer: ArrayBuffer + grow(delta: number): number + } + type ImportExportKind = 'function' | 'global' | 'memory' | 'table' + interface ModuleExportDescriptor { + kind: ImportExportKind + name: string + } + interface ModuleImportDescriptor { + kind: ImportExportKind + module: string + name: string + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[] + static exports(module: Module): ModuleExportDescriptor[] + static imports(module: Module): ModuleImportDescriptor[] + } + type TableKind = 'anyfunc' | 'externref' + interface TableDescriptor { + element: TableKind + initial: number + maximum?: number + } + class Table { + constructor(descriptor: TableDescriptor, value?: any) + readonly length: number + get(index: number): any + grow(delta: number, value?: any): number + set(index: number, value?: any): void + } + function instantiate(module: Module, imports?: Imports): Promise + function validate(bytes: BufferSource): boolean } /** * The **`ServiceWorkerGlobalScope`** interface of the Service Worker API represents the global execution context of a service worker. @@ -290,311 +308,452 @@ declare namespace WebAssembly { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) */ interface ServiceWorkerGlobalScope extends WorkerGlobalScope { - DOMException: typeof DOMException; - WorkerGlobalScope: typeof WorkerGlobalScope; - btoa(data: string): string; - atob(data: string): string; - setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; - setTimeout(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; - clearTimeout(timeoutId: number | null): void; - setInterval(callback: (...args: any[]) => void, msDelay?: number): number; - setInterval(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; - clearInterval(timeoutId: number | null): void; - queueMicrotask(task: Function): void; - structuredClone(value: T, options?: StructuredSerializeOptions): T; - reportError(error: any): void; - fetch(input: RequestInfo | URL, init?: RequestInit): Promise; - self: ServiceWorkerGlobalScope; - crypto: Crypto; - caches: CacheStorage; - scheduler: Scheduler; - performance: Performance; - Cloudflare: Cloudflare; - readonly origin: string; - Event: typeof Event; - ExtendableEvent: typeof ExtendableEvent; - CustomEvent: typeof CustomEvent; - PromiseRejectionEvent: typeof PromiseRejectionEvent; - FetchEvent: typeof FetchEvent; - TailEvent: typeof TailEvent; - TraceEvent: typeof TailEvent; - ScheduledEvent: typeof ScheduledEvent; - MessageEvent: typeof MessageEvent; - CloseEvent: typeof CloseEvent; - ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; - ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; - ReadableStream: typeof ReadableStream; - WritableStream: typeof WritableStream; - WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; - TransformStream: typeof TransformStream; - ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; - CountQueuingStrategy: typeof CountQueuingStrategy; - ErrorEvent: typeof ErrorEvent; - MessageChannel: typeof MessageChannel; - MessagePort: typeof MessagePort; - EventSource: typeof EventSource; - ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; - ReadableStreamDefaultController: typeof ReadableStreamDefaultController; - ReadableByteStreamController: typeof ReadableByteStreamController; - WritableStreamDefaultController: typeof WritableStreamDefaultController; - TransformStreamDefaultController: typeof TransformStreamDefaultController; - CompressionStream: typeof CompressionStream; - DecompressionStream: typeof DecompressionStream; - TextEncoderStream: typeof TextEncoderStream; - TextDecoderStream: typeof TextDecoderStream; - Headers: typeof Headers; - Body: typeof Body; - Request: typeof Request; - Response: typeof Response; - WebSocket: typeof WebSocket; - WebSocketPair: typeof WebSocketPair; - WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; - AbortController: typeof AbortController; - AbortSignal: typeof AbortSignal; - TextDecoder: typeof TextDecoder; - TextEncoder: typeof TextEncoder; - navigator: Navigator; - Navigator: typeof Navigator; - URL: typeof URL; - URLSearchParams: typeof URLSearchParams; - URLPattern: typeof URLPattern; - Blob: typeof Blob; - File: typeof File; - FormData: typeof FormData; - Crypto: typeof Crypto; - SubtleCrypto: typeof SubtleCrypto; - CryptoKey: typeof CryptoKey; - CacheStorage: typeof CacheStorage; - Cache: typeof Cache; - FixedLengthStream: typeof FixedLengthStream; - IdentityTransformStream: typeof IdentityTransformStream; - HTMLRewriter: typeof HTMLRewriter; + DOMException: typeof DOMException + WorkerGlobalScope: typeof WorkerGlobalScope + btoa(data: string): string + atob(data: string): string + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number + setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number + clearTimeout(timeoutId: number | null): void + setInterval(callback: (...args: any[]) => void, msDelay?: number): number + setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args + ): number + clearInterval(timeoutId: number | null): void + queueMicrotask(task: Function): void + structuredClone(value: T, options?: StructuredSerializeOptions): T + reportError(error: any): void + fetch( + input: RequestInfo | URL, + init?: RequestInit, + ): Promise + self: ServiceWorkerGlobalScope + crypto: Crypto + caches: CacheStorage + scheduler: Scheduler + performance: Performance + Cloudflare: Cloudflare + readonly origin: string + Event: typeof Event + ExtendableEvent: typeof ExtendableEvent + CustomEvent: typeof CustomEvent + PromiseRejectionEvent: typeof PromiseRejectionEvent + FetchEvent: typeof FetchEvent + TailEvent: typeof TailEvent + TraceEvent: typeof TailEvent + ScheduledEvent: typeof ScheduledEvent + MessageEvent: typeof MessageEvent + CloseEvent: typeof CloseEvent + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader + ReadableStream: typeof ReadableStream + WritableStream: typeof WritableStream + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter + TransformStream: typeof TransformStream + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy + CountQueuingStrategy: typeof CountQueuingStrategy + ErrorEvent: typeof ErrorEvent + MessageChannel: typeof MessageChannel + MessagePort: typeof MessagePort + EventSource: typeof EventSource + ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest + ReadableStreamDefaultController: typeof ReadableStreamDefaultController + ReadableByteStreamController: typeof ReadableByteStreamController + WritableStreamDefaultController: typeof WritableStreamDefaultController + TransformStreamDefaultController: typeof TransformStreamDefaultController + CompressionStream: typeof CompressionStream + DecompressionStream: typeof DecompressionStream + TextEncoderStream: typeof TextEncoderStream + TextDecoderStream: typeof TextDecoderStream + Headers: typeof Headers + Body: typeof Body + Request: typeof Request + Response: typeof Response + WebSocket: typeof WebSocket + WebSocketPair: typeof WebSocketPair + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair + AbortController: typeof AbortController + AbortSignal: typeof AbortSignal + TextDecoder: typeof TextDecoder + TextEncoder: typeof TextEncoder + navigator: Navigator + Navigator: typeof Navigator + URL: typeof URL + URLSearchParams: typeof URLSearchParams + URLPattern: typeof URLPattern + Blob: typeof Blob + File: typeof File + FormData: typeof FormData + Crypto: typeof Crypto + SubtleCrypto: typeof SubtleCrypto + CryptoKey: typeof CryptoKey + CacheStorage: typeof CacheStorage + Cache: typeof Cache + FixedLengthStream: typeof FixedLengthStream + IdentityTransformStream: typeof IdentityTransformStream + HTMLRewriter: typeof HTMLRewriter } -declare function addEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void; -declare function removeEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetEventListenerOptions | boolean): void; +declare function addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, +): void +declare function removeEventListener< + Type extends keyof WorkerGlobalScopeEventMap, +>( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | boolean, +): void /** * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) */ -declare function dispatchEvent(event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap]): boolean; +declare function dispatchEvent( + event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap], +): boolean /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/btoa) */ -declare function btoa(data: string): string; +declare function btoa(data: string): string /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/atob) */ -declare function atob(data: string): string; +declare function atob(data: string): string /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */ -declare function setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; +declare function setTimeout( + callback: (...args: any[]) => void, + msDelay?: number, +): number /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */ -declare function setTimeout(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; +declare function setTimeout( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearTimeout) */ -declare function clearTimeout(timeoutId: number | null): void; +declare function clearTimeout(timeoutId: number | null): void /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */ -declare function setInterval(callback: (...args: any[]) => void, msDelay?: number): number; +declare function setInterval( + callback: (...args: any[]) => void, + msDelay?: number, +): number /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */ -declare function setInterval(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; +declare function setInterval( + callback: (...args: Args) => void, + msDelay?: number, + ...args: Args +): number /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearInterval) */ -declare function clearInterval(timeoutId: number | null): void; +declare function clearInterval(timeoutId: number | null): void /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/queueMicrotask) */ -declare function queueMicrotask(task: Function): void; +declare function queueMicrotask(task: Function): void /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/structuredClone) */ -declare function structuredClone(value: T, options?: StructuredSerializeOptions): T; +declare function structuredClone( + value: T, + options?: StructuredSerializeOptions, +): T /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/reportError) */ -declare function reportError(error: any): void; +declare function reportError(error: any): void /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) */ -declare function fetch(input: RequestInfo | URL, init?: RequestInit): Promise; -declare const self: ServiceWorkerGlobalScope; +declare function fetch( + input: RequestInfo | URL, + init?: RequestInit, +): Promise +declare const self: ServiceWorkerGlobalScope /** -* The Web Crypto API provides a set of low-level functions for common cryptographic tasks. -* The Workers runtime implements the full surface of this API, but with some differences in -* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) -* compared to those implemented in most browsers. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) -*/ -declare const crypto: Crypto; + * The Web Crypto API provides a set of low-level functions for common cryptographic tasks. + * The Workers runtime implements the full surface of this API, but with some differences in + * the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) + * compared to those implemented in most browsers. + * + * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) + */ +declare const crypto: Crypto /** -* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) -*/ -declare const caches: CacheStorage; -declare const scheduler: Scheduler; + * The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. + * + * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) + */ +declare const caches: CacheStorage +declare const scheduler: Scheduler /** -* The Workers runtime supports a subset of the Performance API, used to measure timing and performance, -* as well as timing of subrequests and other operations. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) -*/ -declare const performance: Performance; -declare const Cloudflare: Cloudflare; -declare const origin: string; -declare const navigator: Navigator; -interface TestController { -} + * The Workers runtime supports a subset of the Performance API, used to measure timing and performance, + * as well as timing of subrequests and other operations. + * + * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) + */ +declare const performance: Performance +declare const Cloudflare: Cloudflare +declare const origin: string +declare const navigator: Navigator +interface TestController {} interface ExecutionContext { - waitUntil(promise: Promise): void; - passThroughOnException(): void; - readonly props: Props; + waitUntil(promise: Promise): void + passThroughOnException(): void + readonly props: Props } -type ExportedHandlerFetchHandler = (request: Request>, env: Env, ctx: ExecutionContext) => Response | Promise; -type ExportedHandlerTailHandler = (events: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTraceHandler = (traces: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTailStreamHandler = (event: TailStream.TailEvent, env: Env, ctx: ExecutionContext) => TailStream.TailEventHandlerType | Promise; -type ExportedHandlerScheduledHandler = (controller: ScheduledController, env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerQueueHandler = (batch: MessageBatch, env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTestHandler = (controller: TestController, env: Env, ctx: ExecutionContext) => void | Promise; -interface ExportedHandler { - fetch?: ExportedHandlerFetchHandler; - tail?: ExportedHandlerTailHandler; - trace?: ExportedHandlerTraceHandler; - tailStream?: ExportedHandlerTailStreamHandler; - scheduled?: ExportedHandlerScheduledHandler; - test?: ExportedHandlerTestHandler; - email?: EmailExportedHandler; - queue?: ExportedHandlerQueueHandler; +type ExportedHandlerFetchHandler = ( + request: Request>, + env: Env, + ctx: ExecutionContext, +) => Response | Promise +type ExportedHandlerTailHandler = ( + events: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise +type ExportedHandlerTraceHandler = ( + traces: TraceItem[], + env: Env, + ctx: ExecutionContext, +) => void | Promise +type ExportedHandlerTailStreamHandler = ( + event: TailStream.TailEvent, + env: Env, + ctx: ExecutionContext, +) => TailStream.TailEventHandlerType | Promise +type ExportedHandlerScheduledHandler = ( + controller: ScheduledController, + env: Env, + ctx: ExecutionContext, +) => void | Promise +type ExportedHandlerQueueHandler = ( + batch: MessageBatch, + env: Env, + ctx: ExecutionContext, +) => void | Promise +type ExportedHandlerTestHandler = ( + controller: TestController, + env: Env, + ctx: ExecutionContext, +) => void | Promise +interface ExportedHandler< + Env = unknown, + QueueHandlerMessage = unknown, + CfHostMetadata = unknown, +> { + fetch?: ExportedHandlerFetchHandler + tail?: ExportedHandlerTailHandler + trace?: ExportedHandlerTraceHandler + tailStream?: ExportedHandlerTailStreamHandler + scheduled?: ExportedHandlerScheduledHandler + test?: ExportedHandlerTestHandler + email?: EmailExportedHandler + queue?: ExportedHandlerQueueHandler } interface StructuredSerializeOptions { - transfer?: any[]; + transfer?: any[] } declare abstract class Navigator { - sendBeacon(url: string, body?: BodyInit): boolean; - readonly userAgent: string; - readonly hardwareConcurrency: number; - readonly language: string; - readonly languages: string[]; + sendBeacon(url: string, body?: BodyInit): boolean + readonly userAgent: string + readonly hardwareConcurrency: number + readonly language: string + readonly languages: string[] } interface AlarmInvocationInfo { - readonly isRetry: boolean; - readonly retryCount: number; + readonly isRetry: boolean + readonly retryCount: number } interface Cloudflare { - readonly compatibilityFlags: Record; + readonly compatibilityFlags: Record } interface DurableObject { - fetch(request: Request): Response | Promise; - alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; - webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; - webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise; - webSocketError?(ws: WebSocket, error: unknown): void | Promise; + fetch(request: Request): Response | Promise + alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise + webSocketError?(ws: WebSocket, error: unknown): void | Promise +} +type DurableObjectStub< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> = Fetcher< + T, + 'alarm' | 'webSocketMessage' | 'webSocketClose' | 'webSocketError' +> & { + readonly id: DurableObjectId + readonly name?: string } -type DurableObjectStub = Fetcher & { - readonly id: DurableObjectId; - readonly name?: string; -}; interface DurableObjectId { - toString(): string; - equals(other: DurableObjectId): boolean; - readonly name?: string; + toString(): string + equals(other: DurableObjectId): boolean + readonly name?: string } -declare abstract class DurableObjectNamespace { - newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId; - idFromName(name: string): DurableObjectId; - idFromString(id: string): DurableObjectId; - get(id: DurableObjectId, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; - getByName(name: string, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; - jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; +declare abstract class DurableObjectNamespace< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> { + newUniqueId( + options?: DurableObjectNamespaceNewUniqueIdOptions, + ): DurableObjectId + idFromName(name: string): DurableObjectId + idFromString(id: string): DurableObjectId + get( + id: DurableObjectId, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub + getByName( + name: string, + options?: DurableObjectNamespaceGetDurableObjectOptions, + ): DurableObjectStub + jurisdiction( + jurisdiction: DurableObjectJurisdiction, + ): DurableObjectNamespace } -type DurableObjectJurisdiction = "eu" | "fedramp" | "fedramp-high"; +type DurableObjectJurisdiction = 'eu' | 'fedramp' | 'fedramp-high' interface DurableObjectNamespaceNewUniqueIdOptions { - jurisdiction?: DurableObjectJurisdiction; + jurisdiction?: DurableObjectJurisdiction } -type DurableObjectLocationHint = "wnam" | "enam" | "sam" | "weur" | "eeur" | "apac" | "oc" | "afr" | "me"; -type DurableObjectRoutingMode = "primary-only"; +type DurableObjectLocationHint = + | 'wnam' + | 'enam' + | 'sam' + | 'weur' + | 'eeur' + | 'apac' + | 'oc' + | 'afr' + | 'me' interface DurableObjectNamespaceGetDurableObjectOptions { - locationHint?: DurableObjectLocationHint; - routingMode?: DurableObjectRoutingMode; -} -interface DurableObjectClass<_T extends Rpc.DurableObjectBranded | undefined = undefined> { + locationHint?: DurableObjectLocationHint } +interface DurableObjectClass< + _T extends Rpc.DurableObjectBranded | undefined = undefined, +> {} interface DurableObjectState { - waitUntil(promise: Promise): void; - readonly props: Props; - readonly id: DurableObjectId; - readonly storage: DurableObjectStorage; - container?: Container; - blockConcurrencyWhile(callback: () => Promise): Promise; - acceptWebSocket(ws: WebSocket, tags?: string[]): void; - getWebSockets(tag?: string): WebSocket[]; - setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; - getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; - getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; - setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; - getHibernatableWebSocketEventTimeout(): number | null; - getTags(ws: WebSocket): string[]; - abort(reason?: string): void; + waitUntil(promise: Promise): void + readonly props: Props + readonly id: DurableObjectId + readonly storage: DurableObjectStorage + container?: Container + blockConcurrencyWhile(callback: () => Promise): Promise + acceptWebSocket(ws: WebSocket, tags?: string[]): void + getWebSockets(tag?: string): WebSocket[] + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void + getHibernatableWebSocketEventTimeout(): number | null + getTags(ws: WebSocket): string[] + abort(reason?: string): void } interface DurableObjectTransaction { - get(key: string, options?: DurableObjectGetOptions): Promise; - get(keys: string[], options?: DurableObjectGetOptions): Promise>; - list(options?: DurableObjectListOptions): Promise>; - put(key: string, value: T, options?: DurableObjectPutOptions): Promise; - put(entries: Record, options?: DurableObjectPutOptions): Promise; - delete(key: string, options?: DurableObjectPutOptions): Promise; - delete(keys: string[], options?: DurableObjectPutOptions): Promise; - rollback(): void; - getAlarm(options?: DurableObjectGetAlarmOptions): Promise; - setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; - deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise> + list(options?: DurableObjectListOptions): Promise> + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise + delete(key: string, options?: DurableObjectPutOptions): Promise + delete(keys: string[], options?: DurableObjectPutOptions): Promise + rollback(): void + getAlarm(options?: DurableObjectGetAlarmOptions): Promise + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise } interface DurableObjectStorage { - get(key: string, options?: DurableObjectGetOptions): Promise; - get(keys: string[], options?: DurableObjectGetOptions): Promise>; - list(options?: DurableObjectListOptions): Promise>; - put(key: string, value: T, options?: DurableObjectPutOptions): Promise; - put(entries: Record, options?: DurableObjectPutOptions): Promise; - delete(key: string, options?: DurableObjectPutOptions): Promise; - delete(keys: string[], options?: DurableObjectPutOptions): Promise; - deleteAll(options?: DurableObjectPutOptions): Promise; - transaction(closure: (txn: DurableObjectTransaction) => Promise): Promise; - getAlarm(options?: DurableObjectGetAlarmOptions): Promise; - setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; - deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; - sync(): Promise; - sql: SqlStorage; - kv: SyncKvStorage; - transactionSync(closure: () => T): T; - getCurrentBookmark(): Promise; - getBookmarkForTime(timestamp: number | Date): Promise; - onNextSessionRestoreBookmark(bookmark: string): Promise; + get( + key: string, + options?: DurableObjectGetOptions, + ): Promise + get( + keys: string[], + options?: DurableObjectGetOptions, + ): Promise> + list(options?: DurableObjectListOptions): Promise> + put( + key: string, + value: T, + options?: DurableObjectPutOptions, + ): Promise + put( + entries: Record, + options?: DurableObjectPutOptions, + ): Promise + delete(key: string, options?: DurableObjectPutOptions): Promise + delete(keys: string[], options?: DurableObjectPutOptions): Promise + deleteAll(options?: DurableObjectPutOptions): Promise + transaction( + closure: (txn: DurableObjectTransaction) => Promise, + ): Promise + getAlarm(options?: DurableObjectGetAlarmOptions): Promise + setAlarm( + scheduledTime: number | Date, + options?: DurableObjectSetAlarmOptions, + ): Promise + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise + sync(): Promise + sql: SqlStorage + kv: SyncKvStorage + transactionSync(closure: () => T): T + getCurrentBookmark(): Promise + getBookmarkForTime(timestamp: number | Date): Promise + onNextSessionRestoreBookmark(bookmark: string): Promise } interface DurableObjectListOptions { - start?: string; - startAfter?: string; - end?: string; - prefix?: string; - reverse?: boolean; - limit?: number; - allowConcurrency?: boolean; - noCache?: boolean; + start?: string + startAfter?: string + end?: string + prefix?: string + reverse?: boolean + limit?: number + allowConcurrency?: boolean + noCache?: boolean } interface DurableObjectGetOptions { - allowConcurrency?: boolean; - noCache?: boolean; + allowConcurrency?: boolean + noCache?: boolean } interface DurableObjectGetAlarmOptions { - allowConcurrency?: boolean; + allowConcurrency?: boolean } interface DurableObjectPutOptions { - allowConcurrency?: boolean; - allowUnconfirmed?: boolean; - noCache?: boolean; + allowConcurrency?: boolean + allowUnconfirmed?: boolean + noCache?: boolean } interface DurableObjectSetAlarmOptions { - allowConcurrency?: boolean; - allowUnconfirmed?: boolean; + allowConcurrency?: boolean + allowUnconfirmed?: boolean } declare class WebSocketRequestResponsePair { - constructor(request: string, response: string); - get request(): string; - get response(): string; + constructor(request: string, response: string) + get request(): string + get response(): string } interface AnalyticsEngineDataset { - writeDataPoint(event?: AnalyticsEngineDataPoint): void; + writeDataPoint(event?: AnalyticsEngineDataPoint): void } interface AnalyticsEngineDataPoint { - indexes?: ((ArrayBuffer | string) | null)[]; - doubles?: number[]; - blobs?: ((ArrayBuffer | string) | null)[]; + indexes?: ((ArrayBuffer | string) | null)[] + doubles?: number[] + blobs?: ((ArrayBuffer | string) | null)[] } /** * The **`Event`** interface represents an event which takes place on an `EventTarget`. @@ -602,171 +761,183 @@ interface AnalyticsEngineDataPoint { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event) */ declare class Event { - constructor(type: string, init?: EventInit); - /** - * The **`type`** read-only property of the Event interface returns a string containing the event's type. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) - */ - get type(): string; - /** - * The **`eventPhase`** read-only property of the being evaluated. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) - */ - get eventPhase(): number; - /** - * The read-only **`composed`** property of the or not the event will propagate across the shadow DOM boundary into the standard DOM. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) - */ - get composed(): boolean; - /** - * The **`bubbles`** read-only property of the Event interface indicates whether the event bubbles up through the DOM tree or not. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) - */ - get bubbles(): boolean; - /** - * The **`cancelable`** read-only property of the Event interface indicates whether the event can be canceled, and therefore prevented as if the event never happened. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) - */ - get cancelable(): boolean; - /** - * The **`defaultPrevented`** read-only property of the Event interface returns a boolean value indicating whether or not the call to Event.preventDefault() canceled the event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) - */ - get defaultPrevented(): boolean; - /** - * The Event property **`returnValue`** indicates whether the default action for this event has been prevented or not. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) - */ - get returnValue(): boolean; - /** - * The **`currentTarget`** read-only property of the Event interface identifies the element to which the event handler has been attached. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) - */ - get currentTarget(): EventTarget | undefined; - /** - * The read-only **`target`** property of the dispatched. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target) - */ - get target(): EventTarget | undefined; - /** - * The deprecated **`Event.srcElement`** is an alias for the Event.target property. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) - */ - get srcElement(): EventTarget | undefined; - /** - * The **`timeStamp`** read-only property of the Event interface returns the time (in milliseconds) at which the event was created. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) - */ - get timeStamp(): number; - /** - * The **`isTrusted`** read-only property of the when the event was generated by the user agent (including via user actions and programmatic methods such as HTMLElement.focus()), and `false` when the event was dispatched via The only exception is the `click` event, which initializes the `isTrusted` property to `false` in user agents. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) - */ - get isTrusted(): boolean; - /** - * The **`cancelBubble`** property of the Event interface is deprecated. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) - */ - get cancelBubble(): boolean; - /** - * The **`cancelBubble`** property of the Event interface is deprecated. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) - */ - set cancelBubble(value: boolean); - /** - * The **`stopImmediatePropagation()`** method of the If several listeners are attached to the same element for the same event type, they are called in the order in which they were added. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) - */ - stopImmediatePropagation(): void; - /** - * The **`preventDefault()`** method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) - */ - preventDefault(): void; - /** - * The **`stopPropagation()`** method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) - */ - stopPropagation(): void; - /** - * The **`composedPath()`** method of the Event interface returns the event's path which is an array of the objects on which listeners will be invoked. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) - */ - composedPath(): EventTarget[]; - static readonly NONE: number; - static readonly CAPTURING_PHASE: number; - static readonly AT_TARGET: number; - static readonly BUBBLING_PHASE: number; + constructor(type: string, init?: EventInit) + /** + * The **`type`** read-only property of the Event interface returns a string containing the event's type. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + get type(): string + /** + * The **`eventPhase`** read-only property of the being evaluated. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + get eventPhase(): number + /** + * The read-only **`composed`** property of the or not the event will propagate across the shadow DOM boundary into the standard DOM. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + get composed(): boolean + /** + * The **`bubbles`** read-only property of the Event interface indicates whether the event bubbles up through the DOM tree or not. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + get bubbles(): boolean + /** + * The **`cancelable`** read-only property of the Event interface indicates whether the event can be canceled, and therefore prevented as if the event never happened. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + get cancelable(): boolean + /** + * The **`defaultPrevented`** read-only property of the Event interface returns a boolean value indicating whether or not the call to Event.preventDefault() canceled the event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + get defaultPrevented(): boolean + /** + * The Event property **`returnValue`** indicates whether the default action for this event has been prevented or not. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + get returnValue(): boolean + /** + * The **`currentTarget`** read-only property of the Event interface identifies the element to which the event handler has been attached. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + get currentTarget(): EventTarget | undefined + /** + * The read-only **`target`** property of the dispatched. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target) + */ + get target(): EventTarget | undefined + /** + * The deprecated **`Event.srcElement`** is an alias for the Event.target property. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + get srcElement(): EventTarget | undefined + /** + * The **`timeStamp`** read-only property of the Event interface returns the time (in milliseconds) at which the event was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + get timeStamp(): number + /** + * The **`isTrusted`** read-only property of the when the event was generated by the user agent (including via user actions and programmatic methods such as HTMLElement.focus()), and `false` when the event was dispatched via The only exception is the `click` event, which initializes the `isTrusted` property to `false` in user agents. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + get isTrusted(): boolean + /** + * The **`cancelBubble`** property of the Event interface is deprecated. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + get cancelBubble(): boolean + /** + * The **`cancelBubble`** property of the Event interface is deprecated. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + set cancelBubble(value: boolean) + /** + * The **`stopImmediatePropagation()`** method of the If several listeners are attached to the same element for the same event type, they are called in the order in which they were added. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void + /** + * The **`preventDefault()`** method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void + /** + * The **`stopPropagation()`** method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void + /** + * The **`composedPath()`** method of the Event interface returns the event's path which is an array of the objects on which listeners will be invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[] + static readonly NONE: number + static readonly CAPTURING_PHASE: number + static readonly AT_TARGET: number + static readonly BUBBLING_PHASE: number } interface EventInit { - bubbles?: boolean; - cancelable?: boolean; - composed?: boolean; + bubbles?: boolean + cancelable?: boolean + composed?: boolean } -type EventListener = (event: EventType) => void; +type EventListener = (event: EventType) => void interface EventListenerObject { - handleEvent(event: EventType): void; + handleEvent(event: EventType): void } -type EventListenerOrEventListenerObject = EventListener | EventListenerObject; +type EventListenerOrEventListenerObject = + | EventListener + | EventListenerObject /** * The **`EventTarget`** interface is implemented by objects that can receive events and may have listeners for them. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget) */ -declare class EventTarget = Record> { - constructor(); - /** - * The **`addEventListener()`** method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) - */ - addEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void; - /** - * The **`removeEventListener()`** method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) - */ - removeEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetEventListenerOptions | boolean): void; - /** - * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) - */ - dispatchEvent(event: EventMap[keyof EventMap]): boolean; +declare class EventTarget< + EventMap extends Record = Record, +> { + constructor() + /** + * The **`addEventListener()`** method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetAddEventListenerOptions | boolean, + ): void + /** + * The **`removeEventListener()`** method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener( + type: Type, + handler: EventListenerOrEventListenerObject, + options?: EventTargetEventListenerOptions | boolean, + ): void + /** + * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean } interface EventTargetEventListenerOptions { - capture?: boolean; + capture?: boolean } interface EventTargetAddEventListenerOptions { - capture?: boolean; - passive?: boolean; - once?: boolean; - signal?: AbortSignal; + capture?: boolean + passive?: boolean + once?: boolean + signal?: AbortSignal } interface EventTargetHandlerObject { - handleEvent: (event: Event) => any | undefined; + handleEvent: (event: Event) => any | undefined } /** * The **`AbortController`** interface represents a controller object that allows you to abort one or more Web requests as and when desired. @@ -774,19 +945,19 @@ interface EventTargetHandlerObject { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController) */ declare class AbortController { - constructor(); - /** - * The **`signal`** read-only property of the AbortController interface returns an AbortSignal object instance, which can be used to communicate with/abort an asynchronous operation as desired. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) - */ - get signal(): AbortSignal; - /** - * The **`abort()`** method of the AbortController interface aborts an asynchronous operation before it has completed. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) - */ - abort(reason?: any): void; + constructor() + /** + * The **`signal`** read-only property of the AbortController interface returns an AbortSignal object instance, which can be used to communicate with/abort an asynchronous operation as desired. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + get signal(): AbortSignal + /** + * The **`abort()`** method of the AbortController interface aborts an asynchronous operation before it has completed. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void } /** * The **`AbortSignal`** interface represents a signal object that allows you to communicate with an asynchronous operation (such as a fetch request) and abort it if required via an AbortController object. @@ -794,52 +965,52 @@ declare class AbortController { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal) */ declare abstract class AbortSignal extends EventTarget { - /** - * The **`AbortSignal.abort()`** static method returns an AbortSignal that is already set as aborted (and which does not trigger an AbortSignal/abort_event event). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) - */ - static abort(reason?: any): AbortSignal; - /** - * The **`AbortSignal.timeout()`** static method returns an AbortSignal that will automatically abort after a specified time. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) - */ - static timeout(delay: number): AbortSignal; - /** - * The **`AbortSignal.any()`** static method takes an iterable of abort signals and returns an AbortSignal. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static) - */ - static any(signals: AbortSignal[]): AbortSignal; - /** - * The **`aborted`** read-only property returns a value that indicates whether the asynchronous operations the signal is communicating with are aborted (`true`) or not (`false`). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) - */ - get aborted(): boolean; - /** - * The **`reason`** read-only property returns a JavaScript value that indicates the abort reason. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) - */ - get reason(): any; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ - get onabort(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ - set onabort(value: any | null); - /** - * The **`throwIfAborted()`** method throws the signal's abort AbortSignal.reason if the signal has been aborted; otherwise it does nothing. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) - */ - throwIfAborted(): void; + /** + * The **`AbortSignal.abort()`** static method returns an AbortSignal that is already set as aborted (and which does not trigger an AbortSignal/abort_event event). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) + */ + static abort(reason?: any): AbortSignal + /** + * The **`AbortSignal.timeout()`** static method returns an AbortSignal that will automatically abort after a specified time. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) + */ + static timeout(delay: number): AbortSignal + /** + * The **`AbortSignal.any()`** static method takes an iterable of abort signals and returns an AbortSignal. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static) + */ + static any(signals: AbortSignal[]): AbortSignal + /** + * The **`aborted`** read-only property returns a value that indicates whether the asynchronous operations the signal is communicating with are aborted (`true`) or not (`false`). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + get aborted(): boolean + /** + * The **`reason`** read-only property returns a JavaScript value that indicates the abort reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) + */ + get reason(): any + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + get onabort(): any | null + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + set onabort(value: any | null) + /** + * The **`throwIfAborted()`** method throws the signal's abort AbortSignal.reason if the signal has been aborted; otherwise it does nothing. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) + */ + throwIfAborted(): void } interface Scheduler { - wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise } interface SchedulerWaitOptions { - signal?: AbortSignal; + signal?: AbortSignal } /** * The **`ExtendableEvent`** interface extends the lifetime of the `install` and `activate` events dispatched on the global scope as part of the service worker lifecycle. @@ -847,12 +1018,12 @@ interface SchedulerWaitOptions { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent) */ declare abstract class ExtendableEvent extends Event { - /** - * The **`ExtendableEvent.waitUntil()`** method tells the event dispatcher that work is ongoing. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) - */ - waitUntil(promise: Promise): void; + /** + * The **`ExtendableEvent.waitUntil()`** method tells the event dispatcher that work is ongoing. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) + */ + waitUntil(promise: Promise): void } /** * The **`CustomEvent`** interface represents events initialized by an application for any purpose. @@ -860,19 +1031,19 @@ declare abstract class ExtendableEvent extends Event { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent) */ declare class CustomEvent extends Event { - constructor(type: string, init?: CustomEventCustomEventInit); - /** - * The read-only **`detail`** property of the CustomEvent interface returns any data passed when initializing the event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) - */ - get detail(): T; + constructor(type: string, init?: CustomEventCustomEventInit) + /** + * The read-only **`detail`** property of the CustomEvent interface returns any data passed when initializing the event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T } interface CustomEventCustomEventInit { - bubbles?: boolean; - cancelable?: boolean; - composed?: boolean; - detail?: any; + bubbles?: boolean + cancelable?: boolean + composed?: boolean + detail?: any } /** * The **`Blob`** interface represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a ReadableStream so its methods can be used for processing the data. @@ -880,52 +1051,55 @@ interface CustomEventCustomEventInit { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob) */ declare class Blob { - constructor(type?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], options?: BlobOptions); - /** - * The **`size`** read-only property of the Blob interface returns the size of the Blob or File in bytes. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) - */ - get size(): number; - /** - * The **`type`** read-only property of the Blob interface returns the MIME type of the file. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) - */ - get type(): string; - /** - * The **`slice()`** method of the Blob interface creates and returns a new `Blob` object which contains data from a subset of the blob on which it's called. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) - */ - slice(start?: number, end?: number, type?: string): Blob; - /** - * The **`arrayBuffer()`** method of the Blob interface returns a Promise that resolves with the contents of the blob as binary data contained in an ArrayBuffer. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) - */ - arrayBuffer(): Promise; - /** - * The **`bytes()`** method of the Blob interface returns a Promise that resolves with a Uint8Array containing the contents of the blob as an array of bytes. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/bytes) - */ - bytes(): Promise; - /** - * The **`text()`** method of the string containing the contents of the blob, interpreted as UTF-8. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) - */ - text(): Promise; - /** - * The **`stream()`** method of the Blob interface returns a ReadableStream which upon reading returns the data contained within the `Blob`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) - */ - stream(): ReadableStream; + constructor( + type?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], + options?: BlobOptions, + ) + /** + * The **`size`** read-only property of the Blob interface returns the size of the Blob or File in bytes. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) + */ + get size(): number + /** + * The **`type`** read-only property of the Blob interface returns the MIME type of the file. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) + */ + get type(): string + /** + * The **`slice()`** method of the Blob interface creates and returns a new `Blob` object which contains data from a subset of the blob on which it's called. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) + */ + slice(start?: number, end?: number, type?: string): Blob + /** + * The **`arrayBuffer()`** method of the Blob interface returns a Promise that resolves with the contents of the blob as binary data contained in an ArrayBuffer. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) + */ + arrayBuffer(): Promise + /** + * The **`bytes()`** method of the Blob interface returns a Promise that resolves with a Uint8Array containing the contents of the blob as an array of bytes. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/bytes) + */ + bytes(): Promise + /** + * The **`text()`** method of the string containing the contents of the blob, interpreted as UTF-8. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) + */ + text(): Promise + /** + * The **`stream()`** method of the Blob interface returns a ReadableStream which upon reading returns the data contained within the `Blob`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) + */ + stream(): ReadableStream } interface BlobOptions { - type?: string; + type?: string } /** * The **`File`** interface provides information about files and allows JavaScript in a web page to access their content. @@ -933,84 +1107,104 @@ interface BlobOptions { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File) */ declare class File extends Blob { - constructor(bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, name: string, options?: FileOptions); - /** - * The **`name`** read-only property of the File interface returns the name of the file represented by a File object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) - */ - get name(): string; - /** - * The **`lastModified`** read-only property of the File interface provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) - */ - get lastModified(): number; + constructor( + bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, + name: string, + options?: FileOptions, + ) + /** + * The **`name`** read-only property of the File interface returns the name of the file represented by a File object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) + */ + get name(): string + /** + * The **`lastModified`** read-only property of the File interface provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) + */ + get lastModified(): number } interface FileOptions { - type?: string; - lastModified?: number; + type?: string + lastModified?: number } /** -* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) -*/ + * The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. + * + * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) + */ declare abstract class CacheStorage { - /** - * The **`open()`** method of the the Cache object matching the `cacheName`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) - */ - open(cacheName: string): Promise; - readonly default: Cache; + /** + * The **`open()`** method of the the Cache object matching the `cacheName`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) + */ + open(cacheName: string): Promise + readonly default: Cache } /** -* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) -*/ + * The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. + * + * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) + */ declare abstract class Cache { - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#delete) */ - delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#match) */ - match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#put) */ - put(request: RequestInfo | URL, response: Response): Promise; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#delete) */ + delete( + request: RequestInfo | URL, + options?: CacheQueryOptions, + ): Promise + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#match) */ + match( + request: RequestInfo | URL, + options?: CacheQueryOptions, + ): Promise + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#put) */ + put(request: RequestInfo | URL, response: Response): Promise } interface CacheQueryOptions { - ignoreMethod?: boolean; + ignoreMethod?: boolean } /** -* The Web Crypto API provides a set of low-level functions for common cryptographic tasks. -* The Workers runtime implements the full surface of this API, but with some differences in -* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) -* compared to those implemented in most browsers. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) -*/ + * The Web Crypto API provides a set of low-level functions for common cryptographic tasks. + * The Workers runtime implements the full surface of this API, but with some differences in + * the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) + * compared to those implemented in most browsers. + * + * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) + */ declare abstract class Crypto { - /** - * The **`Crypto.subtle`** read-only property returns a cryptographic operations. - * Available only in secure contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) - */ - get subtle(): SubtleCrypto; - /** - * The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) - */ - getRandomValues(buffer: T): T; - /** - * The **`randomUUID()`** method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator. - * Available only in secure contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) - */ - randomUUID(): string; - DigestStream: typeof DigestStream; + /** + * The **`Crypto.subtle`** read-only property returns a cryptographic operations. + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + get subtle(): SubtleCrypto + /** + * The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) + */ + getRandomValues< + T extends + | Int8Array + | Uint8Array + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | BigInt64Array + | BigUint64Array, + >(buffer: T): T + /** + * The **`randomUUID()`** method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator. + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string + DigestStream: typeof DigestStream } /** * The **`SubtleCrypto`** interface of the Web Crypto API provides a number of low-level cryptographic functions. @@ -1019,79 +1213,135 @@ declare abstract class Crypto { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto) */ declare abstract class SubtleCrypto { - /** - * The **`encrypt()`** method of the SubtleCrypto interface encrypts data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/encrypt) - */ - encrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, plainText: ArrayBuffer | ArrayBufferView): Promise; - /** - * The **`decrypt()`** method of the SubtleCrypto interface decrypts some encrypted data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt) - */ - decrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, cipherText: ArrayBuffer | ArrayBufferView): Promise; - /** - * The **`sign()`** method of the SubtleCrypto interface generates a digital signature. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/sign) - */ - sign(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, data: ArrayBuffer | ArrayBufferView): Promise; - /** - * The **`verify()`** method of the SubtleCrypto interface verifies a digital signature. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/verify) - */ - verify(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, signature: ArrayBuffer | ArrayBufferView, data: ArrayBuffer | ArrayBufferView): Promise; - /** - * The **`digest()`** method of the SubtleCrypto interface generates a _digest_ of the given data, using the specified hash function. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest) - */ - digest(algorithm: string | SubtleCryptoHashAlgorithm, data: ArrayBuffer | ArrayBufferView): Promise; - /** - * The **`generateKey()`** method of the SubtleCrypto interface is used to generate a new key (for symmetric algorithms) or key pair (for public-key algorithms). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) - */ - generateKey(algorithm: string | SubtleCryptoGenerateKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; - /** - * The **`deriveKey()`** method of the SubtleCrypto interface can be used to derive a secret key from a master key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) - */ - deriveKey(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; - /** - * The **`deriveBits()`** method of the key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits) - */ - deriveBits(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, length?: number | null): Promise; - /** - * The **`importKey()`** method of the SubtleCrypto interface imports a key: that is, it takes as input a key in an external, portable format and gives you a CryptoKey object that you can use in the Web Crypto API. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) - */ - importKey(format: string, keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, algorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; - /** - * The **`exportKey()`** method of the SubtleCrypto interface exports a key: that is, it takes as input a CryptoKey object and gives you the key in an external, portable format. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey) - */ - exportKey(format: string, key: CryptoKey): Promise; - /** - * The **`wrapKey()`** method of the SubtleCrypto interface 'wraps' a key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey) - */ - wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm): Promise; - /** - * The **`unwrapKey()`** method of the SubtleCrypto interface 'unwraps' a key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) - */ - unwrapKey(format: string, wrappedKey: ArrayBuffer | ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; - timingSafeEqual(a: ArrayBuffer | ArrayBufferView, b: ArrayBuffer | ArrayBufferView): boolean; + /** + * The **`encrypt()`** method of the SubtleCrypto interface encrypts data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/encrypt) + */ + encrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + plainText: ArrayBuffer | ArrayBufferView, + ): Promise + /** + * The **`decrypt()`** method of the SubtleCrypto interface decrypts some encrypted data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt) + */ + decrypt( + algorithm: string | SubtleCryptoEncryptAlgorithm, + key: CryptoKey, + cipherText: ArrayBuffer | ArrayBufferView, + ): Promise + /** + * The **`sign()`** method of the SubtleCrypto interface generates a digital signature. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/sign) + */ + sign( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + data: ArrayBuffer | ArrayBufferView, + ): Promise + /** + * The **`verify()`** method of the SubtleCrypto interface verifies a digital signature. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/verify) + */ + verify( + algorithm: string | SubtleCryptoSignAlgorithm, + key: CryptoKey, + signature: ArrayBuffer | ArrayBufferView, + data: ArrayBuffer | ArrayBufferView, + ): Promise + /** + * The **`digest()`** method of the SubtleCrypto interface generates a _digest_ of the given data, using the specified hash function. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest) + */ + digest( + algorithm: string | SubtleCryptoHashAlgorithm, + data: ArrayBuffer | ArrayBufferView, + ): Promise + /** + * The **`generateKey()`** method of the SubtleCrypto interface is used to generate a new key (for symmetric algorithms) or key pair (for public-key algorithms). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) + */ + generateKey( + algorithm: string | SubtleCryptoGenerateKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise + /** + * The **`deriveKey()`** method of the SubtleCrypto interface can be used to derive a secret key from a master key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) + */ + deriveKey( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise + /** + * The **`deriveBits()`** method of the key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits) + */ + deriveBits( + algorithm: string | SubtleCryptoDeriveKeyAlgorithm, + baseKey: CryptoKey, + length?: number | null, + ): Promise + /** + * The **`importKey()`** method of the SubtleCrypto interface imports a key: that is, it takes as input a key in an external, portable format and gives you a CryptoKey object that you can use in the Web Crypto API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) + */ + importKey( + format: string, + keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, + algorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise + /** + * The **`exportKey()`** method of the SubtleCrypto interface exports a key: that is, it takes as input a CryptoKey object and gives you the key in an external, portable format. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey) + */ + exportKey(format: string, key: CryptoKey): Promise + /** + * The **`wrapKey()`** method of the SubtleCrypto interface 'wraps' a key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey) + */ + wrapKey( + format: string, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + ): Promise + /** + * The **`unwrapKey()`** method of the SubtleCrypto interface 'unwraps' a key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) + */ + unwrapKey( + format: string, + wrappedKey: ArrayBuffer | ArrayBufferView, + unwrappingKey: CryptoKey, + unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, + unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, + extractable: boolean, + keyUsages: string[], + ): Promise + timingSafeEqual( + a: ArrayBuffer | ArrayBufferView, + b: ArrayBuffer | ArrayBufferView, + ): boolean } /** * The **`CryptoKey`** interface of the Web Crypto API represents a cryptographic key obtained from one of the SubtleCrypto methods SubtleCrypto.generateKey, SubtleCrypto.deriveKey, SubtleCrypto.importKey, or SubtleCrypto.unwrapKey. @@ -1100,133 +1350,141 @@ declare abstract class SubtleCrypto { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey) */ declare abstract class CryptoKey { - /** - * The read-only **`type`** property of the CryptoKey interface indicates which kind of key is represented by the object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) - */ - readonly type: string; - /** - * The read-only **`extractable`** property of the CryptoKey interface indicates whether or not the key may be extracted using `SubtleCrypto.exportKey()` or `SubtleCrypto.wrapKey()`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) - */ - readonly extractable: boolean; - /** - * The read-only **`algorithm`** property of the CryptoKey interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) - */ - readonly algorithm: CryptoKeyKeyAlgorithm | CryptoKeyAesKeyAlgorithm | CryptoKeyHmacKeyAlgorithm | CryptoKeyRsaKeyAlgorithm | CryptoKeyEllipticKeyAlgorithm | CryptoKeyArbitraryKeyAlgorithm; - /** - * The read-only **`usages`** property of the CryptoKey interface indicates what can be done with the key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) - */ - readonly usages: string[]; + /** + * The read-only **`type`** property of the CryptoKey interface indicates which kind of key is represented by the object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) + */ + readonly type: string + /** + * The read-only **`extractable`** property of the CryptoKey interface indicates whether or not the key may be extracted using `SubtleCrypto.exportKey()` or `SubtleCrypto.wrapKey()`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) + */ + readonly extractable: boolean + /** + * The read-only **`algorithm`** property of the CryptoKey interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) + */ + readonly algorithm: + | CryptoKeyKeyAlgorithm + | CryptoKeyAesKeyAlgorithm + | CryptoKeyHmacKeyAlgorithm + | CryptoKeyRsaKeyAlgorithm + | CryptoKeyEllipticKeyAlgorithm + | CryptoKeyArbitraryKeyAlgorithm + /** + * The read-only **`usages`** property of the CryptoKey interface indicates what can be done with the key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) + */ + readonly usages: string[] } interface CryptoKeyPair { - publicKey: CryptoKey; - privateKey: CryptoKey; + publicKey: CryptoKey + privateKey: CryptoKey } interface JsonWebKey { - kty: string; - use?: string; - key_ops?: string[]; - alg?: string; - ext?: boolean; - crv?: string; - x?: string; - y?: string; - d?: string; - n?: string; - e?: string; - p?: string; - q?: string; - dp?: string; - dq?: string; - qi?: string; - oth?: RsaOtherPrimesInfo[]; - k?: string; + kty: string + use?: string + key_ops?: string[] + alg?: string + ext?: boolean + crv?: string + x?: string + y?: string + d?: string + n?: string + e?: string + p?: string + q?: string + dp?: string + dq?: string + qi?: string + oth?: RsaOtherPrimesInfo[] + k?: string } interface RsaOtherPrimesInfo { - r?: string; - d?: string; - t?: string; + r?: string + d?: string + t?: string } interface SubtleCryptoDeriveKeyAlgorithm { - name: string; - salt?: (ArrayBuffer | ArrayBufferView); - iterations?: number; - hash?: (string | SubtleCryptoHashAlgorithm); - $public?: CryptoKey; - info?: (ArrayBuffer | ArrayBufferView); + name: string + salt?: ArrayBuffer | ArrayBufferView + iterations?: number + hash?: string | SubtleCryptoHashAlgorithm + $public?: CryptoKey + info?: ArrayBuffer | ArrayBufferView } interface SubtleCryptoEncryptAlgorithm { - name: string; - iv?: (ArrayBuffer | ArrayBufferView); - additionalData?: (ArrayBuffer | ArrayBufferView); - tagLength?: number; - counter?: (ArrayBuffer | ArrayBufferView); - length?: number; - label?: (ArrayBuffer | ArrayBufferView); + name: string + iv?: ArrayBuffer | ArrayBufferView + additionalData?: ArrayBuffer | ArrayBufferView + tagLength?: number + counter?: ArrayBuffer | ArrayBufferView + length?: number + label?: ArrayBuffer | ArrayBufferView } interface SubtleCryptoGenerateKeyAlgorithm { - name: string; - hash?: (string | SubtleCryptoHashAlgorithm); - modulusLength?: number; - publicExponent?: (ArrayBuffer | ArrayBufferView); - length?: number; - namedCurve?: string; + name: string + hash?: string | SubtleCryptoHashAlgorithm + modulusLength?: number + publicExponent?: ArrayBuffer | ArrayBufferView + length?: number + namedCurve?: string } interface SubtleCryptoHashAlgorithm { - name: string; + name: string } interface SubtleCryptoImportKeyAlgorithm { - name: string; - hash?: (string | SubtleCryptoHashAlgorithm); - length?: number; - namedCurve?: string; - compressed?: boolean; + name: string + hash?: string | SubtleCryptoHashAlgorithm + length?: number + namedCurve?: string + compressed?: boolean } interface SubtleCryptoSignAlgorithm { - name: string; - hash?: (string | SubtleCryptoHashAlgorithm); - dataLength?: number; - saltLength?: number; + name: string + hash?: string | SubtleCryptoHashAlgorithm + dataLength?: number + saltLength?: number } interface CryptoKeyKeyAlgorithm { - name: string; + name: string } interface CryptoKeyAesKeyAlgorithm { - name: string; - length: number; + name: string + length: number } interface CryptoKeyHmacKeyAlgorithm { - name: string; - hash: CryptoKeyKeyAlgorithm; - length: number; + name: string + hash: CryptoKeyKeyAlgorithm + length: number } interface CryptoKeyRsaKeyAlgorithm { - name: string; - modulusLength: number; - publicExponent: ArrayBuffer | ArrayBufferView; - hash?: CryptoKeyKeyAlgorithm; + name: string + modulusLength: number + publicExponent: ArrayBuffer | ArrayBufferView + hash?: CryptoKeyKeyAlgorithm } interface CryptoKeyEllipticKeyAlgorithm { - name: string; - namedCurve: string; + name: string + namedCurve: string } interface CryptoKeyArbitraryKeyAlgorithm { - name: string; - hash?: CryptoKeyKeyAlgorithm; - namedCurve?: string; - length?: number; + name: string + hash?: CryptoKeyKeyAlgorithm + namedCurve?: string + length?: number } -declare class DigestStream extends WritableStream { - constructor(algorithm: string | SubtleCryptoHashAlgorithm); - readonly digest: Promise; - get bytesWritten(): number | bigint; +declare class DigestStream extends WritableStream< + ArrayBuffer | ArrayBufferView +> { + constructor(algorithm: string | SubtleCryptoHashAlgorithm) + readonly digest: Promise + get bytesWritten(): number | bigint } /** * The **`TextDecoder`** interface represents a decoder for a specific text encoding, such as `UTF-8`, `ISO-8859-2`, `KOI8-R`, `GBK`, etc. @@ -1234,16 +1492,19 @@ declare class DigestStream extends WritableStream * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder) */ declare class TextDecoder { - constructor(label?: string, options?: TextDecoderConstructorOptions); - /** - * The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) - */ - decode(input?: (ArrayBuffer | ArrayBufferView), options?: TextDecoderDecodeOptions): string; - get encoding(): string; - get fatal(): boolean; - get ignoreBOM(): boolean; + constructor(label?: string, options?: TextDecoderConstructorOptions) + /** + * The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) + */ + decode( + input?: ArrayBuffer | ArrayBufferView, + options?: TextDecoderDecodeOptions, + ): string + get encoding(): string + get fatal(): boolean + get ignoreBOM(): boolean } /** * The **`TextEncoder`** interface takes a stream of code points as input and emits a stream of UTF-8 bytes. @@ -1251,31 +1512,31 @@ declare class TextDecoder { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder) */ declare class TextEncoder { - constructor(); - /** - * The **`TextEncoder.encode()`** method takes a string as input, and returns a Global_Objects/Uint8Array containing the text given in parameters encoded with the specific method for that TextEncoder object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) - */ - encode(input?: string): Uint8Array; - /** - * The **`TextEncoder.encodeInto()`** method takes a string to encode and a destination Uint8Array to put resulting UTF-8 encoded text into, and returns a dictionary object indicating the progress of the encoding. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) - */ - encodeInto(input: string, buffer: Uint8Array): TextEncoderEncodeIntoResult; - get encoding(): string; + constructor() + /** + * The **`TextEncoder.encode()`** method takes a string as input, and returns a Global_Objects/Uint8Array containing the text given in parameters encoded with the specific method for that TextEncoder object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array + /** + * The **`TextEncoder.encodeInto()`** method takes a string to encode and a destination Uint8Array to put resulting UTF-8 encoded text into, and returns a dictionary object indicating the progress of the encoding. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto(input: string, buffer: Uint8Array): TextEncoderEncodeIntoResult + get encoding(): string } interface TextDecoderConstructorOptions { - fatal: boolean; - ignoreBOM: boolean; + fatal: boolean + ignoreBOM: boolean } interface TextDecoderDecodeOptions { - stream: boolean; + stream: boolean } interface TextEncoderEncodeIntoResult { - read: number; - written: number; + read: number + written: number } /** * The **`ErrorEvent`** interface represents events providing information related to errors in scripts or in files. @@ -1283,44 +1544,44 @@ interface TextEncoderEncodeIntoResult { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent) */ declare class ErrorEvent extends Event { - constructor(type: string, init?: ErrorEventErrorEventInit); - /** - * The **`filename`** read-only property of the ErrorEvent interface returns a string containing the name of the script file in which the error occurred. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) - */ - get filename(): string; - /** - * The **`message`** read-only property of the ErrorEvent interface returns a string containing a human-readable error message describing the problem. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) - */ - get message(): string; - /** - * The **`lineno`** read-only property of the ErrorEvent interface returns an integer containing the line number of the script file on which the error occurred. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) - */ - get lineno(): number; - /** - * The **`colno`** read-only property of the ErrorEvent interface returns an integer containing the column number of the script file on which the error occurred. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) - */ - get colno(): number; - /** - * The **`error`** read-only property of the ErrorEvent interface returns a JavaScript value, such as an Error or DOMException, representing the error associated with this event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) - */ - get error(): any; + constructor(type: string, init?: ErrorEventErrorEventInit) + /** + * The **`filename`** read-only property of the ErrorEvent interface returns a string containing the name of the script file in which the error occurred. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) + */ + get filename(): string + /** + * The **`message`** read-only property of the ErrorEvent interface returns a string containing a human-readable error message describing the problem. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) + */ + get message(): string + /** + * The **`lineno`** read-only property of the ErrorEvent interface returns an integer containing the line number of the script file on which the error occurred. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) + */ + get lineno(): number + /** + * The **`colno`** read-only property of the ErrorEvent interface returns an integer containing the column number of the script file on which the error occurred. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) + */ + get colno(): number + /** + * The **`error`** read-only property of the ErrorEvent interface returns a JavaScript value, such as an Error or DOMException, representing the error associated with this event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) + */ + get error(): any } interface ErrorEventErrorEventInit { - message?: string; - filename?: string; - lineno?: number; - colno?: number; - error?: any; + message?: string + filename?: string + lineno?: number + colno?: number + error?: any } /** * The **`MessageEvent`** interface represents a message received by a target object. @@ -1328,40 +1589,40 @@ interface ErrorEventErrorEventInit { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent) */ declare class MessageEvent extends Event { - constructor(type: string, initializer: MessageEventInit); - /** - * The **`data`** read-only property of the The data sent by the message emitter; this can be any data type, depending on what originated this event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data) - */ - readonly data: any; - /** - * The **`origin`** read-only property of the origin of the message emitter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/origin) - */ - readonly origin: string | null; - /** - * The **`lastEventId`** read-only property of the unique ID for the event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/lastEventId) - */ - readonly lastEventId: string; - /** - * The **`source`** read-only property of the a WindowProxy, MessagePort, or a `MessageEventSource` (which can be a WindowProxy, message emitter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source) - */ - readonly source: MessagePort | null; - /** - * The **`ports`** read-only property of the containing all MessagePort objects sent with the message, in order. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/ports) - */ - readonly ports: MessagePort[]; + constructor(type: string, initializer: MessageEventInit) + /** + * The **`data`** read-only property of the The data sent by the message emitter; this can be any data type, depending on what originated this event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data) + */ + readonly data: any + /** + * The **`origin`** read-only property of the origin of the message emitter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/origin) + */ + readonly origin: string | null + /** + * The **`lastEventId`** read-only property of the unique ID for the event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/lastEventId) + */ + readonly lastEventId: string + /** + * The **`source`** read-only property of the a WindowProxy, MessagePort, or a `MessageEventSource` (which can be a WindowProxy, message emitter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source) + */ + readonly source: MessagePort | null + /** + * The **`ports`** read-only property of the containing all MessagePort objects sent with the message, in order. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/ports) + */ + readonly ports: MessagePort[] } interface MessageEventInit { - data: ArrayBuffer | string; + data: ArrayBuffer | string } /** * The **`PromiseRejectionEvent`** interface represents events which are sent to the global script context when JavaScript Promises are rejected. @@ -1369,18 +1630,18 @@ interface MessageEventInit { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent) */ declare abstract class PromiseRejectionEvent extends Event { - /** - * The PromiseRejectionEvent interface's **`promise`** read-only property indicates the JavaScript rejected. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) - */ - readonly promise: Promise; - /** - * The PromiseRejectionEvent **`reason`** read-only property is any JavaScript value or Object which provides the reason passed into Promise.reject(). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) - */ - readonly reason: any; + /** + * The PromiseRejectionEvent interface's **`promise`** read-only property indicates the JavaScript rejected. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) + */ + readonly promise: Promise + /** + * The PromiseRejectionEvent **`reason`** read-only property is any JavaScript value or Object which provides the reason passed into Promise.reject(). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) + */ + readonly reason: any } /** * The **`FormData`** interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using the Window/fetch, XMLHttpRequest.send() or navigator.sendBeacon() methods. @@ -1388,151 +1649,177 @@ declare abstract class PromiseRejectionEvent extends Event { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData) */ declare class FormData { - constructor(); - /** - * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) - */ - append(name: string, value: string | Blob): void; - /** - * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) - */ - append(name: string, value: string): void; - /** - * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) - */ - append(name: string, value: Blob, filename?: string): void; - /** - * The **`delete()`** method of the FormData interface deletes a key and its value(s) from a `FormData` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete) - */ - delete(name: string): void; - /** - * The **`get()`** method of the FormData interface returns the first value associated with a given key from within a `FormData` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get) - */ - get(name: string): (File | string) | null; - /** - * The **`getAll()`** method of the FormData interface returns all the values associated with a given key from within a `FormData` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/getAll) - */ - getAll(name: string): (File | string)[]; - /** - * The **`has()`** method of the FormData interface returns whether a `FormData` object contains a certain key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has) - */ - has(name: string): boolean; - /** - * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) - */ - set(name: string, value: string | Blob): void; - /** - * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) - */ - set(name: string, value: string): void; - /** - * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) - */ - set(name: string, value: Blob, filename?: string): void; - /* Returns an array of key, value pairs for every entry in the list. */ - entries(): IterableIterator<[ - key: string, - value: File | string - ]>; - /* Returns a list of keys in the list. */ - keys(): IterableIterator; - /* Returns a list of values in the list. */ - values(): IterableIterator<(File | string)>; - forEach(callback: (this: This, value: File | string, key: string, parent: FormData) => void, thisArg?: This): void; - [Symbol.iterator](): IterableIterator<[ - key: string, - value: File | string - ]>; + constructor() + /** + * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) + */ + append(name: string, value: string): void + /** + * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) + */ + append(name: string, value: Blob, filename?: string): void + /** + * The **`delete()`** method of the FormData interface deletes a key and its value(s) from a `FormData` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete) + */ + delete(name: string): void + /** + * The **`get()`** method of the FormData interface returns the first value associated with a given key from within a `FormData` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get) + */ + get(name: string): (File | string) | null + /** + * The **`getAll()`** method of the FormData interface returns all the values associated with a given key from within a `FormData` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/getAll) + */ + getAll(name: string): (File | string)[] + /** + * The **`has()`** method of the FormData interface returns whether a `FormData` object contains a certain key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has) + */ + has(name: string): boolean + /** + * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) + */ + set(name: string, value: string): void + /** + * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) + */ + set(name: string, value: Blob, filename?: string): void + /* Returns an array of key, value pairs for every entry in the list. */ + entries(): IterableIterator<[key: string, value: File | string]> + /* Returns a list of keys in the list. */ + keys(): IterableIterator + /* Returns a list of values in the list. */ + values(): IterableIterator + forEach( + callback: ( + this: This, + value: File | string, + key: string, + parent: FormData, + ) => void, + thisArg?: This, + ): void + [Symbol.iterator](): IterableIterator<[key: string, value: File | string]> } interface ContentOptions { - html?: boolean; + html?: boolean } declare class HTMLRewriter { - constructor(); - on(selector: string, handlers: HTMLRewriterElementContentHandlers): HTMLRewriter; - onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; - transform(response: Response): Response; + constructor() + on( + selector: string, + handlers: HTMLRewriterElementContentHandlers, + ): HTMLRewriter + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter + transform(response: Response): Response } interface HTMLRewriterElementContentHandlers { - element?(element: Element): void | Promise; - comments?(comment: Comment): void | Promise; - text?(element: Text): void | Promise; + element?(element: Element): void | Promise + comments?(comment: Comment): void | Promise + text?(element: Text): void | Promise } interface HTMLRewriterDocumentContentHandlers { - doctype?(doctype: Doctype): void | Promise; - comments?(comment: Comment): void | Promise; - text?(text: Text): void | Promise; - end?(end: DocumentEnd): void | Promise; + doctype?(doctype: Doctype): void | Promise + comments?(comment: Comment): void | Promise + text?(text: Text): void | Promise + end?(end: DocumentEnd): void | Promise } interface Doctype { - readonly name: string | null; - readonly publicId: string | null; - readonly systemId: string | null; + readonly name: string | null + readonly publicId: string | null + readonly systemId: string | null } interface Element { - tagName: string; - readonly attributes: IterableIterator; - readonly removed: boolean; - readonly namespaceURI: string; - getAttribute(name: string): string | null; - hasAttribute(name: string): boolean; - setAttribute(name: string, value: string): Element; - removeAttribute(name: string): Element; - before(content: string | ReadableStream | Response, options?: ContentOptions): Element; - after(content: string | ReadableStream | Response, options?: ContentOptions): Element; - prepend(content: string | ReadableStream | Response, options?: ContentOptions): Element; - append(content: string | ReadableStream | Response, options?: ContentOptions): Element; - replace(content: string | ReadableStream | Response, options?: ContentOptions): Element; - remove(): Element; - removeAndKeepContent(): Element; - setInnerContent(content: string | ReadableStream | Response, options?: ContentOptions): Element; - onEndTag(handler: (tag: EndTag) => void | Promise): void; + tagName: string + readonly attributes: IterableIterator + readonly removed: boolean + readonly namespaceURI: string + getAttribute(name: string): string | null + hasAttribute(name: string): boolean + setAttribute(name: string, value: string): Element + removeAttribute(name: string): Element + before( + content: string | ReadableStream | Response, + options?: ContentOptions, + ): Element + after( + content: string | ReadableStream | Response, + options?: ContentOptions, + ): Element + prepend( + content: string | ReadableStream | Response, + options?: ContentOptions, + ): Element + append( + content: string | ReadableStream | Response, + options?: ContentOptions, + ): Element + replace( + content: string | ReadableStream | Response, + options?: ContentOptions, + ): Element + remove(): Element + removeAndKeepContent(): Element + setInnerContent( + content: string | ReadableStream | Response, + options?: ContentOptions, + ): Element + onEndTag(handler: (tag: EndTag) => void | Promise): void } interface EndTag { - name: string; - before(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; - after(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; - remove(): EndTag; + name: string + before( + content: string | ReadableStream | Response, + options?: ContentOptions, + ): EndTag + after( + content: string | ReadableStream | Response, + options?: ContentOptions, + ): EndTag + remove(): EndTag } interface Comment { - text: string; - readonly removed: boolean; - before(content: string, options?: ContentOptions): Comment; - after(content: string, options?: ContentOptions): Comment; - replace(content: string, options?: ContentOptions): Comment; - remove(): Comment; + text: string + readonly removed: boolean + before(content: string, options?: ContentOptions): Comment + after(content: string, options?: ContentOptions): Comment + replace(content: string, options?: ContentOptions): Comment + remove(): Comment } interface Text { - readonly text: string; - readonly lastInTextNode: boolean; - readonly removed: boolean; - before(content: string | ReadableStream | Response, options?: ContentOptions): Text; - after(content: string | ReadableStream | Response, options?: ContentOptions): Text; - replace(content: string | ReadableStream | Response, options?: ContentOptions): Text; - remove(): Text; + readonly text: string + readonly lastInTextNode: boolean + readonly removed: boolean + before( + content: string | ReadableStream | Response, + options?: ContentOptions, + ): Text + after( + content: string | ReadableStream | Response, + options?: ContentOptions, + ): Text + replace( + content: string | ReadableStream | Response, + options?: ContentOptions, + ): Text + remove(): Text } interface DocumentEnd { - append(content: string, options?: ContentOptions): DocumentEnd; + append(content: string, options?: ContentOptions): DocumentEnd } /** * This is the event type for `fetch` events dispatched on the ServiceWorkerGlobalScope. @@ -1540,98 +1827,102 @@ interface DocumentEnd { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent) */ declare abstract class FetchEvent extends ExtendableEvent { - /** - * The **`request`** read-only property of the the event handler. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) - */ - readonly request: Request; - /** - * The **`respondWith()`** method of allows you to provide a promise for a Response yourself. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) - */ - respondWith(promise: Response | Promise): void; - passThroughOnException(): void; + /** + * The **`request`** read-only property of the the event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) + */ + readonly request: Request + /** + * The **`respondWith()`** method of allows you to provide a promise for a Response yourself. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) + */ + respondWith(promise: Response | Promise): void + passThroughOnException(): void } -type HeadersInit = Headers | Iterable> | Record; +type HeadersInit = Headers | Iterable> | Record /** * The **`Headers`** interface of the Fetch API allows you to perform various actions on HTTP request and response headers. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers) */ declare class Headers { - constructor(init?: HeadersInit); - /** - * The **`get()`** method of the Headers interface returns a byte string of all the values of a header within a `Headers` object with a given name. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get) - */ - get(name: string): string | null; - getAll(name: string): string[]; - /** - * The **`getSetCookie()`** method of the Headers interface returns an array containing the values of all Set-Cookie headers associated with a response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie) - */ - getSetCookie(): string[]; - /** - * The **`has()`** method of the Headers interface returns a boolean stating whether a `Headers` object contains a certain header. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has) - */ - has(name: string): boolean; - /** - * The **`set()`** method of the Headers interface sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set) - */ - set(name: string, value: string): void; - /** - * The **`append()`** method of the Headers interface appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append) - */ - append(name: string, value: string): void; - /** - * The **`delete()`** method of the Headers interface deletes a header from the current `Headers` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete) - */ - delete(name: string): void; - forEach(callback: (this: This, value: string, key: string, parent: Headers) => void, thisArg?: This): void; - /* Returns an iterator allowing to go through all key/value pairs contained in this object. */ - entries(): IterableIterator<[ - key: string, - value: string - ]>; - /* Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ - keys(): IterableIterator; - /* Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ - values(): IterableIterator; - [Symbol.iterator](): IterableIterator<[ - key: string, - value: string - ]>; + constructor(init?: HeadersInit) + /** + * The **`get()`** method of the Headers interface returns a byte string of all the values of a header within a `Headers` object with a given name. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get) + */ + get(name: string): string | null + getAll(name: string): string[] + /** + * The **`getSetCookie()`** method of the Headers interface returns an array containing the values of all Set-Cookie headers associated with a response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie) + */ + getSetCookie(): string[] + /** + * The **`has()`** method of the Headers interface returns a boolean stating whether a `Headers` object contains a certain header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has) + */ + has(name: string): boolean + /** + * The **`set()`** method of the Headers interface sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set) + */ + set(name: string, value: string): void + /** + * The **`append()`** method of the Headers interface appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append) + */ + append(name: string, value: string): void + /** + * The **`delete()`** method of the Headers interface deletes a header from the current `Headers` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete) + */ + delete(name: string): void + forEach( + callback: (this: This, value: string, key: string, parent: Headers) => void, + thisArg?: This, + ): void + /* Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[key: string, value: string]> + /* Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator + /* Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator + [Symbol.iterator](): IterableIterator<[key: string, value: string]> } -type BodyInit = ReadableStream | string | ArrayBuffer | ArrayBufferView | Blob | URLSearchParams | FormData; +type BodyInit = + | ReadableStream + | string + | ArrayBuffer + | ArrayBufferView + | Blob + | URLSearchParams + | FormData declare abstract class Body { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) */ - get body(): ReadableStream | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */ - get bodyUsed(): boolean; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */ - arrayBuffer(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) */ - bytes(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/text) */ - text(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */ - json(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData) */ - formData(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */ - blob(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) */ + get body(): ReadableStream | null + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */ + get bodyUsed(): boolean + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */ + arrayBuffer(): Promise + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) */ + bytes(): Promise + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/text) */ + text(): Promise + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */ + json(): Promise + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData) */ + formData(): Promise + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */ + blob(): Promise } /** * The **`Response`** interface of the Fetch API represents the response to a request. @@ -1639,547 +1930,711 @@ declare abstract class Body { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) */ declare var Response: { - prototype: Response; - new (body?: BodyInit | null, init?: ResponseInit): Response; - error(): Response; - redirect(url: string, status?: number): Response; - json(any: any, maybeInit?: (ResponseInit | Response)): Response; -}; + prototype: Response + new (body?: BodyInit | null, init?: ResponseInit): Response + error(): Response + redirect(url: string, status?: number): Response + json(any: any, maybeInit?: ResponseInit | Response): Response +} /** * The **`Response`** interface of the Fetch API represents the response to a request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) */ interface Response extends Body { - /** - * The **`clone()`** method of the Response interface creates a clone of a response object, identical in every way, but stored in a different variable. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) - */ - clone(): Response; - /** - * The **`status`** read-only property of the Response interface contains the HTTP status codes of the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) - */ - status: number; - /** - * The **`statusText`** read-only property of the Response interface contains the status message corresponding to the HTTP status code in Response.status. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) - */ - statusText: string; - /** - * The **`headers`** read-only property of the with the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) - */ - headers: Headers; - /** - * The **`ok`** read-only property of the Response interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) - */ - ok: boolean; - /** - * The **`redirected`** read-only property of the Response interface indicates whether or not the response is the result of a request you made which was redirected. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) - */ - redirected: boolean; - /** - * The **`url`** read-only property of the Response interface contains the URL of the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) - */ - url: string; - webSocket: WebSocket | null; - cf: any | undefined; - /** - * The **`type`** read-only property of the Response interface contains the type of the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/type) - */ - type: "default" | "error"; + /** + * The **`clone()`** method of the Response interface creates a clone of a response object, identical in every way, but stored in a different variable. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) + */ + clone(): Response + /** + * The **`status`** read-only property of the Response interface contains the HTTP status codes of the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) + */ + status: number + /** + * The **`statusText`** read-only property of the Response interface contains the status message corresponding to the HTTP status code in Response.status. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) + */ + statusText: string + /** + * The **`headers`** read-only property of the with the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) + */ + headers: Headers + /** + * The **`ok`** read-only property of the Response interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) + */ + ok: boolean + /** + * The **`redirected`** read-only property of the Response interface indicates whether or not the response is the result of a request you made which was redirected. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) + */ + redirected: boolean + /** + * The **`url`** read-only property of the Response interface contains the URL of the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) + */ + url: string + webSocket: WebSocket | null + cf: any | undefined + /** + * The **`type`** read-only property of the Response interface contains the type of the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/type) + */ + type: 'default' | 'error' } interface ResponseInit { - status?: number; - statusText?: string; - headers?: HeadersInit; - cf?: any; - webSocket?: (WebSocket | null); - encodeBody?: "automatic" | "manual"; + status?: number + statusText?: string + headers?: HeadersInit + cf?: any + webSocket?: WebSocket | null + encodeBody?: 'automatic' | 'manual' } -type RequestInfo> = Request | string; +type RequestInfo> = + | Request + | string /** * The **`Request`** interface of the Fetch API represents a resource request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) */ declare var Request: { - prototype: Request; - new >(input: RequestInfo | URL, init?: RequestInit): Request; -}; + prototype: Request + new >( + input: RequestInfo | URL, + init?: RequestInit, + ): Request +} /** * The **`Request`** interface of the Fetch API represents a resource request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) */ -interface Request> extends Body { - /** - * The **`clone()`** method of the Request interface creates a copy of the current `Request` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) - */ - clone(): Request; - /** - * The **`method`** read-only property of the `POST`, etc.) A String indicating the method of the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) - */ - method: string; - /** - * The **`url`** read-only property of the Request interface contains the URL of the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) - */ - url: string; - /** - * The **`headers`** read-only property of the with the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) - */ - headers: Headers; - /** - * The **`redirect`** read-only property of the Request interface contains the mode for how redirects are handled. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) - */ - redirect: string; - fetcher: Fetcher | null; - /** - * The read-only **`signal`** property of the Request interface returns the AbortSignal associated with the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) - */ - signal: AbortSignal; - cf?: Cf; - /** - * The **`integrity`** read-only property of the Request interface contains the subresource integrity value of the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) - */ - integrity: string; - /** - * The **`keepalive`** read-only property of the Request interface contains the request's `keepalive` setting (`true` or `false`), which indicates whether the browser will keep the associated request alive if the page that initiated it is unloaded before the request is complete. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) - */ - keepalive: boolean; - /** - * The **`cache`** read-only property of the Request interface contains the cache mode of the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/cache) - */ - cache?: "no-store" | "no-cache"; +interface Request> + extends Body { + /** + * The **`clone()`** method of the Request interface creates a copy of the current `Request` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) + */ + clone(): Request + /** + * The **`method`** read-only property of the `POST`, etc.) A String indicating the method of the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + method: string + /** + * The **`url`** read-only property of the Request interface contains the URL of the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + url: string + /** + * The **`headers`** read-only property of the with the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + headers: Headers + /** + * The **`redirect`** read-only property of the Request interface contains the mode for how redirects are handled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + redirect: string + fetcher: Fetcher | null + /** + * The read-only **`signal`** property of the Request interface returns the AbortSignal associated with the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + signal: AbortSignal + cf: Cf | undefined + /** + * The **`integrity`** read-only property of the Request interface contains the subresource integrity value of the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + integrity: string + /** + * The **`keepalive`** read-only property of the Request interface contains the request's `keepalive` setting (`true` or `false`), which indicates whether the browser will keep the associated request alive if the page that initiated it is unloaded before the request is complete. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + keepalive: boolean + /** + * The **`cache`** read-only property of the Request interface contains the cache mode of the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/cache) + */ + cache?: 'no-store' | 'no-cache' } interface RequestInit { - /* A string to set request's method. */ - method?: string; - /* A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ - headers?: HeadersInit; - /* A BodyInit object or null to set request's body. */ - body?: BodyInit | null; - /* A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ - redirect?: string; - fetcher?: (Fetcher | null); - cf?: Cf; - /* A string indicating how the request will interact with the browser's cache to set request's cache. */ - cache?: "no-store" | "no-cache"; - /* A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ - integrity?: string; - /* An AbortSignal to set request's signal. */ - signal?: (AbortSignal | null); - encodeResponseBody?: "automatic" | "manual"; + /* A string to set request's method. */ + method?: string + /* A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit + /* A BodyInit object or null to set request's body. */ + body?: BodyInit | null + /* A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string + fetcher?: Fetcher | null + cf?: Cf + /* A string indicating how the request will interact with the browser's cache to set request's cache. */ + cache?: 'no-store' | 'no-cache' + /* A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string + /* An AbortSignal to set request's signal. */ + signal?: AbortSignal | null + encodeResponseBody?: 'automatic' | 'manual' +} +type Service< + T extends + | (new (...args: any[]) => Rpc.WorkerEntrypointBranded) + | Rpc.WorkerEntrypointBranded + | ExportedHandler + | undefined = undefined, +> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded + ? Fetcher> + : T extends Rpc.WorkerEntrypointBranded + ? Fetcher + : T extends Exclude + ? never + : Fetcher +type Fetcher< + T extends Rpc.EntrypointBranded | undefined = undefined, + Reserved extends string = never, +> = (T extends Rpc.EntrypointBranded + ? Rpc.Provider + : unknown) & { + fetch(input: RequestInfo | URL, init?: RequestInit): Promise + connect(address: SocketAddress | string, options?: SocketOptions): Socket } -type Service Rpc.WorkerEntrypointBranded) | Rpc.WorkerEntrypointBranded | ExportedHandler | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? Fetcher> : T extends Rpc.WorkerEntrypointBranded ? Fetcher : T extends Exclude ? never : Fetcher; -type Fetcher = (T extends Rpc.EntrypointBranded ? Rpc.Provider : unknown) & { - fetch(input: RequestInfo | URL, init?: RequestInit): Promise; - connect(address: SocketAddress | string, options?: SocketOptions): Socket; -}; interface KVNamespaceListKey { - name: Key; - expiration?: number; - metadata?: Metadata; + name: Key + expiration?: number + metadata?: Metadata } -type KVNamespaceListResult = { - list_complete: false; - keys: KVNamespaceListKey[]; - cursor: string; - cacheStatus: string | null; -} | { - list_complete: true; - keys: KVNamespaceListKey[]; - cacheStatus: string | null; -}; +type KVNamespaceListResult = + | { + list_complete: false + keys: KVNamespaceListKey[] + cursor: string + cacheStatus: string | null + } + | { + list_complete: true + keys: KVNamespaceListKey[] + cacheStatus: string | null + } interface KVNamespace { - get(key: Key, options?: Partial>): Promise; - get(key: Key, type: "text"): Promise; - get(key: Key, type: "json"): Promise; - get(key: Key, type: "arrayBuffer"): Promise; - get(key: Key, type: "stream"): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"text">): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"json">): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"arrayBuffer">): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"stream">): Promise; - get(key: Array, type: "text"): Promise>; - get(key: Array, type: "json"): Promise>; - get(key: Array, options?: Partial>): Promise>; - get(key: Array, options?: KVNamespaceGetOptions<"text">): Promise>; - get(key: Array, options?: KVNamespaceGetOptions<"json">): Promise>; - list(options?: KVNamespaceListOptions): Promise>; - put(key: Key, value: string | ArrayBuffer | ArrayBufferView | ReadableStream, options?: KVNamespacePutOptions): Promise; - getWithMetadata(key: Key, options?: Partial>): Promise>; - getWithMetadata(key: Key, type: "text"): Promise>; - getWithMetadata(key: Key, type: "json"): Promise>; - getWithMetadata(key: Key, type: "arrayBuffer"): Promise>; - getWithMetadata(key: Key, type: "stream"): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"text">): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"json">): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"arrayBuffer">): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"stream">): Promise>; - getWithMetadata(key: Array, type: "text"): Promise>>; - getWithMetadata(key: Array, type: "json"): Promise>>; - getWithMetadata(key: Array, options?: Partial>): Promise>>; - getWithMetadata(key: Array, options?: KVNamespaceGetOptions<"text">): Promise>>; - getWithMetadata(key: Array, options?: KVNamespaceGetOptions<"json">): Promise>>; - delete(key: Key): Promise; + get( + key: Key, + options?: Partial>, + ): Promise + get(key: Key, type: 'text'): Promise + get( + key: Key, + type: 'json', + ): Promise + get(key: Key, type: 'arrayBuffer'): Promise + get(key: Key, type: 'stream'): Promise + get(key: Key, options?: KVNamespaceGetOptions<'text'>): Promise + get( + key: Key, + options?: KVNamespaceGetOptions<'json'>, + ): Promise + get( + key: Key, + options?: KVNamespaceGetOptions<'arrayBuffer'>, + ): Promise + get( + key: Key, + options?: KVNamespaceGetOptions<'stream'>, + ): Promise + get(key: Array, type: 'text'): Promise> + get( + key: Array, + type: 'json', + ): Promise> + get( + key: Array, + options?: Partial>, + ): Promise> + get( + key: Array, + options?: KVNamespaceGetOptions<'text'>, + ): Promise> + get( + key: Array, + options?: KVNamespaceGetOptions<'json'>, + ): Promise> + list( + options?: KVNamespaceListOptions, + ): Promise> + put( + key: Key, + value: string | ArrayBuffer | ArrayBufferView | ReadableStream, + options?: KVNamespacePutOptions, + ): Promise + getWithMetadata( + key: Key, + options?: Partial>, + ): Promise> + getWithMetadata( + key: Key, + type: 'text', + ): Promise> + getWithMetadata( + key: Key, + type: 'json', + ): Promise> + getWithMetadata( + key: Key, + type: 'arrayBuffer', + ): Promise> + getWithMetadata( + key: Key, + type: 'stream', + ): Promise> + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<'text'>, + ): Promise> + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<'json'>, + ): Promise> + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<'arrayBuffer'>, + ): Promise> + getWithMetadata( + key: Key, + options: KVNamespaceGetOptions<'stream'>, + ): Promise> + getWithMetadata( + key: Array, + type: 'text', + ): Promise>> + getWithMetadata( + key: Array, + type: 'json', + ): Promise< + Map> + > + getWithMetadata( + key: Array, + options?: Partial>, + ): Promise>> + getWithMetadata( + key: Array, + options?: KVNamespaceGetOptions<'text'>, + ): Promise>> + getWithMetadata( + key: Array, + options?: KVNamespaceGetOptions<'json'>, + ): Promise< + Map> + > + delete(key: Key): Promise } interface KVNamespaceListOptions { - limit?: number; - prefix?: (string | null); - cursor?: (string | null); + limit?: number + prefix?: string | null + cursor?: string | null } interface KVNamespaceGetOptions { - type: Type; - cacheTtl?: number; + type: Type + cacheTtl?: number } interface KVNamespacePutOptions { - expiration?: number; - expirationTtl?: number; - metadata?: (any | null); + expiration?: number + expirationTtl?: number + metadata?: any | null } interface KVNamespaceGetWithMetadataResult { - value: Value | null; - metadata: Metadata | null; - cacheStatus: string | null; + value: Value | null + metadata: Metadata | null + cacheStatus: string | null } -type QueueContentType = "text" | "bytes" | "json" | "v8"; +type QueueContentType = 'text' | 'bytes' | 'json' | 'v8' interface Queue { - send(message: Body, options?: QueueSendOptions): Promise; - sendBatch(messages: Iterable>, options?: QueueSendBatchOptions): Promise; + send(message: Body, options?: QueueSendOptions): Promise + sendBatch( + messages: Iterable>, + options?: QueueSendBatchOptions, + ): Promise } interface QueueSendOptions { - contentType?: QueueContentType; - delaySeconds?: number; + contentType?: QueueContentType + delaySeconds?: number } interface QueueSendBatchOptions { - delaySeconds?: number; + delaySeconds?: number } interface MessageSendRequest { - body: Body; - contentType?: QueueContentType; - delaySeconds?: number; + body: Body + contentType?: QueueContentType + delaySeconds?: number } interface QueueRetryOptions { - delaySeconds?: number; + delaySeconds?: number } interface Message { - readonly id: string; - readonly timestamp: Date; - readonly body: Body; - readonly attempts: number; - retry(options?: QueueRetryOptions): void; - ack(): void; + readonly id: string + readonly timestamp: Date + readonly body: Body + readonly attempts: number + retry(options?: QueueRetryOptions): void + ack(): void } interface QueueEvent extends ExtendableEvent { - readonly messages: readonly Message[]; - readonly queue: string; - retryAll(options?: QueueRetryOptions): void; - ackAll(): void; + readonly messages: readonly Message[] + readonly queue: string + retryAll(options?: QueueRetryOptions): void + ackAll(): void } interface MessageBatch { - readonly messages: readonly Message[]; - readonly queue: string; - retryAll(options?: QueueRetryOptions): void; - ackAll(): void; + readonly messages: readonly Message[] + readonly queue: string + retryAll(options?: QueueRetryOptions): void + ackAll(): void } interface R2Error extends Error { - readonly name: string; - readonly code: number; - readonly message: string; - readonly action: string; - readonly stack: any; + readonly name: string + readonly code: number + readonly message: string + readonly action: string + readonly stack: any } interface R2ListOptions { - limit?: number; - prefix?: string; - cursor?: string; - delimiter?: string; - startAfter?: string; - include?: ("httpMetadata" | "customMetadata")[]; + limit?: number + prefix?: string + cursor?: string + delimiter?: string + startAfter?: string + include?: ('httpMetadata' | 'customMetadata')[] } declare abstract class R2Bucket { - head(key: string): Promise; - get(key: string, options: R2GetOptions & { - onlyIf: R2Conditional | Headers; - }): Promise; - get(key: string, options?: R2GetOptions): Promise; - put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions & { - onlyIf: R2Conditional | Headers; - }): Promise; - put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions): Promise; - createMultipartUpload(key: string, options?: R2MultipartOptions): Promise; - resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; - delete(keys: string | string[]): Promise; - list(options?: R2ListOptions): Promise; + head(key: string): Promise + get( + key: string, + options: R2GetOptions & { + onlyIf: R2Conditional | Headers + }, + ): Promise + get(key: string, options?: R2GetOptions): Promise + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions & { + onlyIf: R2Conditional | Headers + }, + ): Promise + put( + key: string, + value: + | ReadableStream + | ArrayBuffer + | ArrayBufferView + | string + | null + | Blob, + options?: R2PutOptions, + ): Promise + createMultipartUpload( + key: string, + options?: R2MultipartOptions, + ): Promise + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload + delete(keys: string | string[]): Promise + list(options?: R2ListOptions): Promise } interface R2MultipartUpload { - readonly key: string; - readonly uploadId: string; - uploadPart(partNumber: number, value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, options?: R2UploadPartOptions): Promise; - abort(): Promise; - complete(uploadedParts: R2UploadedPart[]): Promise; + readonly key: string + readonly uploadId: string + uploadPart( + partNumber: number, + value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, + options?: R2UploadPartOptions, + ): Promise + abort(): Promise + complete(uploadedParts: R2UploadedPart[]): Promise } interface R2UploadedPart { - partNumber: number; - etag: string; + partNumber: number + etag: string } declare abstract class R2Object { - readonly key: string; - readonly version: string; - readonly size: number; - readonly etag: string; - readonly httpEtag: string; - readonly checksums: R2Checksums; - readonly uploaded: Date; - readonly httpMetadata?: R2HTTPMetadata; - readonly customMetadata?: Record; - readonly range?: R2Range; - readonly storageClass: string; - readonly ssecKeyMd5?: string; - writeHttpMetadata(headers: Headers): void; + readonly key: string + readonly version: string + readonly size: number + readonly etag: string + readonly httpEtag: string + readonly checksums: R2Checksums + readonly uploaded: Date + readonly httpMetadata?: R2HTTPMetadata + readonly customMetadata?: Record + readonly range?: R2Range + readonly storageClass: string + readonly ssecKeyMd5?: string + writeHttpMetadata(headers: Headers): void } interface R2ObjectBody extends R2Object { - get body(): ReadableStream; - get bodyUsed(): boolean; - arrayBuffer(): Promise; - bytes(): Promise; - text(): Promise; - json(): Promise; - blob(): Promise; + get body(): ReadableStream + get bodyUsed(): boolean + arrayBuffer(): Promise + bytes(): Promise + text(): Promise + json(): Promise + blob(): Promise } -type R2Range = { - offset: number; - length?: number; -} | { - offset?: number; - length: number; -} | { - suffix: number; -}; +type R2Range = + | { + offset: number + length?: number + } + | { + offset?: number + length: number + } + | { + suffix: number + } interface R2Conditional { - etagMatches?: string; - etagDoesNotMatch?: string; - uploadedBefore?: Date; - uploadedAfter?: Date; - secondsGranularity?: boolean; + etagMatches?: string + etagDoesNotMatch?: string + uploadedBefore?: Date + uploadedAfter?: Date + secondsGranularity?: boolean } interface R2GetOptions { - onlyIf?: (R2Conditional | Headers); - range?: (R2Range | Headers); - ssecKey?: (ArrayBuffer | string); + onlyIf?: R2Conditional | Headers + range?: R2Range | Headers + ssecKey?: ArrayBuffer | string } interface R2PutOptions { - onlyIf?: (R2Conditional | Headers); - httpMetadata?: (R2HTTPMetadata | Headers); - customMetadata?: Record; - md5?: ((ArrayBuffer | ArrayBufferView) | string); - sha1?: ((ArrayBuffer | ArrayBufferView) | string); - sha256?: ((ArrayBuffer | ArrayBufferView) | string); - sha384?: ((ArrayBuffer | ArrayBufferView) | string); - sha512?: ((ArrayBuffer | ArrayBufferView) | string); - storageClass?: string; - ssecKey?: (ArrayBuffer | string); + onlyIf?: R2Conditional | Headers + httpMetadata?: R2HTTPMetadata | Headers + customMetadata?: Record + md5?: (ArrayBuffer | ArrayBufferView) | string + sha1?: (ArrayBuffer | ArrayBufferView) | string + sha256?: (ArrayBuffer | ArrayBufferView) | string + sha384?: (ArrayBuffer | ArrayBufferView) | string + sha512?: (ArrayBuffer | ArrayBufferView) | string + storageClass?: string + ssecKey?: ArrayBuffer | string } interface R2MultipartOptions { - httpMetadata?: (R2HTTPMetadata | Headers); - customMetadata?: Record; - storageClass?: string; - ssecKey?: (ArrayBuffer | string); + httpMetadata?: R2HTTPMetadata | Headers + customMetadata?: Record + storageClass?: string + ssecKey?: ArrayBuffer | string } interface R2Checksums { - readonly md5?: ArrayBuffer; - readonly sha1?: ArrayBuffer; - readonly sha256?: ArrayBuffer; - readonly sha384?: ArrayBuffer; - readonly sha512?: ArrayBuffer; - toJSON(): R2StringChecksums; + readonly md5?: ArrayBuffer + readonly sha1?: ArrayBuffer + readonly sha256?: ArrayBuffer + readonly sha384?: ArrayBuffer + readonly sha512?: ArrayBuffer + toJSON(): R2StringChecksums } interface R2StringChecksums { - md5?: string; - sha1?: string; - sha256?: string; - sha384?: string; - sha512?: string; + md5?: string + sha1?: string + sha256?: string + sha384?: string + sha512?: string } interface R2HTTPMetadata { - contentType?: string; - contentLanguage?: string; - contentDisposition?: string; - contentEncoding?: string; - cacheControl?: string; - cacheExpiry?: Date; + contentType?: string + contentLanguage?: string + contentDisposition?: string + contentEncoding?: string + cacheControl?: string + cacheExpiry?: Date } type R2Objects = { - objects: R2Object[]; - delimitedPrefixes: string[]; -} & ({ - truncated: true; - cursor: string; -} | { - truncated: false; -}); + objects: R2Object[] + delimitedPrefixes: string[] +} & ( + | { + truncated: true + cursor: string + } + | { + truncated: false + } +) interface R2UploadPartOptions { - ssecKey?: (ArrayBuffer | string); + ssecKey?: ArrayBuffer | string } declare abstract class ScheduledEvent extends ExtendableEvent { - readonly scheduledTime: number; - readonly cron: string; - noRetry(): void; + readonly scheduledTime: number + readonly cron: string + noRetry(): void } interface ScheduledController { - readonly scheduledTime: number; - readonly cron: string; - noRetry(): void; + readonly scheduledTime: number + readonly cron: string + noRetry(): void } interface QueuingStrategy { - highWaterMark?: (number | bigint); - size?: (chunk: T) => number | bigint; + highWaterMark?: number | bigint + size?: (chunk: T) => number | bigint } interface UnderlyingSink { - type?: string; - start?: (controller: WritableStreamDefaultController) => void | Promise; - write?: (chunk: W, controller: WritableStreamDefaultController) => void | Promise; - abort?: (reason: any) => void | Promise; - close?: () => void | Promise; + type?: string + start?: (controller: WritableStreamDefaultController) => void | Promise + write?: ( + chunk: W, + controller: WritableStreamDefaultController, + ) => void | Promise + abort?: (reason: any) => void | Promise + close?: () => void | Promise } interface UnderlyingByteSource { - type: "bytes"; - autoAllocateChunkSize?: number; - start?: (controller: ReadableByteStreamController) => void | Promise; - pull?: (controller: ReadableByteStreamController) => void | Promise; - cancel?: (reason: any) => void | Promise; + type: 'bytes' + autoAllocateChunkSize?: number + start?: (controller: ReadableByteStreamController) => void | Promise + pull?: (controller: ReadableByteStreamController) => void | Promise + cancel?: (reason: any) => void | Promise } interface UnderlyingSource { - type?: "" | undefined; - start?: (controller: ReadableStreamDefaultController) => void | Promise; - pull?: (controller: ReadableStreamDefaultController) => void | Promise; - cancel?: (reason: any) => void | Promise; - expectedLength?: (number | bigint); + type?: '' | undefined + start?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise + pull?: ( + controller: ReadableStreamDefaultController, + ) => void | Promise + cancel?: (reason: any) => void | Promise + expectedLength?: number | bigint } interface Transformer { - readableType?: string; - writableType?: string; - start?: (controller: TransformStreamDefaultController) => void | Promise; - transform?: (chunk: I, controller: TransformStreamDefaultController) => void | Promise; - flush?: (controller: TransformStreamDefaultController) => void | Promise; - cancel?: (reason: any) => void | Promise; - expectedLength?: number; + readableType?: string + writableType?: string + start?: ( + controller: TransformStreamDefaultController, + ) => void | Promise + transform?: ( + chunk: I, + controller: TransformStreamDefaultController, + ) => void | Promise + flush?: ( + controller: TransformStreamDefaultController, + ) => void | Promise + cancel?: (reason: any) => void | Promise + expectedLength?: number } interface StreamPipeOptions { - preventAbort?: boolean; - preventCancel?: boolean; - /** - * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. - * - * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. - * - * Errors and closures of the source and destination streams propagate as follows: - * - * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination. - * - * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source. - * - * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. - * - * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. - * - * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. - */ - preventClose?: boolean; - signal?: AbortSignal; + /** + * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination. + * + * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source. + * + * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. + * + * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. + * + * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. + */ + preventClose?: boolean + preventAbort?: boolean + preventCancel?: boolean + signal?: AbortSignal } -type ReadableStreamReadResult = { - done: false; - value: R; -} | { - done: true; - value?: undefined; -}; +type ReadableStreamReadResult = + | { + done: false + value: R + } + | { + done: true + value?: undefined + } /** * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) */ interface ReadableStream { - /** - * The **`locked`** read-only property of the ReadableStream interface returns whether or not the readable stream is locked to a reader. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) - */ - get locked(): boolean; - /** - * The **`cancel()`** method of the ReadableStream interface returns a Promise that resolves when the stream is canceled. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) - */ - cancel(reason?: any): Promise; - /** - * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) - */ - getReader(): ReadableStreamDefaultReader; - /** - * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) - */ - getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; - /** - * The **`pipeThrough()`** method of the ReadableStream interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) - */ - pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; - /** - * The **`pipeTo()`** method of the ReadableStream interface pipes the current `ReadableStream` to a given WritableStream and returns a Promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) - */ - pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; - /** - * The **`tee()`** method of the two-element array containing the two resulting branches as new ReadableStream instances. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) - */ - tee(): [ - ReadableStream, - ReadableStream - ]; - values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; - [Symbol.asyncIterator](options?: ReadableStreamValuesOptions): AsyncIterableIterator; + /** + * The **`locked`** read-only property of the ReadableStream interface returns whether or not the readable stream is locked to a reader. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) + */ + get locked(): boolean + /** + * The **`cancel()`** method of the ReadableStream interface returns a Promise that resolves when the stream is canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) + */ + cancel(reason?: any): Promise + /** + * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) + */ + getReader(): ReadableStreamDefaultReader + /** + * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) + */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader + /** + * The **`pipeThrough()`** method of the ReadableStream interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) + */ + pipeThrough( + transform: ReadableWritablePair, + options?: StreamPipeOptions, + ): ReadableStream + /** + * The **`pipeTo()`** method of the ReadableStream interface pipes the current `ReadableStream` to a given WritableStream and returns a Promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) + */ + pipeTo( + destination: WritableStream, + options?: StreamPipeOptions, + ): Promise + /** + * The **`tee()`** method of the two-element array containing the two resulting branches as new ReadableStream instances. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) + */ + tee(): [ReadableStream, ReadableStream] + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator + [Symbol.asyncIterator]( + options?: ReadableStreamValuesOptions, + ): AsyncIterableIterator } /** * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. @@ -2187,31 +2642,37 @@ interface ReadableStream { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) */ declare const ReadableStream: { - prototype: ReadableStream; - new (underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; - new (underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; -}; + prototype: ReadableStream + new ( + underlyingSource: UnderlyingByteSource, + strategy?: QueuingStrategy, + ): ReadableStream + new ( + underlyingSource?: UnderlyingSource, + strategy?: QueuingStrategy, + ): ReadableStream +} /** * The **`ReadableStreamDefaultReader`** interface of the Streams API represents a default reader that can be used to read stream data supplied from a network (such as a fetch request). * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader) */ declare class ReadableStreamDefaultReader { - constructor(stream: ReadableStream); - get closed(): Promise; - cancel(reason?: any): Promise; - /** - * The **`read()`** method of the ReadableStreamDefaultReader interface returns a Promise providing access to the next chunk in the stream's internal queue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) - */ - read(): Promise>; - /** - * The **`releaseLock()`** method of the ReadableStreamDefaultReader interface releases the reader's lock on the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) - */ - releaseLock(): void; + constructor(stream: ReadableStream) + get closed(): Promise + cancel(reason?: any): Promise + /** + * The **`read()`** method of the ReadableStreamDefaultReader interface returns a Promise providing access to the next chunk in the stream's internal queue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) + */ + read(): Promise> + /** + * The **`releaseLock()`** method of the ReadableStreamDefaultReader interface releases the reader's lock on the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) + */ + releaseLock(): void } /** * The `ReadableStreamBYOBReader` interface of the Streams API defines a reader for a ReadableStream that supports zero-copy reading from an underlying byte source. @@ -2219,33 +2680,36 @@ declare class ReadableStreamDefaultReader { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) */ declare class ReadableStreamBYOBReader { - constructor(stream: ReadableStream); - get closed(): Promise; - cancel(reason?: any): Promise; - /** - * The **`read()`** method of the ReadableStreamBYOBReader interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) - */ - read(view: T): Promise>; - /** - * The **`releaseLock()`** method of the ReadableStreamBYOBReader interface releases the reader's lock on the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) - */ - releaseLock(): void; - readAtLeast(minElements: number, view: T): Promise>; + constructor(stream: ReadableStream) + get closed(): Promise + cancel(reason?: any): Promise + /** + * The **`read()`** method of the ReadableStreamBYOBReader interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) + */ + read(view: T): Promise> + /** + * The **`releaseLock()`** method of the ReadableStreamBYOBReader interface releases the reader's lock on the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) + */ + releaseLock(): void + readAtLeast( + minElements: number, + view: T, + ): Promise> } interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { - min?: number; + min?: number } interface ReadableStreamGetReaderOptions { - /** - * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. - * - * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. - */ - mode: "byob"; + /** + * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. + * + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: 'byob' } /** * The **`ReadableStreamBYOBRequest`** interface of the Streams API represents a 'pull request' for data from an underlying source that will made as a zero-copy transfer to a consumer (bypassing the stream's internal queues). @@ -2253,25 +2717,25 @@ interface ReadableStreamGetReaderOptions { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ declare abstract class ReadableStreamBYOBRequest { - /** - * The **`view`** getter property of the ReadableStreamBYOBRequest interface returns the current view. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) - */ - get view(): Uint8Array | null; - /** - * The **`respond()`** method of the ReadableStreamBYOBRequest interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the ReadableStreamBYOBRequest.view. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) - */ - respond(bytesWritten: number): void; - /** - * The **`respondWithNewView()`** method of the ReadableStreamBYOBRequest interface specifies a new view that the consumer of the associated readable byte stream should write to instead of ReadableStreamBYOBRequest.view. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) - */ - respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; - get atLeast(): number | null; + /** + * The **`view`** getter property of the ReadableStreamBYOBRequest interface returns the current view. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) + */ + get view(): Uint8Array | null + /** + * The **`respond()`** method of the ReadableStreamBYOBRequest interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the ReadableStreamBYOBRequest.view. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) + */ + respond(bytesWritten: number): void + /** + * The **`respondWithNewView()`** method of the ReadableStreamBYOBRequest interface specifies a new view that the consumer of the associated readable byte stream should write to instead of ReadableStreamBYOBRequest.view. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) + */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void + get atLeast(): number | null } /** * The **`ReadableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a ReadableStream's state and internal queue. @@ -2279,30 +2743,30 @@ declare abstract class ReadableStreamBYOBRequest { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) */ declare abstract class ReadableStreamDefaultController { - /** - * The **`desiredSize`** read-only property of the required to fill the stream's internal queue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) - */ - get desiredSize(): number | null; - /** - * The **`close()`** method of the ReadableStreamDefaultController interface closes the associated stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) - */ - close(): void; - /** - * The **`enqueue()`** method of the ```js-nolint enqueue(chunk) ``` - `chunk` - : The chunk to enqueue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) - */ - enqueue(chunk?: R): void; - /** - * The **`error()`** method of the with the associated stream to error. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) - */ - error(reason: any): void; + /** + * The **`desiredSize`** read-only property of the required to fill the stream's internal queue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) + */ + get desiredSize(): number | null + /** + * The **`close()`** method of the ReadableStreamDefaultController interface closes the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) + */ + close(): void + /** + * The **`enqueue()`** method of the ```js-nolint enqueue(chunk) ``` - `chunk` - : The chunk to enqueue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) + */ + enqueue(chunk?: R): void + /** + * The **`error()`** method of the with the associated stream to error. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) + */ + error(reason: any): void } /** * The **`ReadableByteStreamController`** interface of the Streams API represents a controller for a readable byte stream. @@ -2310,36 +2774,36 @@ declare abstract class ReadableStreamDefaultController { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) */ declare abstract class ReadableByteStreamController { - /** - * The **`byobRequest`** read-only property of the ReadableByteStreamController interface returns the current BYOB request, or `null` if there are no pending requests. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) - */ - get byobRequest(): ReadableStreamBYOBRequest | null; - /** - * The **`desiredSize`** read-only property of the ReadableByteStreamController interface returns the number of bytes required to fill the stream's internal queue to its 'desired size'. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) - */ - get desiredSize(): number | null; - /** - * The **`close()`** method of the ReadableByteStreamController interface closes the associated stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) - */ - close(): void; - /** - * The **`enqueue()`** method of the ReadableByteStreamController interface enqueues a given chunk on the associated readable byte stream (the chunk is copied into the stream's internal queues). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) - */ - enqueue(chunk: ArrayBuffer | ArrayBufferView): void; - /** - * The **`error()`** method of the ReadableByteStreamController interface causes any future interactions with the associated stream to error with the specified reason. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) - */ - error(reason: any): void; + /** + * The **`byobRequest`** read-only property of the ReadableByteStreamController interface returns the current BYOB request, or `null` if there are no pending requests. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) + */ + get byobRequest(): ReadableStreamBYOBRequest | null + /** + * The **`desiredSize`** read-only property of the ReadableByteStreamController interface returns the number of bytes required to fill the stream's internal queue to its 'desired size'. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) + */ + get desiredSize(): number | null + /** + * The **`close()`** method of the ReadableByteStreamController interface closes the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) + */ + close(): void + /** + * The **`enqueue()`** method of the ReadableByteStreamController interface enqueues a given chunk on the associated readable byte stream (the chunk is copied into the stream's internal queues). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) + */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void + /** + * The **`error()`** method of the ReadableByteStreamController interface causes any future interactions with the associated stream to error with the specified reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) + */ + error(reason: any): void } /** * The **`WritableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a WritableStream's state. @@ -2347,18 +2811,18 @@ declare abstract class ReadableByteStreamController { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) */ declare abstract class WritableStreamDefaultController { - /** - * The read-only **`signal`** property of the WritableStreamDefaultController interface returns the AbortSignal associated with the controller. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) - */ - get signal(): AbortSignal; - /** - * The **`error()`** method of the with the associated stream to error. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) - */ - error(reason?: any): void; + /** + * The read-only **`signal`** property of the WritableStreamDefaultController interface returns the AbortSignal associated with the controller. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) + */ + get signal(): AbortSignal + /** + * The **`error()`** method of the with the associated stream to error. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) + */ + error(reason?: any): void } /** * The **`TransformStreamDefaultController`** interface of the Streams API provides methods to manipulate the associated ReadableStream and WritableStream. @@ -2366,39 +2830,39 @@ declare abstract class WritableStreamDefaultController { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ declare abstract class TransformStreamDefaultController { - /** - * The **`desiredSize`** read-only property of the TransformStreamDefaultController interface returns the desired size to fill the queue of the associated ReadableStream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) - */ - get desiredSize(): number | null; - /** - * The **`enqueue()`** method of the TransformStreamDefaultController interface enqueues the given chunk in the readable side of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) - */ - enqueue(chunk?: O): void; - /** - * The **`error()`** method of the TransformStreamDefaultController interface errors both sides of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) - */ - error(reason: any): void; - /** - * The **`terminate()`** method of the TransformStreamDefaultController interface closes the readable side and errors the writable side of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) - */ - terminate(): void; + /** + * The **`desiredSize`** read-only property of the TransformStreamDefaultController interface returns the desired size to fill the queue of the associated ReadableStream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) + */ + get desiredSize(): number | null + /** + * The **`enqueue()`** method of the TransformStreamDefaultController interface enqueues the given chunk in the readable side of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) + */ + enqueue(chunk?: O): void + /** + * The **`error()`** method of the TransformStreamDefaultController interface errors both sides of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) + */ + error(reason: any): void + /** + * The **`terminate()`** method of the TransformStreamDefaultController interface closes the readable side and errors the writable side of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) + */ + terminate(): void } interface ReadableWritablePair { - readable: ReadableStream; - /** - * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use. - * - * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. - */ - writable: WritableStream; + /** + * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream + readable: ReadableStream } /** * The **`WritableStream`** interface of the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. @@ -2406,31 +2870,34 @@ interface ReadableWritablePair { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream) */ declare class WritableStream { - constructor(underlyingSink?: UnderlyingSink, queuingStrategy?: QueuingStrategy); - /** - * The **`locked`** read-only property of the WritableStream interface returns a boolean indicating whether the `WritableStream` is locked to a writer. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) - */ - get locked(): boolean; - /** - * The **`abort()`** method of the WritableStream interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) - */ - abort(reason?: any): Promise; - /** - * The **`close()`** method of the WritableStream interface closes the associated stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) - */ - close(): Promise; - /** - * The **`getWriter()`** method of the WritableStream interface returns a new instance of WritableStreamDefaultWriter and locks the stream to that instance. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) - */ - getWriter(): WritableStreamDefaultWriter; + constructor( + underlyingSink?: UnderlyingSink, + queuingStrategy?: QueuingStrategy, + ) + /** + * The **`locked`** read-only property of the WritableStream interface returns a boolean indicating whether the `WritableStream` is locked to a writer. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) + */ + get locked(): boolean + /** + * The **`abort()`** method of the WritableStream interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) + */ + abort(reason?: any): Promise + /** + * The **`close()`** method of the WritableStream interface closes the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) + */ + close(): Promise + /** + * The **`getWriter()`** method of the WritableStream interface returns a new instance of WritableStreamDefaultWriter and locks the stream to that instance. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) + */ + getWriter(): WritableStreamDefaultWriter } /** * The **`WritableStreamDefaultWriter`** interface of the Streams API is the object returned by WritableStream.getWriter() and once created locks the writer to the `WritableStream` ensuring that no other streams can write to the underlying sink. @@ -2438,49 +2905,49 @@ declare class WritableStream { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter) */ declare class WritableStreamDefaultWriter { - constructor(stream: WritableStream); - /** - * The **`closed`** read-only property of the the stream errors or the writer's lock is released. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) - */ - get closed(): Promise; - /** - * The **`ready`** read-only property of the that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) - */ - get ready(): Promise; - /** - * The **`desiredSize`** read-only property of the to fill the stream's internal queue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) - */ - get desiredSize(): number | null; - /** - * The **`abort()`** method of the the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) - */ - abort(reason?: any): Promise; - /** - * The **`close()`** method of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) - */ - close(): Promise; - /** - * The **`write()`** method of the operation. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) - */ - write(chunk?: W): Promise; - /** - * The **`releaseLock()`** method of the corresponding stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) - */ - releaseLock(): void; + constructor(stream: WritableStream) + /** + * The **`closed`** read-only property of the the stream errors or the writer's lock is released. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) + */ + get closed(): Promise + /** + * The **`ready`** read-only property of the that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) + */ + get ready(): Promise + /** + * The **`desiredSize`** read-only property of the to fill the stream's internal queue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) + */ + get desiredSize(): number | null + /** + * The **`abort()`** method of the the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) + */ + abort(reason?: any): Promise + /** + * The **`close()`** method of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) + */ + close(): Promise + /** + * The **`write()`** method of the operation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) + */ + write(chunk?: W): Promise + /** + * The **`releaseLock()`** method of the corresponding stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) + */ + releaseLock(): void } /** * The **`TransformStream`** interface of the Streams API represents a concrete implementation of the pipe chain _transform stream_ concept. @@ -2488,47 +2955,63 @@ declare class WritableStreamDefaultWriter { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream) */ declare class TransformStream { - constructor(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy); - /** - * The **`readable`** read-only property of the TransformStream interface returns the ReadableStream instance controlled by this `TransformStream`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) - */ - get readable(): ReadableStream; - /** - * The **`writable`** read-only property of the TransformStream interface returns the WritableStream instance controlled by this `TransformStream`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) - */ - get writable(): WritableStream; + constructor( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ) + /** + * The **`readable`** read-only property of the TransformStream interface returns the ReadableStream instance controlled by this `TransformStream`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) + */ + get readable(): ReadableStream + /** + * The **`writable`** read-only property of the TransformStream interface returns the WritableStream instance controlled by this `TransformStream`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) + */ + get writable(): WritableStream } declare class FixedLengthStream extends IdentityTransformStream { - constructor(expectedLength: number | bigint, queuingStrategy?: IdentityTransformStreamQueuingStrategy); + constructor( + expectedLength: number | bigint, + queuingStrategy?: IdentityTransformStreamQueuingStrategy, + ) } -declare class IdentityTransformStream extends TransformStream { - constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +declare class IdentityTransformStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy) } interface IdentityTransformStreamQueuingStrategy { - highWaterMark?: (number | bigint); + highWaterMark?: number | bigint } interface ReadableStreamValuesOptions { - preventCancel?: boolean; + preventCancel?: boolean } /** * The **`CompressionStream`** interface of the Compression Streams API is an API for compressing a stream of data. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream) */ -declare class CompressionStream extends TransformStream { - constructor(format: "gzip" | "deflate" | "deflate-raw"); +declare class CompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: 'gzip' | 'deflate' | 'deflate-raw') } /** * The **`DecompressionStream`** interface of the Compression Streams API is an API for decompressing a stream of data. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream) */ -declare class DecompressionStream extends TransformStream { - constructor(format: "gzip" | "deflate" | "deflate-raw"); +declare class DecompressionStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + Uint8Array +> { + constructor(format: 'gzip' | 'deflate' | 'deflate-raw') } /** * The **`TextEncoderStream`** interface of the Encoding API converts a stream of strings into bytes in the UTF-8 encoding. @@ -2536,39 +3019,44 @@ declare class DecompressionStream extends TransformStream { - constructor(); - get encoding(): string; + constructor() + get encoding(): string } /** * The **`TextDecoderStream`** interface of the Encoding API converts a stream of text in a binary encoding, such as UTF-8 etc., to a stream of strings. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoderStream) */ -declare class TextDecoderStream extends TransformStream { - constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); - get encoding(): string; - get fatal(): boolean; - get ignoreBOM(): boolean; +declare class TextDecoderStream extends TransformStream< + ArrayBuffer | ArrayBufferView, + string +> { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit) + get encoding(): string + get fatal(): boolean + get ignoreBOM(): boolean } interface TextDecoderStreamTextDecoderStreamInit { - fatal?: boolean; - ignoreBOM?: boolean; + fatal?: boolean + ignoreBOM?: boolean } /** * The **`ByteLengthQueuingStrategy`** interface of the Streams API provides a built-in byte length queuing strategy that can be used when constructing streams. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy) */ -declare class ByteLengthQueuingStrategy implements QueuingStrategy { - constructor(init: QueuingStrategyInit); - /** - * The read-only **`ByteLengthQueuingStrategy.highWaterMark`** property returns the total number of bytes that can be contained in the internal queue before backpressure is applied. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) - */ - get highWaterMark(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ - get size(): (chunk?: any) => number; +declare class ByteLengthQueuingStrategy + implements QueuingStrategy +{ + constructor(init: QueuingStrategyInit) + /** + * The read-only **`ByteLengthQueuingStrategy.highWaterMark`** property returns the total number of bytes that can be contained in the internal queue before backpressure is applied. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) + */ + get highWaterMark(): number + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + get size(): (chunk?: any) => number } /** * The **`CountQueuingStrategy`** interface of the Streams API provides a built-in chunk counting queuing strategy that can be used when constructing streams. @@ -2576,128 +3064,142 @@ declare class ByteLengthQueuingStrategy implements QueuingStrategy number; + constructor(init: QueuingStrategyInit) + /** + * The read-only **`CountQueuingStrategy.highWaterMark`** property returns the total number of chunks that can be contained in the internal queue before backpressure is applied. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) + */ + get highWaterMark(): number + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + get size(): (chunk?: any) => number } interface QueuingStrategyInit { - /** - * Creates a new ByteLengthQueuingStrategy with the provided high water mark. - * - * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw. - */ - highWaterMark: number; + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw. + */ + highWaterMark: number } interface ScriptVersion { - id?: string; - tag?: string; - message?: string; + id?: string + tag?: string + message?: string } declare abstract class TailEvent extends ExtendableEvent { - readonly events: TraceItem[]; - readonly traces: TraceItem[]; + readonly events: TraceItem[] + readonly traces: TraceItem[] } interface TraceItem { - readonly event: (TraceItemFetchEventInfo | TraceItemJsRpcEventInfo | TraceItemScheduledEventInfo | TraceItemAlarmEventInfo | TraceItemQueueEventInfo | TraceItemEmailEventInfo | TraceItemTailEventInfo | TraceItemCustomEventInfo | TraceItemHibernatableWebSocketEventInfo) | null; - readonly eventTimestamp: number | null; - readonly logs: TraceLog[]; - readonly exceptions: TraceException[]; - readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; - readonly scriptName: string | null; - readonly entrypoint?: string; - readonly scriptVersion?: ScriptVersion; - readonly dispatchNamespace?: string; - readonly scriptTags?: string[]; - readonly durableObjectId?: string; - readonly outcome: string; - readonly executionModel: string; - readonly truncated: boolean; - readonly cpuTime: number; - readonly wallTime: number; + readonly event: + | ( + | TraceItemFetchEventInfo + | TraceItemJsRpcEventInfo + | TraceItemScheduledEventInfo + | TraceItemAlarmEventInfo + | TraceItemQueueEventInfo + | TraceItemEmailEventInfo + | TraceItemTailEventInfo + | TraceItemCustomEventInfo + | TraceItemHibernatableWebSocketEventInfo + ) + | null + readonly eventTimestamp: number | null + readonly logs: TraceLog[] + readonly exceptions: TraceException[] + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[] + readonly scriptName: string | null + readonly entrypoint?: string + readonly scriptVersion?: ScriptVersion + readonly dispatchNamespace?: string + readonly scriptTags?: string[] + readonly durableObjectId?: string + readonly outcome: string + readonly executionModel: string + readonly truncated: boolean + readonly cpuTime: number + readonly wallTime: number } interface TraceItemAlarmEventInfo { - readonly scheduledTime: Date; -} -interface TraceItemCustomEventInfo { + readonly scheduledTime: Date } +interface TraceItemCustomEventInfo {} interface TraceItemScheduledEventInfo { - readonly scheduledTime: number; - readonly cron: string; + readonly scheduledTime: number + readonly cron: string } interface TraceItemQueueEventInfo { - readonly queue: string; - readonly batchSize: number; + readonly queue: string + readonly batchSize: number } interface TraceItemEmailEventInfo { - readonly mailFrom: string; - readonly rcptTo: string; - readonly rawSize: number; + readonly mailFrom: string + readonly rcptTo: string + readonly rawSize: number } interface TraceItemTailEventInfo { - readonly consumedEvents: TraceItemTailEventInfoTailItem[]; + readonly consumedEvents: TraceItemTailEventInfoTailItem[] } interface TraceItemTailEventInfoTailItem { - readonly scriptName: string | null; + readonly scriptName: string | null } interface TraceItemFetchEventInfo { - readonly response?: TraceItemFetchEventInfoResponse; - readonly request: TraceItemFetchEventInfoRequest; + readonly response?: TraceItemFetchEventInfoResponse + readonly request: TraceItemFetchEventInfoRequest } interface TraceItemFetchEventInfoRequest { - readonly cf?: any; - readonly headers: Record; - readonly method: string; - readonly url: string; - getUnredacted(): TraceItemFetchEventInfoRequest; + readonly cf?: any + readonly headers: Record + readonly method: string + readonly url: string + getUnredacted(): TraceItemFetchEventInfoRequest } interface TraceItemFetchEventInfoResponse { - readonly status: number; + readonly status: number } interface TraceItemJsRpcEventInfo { - readonly rpcMethod: string; + readonly rpcMethod: string } interface TraceItemHibernatableWebSocketEventInfo { - readonly getWebSocketEvent: TraceItemHibernatableWebSocketEventInfoMessage | TraceItemHibernatableWebSocketEventInfoClose | TraceItemHibernatableWebSocketEventInfoError; + readonly getWebSocketEvent: + | TraceItemHibernatableWebSocketEventInfoMessage + | TraceItemHibernatableWebSocketEventInfoClose + | TraceItemHibernatableWebSocketEventInfoError } interface TraceItemHibernatableWebSocketEventInfoMessage { - readonly webSocketEventType: string; + readonly webSocketEventType: string } interface TraceItemHibernatableWebSocketEventInfoClose { - readonly webSocketEventType: string; - readonly code: number; - readonly wasClean: boolean; + readonly webSocketEventType: string + readonly code: number + readonly wasClean: boolean } interface TraceItemHibernatableWebSocketEventInfoError { - readonly webSocketEventType: string; + readonly webSocketEventType: string } interface TraceLog { - readonly timestamp: number; - readonly level: string; - readonly message: any; + readonly timestamp: number + readonly level: string + readonly message: any } interface TraceException { - readonly timestamp: number; - readonly message: string; - readonly name: string; - readonly stack?: string; + readonly timestamp: number + readonly message: string + readonly name: string + readonly stack?: string } interface TraceDiagnosticChannelEvent { - readonly timestamp: number; - readonly channel: string; - readonly message: any; + readonly timestamp: number + readonly channel: string + readonly message: any } interface TraceMetrics { - readonly cpuTime: number; - readonly wallTime: number; + readonly cpuTime: number + readonly wallTime: number } interface UnsafeTraceMetrics { - fromTrace(item: TraceItem): TraceMetrics; + fromTrace(item: TraceItem): TraceMetrics } /** * The **`URL`** interface is used to parse, construct, normalize, and encode URL. @@ -2705,171 +3207,171 @@ interface UnsafeTraceMetrics { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL) */ declare class URL { - constructor(url: string | URL, base?: string | URL); - /** - * The **`origin`** read-only property of the URL interface returns a string containing the Unicode serialization of the origin of the represented URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) - */ - get origin(): string; - /** - * The **`href`** property of the URL interface is a string containing the whole URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) - */ - get href(): string; - /** - * The **`href`** property of the URL interface is a string containing the whole URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) - */ - set href(value: string); - /** - * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) - */ - get protocol(): string; - /** - * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) - */ - set protocol(value: string); - /** - * The **`username`** property of the URL interface is a string containing the username component of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) - */ - get username(): string; - /** - * The **`username`** property of the URL interface is a string containing the username component of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) - */ - set username(value: string); - /** - * The **`password`** property of the URL interface is a string containing the password component of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) - */ - get password(): string; - /** - * The **`password`** property of the URL interface is a string containing the password component of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) - */ - set password(value: string); - /** - * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) - */ - get host(): string; - /** - * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) - */ - set host(value: string); - /** - * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) - */ - get hostname(): string; - /** - * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) - */ - set hostname(value: string); - /** - * The **`port`** property of the URL interface is a string containing the port number of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) - */ - get port(): string; - /** - * The **`port`** property of the URL interface is a string containing the port number of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) - */ - set port(value: string); - /** - * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) - */ - get pathname(): string; - /** - * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) - */ - set pathname(value: string); - /** - * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) - */ - get search(): string; - /** - * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) - */ - set search(value: string); - /** - * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) - */ - get hash(): string; - /** - * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) - */ - set hash(value: string); - /** - * The **`searchParams`** read-only property of the access to the [MISSING: httpmethod('GET')] decoded query arguments contained in the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) - */ - get searchParams(): URLSearchParams; - /** - * The **`toJSON()`** method of the URL interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as ```js-nolint toJSON() ``` None. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) - */ - toJSON(): string; - /*function toString() { [native code] }*/ - toString(): string; - /** - * The **`URL.canParse()`** static method of the URL interface returns a boolean indicating whether or not an absolute URL, or a relative URL combined with a base URL, are parsable and valid. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) - */ - static canParse(url: string, base?: string): boolean; - /** - * The **`URL.parse()`** static method of the URL interface returns a newly created URL object representing the URL defined by the parameters. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/parse_static) - */ - static parse(url: string, base?: string): URL | null; - /** - * The **`createObjectURL()`** static method of the URL interface creates a string containing a URL representing the object given in the parameter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static) - */ - static createObjectURL(object: File | Blob): string; - /** - * The **`revokeObjectURL()`** static method of the URL interface releases an existing object URL which was previously created by calling Call this method when you've finished using an object URL to let the browser know not to keep the reference to the file any longer. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static) - */ - static revokeObjectURL(object_url: string): void; + constructor(url: string | URL, base?: string | URL) + /** + * The **`origin`** read-only property of the URL interface returns a string containing the Unicode serialization of the origin of the represented URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) + */ + get origin(): string + /** + * The **`href`** property of the URL interface is a string containing the whole URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) + */ + get href(): string + /** + * The **`href`** property of the URL interface is a string containing the whole URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) + */ + set href(value: string) + /** + * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) + */ + get protocol(): string + /** + * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) + */ + set protocol(value: string) + /** + * The **`username`** property of the URL interface is a string containing the username component of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) + */ + get username(): string + /** + * The **`username`** property of the URL interface is a string containing the username component of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) + */ + set username(value: string) + /** + * The **`password`** property of the URL interface is a string containing the password component of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) + */ + get password(): string + /** + * The **`password`** property of the URL interface is a string containing the password component of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) + */ + set password(value: string) + /** + * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) + */ + get host(): string + /** + * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) + */ + set host(value: string) + /** + * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) + */ + get hostname(): string + /** + * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) + */ + set hostname(value: string) + /** + * The **`port`** property of the URL interface is a string containing the port number of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) + */ + get port(): string + /** + * The **`port`** property of the URL interface is a string containing the port number of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) + */ + set port(value: string) + /** + * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) + */ + get pathname(): string + /** + * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) + */ + set pathname(value: string) + /** + * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) + */ + get search(): string + /** + * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) + */ + set search(value: string) + /** + * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) + */ + get hash(): string + /** + * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) + */ + set hash(value: string) + /** + * The **`searchParams`** read-only property of the access to the [MISSING: httpmethod('GET')] decoded query arguments contained in the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) + */ + get searchParams(): URLSearchParams + /** + * The **`toJSON()`** method of the URL interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as ```js-nolint toJSON() ``` None. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) + */ + toJSON(): string + /*function toString() { [native code] }*/ + toString(): string + /** + * The **`URL.canParse()`** static method of the URL interface returns a boolean indicating whether or not an absolute URL, or a relative URL combined with a base URL, are parsable and valid. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) + */ + static canParse(url: string, base?: string): boolean + /** + * The **`URL.parse()`** static method of the URL interface returns a newly created URL object representing the URL defined by the parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/parse_static) + */ + static parse(url: string, base?: string): URL | null + /** + * The **`createObjectURL()`** static method of the URL interface creates a string containing a URL representing the object given in the parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static) + */ + static createObjectURL(object: File | Blob): string + /** + * The **`revokeObjectURL()`** static method of the URL interface releases an existing object URL which was previously created by calling Call this method when you've finished using an object URL to let the browser know not to keep the reference to the file any longer. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static) + */ + static revokeObjectURL(object_url: string): void } /** * The **`URLSearchParams`** interface defines utility methods to work with the query string of a URL. @@ -2877,114 +3379,125 @@ declare class URL { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams) */ declare class URLSearchParams { - constructor(init?: (Iterable> | Record | string)); - /** - * The **`size`** read-only property of the URLSearchParams interface indicates the total number of search parameter entries. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/size) - */ - get size(): number; - /** - * The **`append()`** method of the URLSearchParams interface appends a specified key/value pair as a new search parameter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/append) - */ - append(name: string, value: string): void; - /** - * The **`delete()`** method of the URLSearchParams interface deletes specified parameters and their associated value(s) from the list of all search parameters. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/delete) - */ - delete(name: string, value?: string): void; - /** - * The **`get()`** method of the URLSearchParams interface returns the first value associated to the given search parameter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/get) - */ - get(name: string): string | null; - /** - * The **`getAll()`** method of the URLSearchParams interface returns all the values associated with a given search parameter as an array. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/getAll) - */ - getAll(name: string): string[]; - /** - * The **`has()`** method of the URLSearchParams interface returns a boolean value that indicates whether the specified parameter is in the search parameters. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/has) - */ - has(name: string, value?: string): boolean; - /** - * The **`set()`** method of the URLSearchParams interface sets the value associated with a given search parameter to the given value. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/set) - */ - set(name: string, value: string): void; - /** - * The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns `undefined`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort) - */ - sort(): void; - /* Returns an array of key, value pairs for every entry in the search params. */ - entries(): IterableIterator<[ - key: string, - value: string - ]>; - /* Returns a list of keys in the search params. */ - keys(): IterableIterator; - /* Returns a list of values in the search params. */ - values(): IterableIterator; - forEach(callback: (this: This, value: string, key: string, parent: URLSearchParams) => void, thisArg?: This): void; - /*function toString() { [native code] }*/ - toString(): string; - [Symbol.iterator](): IterableIterator<[ - key: string, - value: string - ]>; + constructor( + init?: Iterable> | Record | string, + ) + /** + * The **`size`** read-only property of the URLSearchParams interface indicates the total number of search parameter entries. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/size) + */ + get size(): number + /** + * The **`append()`** method of the URLSearchParams interface appends a specified key/value pair as a new search parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/append) + */ + append(name: string, value: string): void + /** + * The **`delete()`** method of the URLSearchParams interface deletes specified parameters and their associated value(s) from the list of all search parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/delete) + */ + delete(name: string, value?: string): void + /** + * The **`get()`** method of the URLSearchParams interface returns the first value associated to the given search parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/get) + */ + get(name: string): string | null + /** + * The **`getAll()`** method of the URLSearchParams interface returns all the values associated with a given search parameter as an array. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/getAll) + */ + getAll(name: string): string[] + /** + * The **`has()`** method of the URLSearchParams interface returns a boolean value that indicates whether the specified parameter is in the search parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/has) + */ + has(name: string, value?: string): boolean + /** + * The **`set()`** method of the URLSearchParams interface sets the value associated with a given search parameter to the given value. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/set) + */ + set(name: string, value: string): void + /** + * The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns `undefined`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort) + */ + sort(): void + /* Returns an array of key, value pairs for every entry in the search params. */ + entries(): IterableIterator<[key: string, value: string]> + /* Returns a list of keys in the search params. */ + keys(): IterableIterator + /* Returns a list of values in the search params. */ + values(): IterableIterator + forEach( + callback: ( + this: This, + value: string, + key: string, + parent: URLSearchParams, + ) => void, + thisArg?: This, + ): void + /*function toString() { [native code] }*/ + toString(): string + [Symbol.iterator](): IterableIterator<[key: string, value: string]> } declare class URLPattern { - constructor(input?: (string | URLPatternInit), baseURL?: (string | URLPatternOptions), patternOptions?: URLPatternOptions); - get protocol(): string; - get username(): string; - get password(): string; - get hostname(): string; - get port(): string; - get pathname(): string; - get search(): string; - get hash(): string; - get hasRegExpGroups(): boolean; - test(input?: (string | URLPatternInit), baseURL?: string): boolean; - exec(input?: (string | URLPatternInit), baseURL?: string): URLPatternResult | null; + constructor( + input?: string | URLPatternInit, + baseURL?: string | URLPatternOptions, + patternOptions?: URLPatternOptions, + ) + get protocol(): string + get username(): string + get password(): string + get hostname(): string + get port(): string + get pathname(): string + get search(): string + get hash(): string + get hasRegExpGroups(): boolean + test(input?: string | URLPatternInit, baseURL?: string): boolean + exec( + input?: string | URLPatternInit, + baseURL?: string, + ): URLPatternResult | null } interface URLPatternInit { - protocol?: string; - username?: string; - password?: string; - hostname?: string; - port?: string; - pathname?: string; - search?: string; - hash?: string; - baseURL?: string; + protocol?: string + username?: string + password?: string + hostname?: string + port?: string + pathname?: string + search?: string + hash?: string + baseURL?: string } interface URLPatternComponentResult { - input: string; - groups: Record; + input: string + groups: Record } interface URLPatternResult { - inputs: (string | URLPatternInit)[]; - protocol: URLPatternComponentResult; - username: URLPatternComponentResult; - password: URLPatternComponentResult; - hostname: URLPatternComponentResult; - port: URLPatternComponentResult; - pathname: URLPatternComponentResult; - search: URLPatternComponentResult; - hash: URLPatternComponentResult; + inputs: (string | URLPatternInit)[] + protocol: URLPatternComponentResult + username: URLPatternComponentResult + password: URLPatternComponentResult + hostname: URLPatternComponentResult + port: URLPatternComponentResult + pathname: URLPatternComponentResult + search: URLPatternComponentResult + hash: URLPatternComponentResult } interface URLPatternOptions { - ignoreCase?: boolean; + ignoreCase?: boolean } /** * A `CloseEvent` is sent to clients using WebSockets when the connection is closed. @@ -2992,172 +3505,162 @@ interface URLPatternOptions { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent) */ declare class CloseEvent extends Event { - constructor(type: string, initializer?: CloseEventInit); - /** - * The **`code`** read-only property of the CloseEvent interface returns a WebSocket connection close code indicating the reason the connection was closed. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) - */ - readonly code: number; - /** - * The **`reason`** read-only property of the CloseEvent interface returns the WebSocket connection close reason the server gave for closing the connection; that is, a concise human-readable prose explanation for the closure. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) - */ - readonly reason: string; - /** - * The **`wasClean`** read-only property of the CloseEvent interface returns `true` if the connection closed cleanly. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) - */ - readonly wasClean: boolean; + constructor(type: string, initializer?: CloseEventInit) + /** + * The **`code`** read-only property of the CloseEvent interface returns a WebSocket connection close code indicating the reason the connection was closed. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number + /** + * The **`reason`** read-only property of the CloseEvent interface returns the WebSocket connection close reason the server gave for closing the connection; that is, a concise human-readable prose explanation for the closure. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string + /** + * The **`wasClean`** read-only property of the CloseEvent interface returns `true` if the connection closed cleanly. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean } interface CloseEventInit { - code?: number; - reason?: string; - wasClean?: boolean; + code?: number + reason?: string + wasClean?: boolean } type WebSocketEventMap = { - close: CloseEvent; - message: MessageEvent; - open: Event; - error: ErrorEvent; -}; + close: CloseEvent + message: MessageEvent + open: Event + error: ErrorEvent +} /** * The `WebSocket` object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) */ declare var WebSocket: { - prototype: WebSocket; - new (url: string, protocols?: (string[] | string)): WebSocket; - readonly READY_STATE_CONNECTING: number; - readonly CONNECTING: number; - readonly READY_STATE_OPEN: number; - readonly OPEN: number; - readonly READY_STATE_CLOSING: number; - readonly CLOSING: number; - readonly READY_STATE_CLOSED: number; - readonly CLOSED: number; -}; + prototype: WebSocket + new (url: string, protocols?: string[] | string): WebSocket + readonly READY_STATE_CONNECTING: number + readonly CONNECTING: number + readonly READY_STATE_OPEN: number + readonly OPEN: number + readonly READY_STATE_CLOSING: number + readonly CLOSING: number + readonly READY_STATE_CLOSED: number + readonly CLOSED: number +} /** * The `WebSocket` object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) */ interface WebSocket extends EventTarget { - accept(options?: WebSocketAcceptOptions): void; - /** - * The **`WebSocket.send()`** method enqueues the specified data to be transmitted to the server over the WebSocket connection, increasing the value of `bufferedAmount` by the number of bytes needed to contain the data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) - */ - send(message: (ArrayBuffer | ArrayBufferView) | string): void; - /** - * The **`WebSocket.close()`** method closes the already `CLOSED`, this method does nothing. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) - */ - close(code?: number, reason?: string): void; - serializeAttachment(attachment: any): void; - deserializeAttachment(): any | null; - /** - * The **`WebSocket.readyState`** read-only property returns the current state of the WebSocket connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) - */ - readyState: number; - /** - * The **`WebSocket.url`** read-only property returns the absolute URL of the WebSocket as resolved by the constructor. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) - */ - url: string | null; - /** - * The **`WebSocket.protocol`** read-only property returns the name of the sub-protocol the server selected; this will be one of the strings specified in the `protocols` parameter when creating the WebSocket object, or the empty string if no connection is established. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) - */ - protocol: string | null; - /** - * The **`WebSocket.extensions`** read-only property returns the extensions selected by the server. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) - */ - extensions: string | null; - /** - * The **`WebSocket.binaryType`** property controls the type of binary data being received over the WebSocket connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/binaryType) - */ - binaryType: "blob" | "arraybuffer"; -} -interface WebSocketAcceptOptions { - /** - * When set to `true`, receiving a server-initiated WebSocket Close frame will not - * automatically send a reciprocal Close frame, leaving the connection in a half-open - * state. This is useful for proxying scenarios where you need to coordinate closing - * both sides independently. Defaults to `false` when the - * `no_web_socket_half_open_by_default` compatibility flag is enabled. - */ - allowHalfOpen?: boolean; + accept(): void + /** + * The **`WebSocket.send()`** method enqueues the specified data to be transmitted to the server over the WebSocket connection, increasing the value of `bufferedAmount` by the number of bytes needed to contain the data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void + /** + * The **`WebSocket.close()`** method closes the already `CLOSED`, this method does nothing. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void + serializeAttachment(attachment: any): void + deserializeAttachment(): any | null + /** + * The **`WebSocket.readyState`** read-only property returns the current state of the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + readyState: number + /** + * The **`WebSocket.url`** read-only property returns the absolute URL of the WebSocket as resolved by the constructor. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + url: string | null + /** + * The **`WebSocket.protocol`** read-only property returns the name of the sub-protocol the server selected; this will be one of the strings specified in the `protocols` parameter when creating the WebSocket object, or the empty string if no connection is established. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + protocol: string | null + /** + * The **`WebSocket.extensions`** read-only property returns the extensions selected by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + extensions: string | null } declare const WebSocketPair: { - new (): { - 0: WebSocket; - 1: WebSocket; - }; -}; + new (): { + 0: WebSocket + 1: WebSocket + } +} interface SqlStorage { - exec>(query: string, ...bindings: any[]): SqlStorageCursor; - get databaseSize(): number; - Cursor: typeof SqlStorageCursor; - Statement: typeof SqlStorageStatement; + exec>( + query: string, + ...bindings: any[] + ): SqlStorageCursor + get databaseSize(): number + Cursor: typeof SqlStorageCursor + Statement: typeof SqlStorageStatement } -declare abstract class SqlStorageStatement { -} -type SqlStorageValue = ArrayBuffer | string | number | null; -declare abstract class SqlStorageCursor> { - next(): { - done?: false; - value: T; - } | { - done: true; - value?: never; - }; - toArray(): T[]; - one(): T; - raw(): IterableIterator; - columnNames: string[]; - get rowsRead(): number; - get rowsWritten(): number; - [Symbol.iterator](): IterableIterator; +declare abstract class SqlStorageStatement {} +type SqlStorageValue = ArrayBuffer | string | number | null +declare abstract class SqlStorageCursor< + T extends Record, +> { + next(): + | { + done?: false + value: T + } + | { + done: true + value?: never + } + toArray(): T[] + one(): T + raw(): IterableIterator + columnNames: string[] + get rowsRead(): number + get rowsWritten(): number + [Symbol.iterator](): IterableIterator } interface Socket { - get readable(): ReadableStream; - get writable(): WritableStream; - get closed(): Promise; - get opened(): Promise; - get upgraded(): boolean; - get secureTransport(): "on" | "off" | "starttls"; - close(): Promise; - startTls(options?: TlsOptions): Socket; + get readable(): ReadableStream + get writable(): WritableStream + get closed(): Promise + get opened(): Promise + get upgraded(): boolean + get secureTransport(): 'on' | 'off' | 'starttls' + close(): Promise + startTls(options?: TlsOptions): Socket } interface SocketOptions { - secureTransport?: string; - allowHalfOpen: boolean; - highWaterMark?: (number | bigint); + secureTransport?: string + allowHalfOpen: boolean + highWaterMark?: number | bigint } interface SocketAddress { - hostname: string; - port: number; + hostname: string + port: number } interface TlsOptions { - expectedServerHostname?: string; + expectedServerHostname?: string } interface SocketInfo { - remoteAddress?: string; - localAddress?: string; + remoteAddress?: string + localAddress?: string } /** * The **`EventSource`** interface is web content's interface to server-sent events. @@ -3165,68 +3668,66 @@ interface SocketInfo { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource) */ declare class EventSource extends EventTarget { - constructor(url: string, init?: EventSourceEventSourceInit); - /** - * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the ```js-nolint close() ``` None. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) - */ - close(): void; - /** - * The **`url`** read-only property of the URL of the source. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) - */ - get url(): string; - /** - * The **`withCredentials`** read-only property of the the `EventSource` object was instantiated with CORS credentials set. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) - */ - get withCredentials(): boolean; - /** - * The **`readyState`** read-only property of the connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) - */ - get readyState(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ - get onopen(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ - set onopen(value: any | null); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ - get onmessage(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ - set onmessage(value: any | null); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ - get onerror(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ - set onerror(value: any | null); - static readonly CONNECTING: number; - static readonly OPEN: number; - static readonly CLOSED: number; - static from(stream: ReadableStream): EventSource; + constructor(url: string, init?: EventSourceEventSourceInit) + /** + * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the ```js-nolint close() ``` None. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) + */ + close(): void + /** + * The **`url`** read-only property of the URL of the source. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) + */ + get url(): string + /** + * The **`withCredentials`** read-only property of the the `EventSource` object was instantiated with CORS credentials set. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) + */ + get withCredentials(): boolean + /** + * The **`readyState`** read-only property of the connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) + */ + get readyState(): number + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + get onopen(): any | null + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + set onopen(value: any | null) + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + get onmessage(): any | null + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + set onmessage(value: any | null) + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + get onerror(): any | null + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + set onerror(value: any | null) + static readonly CONNECTING: number + static readonly OPEN: number + static readonly CLOSED: number + static from(stream: ReadableStream): EventSource } interface EventSourceEventSourceInit { - withCredentials?: boolean; - fetcher?: Fetcher; + withCredentials?: boolean + fetcher?: Fetcher } interface Container { - get running(): boolean; - start(options?: ContainerStartupOptions): void; - monitor(): Promise; - destroy(error?: any): Promise; - signal(signo: number): void; - getTcpPort(port: number): Fetcher; - setInactivityTimeout(durationMs: number | bigint): Promise; - interceptOutboundHttp(addr: string, binding: Fetcher): Promise; - interceptAllOutboundHttp(binding: Fetcher): Promise; + get running(): boolean + start(options?: ContainerStartupOptions): void + monitor(): Promise + destroy(error?: any): Promise + signal(signo: number): void + getTcpPort(port: number): Fetcher + setInactivityTimeout(durationMs: number | bigint): Promise } interface ContainerStartupOptions { - entrypoint?: string[]; - enableInternet: boolean; - env?: Record; - hardTimeout?: (number | bigint); + entrypoint?: string[] + enableInternet: boolean + env?: Record + hardTimeout?: number | bigint } /** * The **`MessagePort`** interface of the Channel Messaging API represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other. @@ -3234,26 +3735,26 @@ interface ContainerStartupOptions { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort) */ declare abstract class MessagePort extends EventTarget { - /** - * The **`postMessage()`** method of the transfers ownership of objects to other browsing contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/postMessage) - */ - postMessage(data?: any, options?: (any[] | MessagePortPostMessageOptions)): void; - /** - * The **`close()`** method of the MessagePort interface disconnects the port, so it is no longer active. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/close) - */ - close(): void; - /** - * The **`start()`** method of the MessagePort interface starts the sending of messages queued on the port. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/start) - */ - start(): void; - get onmessage(): any | null; - set onmessage(value: any | null); + /** + * The **`postMessage()`** method of the transfers ownership of objects to other browsing contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/postMessage) + */ + postMessage(data?: any, options?: any[] | MessagePortPostMessageOptions): void + /** + * The **`close()`** method of the MessagePort interface disconnects the port, so it is no longer active. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/close) + */ + close(): void + /** + * The **`start()`** method of the MessagePort interface starts the sending of messages queued on the port. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/start) + */ + start(): void + get onmessage(): any | null + set onmessage(value: any | null) } /** * The **`MessageChannel`** interface of the Channel Messaging API allows us to create a new message channel and send data through it via its two MessagePort properties. @@ -3261,5826 +3762,3988 @@ declare abstract class MessagePort extends EventTarget { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel) */ declare class MessageChannel { - constructor(); - /** - * The **`port1`** read-only property of the the port attached to the context that originated the channel. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port1) - */ - readonly port1: MessagePort; - /** - * The **`port2`** read-only property of the the port attached to the context at the other end of the channel, which the message is initially sent to. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port2) - */ - readonly port2: MessagePort; + constructor() + /** + * The **`port1`** read-only property of the the port attached to the context that originated the channel. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port1) + */ + readonly port1: MessagePort + /** + * The **`port2`** read-only property of the the port attached to the context at the other end of the channel, which the message is initially sent to. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port2) + */ + readonly port2: MessagePort } interface MessagePortPostMessageOptions { - transfer?: any[]; + transfer?: any[] } -type LoopbackForExport Rpc.EntrypointBranded) | ExportedHandler | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? LoopbackServiceStub> : T extends new (...args: any[]) => Rpc.DurableObjectBranded ? LoopbackDurableObjectClass> : T extends ExportedHandler ? LoopbackServiceStub : undefined; -type LoopbackServiceStub = Fetcher & (T extends CloudflareWorkersModule.WorkerEntrypoint ? (opts: { - props?: Props; -}) => Fetcher : (opts: { - props?: any; -}) => Fetcher); -type LoopbackDurableObjectClass = DurableObjectClass & (T extends CloudflareWorkersModule.DurableObject ? (opts: { - props?: Props; -}) => DurableObjectClass : (opts: { - props?: any; -}) => DurableObjectClass); +type LoopbackForExport< + T extends + | (new (...args: any[]) => Rpc.EntrypointBranded) + | ExportedHandler + | undefined = undefined, +> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded + ? LoopbackServiceStub> + : T extends new (...args: any[]) => Rpc.DurableObjectBranded + ? LoopbackDurableObjectClass> + : T extends ExportedHandler + ? LoopbackServiceStub + : undefined +type LoopbackServiceStub< + T extends Rpc.WorkerEntrypointBranded | undefined = undefined, +> = Fetcher & + (T extends CloudflareWorkersModule.WorkerEntrypoint + ? (opts: { props?: Props }) => Fetcher + : (opts: { props?: any }) => Fetcher) +type LoopbackDurableObjectClass< + T extends Rpc.DurableObjectBranded | undefined = undefined, +> = DurableObjectClass & + (T extends CloudflareWorkersModule.DurableObject + ? (opts: { props?: Props }) => DurableObjectClass + : (opts: { props?: any }) => DurableObjectClass) interface SyncKvStorage { - get(key: string): T | undefined; - list(options?: SyncKvListOptions): Iterable<[ - string, - T - ]>; - put(key: string, value: T): void; - delete(key: string): boolean; + get(key: string): T | undefined + list(options?: SyncKvListOptions): Iterable<[string, T]> + put(key: string, value: T): void + delete(key: string): boolean } interface SyncKvListOptions { - start?: string; - startAfter?: string; - end?: string; - prefix?: string; - reverse?: boolean; - limit?: number; + start?: string + startAfter?: string + end?: string + prefix?: string + reverse?: boolean + limit?: number } interface WorkerStub { - getEntrypoint(name?: string, options?: WorkerStubEntrypointOptions): Fetcher; + getEntrypoint( + name?: string, + options?: WorkerStubEntrypointOptions, + ): Fetcher } interface WorkerStubEntrypointOptions { - props?: any; + props?: any } interface WorkerLoader { - get(name: string | null, getCode: () => WorkerLoaderWorkerCode | Promise): WorkerStub; - load(code: WorkerLoaderWorkerCode): WorkerStub; + get( + name: string, + getCode: () => WorkerLoaderWorkerCode | Promise, + ): WorkerStub } interface WorkerLoaderModule { - js?: string; - cjs?: string; - text?: string; - data?: ArrayBuffer; - json?: any; - py?: string; - wasm?: ArrayBuffer; + js?: string + cjs?: string + text?: string + data?: ArrayBuffer + json?: any + py?: string + wasm?: ArrayBuffer } interface WorkerLoaderWorkerCode { - compatibilityDate: string; - compatibilityFlags?: string[]; - allowExperimental?: boolean; - mainModule: string; - modules: Record; - env?: any; - globalOutbound?: (Fetcher | null); - tails?: Fetcher[]; - streamingTails?: Fetcher[]; + compatibilityDate: string + compatibilityFlags?: string[] + allowExperimental?: boolean + mainModule: string + modules: Record + env?: any + globalOutbound?: Fetcher | null + tails?: Fetcher[] + streamingTails?: Fetcher[] } /** -* The Workers runtime supports a subset of the Performance API, used to measure timing and performance, -* as well as timing of subrequests and other operations. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) -*/ + * The Workers runtime supports a subset of the Performance API, used to measure timing and performance, + * as well as timing of subrequests and other operations. + * + * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) + */ declare abstract class Performance { - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancetimeorigin) */ - get timeOrigin(): number; - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */ - now(): number; - /** - * The **`toJSON()`** method of the Performance interface is a Serialization; it returns a JSON representation of the Performance object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/toJSON) - */ - toJSON(): object; -} -// AI Search V2 API Error Interfaces -interface AiSearchInternalError extends Error { -} -interface AiSearchNotFoundError extends Error { -} -interface AiSearchNameNotSetError extends Error { -} -// AI Search V2 Request Types -type AiSearchSearchRequest = { - messages: Array<{ - role: 'system' | 'developer' | 'user' | 'assistant' | 'tool'; - content: string | null; - }>; - ai_search_options?: { - retrieval?: { - retrieval_type?: 'vector' | 'keyword' | 'hybrid'; - /** Match threshold (0-1, default 0.4) */ - match_threshold?: number; - /** Maximum number of results (1-50, default 10) */ - max_num_results?: number; - filters?: VectorizeVectorMetadataFilter; - /** Context expansion (0-3, default 0) */ - context_expansion?: number; - [key: string]: unknown; - }; - query_rewrite?: { - enabled?: boolean; - model?: string; - rewrite_prompt?: string; - [key: string]: unknown; - }; - reranking?: { - /** Enable reranking (default false) */ - enabled?: boolean; - model?: '@cf/baai/bge-reranker-base' | ''; - /** Match threshold (0-1, default 0.4) */ - match_threshold?: number; - [key: string]: unknown; - }; - [key: string]: unknown; - }; -}; -type AiSearchChatCompletionsRequest = { - messages: Array<{ - role: 'system' | 'developer' | 'user' | 'assistant' | 'tool'; - content: string | null; - }>; - model?: string; - stream?: boolean; - ai_search_options?: { - retrieval?: { - retrieval_type?: 'vector' | 'keyword' | 'hybrid'; - match_threshold?: number; - max_num_results?: number; - filters?: VectorizeVectorMetadataFilter; - context_expansion?: number; - [key: string]: unknown; - }; - query_rewrite?: { - enabled?: boolean; - model?: string; - rewrite_prompt?: string; - [key: string]: unknown; - }; - reranking?: { - enabled?: boolean; - model?: '@cf/baai/bge-reranker-base' | ''; - match_threshold?: number; - [key: string]: unknown; - }; - [key: string]: unknown; - }; - [key: string]: unknown; -}; -// AI Search V2 Response Types -type AiSearchSearchResponse = { - search_query: string; - chunks: Array<{ - id: string; - type: string; - /** Match score (0-1) */ - score: number; - text: string; - item: { - timestamp?: number; - key: string; - metadata?: Record; - }; - scoring_details?: { - /** Keyword match score (0-1) */ - keyword_score?: number; - /** Vector similarity score (0-1) */ - vector_score?: number; - }; - }>; -}; -type AiSearchListResponse = Array<{ - id: string; - internal_id?: string; - account_id?: string; - account_tag?: string; - /** Whether the instance is enabled (default true) */ - enable?: boolean; - type?: 'r2' | 'web-crawler'; - source?: string; - [key: string]: unknown; -}>; -type AiSearchConfig = { - /** Instance ID (1-32 chars, pattern: ^[a-z0-9_]+(?:-[a-z0-9_]+)*$) */ - id: string; - type: 'r2' | 'web-crawler'; - source: string; - source_params?: object; - /** Token ID (UUID format) */ - token_id?: string; - ai_gateway_id?: string; - /** Enable query rewriting (default false) */ - rewrite_query?: boolean; - /** Enable reranking (default false) */ - reranking?: boolean; - embedding_model?: string; - ai_search_model?: string; -}; -type AiSearchInstance = { - id: string; - enable?: boolean; - type?: 'r2' | 'web-crawler'; - source?: string; - [key: string]: unknown; -}; -// AI Search Instance Service - Instance-level operations -declare abstract class AiSearchInstanceService { - /** - * Search the AI Search instance for relevant chunks. - * @param params Search request with messages and AI search options - * @returns Search response with matching chunks - */ - search(params: AiSearchSearchRequest): Promise; - /** - * Generate chat completions with AI Search context. - * @param params Chat completions request with optional streaming - * @returns Response object (if streaming) or chat completion result - */ - chatCompletions(params: AiSearchChatCompletionsRequest): Promise; - /** - * Delete this AI Search instance. - */ - delete(): Promise; -} -// AI Search Account Service - Account-level operations -declare abstract class AiSearchAccountService { - /** - * List all AI Search instances in the account. - * @returns Array of AI Search instances - */ - list(): Promise; - /** - * Get an AI Search instance by ID. - * @param name Instance ID - * @returns Instance service for performing operations - */ - get(name: string): AiSearchInstanceService; - /** - * Create a new AI Search instance. - * @param config Instance configuration - * @returns Instance service for performing operations - */ - create(config: AiSearchConfig): Promise; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancetimeorigin) */ + get timeOrigin(): number + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */ + now(): number } type AiImageClassificationInput = { - image: number[]; -}; + image: number[] +} type AiImageClassificationOutput = { - score?: number; - label?: string; -}[]; + score?: number + label?: string +}[] declare abstract class BaseAiImageClassification { - inputs: AiImageClassificationInput; - postProcessedOutputs: AiImageClassificationOutput; + inputs: AiImageClassificationInput + postProcessedOutputs: AiImageClassificationOutput } type AiImageToTextInput = { - image: number[]; - prompt?: string; - max_tokens?: number; - temperature?: number; - top_p?: number; - top_k?: number; - seed?: number; - repetition_penalty?: number; - frequency_penalty?: number; - presence_penalty?: number; - raw?: boolean; - messages?: RoleScopedChatInput[]; -}; + image: number[] + prompt?: string + max_tokens?: number + temperature?: number + top_p?: number + top_k?: number + seed?: number + repetition_penalty?: number + frequency_penalty?: number + presence_penalty?: number + raw?: boolean + messages?: RoleScopedChatInput[] +} type AiImageToTextOutput = { - description: string; -}; + description: string +} declare abstract class BaseAiImageToText { - inputs: AiImageToTextInput; - postProcessedOutputs: AiImageToTextOutput; + inputs: AiImageToTextInput + postProcessedOutputs: AiImageToTextOutput } type AiImageTextToTextInput = { - image: string; - prompt?: string; - max_tokens?: number; - temperature?: number; - ignore_eos?: boolean; - top_p?: number; - top_k?: number; - seed?: number; - repetition_penalty?: number; - frequency_penalty?: number; - presence_penalty?: number; - raw?: boolean; - messages?: RoleScopedChatInput[]; -}; + image: string + prompt?: string + max_tokens?: number + temperature?: number + ignore_eos?: boolean + top_p?: number + top_k?: number + seed?: number + repetition_penalty?: number + frequency_penalty?: number + presence_penalty?: number + raw?: boolean + messages?: RoleScopedChatInput[] +} type AiImageTextToTextOutput = { - description: string; -}; + description: string +} declare abstract class BaseAiImageTextToText { - inputs: AiImageTextToTextInput; - postProcessedOutputs: AiImageTextToTextOutput; + inputs: AiImageTextToTextInput + postProcessedOutputs: AiImageTextToTextOutput } type AiMultimodalEmbeddingsInput = { - image: string; - text: string[]; -}; + image: string + text: string[] +} type AiIMultimodalEmbeddingsOutput = { - data: number[][]; - shape: number[]; -}; + data: number[][] + shape: number[] +} declare abstract class BaseAiMultimodalEmbeddings { - inputs: AiImageTextToTextInput; - postProcessedOutputs: AiImageTextToTextOutput; + inputs: AiImageTextToTextInput + postProcessedOutputs: AiImageTextToTextOutput } type AiObjectDetectionInput = { - image: number[]; -}; + image: number[] +} type AiObjectDetectionOutput = { - score?: number; - label?: string; -}[]; + score?: number + label?: string +}[] declare abstract class BaseAiObjectDetection { - inputs: AiObjectDetectionInput; - postProcessedOutputs: AiObjectDetectionOutput; + inputs: AiObjectDetectionInput + postProcessedOutputs: AiObjectDetectionOutput } type AiSentenceSimilarityInput = { - source: string; - sentences: string[]; -}; -type AiSentenceSimilarityOutput = number[]; + source: string + sentences: string[] +} +type AiSentenceSimilarityOutput = number[] declare abstract class BaseAiSentenceSimilarity { - inputs: AiSentenceSimilarityInput; - postProcessedOutputs: AiSentenceSimilarityOutput; + inputs: AiSentenceSimilarityInput + postProcessedOutputs: AiSentenceSimilarityOutput } type AiAutomaticSpeechRecognitionInput = { - audio: number[]; -}; + audio: number[] +} type AiAutomaticSpeechRecognitionOutput = { - text?: string; - words?: { - word: string; - start: number; - end: number; - }[]; - vtt?: string; -}; + text?: string + words?: { + word: string + start: number + end: number + }[] + vtt?: string +} declare abstract class BaseAiAutomaticSpeechRecognition { - inputs: AiAutomaticSpeechRecognitionInput; - postProcessedOutputs: AiAutomaticSpeechRecognitionOutput; + inputs: AiAutomaticSpeechRecognitionInput + postProcessedOutputs: AiAutomaticSpeechRecognitionOutput } type AiSummarizationInput = { - input_text: string; - max_length?: number; -}; + input_text: string + max_length?: number +} type AiSummarizationOutput = { - summary: string; -}; + summary: string +} declare abstract class BaseAiSummarization { - inputs: AiSummarizationInput; - postProcessedOutputs: AiSummarizationOutput; + inputs: AiSummarizationInput + postProcessedOutputs: AiSummarizationOutput } type AiTextClassificationInput = { - text: string; -}; + text: string +} type AiTextClassificationOutput = { - score?: number; - label?: string; -}[]; + score?: number + label?: string +}[] declare abstract class BaseAiTextClassification { - inputs: AiTextClassificationInput; - postProcessedOutputs: AiTextClassificationOutput; + inputs: AiTextClassificationInput + postProcessedOutputs: AiTextClassificationOutput } type AiTextEmbeddingsInput = { - text: string | string[]; -}; + text: string | string[] +} type AiTextEmbeddingsOutput = { - shape: number[]; - data: number[][]; -}; + shape: number[] + data: number[][] +} declare abstract class BaseAiTextEmbeddings { - inputs: AiTextEmbeddingsInput; - postProcessedOutputs: AiTextEmbeddingsOutput; + inputs: AiTextEmbeddingsInput + postProcessedOutputs: AiTextEmbeddingsOutput } type RoleScopedChatInput = { - role: "user" | "assistant" | "system" | "tool" | (string & NonNullable); - content: string; - name?: string; -}; + role: + | 'user' + | 'assistant' + | 'system' + | 'tool' + | (string & NonNullable) + content: string + name?: string +} type AiTextGenerationToolLegacyInput = { - name: string; - description: string; - parameters?: { - type: "object" | (string & NonNullable); - properties: { - [key: string]: { - type: string; - description?: string; - }; - }; - required: string[]; - }; -}; + name: string + description: string + parameters?: { + type: 'object' | (string & NonNullable) + properties: { + [key: string]: { + type: string + description?: string + } + } + required: string[] + } +} type AiTextGenerationToolInput = { - type: "function" | (string & NonNullable); - function: { - name: string; - description: string; - parameters?: { - type: "object" | (string & NonNullable); - properties: { - [key: string]: { - type: string; - description?: string; - }; - }; - required: string[]; - }; - }; -}; + type: 'function' | (string & NonNullable) + function: { + name: string + description: string + parameters?: { + type: 'object' | (string & NonNullable) + properties: { + [key: string]: { + type: string + description?: string + } + } + required: string[] + } + } +} type AiTextGenerationFunctionsInput = { - name: string; - code: string; -}; + name: string + code: string +} type AiTextGenerationResponseFormat = { - type: string; - json_schema?: any; -}; + type: string + json_schema?: any +} type AiTextGenerationInput = { - prompt?: string; - raw?: boolean; - stream?: boolean; - max_tokens?: number; - temperature?: number; - top_p?: number; - top_k?: number; - seed?: number; - repetition_penalty?: number; - frequency_penalty?: number; - presence_penalty?: number; - messages?: RoleScopedChatInput[]; - response_format?: AiTextGenerationResponseFormat; - tools?: AiTextGenerationToolInput[] | AiTextGenerationToolLegacyInput[] | (object & NonNullable); - functions?: AiTextGenerationFunctionsInput[]; -}; + prompt?: string + raw?: boolean + stream?: boolean + max_tokens?: number + temperature?: number + top_p?: number + top_k?: number + seed?: number + repetition_penalty?: number + frequency_penalty?: number + presence_penalty?: number + messages?: RoleScopedChatInput[] + response_format?: AiTextGenerationResponseFormat + tools?: + | AiTextGenerationToolInput[] + | AiTextGenerationToolLegacyInput[] + | (object & NonNullable) + functions?: AiTextGenerationFunctionsInput[] +} type AiTextGenerationToolLegacyOutput = { - name: string; - arguments: unknown; -}; + name: string + arguments: unknown +} type AiTextGenerationToolOutput = { - id: string; - type: "function"; - function: { - name: string; - arguments: string; - }; -}; + id: string + type: 'function' + function: { + name: string + arguments: string + } +} type UsageTags = { - prompt_tokens: number; - completion_tokens: number; - total_tokens: number; -}; + prompt_tokens: number + completion_tokens: number + total_tokens: number +} type AiTextGenerationOutput = { - response?: string; - tool_calls?: AiTextGenerationToolLegacyOutput[] & AiTextGenerationToolOutput[]; - usage?: UsageTags; -}; + response?: string + tool_calls?: AiTextGenerationToolLegacyOutput[] & AiTextGenerationToolOutput[] + usage?: UsageTags +} declare abstract class BaseAiTextGeneration { - inputs: AiTextGenerationInput; - postProcessedOutputs: AiTextGenerationOutput; + inputs: AiTextGenerationInput + postProcessedOutputs: AiTextGenerationOutput } type AiTextToSpeechInput = { - prompt: string; - lang?: string; -}; -type AiTextToSpeechOutput = Uint8Array | { - audio: string; -}; + prompt: string + lang?: string +} +type AiTextToSpeechOutput = + | Uint8Array + | { + audio: string + } declare abstract class BaseAiTextToSpeech { - inputs: AiTextToSpeechInput; - postProcessedOutputs: AiTextToSpeechOutput; + inputs: AiTextToSpeechInput + postProcessedOutputs: AiTextToSpeechOutput } type AiTextToImageInput = { - prompt: string; - negative_prompt?: string; - height?: number; - width?: number; - image?: number[]; - image_b64?: string; - mask?: number[]; - num_steps?: number; - strength?: number; - guidance?: number; - seed?: number; -}; -type AiTextToImageOutput = ReadableStream; + prompt: string + negative_prompt?: string + height?: number + width?: number + image?: number[] + image_b64?: string + mask?: number[] + num_steps?: number + strength?: number + guidance?: number + seed?: number +} +type AiTextToImageOutput = ReadableStream declare abstract class BaseAiTextToImage { - inputs: AiTextToImageInput; - postProcessedOutputs: AiTextToImageOutput; + inputs: AiTextToImageInput + postProcessedOutputs: AiTextToImageOutput } type AiTranslationInput = { - text: string; - target_lang: string; - source_lang?: string; -}; + text: string + target_lang: string + source_lang?: string +} type AiTranslationOutput = { - translated_text?: string; -}; + translated_text?: string +} declare abstract class BaseAiTranslation { - inputs: AiTranslationInput; - postProcessedOutputs: AiTranslationOutput; + inputs: AiTranslationInput + postProcessedOutputs: AiTranslationOutput } -/** - * Workers AI support for OpenAI's Responses API - * Reference: https://github.com/openai/openai-node/blob/master/src/resources/responses/responses.ts - * - * It's a stripped down version from its source. - * It currently supports basic function calling, json mode and accepts images as input. - * - * It does not include types for WebSearch, CodeInterpreter, FileInputs, MCP, CustomTools. - * We plan to add those incrementally as model + platform capabilities evolve. - */ -type ResponsesInput = { - background?: boolean | null; - conversation?: string | ResponseConversationParam | null; - include?: Array | null; - input?: string | ResponseInput; - instructions?: string | null; - max_output_tokens?: number | null; - parallel_tool_calls?: boolean | null; - previous_response_id?: string | null; - prompt_cache_key?: string; - reasoning?: Reasoning | null; - safety_identifier?: string; - service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; - stream?: boolean | null; - stream_options?: StreamOptions | null; - temperature?: number | null; - text?: ResponseTextConfig; - tool_choice?: ToolChoiceOptions | ToolChoiceFunction; - tools?: Array; - top_p?: number | null; - truncation?: "auto" | "disabled" | null; -}; -type ResponsesOutput = { - id?: string; - created_at?: number; - output_text?: string; - error?: ResponseError | null; - incomplete_details?: ResponseIncompleteDetails | null; - instructions?: string | Array | null; - object?: "response"; - output?: Array; - parallel_tool_calls?: boolean; - temperature?: number | null; - tool_choice?: ToolChoiceOptions | ToolChoiceFunction; - tools?: Array; - top_p?: number | null; - max_output_tokens?: number | null; - previous_response_id?: string | null; - prompt?: ResponsePrompt | null; - reasoning?: Reasoning | null; - safety_identifier?: string; - service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; - status?: ResponseStatus; - text?: ResponseTextConfig; - truncation?: "auto" | "disabled" | null; - usage?: ResponseUsage; -}; -type EasyInputMessage = { - content: string | ResponseInputMessageContentList; - role: "user" | "assistant" | "system" | "developer"; - type?: "message"; -}; -type ResponsesFunctionTool = { - name: string; - parameters: { - [key: string]: unknown; - } | null; - strict: boolean | null; - type: "function"; - description?: string | null; -}; -type ResponseIncompleteDetails = { - reason?: "max_output_tokens" | "content_filter"; -}; -type ResponsePrompt = { - id: string; - variables?: { - [key: string]: string | ResponseInputText | ResponseInputImage; - } | null; - version?: string | null; -}; -type Reasoning = { - effort?: ReasoningEffort | null; - generate_summary?: "auto" | "concise" | "detailed" | null; - summary?: "auto" | "concise" | "detailed" | null; -}; -type ResponseContent = ResponseInputText | ResponseInputImage | ResponseOutputText | ResponseOutputRefusal | ResponseContentReasoningText; -type ResponseContentReasoningText = { - text: string; - type: "reasoning_text"; -}; -type ResponseConversationParam = { - id: string; -}; -type ResponseCreatedEvent = { - response: Response; - sequence_number: number; - type: "response.created"; -}; -type ResponseCustomToolCallOutput = { - call_id: string; - output: string | Array; - type: "custom_tool_call_output"; - id?: string; -}; -type ResponseError = { - code: "server_error" | "rate_limit_exceeded" | "invalid_prompt" | "vector_store_timeout" | "invalid_image" | "invalid_image_format" | "invalid_base64_image" | "invalid_image_url" | "image_too_large" | "image_too_small" | "image_parse_error" | "image_content_policy_violation" | "invalid_image_mode" | "image_file_too_large" | "unsupported_image_media_type" | "empty_image_file" | "failed_to_download_image" | "image_file_not_found"; - message: string; -}; -type ResponseErrorEvent = { - code: string | null; - message: string; - param: string | null; - sequence_number: number; - type: "error"; -}; -type ResponseFailedEvent = { - response: Response; - sequence_number: number; - type: "response.failed"; -}; -type ResponseFormatText = { - type: "text"; -}; -type ResponseFormatJSONObject = { - type: "json_object"; -}; -type ResponseFormatTextConfig = ResponseFormatText | ResponseFormatTextJSONSchemaConfig | ResponseFormatJSONObject; -type ResponseFormatTextJSONSchemaConfig = { - name: string; - schema: { - [key: string]: unknown; - }; - type: "json_schema"; - description?: string; - strict?: boolean | null; -}; -type ResponseFunctionCallArgumentsDeltaEvent = { - delta: string; - item_id: string; - output_index: number; - sequence_number: number; - type: "response.function_call_arguments.delta"; -}; -type ResponseFunctionCallArgumentsDoneEvent = { - arguments: string; - item_id: string; - name: string; - output_index: number; - sequence_number: number; - type: "response.function_call_arguments.done"; -}; -type ResponseFunctionCallOutputItem = ResponseInputTextContent | ResponseInputImageContent; -type ResponseFunctionCallOutputItemList = Array; -type ResponseFunctionToolCall = { - arguments: string; - call_id: string; - name: string; - type: "function_call"; - id?: string; - status?: "in_progress" | "completed" | "incomplete"; -}; -interface ResponseFunctionToolCallItem extends ResponseFunctionToolCall { - id: string; -} -type ResponseFunctionToolCallOutputItem = { - id: string; - call_id: string; - output: string | Array; - type: "function_call_output"; - status?: "in_progress" | "completed" | "incomplete"; -}; -type ResponseIncludable = "message.input_image.image_url" | "message.output_text.logprobs"; -type ResponseIncompleteEvent = { - response: Response; - sequence_number: number; - type: "response.incomplete"; -}; -type ResponseInput = Array; -type ResponseInputContent = ResponseInputText | ResponseInputImage; -type ResponseInputImage = { - detail: "low" | "high" | "auto"; - type: "input_image"; - /** - * Base64 encoded image - */ - image_url?: string | null; -}; -type ResponseInputImageContent = { - type: "input_image"; - detail?: "low" | "high" | "auto" | null; - /** - * Base64 encoded image - */ - image_url?: string | null; -}; -type ResponseInputItem = EasyInputMessage | ResponseInputItemMessage | ResponseOutputMessage | ResponseFunctionToolCall | ResponseInputItemFunctionCallOutput | ResponseReasoningItem; -type ResponseInputItemFunctionCallOutput = { - call_id: string; - output: string | ResponseFunctionCallOutputItemList; - type: "function_call_output"; - id?: string | null; - status?: "in_progress" | "completed" | "incomplete" | null; -}; -type ResponseInputItemMessage = { - content: ResponseInputMessageContentList; - role: "user" | "system" | "developer"; - status?: "in_progress" | "completed" | "incomplete"; - type?: "message"; -}; -type ResponseInputMessageContentList = Array; -type ResponseInputMessageItem = { - id: string; - content: ResponseInputMessageContentList; - role: "user" | "system" | "developer"; - status?: "in_progress" | "completed" | "incomplete"; - type?: "message"; -}; -type ResponseInputText = { - text: string; - type: "input_text"; -}; -type ResponseInputTextContent = { - text: string; - type: "input_text"; -}; -type ResponseItem = ResponseInputMessageItem | ResponseOutputMessage | ResponseFunctionToolCallItem | ResponseFunctionToolCallOutputItem; -type ResponseOutputItem = ResponseOutputMessage | ResponseFunctionToolCall | ResponseReasoningItem; -type ResponseOutputItemAddedEvent = { - item: ResponseOutputItem; - output_index: number; - sequence_number: number; - type: "response.output_item.added"; -}; -type ResponseOutputItemDoneEvent = { - item: ResponseOutputItem; - output_index: number; - sequence_number: number; - type: "response.output_item.done"; -}; -type ResponseOutputMessage = { - id: string; - content: Array; - role: "assistant"; - status: "in_progress" | "completed" | "incomplete"; - type: "message"; -}; -type ResponseOutputRefusal = { - refusal: string; - type: "refusal"; -}; -type ResponseOutputText = { - text: string; - type: "output_text"; - logprobs?: Array; -}; -type ResponseReasoningItem = { - id: string; - summary: Array; - type: "reasoning"; - content?: Array; - encrypted_content?: string | null; - status?: "in_progress" | "completed" | "incomplete"; -}; -type ResponseReasoningSummaryItem = { - text: string; - type: "summary_text"; -}; -type ResponseReasoningContentItem = { - text: string; - type: "reasoning_text"; -}; -type ResponseReasoningTextDeltaEvent = { - content_index: number; - delta: string; - item_id: string; - output_index: number; - sequence_number: number; - type: "response.reasoning_text.delta"; -}; -type ResponseReasoningTextDoneEvent = { - content_index: number; - item_id: string; - output_index: number; - sequence_number: number; - text: string; - type: "response.reasoning_text.done"; -}; -type ResponseRefusalDeltaEvent = { - content_index: number; - delta: string; - item_id: string; - output_index: number; - sequence_number: number; - type: "response.refusal.delta"; -}; -type ResponseRefusalDoneEvent = { - content_index: number; - item_id: string; - output_index: number; - refusal: string; - sequence_number: number; - type: "response.refusal.done"; -}; -type ResponseStatus = "completed" | "failed" | "in_progress" | "cancelled" | "queued" | "incomplete"; -type ResponseStreamEvent = ResponseCompletedEvent | ResponseCreatedEvent | ResponseErrorEvent | ResponseFunctionCallArgumentsDeltaEvent | ResponseFunctionCallArgumentsDoneEvent | ResponseFailedEvent | ResponseIncompleteEvent | ResponseOutputItemAddedEvent | ResponseOutputItemDoneEvent | ResponseReasoningTextDeltaEvent | ResponseReasoningTextDoneEvent | ResponseRefusalDeltaEvent | ResponseRefusalDoneEvent | ResponseTextDeltaEvent | ResponseTextDoneEvent; -type ResponseCompletedEvent = { - response: Response; - sequence_number: number; - type: "response.completed"; -}; -type ResponseTextConfig = { - format?: ResponseFormatTextConfig; - verbosity?: "low" | "medium" | "high" | null; -}; -type ResponseTextDeltaEvent = { - content_index: number; - delta: string; - item_id: string; - logprobs: Array; - output_index: number; - sequence_number: number; - type: "response.output_text.delta"; -}; -type ResponseTextDoneEvent = { - content_index: number; - item_id: string; - logprobs: Array; - output_index: number; - sequence_number: number; - text: string; - type: "response.output_text.done"; -}; -type Logprob = { - token: string; - logprob: number; - top_logprobs?: Array; -}; -type TopLogprob = { - token?: string; - logprob?: number; -}; -type ResponseUsage = { - input_tokens: number; - output_tokens: number; - total_tokens: number; -}; -type Tool = ResponsesFunctionTool; -type ToolChoiceFunction = { - name: string; - type: "function"; -}; -type ToolChoiceOptions = "none"; -type ReasoningEffort = "minimal" | "low" | "medium" | "high" | null; -type StreamOptions = { - include_obfuscation?: boolean; -}; -type Ai_Cf_Baai_Bge_Base_En_V1_5_Input = { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: "mean" | "cls"; -} | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { - text: string | string[]; +type Ai_Cf_Baai_Bge_Base_En_V1_5_Input = + | { + text: string | string[] + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: 'mean' | 'cls' + } + | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { + text: string | string[] /** * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. */ - pooling?: "mean" | "cls"; - }[]; -}; -type Ai_Cf_Baai_Bge_Base_En_V1_5_Output = { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: "mean" | "cls"; -} | Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse; -interface Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; + pooling?: 'mean' | 'cls' + }[] + } +type Ai_Cf_Baai_Bge_Base_En_V1_5_Output = + | { + shape?: number[] + /** + * Embeddings of the requested text values + */ + data?: number[][] + /** + * The pooling method used in the embedding process. + */ + pooling?: 'mean' | 'cls' + } + | AsyncResponse +interface AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string } declare abstract class Base_Ai_Cf_Baai_Bge_Base_En_V1_5 { - inputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Output; + inputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Input + postProcessedOutputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Output } -type Ai_Cf_Openai_Whisper_Input = string | { - /** - * An array of integers that represent the audio data constrained to 8-bit unsigned integer values - */ - audio: number[]; -}; +type Ai_Cf_Openai_Whisper_Input = + | string + | { + /** + * An array of integers that represent the audio data constrained to 8-bit unsigned integer values + */ + audio: number[] + } interface Ai_Cf_Openai_Whisper_Output { + /** + * The transcription + */ + text: string + word_count?: number + words?: { + word?: string /** - * The transcription + * The second this word begins in the recording */ - text: string; - word_count?: number; - words?: { - word?: string; - /** - * The second this word begins in the recording - */ - start?: number; - /** - * The ending second when the word completes - */ - end?: number; - }[]; - vtt?: string; + start?: number + /** + * The ending second when the word completes + */ + end?: number + }[] + vtt?: string } declare abstract class Base_Ai_Cf_Openai_Whisper { - inputs: Ai_Cf_Openai_Whisper_Input; - postProcessedOutputs: Ai_Cf_Openai_Whisper_Output; + inputs: Ai_Cf_Openai_Whisper_Input + postProcessedOutputs: Ai_Cf_Openai_Whisper_Output } -type Ai_Cf_Meta_M2M100_1_2B_Input = { - /** - * The text to be translated - */ - text: string; - /** - * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified - */ - source_lang?: string; - /** - * The language code to translate the text into (e.g., 'es' for Spanish) - */ - target_lang: string; -} | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { +type Ai_Cf_Meta_M2M100_1_2B_Input = + | { + /** + * The text to be translated + */ + text: string + /** + * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified + */ + source_lang?: string + /** + * The language code to translate the text into (e.g., 'es' for Spanish) + */ + target_lang: string + } + | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { /** * The text to be translated */ - text: string; + text: string /** * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified */ - source_lang?: string; + source_lang?: string /** * The language code to translate the text into (e.g., 'es' for Spanish) */ - target_lang: string; - }[]; -}; -type Ai_Cf_Meta_M2M100_1_2B_Output = { - /** - * The translated text in the target language - */ - translated_text?: string; -} | Ai_Cf_Meta_M2M100_1_2B_AsyncResponse; -interface Ai_Cf_Meta_M2M100_1_2B_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} + target_lang: string + }[] + } +type Ai_Cf_Meta_M2M100_1_2B_Output = + | { + /** + * The translated text in the target language + */ + translated_text?: string + } + | AsyncResponse declare abstract class Base_Ai_Cf_Meta_M2M100_1_2B { - inputs: Ai_Cf_Meta_M2M100_1_2B_Input; - postProcessedOutputs: Ai_Cf_Meta_M2M100_1_2B_Output; + inputs: Ai_Cf_Meta_M2M100_1_2B_Input + postProcessedOutputs: Ai_Cf_Meta_M2M100_1_2B_Output } -type Ai_Cf_Baai_Bge_Small_En_V1_5_Input = { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: "mean" | "cls"; -} | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { - text: string | string[]; +type Ai_Cf_Baai_Bge_Small_En_V1_5_Input = + | { + text: string | string[] + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: 'mean' | 'cls' + } + | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { + text: string | string[] /** * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. */ - pooling?: "mean" | "cls"; - }[]; -}; -type Ai_Cf_Baai_Bge_Small_En_V1_5_Output = { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: "mean" | "cls"; -} | Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse; -interface Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} + pooling?: 'mean' | 'cls' + }[] + } +type Ai_Cf_Baai_Bge_Small_En_V1_5_Output = + | { + shape?: number[] + /** + * Embeddings of the requested text values + */ + data?: number[][] + /** + * The pooling method used in the embedding process. + */ + pooling?: 'mean' | 'cls' + } + | AsyncResponse declare abstract class Base_Ai_Cf_Baai_Bge_Small_En_V1_5 { - inputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Output; + inputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Input + postProcessedOutputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Output } -type Ai_Cf_Baai_Bge_Large_En_V1_5_Input = { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: "mean" | "cls"; -} | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { - text: string | string[]; +type Ai_Cf_Baai_Bge_Large_En_V1_5_Input = + | { + text: string | string[] + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: 'mean' | 'cls' + } + | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { + text: string | string[] /** * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. */ - pooling?: "mean" | "cls"; - }[]; -}; -type Ai_Cf_Baai_Bge_Large_En_V1_5_Output = { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: "mean" | "cls"; -} | Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse; -interface Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} + pooling?: 'mean' | 'cls' + }[] + } +type Ai_Cf_Baai_Bge_Large_En_V1_5_Output = + | { + shape?: number[] + /** + * Embeddings of the requested text values + */ + data?: number[][] + /** + * The pooling method used in the embedding process. + */ + pooling?: 'mean' | 'cls' + } + | AsyncResponse declare abstract class Base_Ai_Cf_Baai_Bge_Large_En_V1_5 { - inputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Output; + inputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Input + postProcessedOutputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Output } -type Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input = string | { - /** - * The input text prompt for the model to generate a response. - */ - prompt?: string; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; - image: number[] | (string & NonNullable); - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; -}; +type Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input = + | string + | { + /** + * The input text prompt for the model to generate a response. + */ + prompt?: string + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean + /** + * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number + /** + * Random seed for reproducibility of the generation. + */ + seed?: number + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number + image: number[] | (string & NonNullable) + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number + } interface Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output { - description?: string; + description?: string } declare abstract class Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M { - inputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input; - postProcessedOutputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output; + inputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input + postProcessedOutputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output } -type Ai_Cf_Openai_Whisper_Tiny_En_Input = string | { - /** - * An array of integers that represent the audio data constrained to 8-bit unsigned integer values - */ - audio: number[]; -}; +type Ai_Cf_Openai_Whisper_Tiny_En_Input = + | string + | { + /** + * An array of integers that represent the audio data constrained to 8-bit unsigned integer values + */ + audio: number[] + } interface Ai_Cf_Openai_Whisper_Tiny_En_Output { + /** + * The transcription + */ + text: string + word_count?: number + words?: { + word?: string /** - * The transcription + * The second this word begins in the recording */ - text: string; - word_count?: number; - words?: { - word?: string; - /** - * The second this word begins in the recording - */ - start?: number; - /** - * The ending second when the word completes - */ - end?: number; - }[]; - vtt?: string; + start?: number + /** + * The ending second when the word completes + */ + end?: number + }[] + vtt?: string } declare abstract class Base_Ai_Cf_Openai_Whisper_Tiny_En { - inputs: Ai_Cf_Openai_Whisper_Tiny_En_Input; - postProcessedOutputs: Ai_Cf_Openai_Whisper_Tiny_En_Output; + inputs: Ai_Cf_Openai_Whisper_Tiny_En_Input + postProcessedOutputs: Ai_Cf_Openai_Whisper_Tiny_En_Output } interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input { - /** - * Base64 encoded value of the audio data. - */ - audio: string; - /** - * Supported tasks are 'translate' or 'transcribe'. - */ - task?: string; + /** + * Base64 encoded value of the audio data. + */ + audio: string + /** + * Supported tasks are 'translate' or 'transcribe'. + */ + task?: string + /** + * The language of the audio being transcribed or translated. + */ + language?: string + /** + * Preprocess the audio with a voice activity detection model. + */ + vad_filter?: boolean + /** + * A text prompt to help provide context to the model on the contents of the audio. + */ + initial_prompt?: string + /** + * The prefix it appended the the beginning of the output of the transcription and can guide the transcription result. + */ + prefix?: string +} +interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output { + transcription_info?: { /** * The language of the audio being transcribed or translated. */ - language?: string; + language?: string /** - * Preprocess the audio with a voice activity detection model. + * The confidence level or probability of the detected language being accurate, represented as a decimal between 0 and 1. */ - vad_filter?: boolean; + language_probability?: number /** - * A text prompt to help provide context to the model on the contents of the audio. + * The total duration of the original audio file, in seconds. */ - initial_prompt?: string; + duration?: number /** - * The prefix it appended the the beginning of the output of the transcription and can guide the transcription result. + * The duration of the audio after applying Voice Activity Detection (VAD) to remove silent or irrelevant sections, in seconds. */ - prefix?: string; -} -interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output { - transcription_info?: { - /** - * The language of the audio being transcribed or translated. - */ - language?: string; - /** - * The confidence level or probability of the detected language being accurate, represented as a decimal between 0 and 1. - */ - language_probability?: number; - /** - * The total duration of the original audio file, in seconds. - */ - duration?: number; - /** - * The duration of the audio after applying Voice Activity Detection (VAD) to remove silent or irrelevant sections, in seconds. - */ - duration_after_vad?: number; - }; + duration_after_vad?: number + } + /** + * The complete transcription of the audio. + */ + text: string + /** + * The total number of words in the transcription. + */ + word_count?: number + segments?: { /** - * The complete transcription of the audio. + * The starting time of the segment within the audio, in seconds. */ - text: string; + start?: number /** - * The total number of words in the transcription. + * The ending time of the segment within the audio, in seconds. */ - word_count?: number; - segments?: { - /** - * The starting time of the segment within the audio, in seconds. - */ - start?: number; - /** - * The ending time of the segment within the audio, in seconds. - */ - end?: number; - /** - * The transcription of the segment. - */ - text?: string; - /** - * The temperature used in the decoding process, controlling randomness in predictions. Lower values result in more deterministic outputs. - */ - temperature?: number; - /** - * The average log probability of the predictions for the words in this segment, indicating overall confidence. - */ - avg_logprob?: number; - /** - * The compression ratio of the input to the output, measuring how much the text was compressed during the transcription process. - */ - compression_ratio?: number; - /** - * The probability that the segment contains no speech, represented as a decimal between 0 and 1. - */ - no_speech_prob?: number; - words?: { - /** - * The individual word transcribed from the audio. - */ - word?: string; - /** - * The starting time of the word within the audio, in seconds. - */ - start?: number; - /** - * The ending time of the word within the audio, in seconds. - */ - end?: number; - }[]; - }[]; + end?: number /** - * The transcription in WebVTT format, which includes timing and text information for use in subtitles. + * The transcription of the segment. */ - vtt?: string; + text?: string + /** + * The temperature used in the decoding process, controlling randomness in predictions. Lower values result in more deterministic outputs. + */ + temperature?: number + /** + * The average log probability of the predictions for the words in this segment, indicating overall confidence. + */ + avg_logprob?: number + /** + * The compression ratio of the input to the output, measuring how much the text was compressed during the transcription process. + */ + compression_ratio?: number + /** + * The probability that the segment contains no speech, represented as a decimal between 0 and 1. + */ + no_speech_prob?: number + words?: { + /** + * The individual word transcribed from the audio. + */ + word?: string + /** + * The starting time of the word within the audio, in seconds. + */ + start?: number + /** + * The ending time of the word within the audio, in seconds. + */ + end?: number + }[] + }[] + /** + * The transcription in WebVTT format, which includes timing and text information for use in subtitles. + */ + vtt?: string } declare abstract class Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo { - inputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input; - postProcessedOutputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output; + inputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input + postProcessedOutputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output } -type Ai_Cf_Baai_Bge_M3_Input = Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts | Ai_Cf_Baai_Bge_M3_Input_Embedding | { +type Ai_Cf_Baai_Bge_M3_Input = + | BGEM3InputQueryAndContexts + | BGEM3InputEmbedding + | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: (BGEM3InputQueryAndContexts1 | BGEM3InputEmbedding1)[] + } +interface BGEM3InputQueryAndContexts { + /** + * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts + */ + query?: string + /** + * List of provided contexts. Note that the index in this array is important, as the response will refer to it. + */ + contexts: { /** - * Batch of the embeddings requests to run using async-queue + * One of the provided context content */ - requests: (Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 | Ai_Cf_Baai_Bge_M3_Input_Embedding_1)[]; -}; -interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts { - /** - * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts - */ - query?: string; - /** - * List of provided contexts. Note that the index in this array is important, as the response will refer to it. - */ - contexts: { - /** - * One of the provided context content - */ - text?: string; - }[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; + text?: string + }[] + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean } -interface Ai_Cf_Baai_Bge_M3_Input_Embedding { - text: string | string[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; +interface BGEM3InputEmbedding { + text: string | string[] + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean } -interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 { +interface BGEM3InputQueryAndContexts1 { + /** + * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts + */ + query?: string + /** + * List of provided contexts. Note that the index in this array is important, as the response will refer to it. + */ + contexts: { /** - * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts + * One of the provided context content */ - query?: string; - /** - * List of provided contexts. Note that the index in this array is important, as the response will refer to it. - */ - contexts: { - /** - * One of the provided context content - */ - text?: string; - }[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; + text?: string + }[] + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean } -interface Ai_Cf_Baai_Bge_M3_Input_Embedding_1 { - text: string | string[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; +interface BGEM3InputEmbedding1 { + text: string | string[] + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean } -type Ai_Cf_Baai_Bge_M3_Output = Ai_Cf_Baai_Bge_M3_Ouput_Query | Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts | Ai_Cf_Baai_Bge_M3_Ouput_Embedding | Ai_Cf_Baai_Bge_M3_AsyncResponse; -interface Ai_Cf_Baai_Bge_M3_Ouput_Query { - response?: { - /** - * Index of the context in the request - */ - id?: number; - /** - * Score of the context under the index. - */ - score?: number; - }[]; +type Ai_Cf_Baai_Bge_M3_Output = + | BGEM3OuputQuery + | BGEM3OutputEmbeddingForContexts + | BGEM3OuputEmbedding + | AsyncResponse +interface BGEM3OuputQuery { + response?: { + /** + * Index of the context in the request + */ + id?: number + /** + * Score of the context under the index. + */ + score?: number + }[] } -interface Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts { - response?: number[][]; - shape?: number[]; - /** - * The pooling method used in the embedding process. - */ - pooling?: "mean" | "cls"; +interface BGEM3OutputEmbeddingForContexts { + response?: number[][] + shape?: number[] + /** + * The pooling method used in the embedding process. + */ + pooling?: 'mean' | 'cls' } -interface Ai_Cf_Baai_Bge_M3_Ouput_Embedding { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: "mean" | "cls"; -} -interface Ai_Cf_Baai_Bge_M3_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; +interface BGEM3OuputEmbedding { + shape?: number[] + /** + * Embeddings of the requested text values + */ + data?: number[][] + /** + * The pooling method used in the embedding process. + */ + pooling?: 'mean' | 'cls' } declare abstract class Base_Ai_Cf_Baai_Bge_M3 { - inputs: Ai_Cf_Baai_Bge_M3_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output; + inputs: Ai_Cf_Baai_Bge_M3_Input + postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output } interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input { - /** - * A text description of the image you want to generate. - */ - prompt: string; - /** - * The number of diffusion steps; higher values can improve quality but take longer. - */ - steps?: number; + /** + * A text description of the image you want to generate. + */ + prompt: string + /** + * The number of diffusion steps; higher values can improve quality but take longer. + */ + steps?: number } interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output { - /** - * The generated image in Base64 format. - */ - image?: string; + /** + * The generated image in Base64 format. + */ + image?: string } declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell { - inputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input; - postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output; + inputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input + postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output } -type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt | Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages; -interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - image?: number[] | (string & NonNullable); - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; +type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = Prompt | Messages +interface Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string + image?: number[] | (string & NonNullable) + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number + /** + * Random seed for reproducibility of the generation. + */ + seed?: number + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string } -interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages { +interface Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { /** - * An array of message objects representing the conversation history. + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: string | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - image?: number[] | (string & NonNullable); - functions?: { - name: string; - code: string; - }[]; + role?: string /** - * A list of tools available for the assistant to use. + * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 */ - tools?: ({ + tool_call_id?: string + content?: + | string + | { + /** + * Type of the content provided + */ + type?: string + text?: string + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string + } + }[] + | { + /** + * Type of the content provided + */ + type?: string + text?: string + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string + } + } + }[] + image?: number[] | (string & NonNullable) + functions?: { + name: string + code: string + }[] + /** + * A list of tools available for the assistant to use. + */ + tools?: ( + | { /** * The name of the tool. More descriptive the better. */ - name: string; + name: string /** * A brief description of what the tool does. */ - description: string; + description: string /** * Schema defining the parameters accepted by the tool. */ parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { + /** + * The type of the parameters object (usually 'object'). + */ + type: string + /** + * List of required parameter names. + */ + required?: string[] + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string + /** + * A description of the expected parameter. + */ + description: string + } + } + } + } + | { /** * Specifies the type of tool (e.g., 'function'). */ - type: string; + type: string /** * Details of the function tool. */ function: { + /** + * The name of the function. + */ + name: string + /** + * A brief description of what the function does. + */ + description: string + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { /** - * The name of the function. + * The type of the parameters object (usually 'object'). */ - name: string; + type: string /** - * A brief description of what the function does. + * List of required parameter names. */ - description: string; + required?: string[] /** - * Schema defining the parameters accepted by the function. + * Definitions of each parameter. */ - parameters: { + properties: { + [k: string]: { /** - * The type of the parameters object (usually 'object'). + * The data type of the parameter. */ - type: string; + type: string /** - * List of required parameter names. + * A description of the expected parameter. */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - /** - * If true, the response will be streamed back incrementally. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; + description: string + } + } + } + } + } + )[] + /** + * If true, the response will be streamed back incrementally. + */ + stream?: boolean + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number + /** + * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number + /** + * Random seed for reproducibility of the generation. + */ + seed?: number + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number } type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output = { + /** + * The generated text response from the model + */ + response?: string + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { /** - * The generated text response from the model + * The arguments passed to be passed to the tool call request */ - response?: string; + arguments?: object /** - * An array of tool calls requests made during the response generation + * The name of the tool to be called */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -}; + name?: string + }[] +} declare abstract class Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct { - inputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output; + inputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input + postProcessedOutputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output } -type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch; -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; +type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = + | Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt + | Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages + | AsyncBatch +interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string + response_format?: JSONMode + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number + /** + * Random seed for reproducibility of the generation. + */ + seed?: number + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number } -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode { - type?: "json_object" | "json_schema"; - json_schema?: unknown; +interface JSONMode { + type?: 'json_object' | 'json_schema' + json_schema?: unknown } -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { +interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { /** - * An array of message objects representing the conversation history. + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - /** - * The content of the message as a string. - */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; + role: string /** - * A list of tools available for the assistant to use. + * The content of the message as a string. */ - tools?: ({ + content: string + }[] + functions?: { + name: string + code: string + }[] + /** + * A list of tools available for the assistant to use. + */ + tools?: ( + | { /** * The name of the tool. More descriptive the better. */ - name: string; + name: string /** * A brief description of what the tool does. */ - description: string; + description: string /** * Schema defining the parameters accepted by the tool. */ parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { + /** + * The type of the parameters object (usually 'object'). + */ + type: string + /** + * List of required parameter names. + */ + required?: string[] + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string + /** + * A description of the expected parameter. + */ + description: string + } + } + } + } + | { /** * Specifies the type of tool (e.g., 'function'). */ - type: string; + type: string /** * Details of the function tool. */ function: { + /** + * The name of the function. + */ + name: string + /** + * A brief description of what the function does. + */ + description: string + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { /** - * The name of the function. + * The type of the parameters object (usually 'object'). */ - name: string; + type: string /** - * A brief description of what the function does. + * List of required parameter names. */ - description: string; + required?: string[] /** - * Schema defining the parameters accepted by the function. + * Definitions of each parameter. */ - parameters: { + properties: { + [k: string]: { /** - * The type of the parameters object (usually 'object'). + * The data type of the parameter. */ - type: string; + type: string /** - * List of required parameter names. + * A description of the expected parameter. */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1; + description: string + } + } + } + } + } + )[] + response_format?: JSONMode + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number + /** + * Random seed for reproducibility of the generation. + */ + seed?: number + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number +} +interface AsyncBatch { + requests?: { /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + * User-supplied reference. This field will be present in the response as well it can be used to reference the request and response. It's NOT validated to be unique. */ - raw?: boolean; + external_reference?: string + /** + * Prompt for the text generation model + */ + prompt?: string /** * If true, the response will be streamed back incrementally using SSE, Server Sent Events. */ - stream?: boolean; + stream?: boolean /** * The maximum number of tokens to generate in the response. */ - max_tokens?: number; + max_tokens?: number /** * Controls the randomness of the output; higher values produce more random results. */ - temperature?: number; + temperature?: number /** * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; + top_p?: number /** * Random seed for reproducibility of the generation. */ - seed?: number; + seed?: number /** * Penalty for repeated tokens; higher values discourage repetition. */ - repetition_penalty?: number; + repetition_penalty?: number /** * Decreases the likelihood of the model repeating the same lines verbatim. */ - frequency_penalty?: number; + frequency_penalty?: number /** * Increases the likelihood of the model introducing new topics. */ - presence_penalty?: number; + presence_penalty?: number + response_format?: JSONMode + }[] } -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch { - requests?: { - /** - * User-supplied reference. This field will be present in the response as well it can be used to reference the request and response. It's NOT validated to be unique. - */ - external_reference?: string; - /** - * Prompt for the text generation model - */ - prompt?: string; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; - response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2; - }[]; -} -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { +type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = + | { + /** + * The generated text response from the model + */ + response: string + /** + * Usage statistics for the inference request + */ + usage?: { /** * Total number of tokens in input */ - prompt_tokens?: number; + prompt_tokens?: number /** * Total number of tokens in output */ - completion_tokens?: number; + completion_tokens?: number /** * Total number of input and output tokens */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { + total_tokens?: number + } + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { /** * The arguments passed to be passed to the tool call request */ - arguments?: object; + arguments?: object /** * The name of the tool to be called */ - name?: string; - }[]; -} | string | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse; -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} + name?: string + }[] + } + | string + | AsyncResponse declare abstract class Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast { - inputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output; + inputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input + postProcessedOutputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output } interface Ai_Cf_Meta_Llama_Guard_3_8B_Input { + /** + * An array of message objects representing the conversation history. + */ + messages: { /** - * An array of message objects representing the conversation history. + * The role of the message sender must alternate between 'user' and 'assistant'. */ - messages: { - /** - * The role of the message sender must alternate between 'user' and 'assistant'. - */ - role: "user" | "assistant"; - /** - * The content of the message as a string. - */ - content: string; - }[]; + role: 'user' | 'assistant' /** - * The maximum number of tokens to generate in the response. + * The content of the message as a string. */ - max_tokens?: number; + content: string + }[] + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number + /** + * Dictate the output format of the generated response. + */ + response_format?: { /** - * Controls the randomness of the output; higher values produce more random results. + * Set to json_object to process and output generated text as JSON. */ - temperature?: number; - /** - * Dictate the output format of the generated response. - */ - response_format?: { - /** - * Set to json_object to process and output generated text as JSON. - */ - type?: string; - }; + type?: string + } } interface Ai_Cf_Meta_Llama_Guard_3_8B_Output { - response?: string | { + response?: + | string + | { /** * Whether the conversation is safe or not. */ - safe?: boolean; + safe?: boolean /** * A list of what hazard categories predicted for the conversation, if the conversation is deemed unsafe. */ - categories?: string[]; - }; + categories?: string[] + } + /** + * Usage statistics for the inference request + */ + usage?: { /** - * Usage statistics for the inference request + * Total number of tokens in input */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; + prompt_tokens?: number + /** + * Total number of tokens in output + */ + completion_tokens?: number + /** + * Total number of input and output tokens + */ + total_tokens?: number + } } declare abstract class Base_Ai_Cf_Meta_Llama_Guard_3_8B { - inputs: Ai_Cf_Meta_Llama_Guard_3_8B_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_Guard_3_8B_Output; + inputs: Ai_Cf_Meta_Llama_Guard_3_8B_Input + postProcessedOutputs: Ai_Cf_Meta_Llama_Guard_3_8B_Output } interface Ai_Cf_Baai_Bge_Reranker_Base_Input { + /** + * A query you wish to perform against the provided contexts. + */ + /** + * Number of returned results starting with the best score. + */ + top_k?: number + /** + * List of provided contexts. Note that the index in this array is important, as the response will refer to it. + */ + contexts: { /** - * A query you wish to perform against the provided contexts. + * One of the provided context content */ - /** - * Number of returned results starting with the best score. - */ - top_k?: number; - /** - * List of provided contexts. Note that the index in this array is important, as the response will refer to it. - */ - contexts: { - /** - * One of the provided context content - */ - text?: string; - }[]; + text?: string + }[] } interface Ai_Cf_Baai_Bge_Reranker_Base_Output { - response?: { - /** - * Index of the context in the request - */ - id?: number; - /** - * Score of the context under the index. - */ - score?: number; - }[]; + response?: { + /** + * Index of the context in the request + */ + id?: number + /** + * Score of the context under the index. + */ + score?: number + }[] } declare abstract class Base_Ai_Cf_Baai_Bge_Reranker_Base { - inputs: Ai_Cf_Baai_Bge_Reranker_Base_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Reranker_Base_Output; + inputs: Ai_Cf_Baai_Bge_Reranker_Base_Input + postProcessedOutputs: Ai_Cf_Baai_Bge_Reranker_Base_Output } -type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt | Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages; -interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; +type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = + | Qwen2_5_Coder_32B_Instruct_Prompt + | Qwen2_5_Coder_32B_Instruct_Messages +interface Qwen2_5_Coder_32B_Instruct_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string + response_format?: JSONMode + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number + /** + * Random seed for reproducibility of the generation. + */ + seed?: number + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number } -interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages { +interface Qwen2_5_Coder_32B_Instruct_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { /** - * An array of message objects representing the conversation history. + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - /** - * The content of the message as a string. - */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; + role: string /** - * A list of tools available for the assistant to use. + * The content of the message as a string. */ - tools?: ({ + content: string + }[] + functions?: { + name: string + code: string + }[] + /** + * A list of tools available for the assistant to use. + */ + tools?: ( + | { /** * The name of the tool. More descriptive the better. */ - name: string; + name: string /** * A brief description of what the tool does. */ - description: string; + description: string /** * Schema defining the parameters accepted by the tool. */ parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { + /** + * The type of the parameters object (usually 'object'). + */ + type: string + /** + * List of required parameter names. + */ + required?: string[] + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string + /** + * A description of the expected parameter. + */ + description: string + } + } + } + } + | { /** * Specifies the type of tool (e.g., 'function'). */ - type: string; + type: string /** * Details of the function tool. */ function: { + /** + * The name of the function. + */ + name: string + /** + * A brief description of what the function does. + */ + description: string + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { /** - * The name of the function. + * The type of the parameters object (usually 'object'). */ - name: string; + type: string /** - * A brief description of what the function does. + * List of required parameter names. */ - description: string; + required?: string[] /** - * Schema defining the parameters accepted by the function. + * Definitions of each parameter. */ - parameters: { + properties: { + [k: string]: { /** - * The type of the parameters object (usually 'object'). + * The data type of the parameter. */ - type: string; + type: string /** - * List of required parameter names. + * A description of the expected parameter. */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; + description: string + } + } + } + } + } + )[] + response_format?: JSONMode + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number + /** + * Random seed for reproducibility of the generation. + */ + seed?: number + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number } type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = { + /** + * The generated text response from the model + */ + response: string + /** + * Usage statistics for the inference request + */ + usage?: { /** - * The generated text response from the model + * Total number of tokens in input */ - response: string; + prompt_tokens?: number /** - * Usage statistics for the inference request + * Total number of tokens in output */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; + completion_tokens?: number /** - * An array of tool calls requests made during the response generation + * Total number of input and output tokens */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -}; + total_tokens?: number + } + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object + /** + * The name of the tool to be called + */ + name?: string + }[] +} declare abstract class Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct { - inputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input; - postProcessedOutputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output; + inputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input + postProcessedOutputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output } -type Ai_Cf_Qwen_Qwq_32B_Input = Ai_Cf_Qwen_Qwq_32B_Prompt | Ai_Cf_Qwen_Qwq_32B_Messages; -interface Ai_Cf_Qwen_Qwq_32B_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; +type Ai_Cf_Qwen_Qwq_32B_Input = Qwen_Qwq_32B_Prompt | Qwen_Qwq_32B_Messages +interface Qwen_Qwq_32B_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number + /** + * Random seed for reproducibility of the generation. + */ + seed?: number + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number } -interface Ai_Cf_Qwen_Qwq_32B_Messages { +interface Qwen_Qwq_32B_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { /** - * An array of message objects representing the conversation history. + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: string | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - functions?: { - name: string; - code: string; - }[]; + role?: string /** - * A list of tools available for the assistant to use. + * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 */ - tools?: ({ + tool_call_id?: string + content?: + | string + | { + /** + * Type of the content provided + */ + type?: string + text?: string + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string + } + }[] + | { + /** + * Type of the content provided + */ + type?: string + text?: string + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string + } + } + }[] + functions?: { + name: string + code: string + }[] + /** + * A list of tools available for the assistant to use. + */ + tools?: ( + | { /** * The name of the tool. More descriptive the better. */ - name: string; + name: string /** * A brief description of what the tool does. */ - description: string; + description: string /** * Schema defining the parameters accepted by the tool. */ parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { + /** + * The type of the parameters object (usually 'object'). + */ + type: string + /** + * List of required parameter names. + */ + required?: string[] + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string + /** + * A description of the expected parameter. + */ + description: string + } + } + } + } + | { /** * Specifies the type of tool (e.g., 'function'). */ - type: string; + type: string /** * Details of the function tool. */ function: { + /** + * The name of the function. + */ + name: string + /** + * A brief description of what the function does. + */ + description: string + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { /** - * The name of the function. + * The type of the parameters object (usually 'object'). */ - name: string; + type: string /** - * A brief description of what the function does. + * List of required parameter names. */ - description: string; + required?: string[] /** - * Schema defining the parameters accepted by the function. + * Definitions of each parameter. */ - parameters: { + properties: { + [k: string]: { /** - * The type of the parameters object (usually 'object'). + * The data type of the parameter. */ - type: string; + type: string /** - * List of required parameter names. + * A description of the expected parameter. */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; + description: string + } + } + } + } + } + )[] + /** + * JSON schema that should be fufilled for the response. + */ + guided_json?: object + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number + /** + * Random seed for reproducibility of the generation. + */ + seed?: number + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number } type Ai_Cf_Qwen_Qwq_32B_Output = { + /** + * The generated text response from the model + */ + response: string + /** + * Usage statistics for the inference request + */ + usage?: { /** - * The generated text response from the model + * Total number of tokens in input */ - response: string; + prompt_tokens?: number /** - * Usage statistics for the inference request + * Total number of tokens in output */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; + completion_tokens?: number /** - * An array of tool calls requests made during the response generation + * Total number of input and output tokens */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -}; + total_tokens?: number + } + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object + /** + * The name of the tool to be called + */ + name?: string + }[] +} declare abstract class Base_Ai_Cf_Qwen_Qwq_32B { - inputs: Ai_Cf_Qwen_Qwq_32B_Input; - postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output; + inputs: Ai_Cf_Qwen_Qwq_32B_Input + postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output } -type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt | Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages; -interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; +type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = + | Mistral_Small_3_1_24B_Instruct_Prompt + | Mistral_Small_3_1_24B_Instruct_Messages +interface Mistral_Small_3_1_24B_Instruct_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number + /** + * Random seed for reproducibility of the generation. + */ + seed?: number + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number } -interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages { +interface Mistral_Small_3_1_24B_Instruct_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { /** - * An array of message objects representing the conversation history. + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: string | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - functions?: { - name: string; - code: string; - }[]; + role?: string /** - * A list of tools available for the assistant to use. + * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 */ - tools?: ({ + tool_call_id?: string + content?: + | string + | { + /** + * Type of the content provided + */ + type?: string + text?: string + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string + } + }[] + | { + /** + * Type of the content provided + */ + type?: string + text?: string + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string + } + } + }[] + functions?: { + name: string + code: string + }[] + /** + * A list of tools available for the assistant to use. + */ + tools?: ( + | { /** * The name of the tool. More descriptive the better. */ - name: string; + name: string /** * A brief description of what the tool does. */ - description: string; + description: string /** * Schema defining the parameters accepted by the tool. */ parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { + /** + * The type of the parameters object (usually 'object'). + */ + type: string + /** + * List of required parameter names. + */ + required?: string[] + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string + /** + * A description of the expected parameter. + */ + description: string + } + } + } + } + | { /** * Specifies the type of tool (e.g., 'function'). */ - type: string; + type: string /** * Details of the function tool. */ function: { + /** + * The name of the function. + */ + name: string + /** + * A brief description of what the function does. + */ + description: string + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { /** - * The name of the function. + * The type of the parameters object (usually 'object'). */ - name: string; + type: string /** - * A brief description of what the function does. + * List of required parameter names. */ - description: string; + required?: string[] /** - * Schema defining the parameters accepted by the function. + * Definitions of each parameter. */ - parameters: { + properties: { + [k: string]: { /** - * The type of the parameters object (usually 'object'). + * The data type of the parameter. */ - type: string; + type: string /** - * List of required parameter names. + * A description of the expected parameter. */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; + description: string + } + } + } + } + } + )[] + /** + * JSON schema that should be fufilled for the response. + */ + guided_json?: object + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number + /** + * Random seed for reproducibility of the generation. + */ + seed?: number + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number } type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output = { + /** + * The generated text response from the model + */ + response: string + /** + * Usage statistics for the inference request + */ + usage?: { /** - * The generated text response from the model + * Total number of tokens in input */ - response: string; + prompt_tokens?: number /** - * Usage statistics for the inference request + * Total number of tokens in output */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; + completion_tokens?: number /** - * An array of tool calls requests made during the response generation + * Total number of input and output tokens */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -}; + total_tokens?: number + } + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object + /** + * The name of the tool to be called + */ + name?: string + }[] +} declare abstract class Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct { - inputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input; - postProcessedOutputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output; + inputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input + postProcessedOutputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output } -type Ai_Cf_Google_Gemma_3_12B_It_Input = Ai_Cf_Google_Gemma_3_12B_It_Prompt | Ai_Cf_Google_Gemma_3_12B_It_Messages; -interface Ai_Cf_Google_Gemma_3_12B_It_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; +type Ai_Cf_Google_Gemma_3_12B_It_Input = + | Google_Gemma_3_12B_It_Prompt + | Google_Gemma_3_12B_It_Messages +interface Google_Gemma_3_12B_It_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string + /** + * JSON schema that should be fufilled for the response. + */ + guided_json?: object + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number + /** + * Random seed for reproducibility of the generation. + */ + seed?: number + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number } -interface Ai_Cf_Google_Gemma_3_12B_It_Messages { +interface Google_Gemma_3_12B_It_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { /** - * An array of message objects representing the conversation history. + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - content?: string | { + role?: string + content?: + | string + | { + /** + * Type of the content provided + */ + type?: string + text?: string + image_url?: { /** - * Type of the content provided + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[]; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ + url?: string + } + }[] + | { + /** + * Type of the content provided + */ + type?: string + text?: string + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string + } + } + }[] + functions?: { + name: string + code: string + }[] + /** + * A list of tools available for the assistant to use. + */ + tools?: ( + | { /** * The name of the tool. More descriptive the better. */ - name: string; + name: string /** * A brief description of what the tool does. */ - description: string; + description: string /** * Schema defining the parameters accepted by the tool. */ parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { + /** + * The type of the parameters object (usually 'object'). + */ + type: string + /** + * List of required parameter names. + */ + required?: string[] + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string + /** + * A description of the expected parameter. + */ + description: string + } + } + } + } + | { /** * Specifies the type of tool (e.g., 'function'). */ - type: string; + type: string /** * Details of the function tool. */ function: { + /** + * The name of the function. + */ + name: string + /** + * A brief description of what the function does. + */ + description: string + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { /** - * The name of the function. + * The type of the parameters object (usually 'object'). */ - name: string; + type: string /** - * A brief description of what the function does. + * List of required parameter names. */ - description: string; + required?: string[] /** - * Schema defining the parameters accepted by the function. + * Definitions of each parameter. */ - parameters: { + properties: { + [k: string]: { /** - * The type of the parameters object (usually 'object'). + * The data type of the parameter. */ - type: string; + type: string /** - * List of required parameter names. + * A description of the expected parameter. */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; + description: string + } + } + } + } + } + )[] + /** + * JSON schema that should be fufilled for the response. + */ + guided_json?: object + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number + /** + * Random seed for reproducibility of the generation. + */ + seed?: number + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number } type Ai_Cf_Google_Gemma_3_12B_It_Output = { + /** + * The generated text response from the model + */ + response: string + /** + * Usage statistics for the inference request + */ + usage?: { /** - * The generated text response from the model + * Total number of tokens in input */ - response: string; + prompt_tokens?: number /** - * Usage statistics for the inference request + * Total number of tokens in output */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; + completion_tokens?: number /** - * An array of tool calls requests made during the response generation + * Total number of input and output tokens */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -}; + total_tokens?: number + } + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object + /** + * The name of the tool to be called + */ + name?: string + }[] +} declare abstract class Base_Ai_Cf_Google_Gemma_3_12B_It { - inputs: Ai_Cf_Google_Gemma_3_12B_It_Input; - postProcessedOutputs: Ai_Cf_Google_Gemma_3_12B_It_Output; + inputs: Ai_Cf_Google_Gemma_3_12B_It_Input + postProcessedOutputs: Ai_Cf_Google_Gemma_3_12B_It_Output } -type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch; -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; +type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = + | Ai_Cf_Meta_Llama_4_Prompt + | Ai_Cf_Meta_Llama_4_Messages + | Ai_Cf_Meta_Llama_4_Async_Batch +interface Ai_Cf_Meta_Llama_4_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object + response_format?: JSONMode + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number + /** + * Random seed for reproducibility of the generation. + */ + seed?: number + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number } -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages { +interface Ai_Cf_Meta_Llama_4_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { /** - * An array of message objects representing the conversation history. + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: string | { + role?: string + /** + * The tool call id. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string + content?: + | string + | { + /** + * Type of the content provided + */ + type?: string + text?: string + image_url?: { /** - * Type of the content provided + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] | { + url?: string + } + }[] + | { + /** + * Type of the content provided + */ + type?: string + text?: string + image_url?: { /** - * Type of the content provided + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ + url?: string + } + } + }[] + functions?: { + name: string + code: string + }[] + /** + * A list of tools available for the assistant to use. + */ + tools?: ( + | { /** * The name of the tool. More descriptive the better. */ - name: string; + name: string /** * A brief description of what the tool does. */ - description: string; + description: string /** * Schema defining the parameters accepted by the tool. */ parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { + /** + * The type of the parameters object (usually 'object'). + */ + type: string + /** + * List of required parameter names. + */ + required?: string[] + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string + /** + * A description of the expected parameter. + */ + description: string + } + } + } + } + | { /** * Specifies the type of tool (e.g., 'function'). */ - type: string; + type: string /** * Details of the function tool. */ function: { + /** + * The name of the function. + */ + name: string + /** + * A brief description of what the function does. + */ + description: string + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { /** - * The name of the function. + * The type of the parameters object (usually 'object'). */ - name: string; + type: string /** - * A brief description of what the function does. + * List of required parameter names. */ - description: string; + required?: string[] /** - * Schema defining the parameters accepted by the function. + * Definitions of each parameter. */ - parameters: { + properties: { + [k: string]: { /** - * The type of the parameters object (usually 'object'). + * The data type of the parameter. */ - type: string; + type: string /** - * List of required parameter names. + * A description of the expected parameter. */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; + description: string + } + } + } + } + } + )[] + response_format?: JSONMode + /** + * JSON schema that should be fufilled for the response. + */ + guided_json?: object + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number + /** + * Random seed for reproducibility of the generation. + */ + seed?: number + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number } -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch { - requests: (Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner)[]; +interface Ai_Cf_Meta_Llama_4_Async_Batch { + requests: ( + | Ai_Cf_Meta_Llama_4_Prompt_Inner + | Ai_Cf_Meta_Llama_4_Messages_Inner + )[] } -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; +interface Ai_Cf_Meta_Llama_4_Prompt_Inner { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object + response_format?: JSONMode + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number + /** + * Random seed for reproducibility of the generation. + */ + seed?: number + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number } -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner { +interface Ai_Cf_Meta_Llama_4_Messages_Inner { + /** + * An array of message objects representing the conversation history. + */ + messages: { /** - * An array of message objects representing the conversation history. + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: string | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - functions?: { - name: string; - code: string; - }[]; + role?: string /** - * A list of tools available for the assistant to use. + * The tool call id. If you don't know what to put here you can fall back to 000000001 */ - tools?: ({ + tool_call_id?: string + content?: + | string + | { + /** + * Type of the content provided + */ + type?: string + text?: string + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string + } + }[] + | { + /** + * Type of the content provided + */ + type?: string + text?: string + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string + } + } + }[] + functions?: { + name: string + code: string + }[] + /** + * A list of tools available for the assistant to use. + */ + tools?: ( + | { /** * The name of the tool. More descriptive the better. */ - name: string; + name: string /** * A brief description of what the tool does. */ - description: string; + description: string /** * Schema defining the parameters accepted by the tool. */ parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { + /** + * The type of the parameters object (usually 'object'). + */ + type: string + /** + * List of required parameter names. + */ + required?: string[] + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string + /** + * A description of the expected parameter. + */ + description: string + } + } + } + } + | { /** * Specifies the type of tool (e.g., 'function'). */ - type: string; + type: string /** * Details of the function tool. */ function: { + /** + * The name of the function. + */ + name: string + /** + * A brief description of what the function does. + */ + description: string + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { /** - * The name of the function. + * The type of the parameters object (usually 'object'). */ - name: string; + type: string /** - * A brief description of what the function does. + * List of required parameter names. */ - description: string; + required?: string[] /** - * Schema defining the parameters accepted by the function. + * Definitions of each parameter. */ - parameters: { + properties: { + [k: string]: { /** - * The type of the parameters object (usually 'object'). + * The data type of the parameter. */ - type: string; + type: string /** - * List of required parameter names. + * A description of the expected parameter. */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; + description: string + } + } + } + } + } + )[] + response_format?: JSONMode + /** + * JSON schema that should be fufilled for the response. + */ + guided_json?: object + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number + /** + * Random seed for reproducibility of the generation. + */ + seed?: number + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number } type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output = { + /** + * The generated text response from the model + */ + response: string + /** + * Usage statistics for the inference request + */ + usage?: { /** - * The generated text response from the model + * Total number of tokens in input */ - response: string; + prompt_tokens?: number /** - * Usage statistics for the inference request + * Total number of tokens in output */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; + completion_tokens?: number /** - * An array of tool calls requests made during the response generation + * Total number of input and output tokens */ - tool_calls?: { - /** - * The tool call id. - */ - id?: string; - /** - * Specifies the type of tool (e.g., 'function'). - */ - type?: string; - /** - * Details of the function tool. - */ - function?: { - /** - * The name of the tool to be called - */ - name?: string; - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - }; - }[]; -}; + total_tokens?: number + } + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The tool call id. + */ + id?: string + /** + * Specifies the type of tool (e.g., 'function'). + */ + type?: string + /** + * Details of the function tool. + */ + function?: { + /** + * The name of the tool to be called + */ + name?: string + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object + } + }[] +} declare abstract class Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct { - inputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output; -} -type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input = Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch; -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - /** - * The content of the message as a string. - */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch { - requests: (Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1)[]; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1 { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - /** - * The content of the message as a string. - */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output = Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response | string | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse; -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response { - /** - * Unique identifier for the completion - */ - id?: string; - /** - * Object type identifier - */ - object?: "chat.completion"; - /** - * Unix timestamp of when the completion was created - */ - created?: number; - /** - * Model used for the completion - */ - model?: string; - /** - * List of completion choices - */ - choices?: { - /** - * Index of the choice in the list - */ - index?: number; - /** - * The message generated by the model - */ - message?: { - /** - * Role of the message author - */ - role: string; - /** - * The content of the message - */ - content: string; - /** - * Internal reasoning content (if available) - */ - reasoning_content?: string; - /** - * Tool calls made by the assistant - */ - tool_calls?: { - /** - * Unique identifier for the tool call - */ - id: string; - /** - * Type of tool call - */ - type: "function"; - function: { - /** - * Name of the function to call - */ - name: string; - /** - * JSON string of arguments for the function - */ - arguments: string; - }; - }[]; - }; - /** - * Reason why the model stopped generating - */ - finish_reason?: string; - /** - * Stop reason (may be null) - */ - stop_reason?: string | null; - /** - * Log probabilities (if requested) - */ - logprobs?: {} | null; - }[]; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * Log probabilities for the prompt (if requested) - */ - prompt_logprobs?: {} | null; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response { - /** - * Unique identifier for the completion - */ - id?: string; - /** - * Object type identifier - */ - object?: "text_completion"; - /** - * Unix timestamp of when the completion was created - */ - created?: number; - /** - * Model used for the completion - */ - model?: string; - /** - * List of completion choices - */ - choices?: { - /** - * Index of the choice in the list - */ - index: number; - /** - * The generated text completion - */ - text: string; - /** - * Reason why the model stopped generating - */ - finish_reason: string; - /** - * Stop reason (may be null) - */ - stop_reason?: string | null; - /** - * Log probabilities (if requested) - */ - logprobs?: {} | null; - /** - * Log probabilities for the prompt (if requested) - */ - prompt_logprobs?: {} | null; - }[]; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8 { - inputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input; - postProcessedOutputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output; + inputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input + postProcessedOutputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output } interface Ai_Cf_Deepgram_Nova_3_Input { - audio: { - body: object; - contentType: string; - }; - /** - * Sets how the model will interpret strings submitted to the custom_topic param. When strict, the model will only return topics submitted using the custom_topic param. When extended, the model will return its own detected topics in addition to those submitted using the custom_topic param. - */ - custom_topic_mode?: "extended" | "strict"; - /** - * Custom topics you want the model to detect within your input audio or text if present Submit up to 100 - */ - custom_topic?: string; - /** - * Sets how the model will interpret intents submitted to the custom_intent param. When strict, the model will only return intents submitted using the custom_intent param. When extended, the model will return its own detected intents in addition those submitted using the custom_intents param - */ - custom_intent_mode?: "extended" | "strict"; - /** - * Custom intents you want the model to detect within your input audio if present - */ - custom_intent?: string; - /** - * Identifies and extracts key entities from content in submitted audio - */ - detect_entities?: boolean; - /** - * Identifies the dominant language spoken in submitted audio - */ - detect_language?: boolean; - /** - * Recognize speaker changes. Each word in the transcript will be assigned a speaker number starting at 0 - */ - diarize?: boolean; - /** - * Identify and extract key entities from content in submitted audio - */ - dictation?: boolean; - /** - * Specify the expected encoding of your submitted audio - */ - encoding?: "linear16" | "flac" | "mulaw" | "amr-nb" | "amr-wb" | "opus" | "speex" | "g729"; - /** - * Arbitrary key-value pairs that are attached to the API response for usage in downstream processing - */ - extra?: string; - /** - * Filler Words can help transcribe interruptions in your audio, like 'uh' and 'um' - */ - filler_words?: boolean; - /** - * Key term prompting can boost or suppress specialized terminology and brands. - */ - keyterm?: string; - /** - * Keywords can boost or suppress specialized terminology and brands. - */ - keywords?: string; - /** - * The BCP-47 language tag that hints at the primary spoken language. Depending on the Model and API endpoint you choose only certain languages are available. - */ - language?: string; - /** - * Spoken measurements will be converted to their corresponding abbreviations. - */ - measurements?: boolean; - /** - * Opts out requests from the Deepgram Model Improvement Program. Refer to our Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip. - */ - mip_opt_out?: boolean; - /** - * Mode of operation for the model representing broad area of topic that will be talked about in the supplied audio - */ - mode?: "general" | "medical" | "finance"; - /** - * Transcribe each audio channel independently. - */ - multichannel?: boolean; - /** - * Numerals converts numbers from written format to numerical format. - */ - numerals?: boolean; - /** - * Splits audio into paragraphs to improve transcript readability. - */ - paragraphs?: boolean; - /** - * Profanity Filter looks for recognized profanity and converts it to the nearest recognized non-profane word or removes it from the transcript completely. - */ - profanity_filter?: boolean; - /** - * Add punctuation and capitalization to the transcript. - */ - punctuate?: boolean; - /** - * Redaction removes sensitive information from your transcripts. - */ - redact?: string; - /** - * Search for terms or phrases in submitted audio and replaces them. - */ - replace?: string; - /** - * Search for terms or phrases in submitted audio. - */ - search?: string; - /** - * Recognizes the sentiment throughout a transcript or text. - */ - sentiment?: boolean; - /** - * Apply formatting to transcript output. When set to true, additional formatting will be applied to transcripts to improve readability. - */ - smart_format?: boolean; - /** - * Detect topics throughout a transcript or text. - */ - topics?: boolean; - /** - * Segments speech into meaningful semantic units. - */ - utterances?: boolean; - /** - * Seconds to wait before detecting a pause between words in submitted audio. - */ - utt_split?: number; - /** - * The number of channels in the submitted audio - */ - channels?: number; - /** - * Specifies whether the streaming endpoint should provide ongoing transcription updates as more audio is received. When set to true, the endpoint sends continuous updates, meaning transcription results may evolve over time. Note: Supported only for webosockets. - */ - interim_results?: boolean; - /** - * Indicates how long model will wait to detect whether a speaker has finished speaking or pauses for a significant period of time. When set to a value, the streaming endpoint immediately finalizes the transcription for the processed time range and returns the transcript with a speech_final parameter set to true. Can also be set to false to disable endpointing - */ - endpointing?: string; - /** - * Indicates that speech has started. You'll begin receiving Speech Started messages upon speech starting. Note: Supported only for webosockets. - */ - vad_events?: boolean; - /** - * Indicates how long model will wait to send an UtteranceEnd message after a word has been transcribed. Use with interim_results. Note: Supported only for webosockets. - */ - utterance_end_ms?: boolean; + audio: { + body: object + contentType: string + } + /** + * Sets how the model will interpret strings submitted to the custom_topic param. When strict, the model will only return topics submitted using the custom_topic param. When extended, the model will return its own detected topics in addition to those submitted using the custom_topic param. + */ + custom_topic_mode?: 'extended' | 'strict' + /** + * Custom topics you want the model to detect within your input audio or text if present Submit up to 100 + */ + custom_topic?: string + /** + * Sets how the model will interpret intents submitted to the custom_intent param. When strict, the model will only return intents submitted using the custom_intent param. When extended, the model will return its own detected intents in addition those submitted using the custom_intents param + */ + custom_intent_mode?: 'extended' | 'strict' + /** + * Custom intents you want the model to detect within your input audio if present + */ + custom_intent?: string + /** + * Identifies and extracts key entities from content in submitted audio + */ + detect_entities?: boolean + /** + * Identifies the dominant language spoken in submitted audio + */ + detect_language?: boolean + /** + * Recognize speaker changes. Each word in the transcript will be assigned a speaker number starting at 0 + */ + diarize?: boolean + /** + * Identify and extract key entities from content in submitted audio + */ + dictation?: boolean + /** + * Specify the expected encoding of your submitted audio + */ + encoding?: + | 'linear16' + | 'flac' + | 'mulaw' + | 'amr-nb' + | 'amr-wb' + | 'opus' + | 'speex' + | 'g729' + /** + * Arbitrary key-value pairs that are attached to the API response for usage in downstream processing + */ + extra?: string + /** + * Filler Words can help transcribe interruptions in your audio, like 'uh' and 'um' + */ + filler_words?: boolean + /** + * Key term prompting can boost or suppress specialized terminology and brands. + */ + keyterm?: string + /** + * Keywords can boost or suppress specialized terminology and brands. + */ + keywords?: string + /** + * The BCP-47 language tag that hints at the primary spoken language. Depending on the Model and API endpoint you choose only certain languages are available. + */ + language?: string + /** + * Spoken measurements will be converted to their corresponding abbreviations. + */ + measurements?: boolean + /** + * Opts out requests from the Deepgram Model Improvement Program. Refer to our Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip. + */ + mip_opt_out?: boolean + /** + * Mode of operation for the model representing broad area of topic that will be talked about in the supplied audio + */ + mode?: 'general' | 'medical' | 'finance' + /** + * Transcribe each audio channel independently. + */ + multichannel?: boolean + /** + * Numerals converts numbers from written format to numerical format. + */ + numerals?: boolean + /** + * Splits audio into paragraphs to improve transcript readability. + */ + paragraphs?: boolean + /** + * Profanity Filter looks for recognized profanity and converts it to the nearest recognized non-profane word or removes it from the transcript completely. + */ + profanity_filter?: boolean + /** + * Add punctuation and capitalization to the transcript. + */ + punctuate?: boolean + /** + * Redaction removes sensitive information from your transcripts. + */ + redact?: string + /** + * Search for terms or phrases in submitted audio and replaces them. + */ + replace?: string + /** + * Search for terms or phrases in submitted audio. + */ + search?: string + /** + * Recognizes the sentiment throughout a transcript or text. + */ + sentiment?: boolean + /** + * Apply formatting to transcript output. When set to true, additional formatting will be applied to transcripts to improve readability. + */ + smart_format?: boolean + /** + * Detect topics throughout a transcript or text. + */ + topics?: boolean + /** + * Segments speech into meaningful semantic units. + */ + utterances?: boolean + /** + * Seconds to wait before detecting a pause between words in submitted audio. + */ + utt_split?: number + /** + * The number of channels in the submitted audio + */ + channels?: number + /** + * Specifies whether the streaming endpoint should provide ongoing transcription updates as more audio is received. When set to true, the endpoint sends continuous updates, meaning transcription results may evolve over time. Note: Supported only for webosockets. + */ + interim_results?: boolean + /** + * Indicates how long model will wait to detect whether a speaker has finished speaking or pauses for a significant period of time. When set to a value, the streaming endpoint immediately finalizes the transcription for the processed time range and returns the transcript with a speech_final parameter set to true. Can also be set to false to disable endpointing + */ + endpointing?: string + /** + * Indicates that speech has started. You'll begin receiving Speech Started messages upon speech starting. Note: Supported only for webosockets. + */ + vad_events?: boolean + /** + * Indicates how long model will wait to send an UtteranceEnd message after a word has been transcribed. Use with interim_results. Note: Supported only for webosockets. + */ + utterance_end_ms?: boolean } interface Ai_Cf_Deepgram_Nova_3_Output { - results?: { - channels?: { - alternatives?: { - confidence?: number; - transcript?: string; - words?: { - confidence?: number; - end?: number; - start?: number; - word?: string; - }[]; - }[]; - }[]; - summary?: { - result?: string; - short?: string; - }; - sentiments?: { - segments?: { - text?: string; - start_word?: number; - end_word?: number; - sentiment?: string; - sentiment_score?: number; - }[]; - average?: { - sentiment?: string; - sentiment_score?: number; - }; - }; - }; + results?: { + channels?: { + alternatives?: { + confidence?: number + transcript?: string + words?: { + confidence?: number + end?: number + start?: number + word?: string + }[] + }[] + }[] + summary?: { + result?: string + short?: string + } + sentiments?: { + segments?: { + text?: string + start_word?: number + end_word?: number + sentiment?: string + sentiment_score?: number + }[] + average?: { + sentiment?: string + sentiment_score?: number + } + } + } } declare abstract class Base_Ai_Cf_Deepgram_Nova_3 { - inputs: Ai_Cf_Deepgram_Nova_3_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Nova_3_Output; + inputs: Ai_Cf_Deepgram_Nova_3_Input + postProcessedOutputs: Ai_Cf_Deepgram_Nova_3_Output } -interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input { - queries?: string | string[]; - /** - * Optional instruction for the task - */ - instruction?: string; - documents?: string | string[]; - text?: string | string[]; -} -interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output { - data?: number[][]; - shape?: number[]; -} -declare abstract class Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B { - inputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input; - postProcessedOutputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output; -} -type Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input = { - /** - * readable stream with audio data and content-type specified for that data - */ - audio: { - body: object; - contentType: string; - }; - /** - * type of data PCM data that's sent to the inference server as raw array - */ - dtype?: "uint8" | "float32" | "float64"; -} | { - /** - * base64 encoded audio data - */ - audio: string; - /** - * type of data PCM data that's sent to the inference server as raw array - */ - dtype?: "uint8" | "float32" | "float64"; -}; +type Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input = + | { + /** + * readable stream with audio data and content-type specified for that data + */ + audio: { + body: object + contentType: string + } + /** + * type of data PCM data that's sent to the inference server as raw array + */ + dtype?: 'uint8' | 'float32' | 'float64' + } + | { + /** + * base64 encoded audio data + */ + audio: string + /** + * type of data PCM data that's sent to the inference server as raw array + */ + dtype?: 'uint8' | 'float32' | 'float64' + } interface Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output { - /** - * if true, end-of-turn was detected - */ - is_complete?: boolean; - /** - * probability of the end-of-turn detection - */ - probability?: number; + /** + * if true, end-of-turn was detected + */ + is_complete?: boolean + /** + * probability of the end-of-turn detection + */ + probability?: number } declare abstract class Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2 { - inputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input; - postProcessedOutputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output; + inputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input + postProcessedOutputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output } +type Ai_Cf_Openai_Gpt_Oss_120B_Input = + | GPT_OSS_120B_Responses + | GPT_OSS_120B_Responses_Async +interface GPT_OSS_120B_Responses { + /** + * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types + */ + input: string | unknown[] + reasoning?: { + /** + * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. + */ + effort?: 'low' | 'medium' | 'high' + /** + * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. + */ + summary?: 'auto' | 'concise' | 'detailed' + } +} +interface GPT_OSS_120B_Responses_Async { + requests: { + /** + * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types + */ + input: string | unknown[] + reasoning?: { + /** + * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. + */ + effort?: 'low' | 'medium' | 'high' + /** + * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. + */ + summary?: 'auto' | 'concise' | 'detailed' + } + }[] +} +type Ai_Cf_Openai_Gpt_Oss_120B_Output = {} | (string & NonNullable) declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_120B { - inputs: ResponsesInput; - postProcessedOutputs: ResponsesOutput; + inputs: Ai_Cf_Openai_Gpt_Oss_120B_Input + postProcessedOutputs: Ai_Cf_Openai_Gpt_Oss_120B_Output } +type Ai_Cf_Openai_Gpt_Oss_20B_Input = + | GPT_OSS_20B_Responses + | GPT_OSS_20B_Responses_Async +interface GPT_OSS_20B_Responses { + /** + * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types + */ + input: string | unknown[] + reasoning?: { + /** + * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. + */ + effort?: 'low' | 'medium' | 'high' + /** + * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. + */ + summary?: 'auto' | 'concise' | 'detailed' + } +} +interface GPT_OSS_20B_Responses_Async { + requests: { + /** + * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types + */ + input: string | unknown[] + reasoning?: { + /** + * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. + */ + effort?: 'low' | 'medium' | 'high' + /** + * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. + */ + summary?: 'auto' | 'concise' | 'detailed' + } + }[] +} +type Ai_Cf_Openai_Gpt_Oss_20B_Output = {} | (string & NonNullable) declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_20B { - inputs: ResponsesInput; - postProcessedOutputs: ResponsesOutput; + inputs: Ai_Cf_Openai_Gpt_Oss_20B_Input + postProcessedOutputs: Ai_Cf_Openai_Gpt_Oss_20B_Output } interface Ai_Cf_Leonardo_Phoenix_1_0_Input { - /** - * A text description of the image you want to generate. - */ - prompt: string; - /** - * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt - */ - guidance?: number; - /** - * Random seed for reproducibility of the image generation - */ - seed?: number; - /** - * The height of the generated image in pixels - */ - height?: number; - /** - * The width of the generated image in pixels - */ - width?: number; - /** - * The number of diffusion steps; higher values can improve quality but take longer - */ - num_steps?: number; - /** - * Specify what to exclude from the generated images - */ - negative_prompt?: string; + /** + * A text description of the image you want to generate. + */ + prompt: string + /** + * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt + */ + guidance?: number + /** + * Random seed for reproducibility of the image generation + */ + seed?: number + /** + * The height of the generated image in pixels + */ + height?: number + /** + * The width of the generated image in pixels + */ + width?: number + /** + * The number of diffusion steps; higher values can improve quality but take longer + */ + num_steps?: number + /** + * Specify what to exclude from the generated images + */ + negative_prompt?: string } /** * The generated image in JPEG format */ -type Ai_Cf_Leonardo_Phoenix_1_0_Output = string; +type Ai_Cf_Leonardo_Phoenix_1_0_Output = string declare abstract class Base_Ai_Cf_Leonardo_Phoenix_1_0 { - inputs: Ai_Cf_Leonardo_Phoenix_1_0_Input; - postProcessedOutputs: Ai_Cf_Leonardo_Phoenix_1_0_Output; + inputs: Ai_Cf_Leonardo_Phoenix_1_0_Input + postProcessedOutputs: Ai_Cf_Leonardo_Phoenix_1_0_Output } interface Ai_Cf_Leonardo_Lucid_Origin_Input { - /** - * A text description of the image you want to generate. - */ - prompt: string; - /** - * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt - */ - guidance?: number; - /** - * Random seed for reproducibility of the image generation - */ - seed?: number; - /** - * The height of the generated image in pixels - */ - height?: number; - /** - * The width of the generated image in pixels - */ - width?: number; - /** - * The number of diffusion steps; higher values can improve quality but take longer - */ - num_steps?: number; - /** - * The number of diffusion steps; higher values can improve quality but take longer - */ - steps?: number; + /** + * A text description of the image you want to generate. + */ + prompt: string + /** + * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt + */ + guidance?: number + /** + * Random seed for reproducibility of the image generation + */ + seed?: number + /** + * The height of the generated image in pixels + */ + height?: number + /** + * The width of the generated image in pixels + */ + width?: number + /** + * The number of diffusion steps; higher values can improve quality but take longer + */ + num_steps?: number + /** + * The number of diffusion steps; higher values can improve quality but take longer + */ + steps?: number } interface Ai_Cf_Leonardo_Lucid_Origin_Output { - /** - * The generated image in Base64 format. - */ - image?: string; + /** + * The generated image in Base64 format. + */ + image?: string } declare abstract class Base_Ai_Cf_Leonardo_Lucid_Origin { - inputs: Ai_Cf_Leonardo_Lucid_Origin_Input; - postProcessedOutputs: Ai_Cf_Leonardo_Lucid_Origin_Output; + inputs: Ai_Cf_Leonardo_Lucid_Origin_Input + postProcessedOutputs: Ai_Cf_Leonardo_Lucid_Origin_Output } interface Ai_Cf_Deepgram_Aura_1_Input { - /** - * Speaker used to produce the audio. - */ - speaker?: "angus" | "asteria" | "arcas" | "orion" | "orpheus" | "athena" | "luna" | "zeus" | "perseus" | "helios" | "hera" | "stella"; - /** - * Encoding of the output audio. - */ - encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; - /** - * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. - */ - container?: "none" | "wav" | "ogg"; - /** - * The text content to be converted to speech - */ - text: string; - /** - * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable - */ - sample_rate?: number; - /** - * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. - */ - bit_rate?: number; + /** + * Speaker used to produce the audio. + */ + speaker?: + | 'angus' + | 'asteria' + | 'arcas' + | 'orion' + | 'orpheus' + | 'athena' + | 'luna' + | 'zeus' + | 'perseus' + | 'helios' + | 'hera' + | 'stella' + /** + * Encoding of the output audio. + */ + encoding?: 'linear16' | 'flac' | 'mulaw' | 'alaw' | 'mp3' | 'opus' | 'aac' + /** + * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. + */ + container?: 'none' | 'wav' | 'ogg' + /** + * The text content to be converted to speech + */ + text: string + /** + * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable + */ + sample_rate?: number + /** + * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. + */ + bit_rate?: number } /** * The generated audio in MP3 format */ -type Ai_Cf_Deepgram_Aura_1_Output = string; +type Ai_Cf_Deepgram_Aura_1_Output = string declare abstract class Base_Ai_Cf_Deepgram_Aura_1 { - inputs: Ai_Cf_Deepgram_Aura_1_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Aura_1_Output; -} -interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input { - /** - * Input text to translate. Can be a single string or a list of strings. - */ - text: string | string[]; - /** - * Target language to translate to - */ - target_language: "asm_Beng" | "awa_Deva" | "ben_Beng" | "bho_Deva" | "brx_Deva" | "doi_Deva" | "eng_Latn" | "gom_Deva" | "gon_Deva" | "guj_Gujr" | "hin_Deva" | "hne_Deva" | "kan_Knda" | "kas_Arab" | "kas_Deva" | "kha_Latn" | "lus_Latn" | "mag_Deva" | "mai_Deva" | "mal_Mlym" | "mar_Deva" | "mni_Beng" | "mni_Mtei" | "npi_Deva" | "ory_Orya" | "pan_Guru" | "san_Deva" | "sat_Olck" | "snd_Arab" | "snd_Deva" | "tam_Taml" | "tel_Telu" | "urd_Arab" | "unr_Deva"; -} -interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output { - /** - * Translated texts - */ - translations: string[]; -} -declare abstract class Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B { - inputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input; - postProcessedOutputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output; -} -type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input = Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch; -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - /** - * The content of the message as a string. - */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch { - requests: (Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1)[]; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1 { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - /** - * The content of the message as a string. - */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output = Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response | string | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse; -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response { - /** - * Unique identifier for the completion - */ - id?: string; - /** - * Object type identifier - */ - object?: "chat.completion"; - /** - * Unix timestamp of when the completion was created - */ - created?: number; - /** - * Model used for the completion - */ - model?: string; - /** - * List of completion choices - */ - choices?: { - /** - * Index of the choice in the list - */ - index?: number; - /** - * The message generated by the model - */ - message?: { - /** - * Role of the message author - */ - role: string; - /** - * The content of the message - */ - content: string; - /** - * Internal reasoning content (if available) - */ - reasoning_content?: string; - /** - * Tool calls made by the assistant - */ - tool_calls?: { - /** - * Unique identifier for the tool call - */ - id: string; - /** - * Type of tool call - */ - type: "function"; - function: { - /** - * Name of the function to call - */ - name: string; - /** - * JSON string of arguments for the function - */ - arguments: string; - }; - }[]; - }; - /** - * Reason why the model stopped generating - */ - finish_reason?: string; - /** - * Stop reason (may be null) - */ - stop_reason?: string | null; - /** - * Log probabilities (if requested) - */ - logprobs?: {} | null; - }[]; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * Log probabilities for the prompt (if requested) - */ - prompt_logprobs?: {} | null; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response { - /** - * Unique identifier for the completion - */ - id?: string; - /** - * Object type identifier - */ - object?: "text_completion"; - /** - * Unix timestamp of when the completion was created - */ - created?: number; - /** - * Model used for the completion - */ - model?: string; - /** - * List of completion choices - */ - choices?: { - /** - * Index of the choice in the list - */ - index: number; - /** - * The generated text completion - */ - text: string; - /** - * Reason why the model stopped generating - */ - finish_reason: string; - /** - * Stop reason (may be null) - */ - stop_reason?: string | null; - /** - * Log probabilities (if requested) - */ - logprobs?: {} | null; - /** - * Log probabilities for the prompt (if requested) - */ - prompt_logprobs?: {} | null; - }[]; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It { - inputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input; - postProcessedOutputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output; -} -interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Input { - /** - * Input text to embed. Can be a single string or a list of strings. - */ - text: string | string[]; -} -interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Output { - /** - * Embedding vectors, where each vector is a list of floats. - */ - data: number[][]; - /** - * Shape of the embedding data as [number_of_embeddings, embedding_dimension]. - * - * @minItems 2 - * @maxItems 2 - */ - shape: [ - number, - number - ]; -} -declare abstract class Base_Ai_Cf_Pfnet_Plamo_Embedding_1B { - inputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Input; - postProcessedOutputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Output; -} -interface Ai_Cf_Deepgram_Flux_Input { - /** - * Encoding of the audio stream. Currently only supports raw signed little-endian 16-bit PCM. - */ - encoding: "linear16"; - /** - * Sample rate of the audio stream in Hz. - */ - sample_rate: string; - /** - * End-of-turn confidence required to fire an eager end-of-turn event. When set, enables EagerEndOfTurn and TurnResumed events. Valid Values 0.3 - 0.9. - */ - eager_eot_threshold?: string; - /** - * End-of-turn confidence required to finish a turn. Valid Values 0.5 - 0.9. - */ - eot_threshold?: string; - /** - * A turn will be finished when this much time has passed after speech, regardless of EOT confidence. - */ - eot_timeout_ms?: string; - /** - * Keyterm prompting can improve recognition of specialized terminology. Pass multiple keyterm query parameters to boost multiple keyterms. - */ - keyterm?: string; - /** - * Opts out requests from the Deepgram Model Improvement Program. Refer to Deepgram Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip - */ - mip_opt_out?: "true" | "false"; - /** - * Label your requests for the purpose of identification during usage reporting - */ - tag?: string; -} -/** - * Output will be returned as websocket messages. - */ -interface Ai_Cf_Deepgram_Flux_Output { - /** - * The unique identifier of the request (uuid) - */ - request_id?: string; - /** - * Starts at 0 and increments for each message the server sends to the client. - */ - sequence_id?: number; - /** - * The type of event being reported. - */ - event?: "Update" | "StartOfTurn" | "EagerEndOfTurn" | "TurnResumed" | "EndOfTurn"; - /** - * The index of the current turn - */ - turn_index?: number; - /** - * Start time in seconds of the audio range that was transcribed - */ - audio_window_start?: number; - /** - * End time in seconds of the audio range that was transcribed - */ - audio_window_end?: number; - /** - * Text that was said over the course of the current turn - */ - transcript?: string; - /** - * The words in the transcript - */ - words?: { - /** - * The individual punctuated, properly-cased word from the transcript - */ - word: string; - /** - * Confidence that this word was transcribed correctly - */ - confidence: number; - }[]; - /** - * Confidence that no more speech is coming in this turn - */ - end_of_turn_confidence?: number; -} -declare abstract class Base_Ai_Cf_Deepgram_Flux { - inputs: Ai_Cf_Deepgram_Flux_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Flux_Output; -} -interface Ai_Cf_Deepgram_Aura_2_En_Input { - /** - * Speaker used to produce the audio. - */ - speaker?: "amalthea" | "andromeda" | "apollo" | "arcas" | "aries" | "asteria" | "athena" | "atlas" | "aurora" | "callista" | "cora" | "cordelia" | "delia" | "draco" | "electra" | "harmonia" | "helena" | "hera" | "hermes" | "hyperion" | "iris" | "janus" | "juno" | "jupiter" | "luna" | "mars" | "minerva" | "neptune" | "odysseus" | "ophelia" | "orion" | "orpheus" | "pandora" | "phoebe" | "pluto" | "saturn" | "thalia" | "theia" | "vesta" | "zeus"; - /** - * Encoding of the output audio. - */ - encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; - /** - * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. - */ - container?: "none" | "wav" | "ogg"; - /** - * The text content to be converted to speech - */ - text: string; - /** - * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable - */ - sample_rate?: number; - /** - * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. - */ - bit_rate?: number; -} -/** - * The generated audio in MP3 format - */ -type Ai_Cf_Deepgram_Aura_2_En_Output = string; -declare abstract class Base_Ai_Cf_Deepgram_Aura_2_En { - inputs: Ai_Cf_Deepgram_Aura_2_En_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_En_Output; -} -interface Ai_Cf_Deepgram_Aura_2_Es_Input { - /** - * Speaker used to produce the audio. - */ - speaker?: "sirio" | "nestor" | "carina" | "celeste" | "alvaro" | "diana" | "aquila" | "selena" | "estrella" | "javier"; - /** - * Encoding of the output audio. - */ - encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; - /** - * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. - */ - container?: "none" | "wav" | "ogg"; - /** - * The text content to be converted to speech - */ - text: string; - /** - * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable - */ - sample_rate?: number; - /** - * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. - */ - bit_rate?: number; -} -/** - * The generated audio in MP3 format - */ -type Ai_Cf_Deepgram_Aura_2_Es_Output = string; -declare abstract class Base_Ai_Cf_Deepgram_Aura_2_Es { - inputs: Ai_Cf_Deepgram_Aura_2_Es_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_Es_Output; + inputs: Ai_Cf_Deepgram_Aura_1_Input + postProcessedOutputs: Ai_Cf_Deepgram_Aura_1_Output } interface AiModels { - "@cf/huggingface/distilbert-sst-2-int8": BaseAiTextClassification; - "@cf/stabilityai/stable-diffusion-xl-base-1.0": BaseAiTextToImage; - "@cf/runwayml/stable-diffusion-v1-5-inpainting": BaseAiTextToImage; - "@cf/runwayml/stable-diffusion-v1-5-img2img": BaseAiTextToImage; - "@cf/lykon/dreamshaper-8-lcm": BaseAiTextToImage; - "@cf/bytedance/stable-diffusion-xl-lightning": BaseAiTextToImage; - "@cf/myshell-ai/melotts": BaseAiTextToSpeech; - "@cf/google/embeddinggemma-300m": BaseAiTextEmbeddings; - "@cf/microsoft/resnet-50": BaseAiImageClassification; - "@cf/meta/llama-2-7b-chat-int8": BaseAiTextGeneration; - "@cf/mistral/mistral-7b-instruct-v0.1": BaseAiTextGeneration; - "@cf/meta/llama-2-7b-chat-fp16": BaseAiTextGeneration; - "@hf/thebloke/llama-2-13b-chat-awq": BaseAiTextGeneration; - "@hf/thebloke/mistral-7b-instruct-v0.1-awq": BaseAiTextGeneration; - "@hf/thebloke/zephyr-7b-beta-awq": BaseAiTextGeneration; - "@hf/thebloke/openhermes-2.5-mistral-7b-awq": BaseAiTextGeneration; - "@hf/thebloke/neural-chat-7b-v3-1-awq": BaseAiTextGeneration; - "@hf/thebloke/llamaguard-7b-awq": BaseAiTextGeneration; - "@hf/thebloke/deepseek-coder-6.7b-base-awq": BaseAiTextGeneration; - "@hf/thebloke/deepseek-coder-6.7b-instruct-awq": BaseAiTextGeneration; - "@cf/deepseek-ai/deepseek-math-7b-instruct": BaseAiTextGeneration; - "@cf/defog/sqlcoder-7b-2": BaseAiTextGeneration; - "@cf/openchat/openchat-3.5-0106": BaseAiTextGeneration; - "@cf/tiiuae/falcon-7b-instruct": BaseAiTextGeneration; - "@cf/thebloke/discolm-german-7b-v1-awq": BaseAiTextGeneration; - "@cf/qwen/qwen1.5-0.5b-chat": BaseAiTextGeneration; - "@cf/qwen/qwen1.5-7b-chat-awq": BaseAiTextGeneration; - "@cf/qwen/qwen1.5-14b-chat-awq": BaseAiTextGeneration; - "@cf/tinyllama/tinyllama-1.1b-chat-v1.0": BaseAiTextGeneration; - "@cf/microsoft/phi-2": BaseAiTextGeneration; - "@cf/qwen/qwen1.5-1.8b-chat": BaseAiTextGeneration; - "@cf/mistral/mistral-7b-instruct-v0.2-lora": BaseAiTextGeneration; - "@hf/nousresearch/hermes-2-pro-mistral-7b": BaseAiTextGeneration; - "@hf/nexusflow/starling-lm-7b-beta": BaseAiTextGeneration; - "@hf/google/gemma-7b-it": BaseAiTextGeneration; - "@cf/meta-llama/llama-2-7b-chat-hf-lora": BaseAiTextGeneration; - "@cf/google/gemma-2b-it-lora": BaseAiTextGeneration; - "@cf/google/gemma-7b-it-lora": BaseAiTextGeneration; - "@hf/mistral/mistral-7b-instruct-v0.2": BaseAiTextGeneration; - "@cf/meta/llama-3-8b-instruct": BaseAiTextGeneration; - "@cf/fblgit/una-cybertron-7b-v2-bf16": BaseAiTextGeneration; - "@cf/meta/llama-3-8b-instruct-awq": BaseAiTextGeneration; - "@cf/meta/llama-3.1-8b-instruct-fp8": BaseAiTextGeneration; - "@cf/meta/llama-3.1-8b-instruct-awq": BaseAiTextGeneration; - "@cf/meta/llama-3.2-3b-instruct": BaseAiTextGeneration; - "@cf/meta/llama-3.2-1b-instruct": BaseAiTextGeneration; - "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b": BaseAiTextGeneration; - "@cf/ibm-granite/granite-4.0-h-micro": BaseAiTextGeneration; - "@cf/facebook/bart-large-cnn": BaseAiSummarization; - "@cf/llava-hf/llava-1.5-7b-hf": BaseAiImageToText; - "@cf/baai/bge-base-en-v1.5": Base_Ai_Cf_Baai_Bge_Base_En_V1_5; - "@cf/openai/whisper": Base_Ai_Cf_Openai_Whisper; - "@cf/meta/m2m100-1.2b": Base_Ai_Cf_Meta_M2M100_1_2B; - "@cf/baai/bge-small-en-v1.5": Base_Ai_Cf_Baai_Bge_Small_En_V1_5; - "@cf/baai/bge-large-en-v1.5": Base_Ai_Cf_Baai_Bge_Large_En_V1_5; - "@cf/unum/uform-gen2-qwen-500m": Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M; - "@cf/openai/whisper-tiny-en": Base_Ai_Cf_Openai_Whisper_Tiny_En; - "@cf/openai/whisper-large-v3-turbo": Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo; - "@cf/baai/bge-m3": Base_Ai_Cf_Baai_Bge_M3; - "@cf/black-forest-labs/flux-1-schnell": Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell; - "@cf/meta/llama-3.2-11b-vision-instruct": Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct; - "@cf/meta/llama-3.3-70b-instruct-fp8-fast": Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast; - "@cf/meta/llama-guard-3-8b": Base_Ai_Cf_Meta_Llama_Guard_3_8B; - "@cf/baai/bge-reranker-base": Base_Ai_Cf_Baai_Bge_Reranker_Base; - "@cf/qwen/qwen2.5-coder-32b-instruct": Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct; - "@cf/qwen/qwq-32b": Base_Ai_Cf_Qwen_Qwq_32B; - "@cf/mistralai/mistral-small-3.1-24b-instruct": Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct; - "@cf/google/gemma-3-12b-it": Base_Ai_Cf_Google_Gemma_3_12B_It; - "@cf/meta/llama-4-scout-17b-16e-instruct": Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct; - "@cf/qwen/qwen3-30b-a3b-fp8": Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8; - "@cf/deepgram/nova-3": Base_Ai_Cf_Deepgram_Nova_3; - "@cf/qwen/qwen3-embedding-0.6b": Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B; - "@cf/pipecat-ai/smart-turn-v2": Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2; - "@cf/openai/gpt-oss-120b": Base_Ai_Cf_Openai_Gpt_Oss_120B; - "@cf/openai/gpt-oss-20b": Base_Ai_Cf_Openai_Gpt_Oss_20B; - "@cf/leonardo/phoenix-1.0": Base_Ai_Cf_Leonardo_Phoenix_1_0; - "@cf/leonardo/lucid-origin": Base_Ai_Cf_Leonardo_Lucid_Origin; - "@cf/deepgram/aura-1": Base_Ai_Cf_Deepgram_Aura_1; - "@cf/ai4bharat/indictrans2-en-indic-1B": Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B; - "@cf/aisingapore/gemma-sea-lion-v4-27b-it": Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It; - "@cf/pfnet/plamo-embedding-1b": Base_Ai_Cf_Pfnet_Plamo_Embedding_1B; - "@cf/deepgram/flux": Base_Ai_Cf_Deepgram_Flux; - "@cf/deepgram/aura-2-en": Base_Ai_Cf_Deepgram_Aura_2_En; - "@cf/deepgram/aura-2-es": Base_Ai_Cf_Deepgram_Aura_2_Es; + '@cf/huggingface/distilbert-sst-2-int8': BaseAiTextClassification + '@cf/stabilityai/stable-diffusion-xl-base-1.0': BaseAiTextToImage + '@cf/runwayml/stable-diffusion-v1-5-inpainting': BaseAiTextToImage + '@cf/runwayml/stable-diffusion-v1-5-img2img': BaseAiTextToImage + '@cf/lykon/dreamshaper-8-lcm': BaseAiTextToImage + '@cf/bytedance/stable-diffusion-xl-lightning': BaseAiTextToImage + '@cf/myshell-ai/melotts': BaseAiTextToSpeech + '@cf/google/embeddinggemma-300m': BaseAiTextEmbeddings + '@cf/microsoft/resnet-50': BaseAiImageClassification + '@cf/meta/llama-2-7b-chat-int8': BaseAiTextGeneration + '@cf/mistral/mistral-7b-instruct-v0.1': BaseAiTextGeneration + '@cf/meta/llama-2-7b-chat-fp16': BaseAiTextGeneration + '@hf/thebloke/llama-2-13b-chat-awq': BaseAiTextGeneration + '@hf/thebloke/mistral-7b-instruct-v0.1-awq': BaseAiTextGeneration + '@hf/thebloke/zephyr-7b-beta-awq': BaseAiTextGeneration + '@hf/thebloke/openhermes-2.5-mistral-7b-awq': BaseAiTextGeneration + '@hf/thebloke/neural-chat-7b-v3-1-awq': BaseAiTextGeneration + '@hf/thebloke/llamaguard-7b-awq': BaseAiTextGeneration + '@hf/thebloke/deepseek-coder-6.7b-base-awq': BaseAiTextGeneration + '@hf/thebloke/deepseek-coder-6.7b-instruct-awq': BaseAiTextGeneration + '@cf/deepseek-ai/deepseek-math-7b-instruct': BaseAiTextGeneration + '@cf/defog/sqlcoder-7b-2': BaseAiTextGeneration + '@cf/openchat/openchat-3.5-0106': BaseAiTextGeneration + '@cf/tiiuae/falcon-7b-instruct': BaseAiTextGeneration + '@cf/thebloke/discolm-german-7b-v1-awq': BaseAiTextGeneration + '@cf/qwen/qwen1.5-0.5b-chat': BaseAiTextGeneration + '@cf/qwen/qwen1.5-7b-chat-awq': BaseAiTextGeneration + '@cf/qwen/qwen1.5-14b-chat-awq': BaseAiTextGeneration + '@cf/tinyllama/tinyllama-1.1b-chat-v1.0': BaseAiTextGeneration + '@cf/microsoft/phi-2': BaseAiTextGeneration + '@cf/qwen/qwen1.5-1.8b-chat': BaseAiTextGeneration + '@cf/mistral/mistral-7b-instruct-v0.2-lora': BaseAiTextGeneration + '@hf/nousresearch/hermes-2-pro-mistral-7b': BaseAiTextGeneration + '@hf/nexusflow/starling-lm-7b-beta': BaseAiTextGeneration + '@hf/google/gemma-7b-it': BaseAiTextGeneration + '@cf/meta-llama/llama-2-7b-chat-hf-lora': BaseAiTextGeneration + '@cf/google/gemma-2b-it-lora': BaseAiTextGeneration + '@cf/google/gemma-7b-it-lora': BaseAiTextGeneration + '@hf/mistral/mistral-7b-instruct-v0.2': BaseAiTextGeneration + '@cf/meta/llama-3-8b-instruct': BaseAiTextGeneration + '@cf/fblgit/una-cybertron-7b-v2-bf16': BaseAiTextGeneration + '@cf/meta/llama-3-8b-instruct-awq': BaseAiTextGeneration + '@hf/meta-llama/meta-llama-3-8b-instruct': BaseAiTextGeneration + '@cf/meta/llama-3.1-8b-instruct-fp8': BaseAiTextGeneration + '@cf/meta/llama-3.1-8b-instruct-awq': BaseAiTextGeneration + '@cf/meta/llama-3.2-3b-instruct': BaseAiTextGeneration + '@cf/meta/llama-3.2-1b-instruct': BaseAiTextGeneration + '@cf/deepseek-ai/deepseek-r1-distill-qwen-32b': BaseAiTextGeneration + '@cf/facebook/bart-large-cnn': BaseAiSummarization + '@cf/llava-hf/llava-1.5-7b-hf': BaseAiImageToText + '@cf/baai/bge-base-en-v1.5': Base_Ai_Cf_Baai_Bge_Base_En_V1_5 + '@cf/openai/whisper': Base_Ai_Cf_Openai_Whisper + '@cf/meta/m2m100-1.2b': Base_Ai_Cf_Meta_M2M100_1_2B + '@cf/baai/bge-small-en-v1.5': Base_Ai_Cf_Baai_Bge_Small_En_V1_5 + '@cf/baai/bge-large-en-v1.5': Base_Ai_Cf_Baai_Bge_Large_En_V1_5 + '@cf/unum/uform-gen2-qwen-500m': Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M + '@cf/openai/whisper-tiny-en': Base_Ai_Cf_Openai_Whisper_Tiny_En + '@cf/openai/whisper-large-v3-turbo': Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo + '@cf/baai/bge-m3': Base_Ai_Cf_Baai_Bge_M3 + '@cf/black-forest-labs/flux-1-schnell': Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell + '@cf/meta/llama-3.2-11b-vision-instruct': Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct + '@cf/meta/llama-3.3-70b-instruct-fp8-fast': Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast + '@cf/meta/llama-guard-3-8b': Base_Ai_Cf_Meta_Llama_Guard_3_8B + '@cf/baai/bge-reranker-base': Base_Ai_Cf_Baai_Bge_Reranker_Base + '@cf/qwen/qwen2.5-coder-32b-instruct': Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct + '@cf/qwen/qwq-32b': Base_Ai_Cf_Qwen_Qwq_32B + '@cf/mistralai/mistral-small-3.1-24b-instruct': Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct + '@cf/google/gemma-3-12b-it': Base_Ai_Cf_Google_Gemma_3_12B_It + '@cf/meta/llama-4-scout-17b-16e-instruct': Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct + '@cf/deepgram/nova-3': Base_Ai_Cf_Deepgram_Nova_3 + '@cf/pipecat-ai/smart-turn-v2': Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2 + '@cf/openai/gpt-oss-120b': Base_Ai_Cf_Openai_Gpt_Oss_120B + '@cf/openai/gpt-oss-20b': Base_Ai_Cf_Openai_Gpt_Oss_20B + '@cf/leonardo/phoenix-1.0': Base_Ai_Cf_Leonardo_Phoenix_1_0 + '@cf/leonardo/lucid-origin': Base_Ai_Cf_Leonardo_Lucid_Origin + '@cf/deepgram/aura-1': Base_Ai_Cf_Deepgram_Aura_1 } type AiOptions = { - /** - * Send requests as an asynchronous batch job, only works for supported models - * https://developers.cloudflare.com/workers-ai/features/batch-api - */ - queueRequest?: boolean; - /** - * Establish websocket connections, only works for supported models - */ - websocket?: boolean; - /** - * Tag your requests to group and view them in Cloudflare dashboard. - * - * Rules: - * Tags must only contain letters, numbers, and the symbols: : - . / @ - * Each tag can have maximum 50 characters. - * Maximum 5 tags are allowed each request. - * Duplicate tags will removed. - */ - tags?: string[]; - gateway?: GatewayOptions; - returnRawResponse?: boolean; - prefix?: string; - extraHeaders?: object; -}; + /** + * Send requests as an asynchronous batch job, only works for supported models + * https://developers.cloudflare.com/workers-ai/features/batch-api + */ + queueRequest?: boolean + /** + * Establish websocket connections, only works for supported models + */ + websocket?: boolean + gateway?: GatewayOptions + returnRawResponse?: boolean + prefix?: string + extraHeaders?: object +} type AiModelsSearchParams = { - author?: string; - hide_experimental?: boolean; - page?: number; - per_page?: number; - search?: string; - source?: number; - task?: string; -}; + author?: string + hide_experimental?: boolean + page?: number + per_page?: number + search?: string + source?: number + task?: string +} type AiModelsSearchObject = { - id: string; - source: number; - name: string; - description: string; - task: { - id: string; - name: string; - description: string; - }; - tags: string[]; - properties: { - property_id: string; - value: string; - }[]; -}; -interface InferenceUpstreamError extends Error { + id: string + source: number + name: string + description: string + task: { + id: string + name: string + description: string + } + tags: string[] + properties: { + property_id: string + value: string + }[] } -interface AiInternalError extends Error { -} -type AiModelListType = Record; +interface InferenceUpstreamError extends Error {} +interface AiInternalError extends Error {} +type AiModelListType = Record declare abstract class Ai { - aiGatewayLogId: string | null; - gateway(gatewayId: string): AiGateway; - /** - * Access the AI Search API for managing AI-powered search instances. - * - * This is the new API that replaces AutoRAG with better namespace separation: - * - Account-level operations: `list()`, `create()` - * - Instance-level operations: `get(id).search()`, `get(id).chatCompletions()`, `get(id).delete()` - * - * @example - * ```typescript - * // List all AI Search instances - * const instances = await env.AI.aiSearch.list(); - * - * // Search an instance - * const results = await env.AI.aiSearch.get('my-search').search({ - * messages: [{ role: 'user', content: 'What is the policy?' }], - * ai_search_options: { - * retrieval: { max_num_results: 10 } - * } - * }); - * - * // Generate chat completions with AI Search context - * const response = await env.AI.aiSearch.get('my-search').chatCompletions({ - * messages: [{ role: 'user', content: 'What is the policy?' }], - * model: '@cf/meta/llama-3.3-70b-instruct-fp8-fast' - * }); - * ``` - */ - aiSearch(): AiSearchAccountService; - /** - * @deprecated AutoRAG has been replaced by AI Search. - * Use `env.AI.aiSearch` instead for better API design and new features. - * - * Migration guide: - * - `env.AI.autorag().list()` → `env.AI.aiSearch.list()` - * - `env.AI.autorag('id').search({ query: '...' })` → `env.AI.aiSearch.get('id').search({ messages: [{ role: 'user', content: '...' }] })` - * - `env.AI.autorag('id').aiSearch(...)` → `env.AI.aiSearch.get('id').chatCompletions(...)` - * - * Note: The old API continues to work for backwards compatibility, but new projects should use AI Search. - * - * @see AiSearchAccountService - * @param autoragId Optional instance ID (omit for account-level operations) - */ - autorag(autoragId: string): AutoRAG; - run(model: Name, inputs: InputOptions, options?: Options): Promise; - models(params?: AiModelsSearchParams): Promise; - toMarkdown(): ToMarkdownService; - toMarkdown(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise; - toMarkdown(files: MarkdownDocument, options?: ConversionRequestOptions): Promise; + aiGatewayLogId: string | null + gateway(gatewayId: string): AiGateway + autorag(autoragId: string): AutoRAG + run< + Name extends keyof AiModelList, + Options extends AiOptions, + InputOptions extends AiModelList[Name]['inputs'], + >( + model: Name, + inputs: InputOptions, + options?: Options, + ): Promise< + Options extends + | { + returnRawResponse: true + } + | { + websocket: true + } + ? Response + : InputOptions extends { + stream: true + } + ? ReadableStream + : AiModelList[Name]['postProcessedOutputs'] + > + models(params?: AiModelsSearchParams): Promise + toMarkdown(): ToMarkdownService + toMarkdown( + files: MarkdownDocument[], + options?: ConversionRequestOptions, + ): Promise + toMarkdown( + files: MarkdownDocument, + options?: ConversionRequestOptions, + ): Promise } type GatewayRetries = { - maxAttempts?: 1 | 2 | 3 | 4 | 5; - retryDelayMs?: number; - backoff?: 'constant' | 'linear' | 'exponential'; -}; + maxAttempts?: 1 | 2 | 3 | 4 | 5 + retryDelayMs?: number + backoff?: 'constant' | 'linear' | 'exponential' +} type GatewayOptions = { - id: string; - cacheKey?: string; - cacheTtl?: number; - skipCache?: boolean; - metadata?: Record; - collectLog?: boolean; - eventId?: string; - requestTimeoutMs?: number; - retries?: GatewayRetries; -}; + id: string + cacheKey?: string + cacheTtl?: number + skipCache?: boolean + metadata?: Record + collectLog?: boolean + eventId?: string + requestTimeoutMs?: number + retries?: GatewayRetries +} type UniversalGatewayOptions = Exclude & { - /** - ** @deprecated - */ - id?: string; -}; + /** + ** @deprecated + */ + id?: string +} type AiGatewayPatchLog = { - score?: number | null; - feedback?: -1 | 1 | null; - metadata?: Record | null; -}; + score?: number | null + feedback?: -1 | 1 | null + metadata?: Record | null +} type AiGatewayLog = { - id: string; - provider: string; - model: string; - model_type?: string; - path: string; - duration: number; - request_type?: string; - request_content_type?: string; - status_code: number; - response_content_type?: string; - success: boolean; - cached: boolean; - tokens_in?: number; - tokens_out?: number; - metadata?: Record; - step?: number; - cost?: number; - custom_cost?: boolean; - request_size: number; - request_head?: string; - request_head_complete: boolean; - response_size: number; - response_head?: string; - response_head_complete: boolean; - created_at: Date; -}; -type AIGatewayProviders = 'workers-ai' | 'anthropic' | 'aws-bedrock' | 'azure-openai' | 'google-vertex-ai' | 'huggingface' | 'openai' | 'perplexity-ai' | 'replicate' | 'groq' | 'cohere' | 'google-ai-studio' | 'mistral' | 'grok' | 'openrouter' | 'deepseek' | 'cerebras' | 'cartesia' | 'elevenlabs' | 'adobe-firefly'; + id: string + provider: string + model: string + model_type?: string + path: string + duration: number + request_type?: string + request_content_type?: string + status_code: number + response_content_type?: string + success: boolean + cached: boolean + tokens_in?: number + tokens_out?: number + metadata?: Record + step?: number + cost?: number + custom_cost?: boolean + request_size: number + request_head?: string + request_head_complete: boolean + response_size: number + response_head?: string + response_head_complete: boolean + created_at: Date +} +type AIGatewayProviders = + | 'workers-ai' + | 'anthropic' + | 'aws-bedrock' + | 'azure-openai' + | 'google-vertex-ai' + | 'huggingface' + | 'openai' + | 'perplexity-ai' + | 'replicate' + | 'groq' + | 'cohere' + | 'google-ai-studio' + | 'mistral' + | 'grok' + | 'openrouter' + | 'deepseek' + | 'cerebras' + | 'cartesia' + | 'elevenlabs' + | 'adobe-firefly' type AIGatewayHeaders = { - 'cf-aig-metadata': Record | string; - 'cf-aig-custom-cost': { - per_token_in?: number; - per_token_out?: number; - } | { - total_cost?: number; - } | string; - 'cf-aig-cache-ttl': number | string; - 'cf-aig-skip-cache': boolean | string; - 'cf-aig-cache-key': string; - 'cf-aig-event-id': string; - 'cf-aig-request-timeout': number | string; - 'cf-aig-max-attempts': number | string; - 'cf-aig-retry-delay': number | string; - 'cf-aig-backoff': string; - 'cf-aig-collect-log': boolean | string; - Authorization: string; - 'Content-Type': string; - [key: string]: string | number | boolean | object; -}; + 'cf-aig-metadata': + | Record + | string + 'cf-aig-custom-cost': + | { + per_token_in?: number + per_token_out?: number + } + | { + total_cost?: number + } + | string + 'cf-aig-cache-ttl': number | string + 'cf-aig-skip-cache': boolean | string + 'cf-aig-cache-key': string + 'cf-aig-event-id': string + 'cf-aig-request-timeout': number | string + 'cf-aig-max-attempts': number | string + 'cf-aig-retry-delay': number | string + 'cf-aig-backoff': string + 'cf-aig-collect-log': boolean | string + Authorization: string + 'Content-Type': string + [key: string]: string | number | boolean | object +} type AIGatewayUniversalRequest = { - provider: AIGatewayProviders | string; // eslint-disable-line - endpoint: string; - headers: Partial; - query: unknown; -}; -interface AiGatewayInternalError extends Error { -} -interface AiGatewayLogNotFound extends Error { + provider: AIGatewayProviders | string // eslint-disable-line + endpoint: string + headers: Partial + query: unknown } +interface AiGatewayInternalError extends Error {} +interface AiGatewayLogNotFound extends Error {} declare abstract class AiGateway { - patchLog(logId: string, data: AiGatewayPatchLog): Promise; - getLog(logId: string): Promise; - run(data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[], options?: { - gateway?: UniversalGatewayOptions; - extraHeaders?: object; - }): Promise; - getUrl(provider?: AIGatewayProviders | string): Promise; // eslint-disable-line -} -/** - * @deprecated AutoRAG has been replaced by AI Search. Use AiSearchInternalError instead. - * @see AiSearchInternalError - */ -interface AutoRAGInternalError extends Error { -} -/** - * @deprecated AutoRAG has been replaced by AI Search. Use AiSearchNotFoundError instead. - * @see AiSearchNotFoundError - */ -interface AutoRAGNotFoundError extends Error { -} -/** - * @deprecated This error type is no longer used in the AI Search API. - */ -interface AutoRAGUnauthorizedError extends Error { -} -/** - * @deprecated AutoRAG has been replaced by AI Search. Use AiSearchNameNotSetError instead. - * @see AiSearchNameNotSetError - */ -interface AutoRAGNameNotSetError extends Error { + patchLog(logId: string, data: AiGatewayPatchLog): Promise + getLog(logId: string): Promise + run( + data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[], + options?: { + gateway?: UniversalGatewayOptions + extraHeaders?: object + }, + ): Promise + getUrl(provider?: AIGatewayProviders | string): Promise // eslint-disable-line } +interface AutoRAGInternalError extends Error {} +interface AutoRAGNotFoundError extends Error {} +interface AutoRAGUnauthorizedError extends Error {} +interface AutoRAGNameNotSetError extends Error {} type ComparisonFilter = { - key: string; - type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte'; - value: string | number | boolean; -}; + key: string + type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte' + value: string | number | boolean +} type CompoundFilter = { - type: 'and' | 'or'; - filters: ComparisonFilter[]; -}; -/** - * @deprecated AutoRAG has been replaced by AI Search. - * Use AiSearchSearchRequest with the new API instead. - * @see AiSearchSearchRequest - */ + type: 'and' | 'or' + filters: ComparisonFilter[] +} type AutoRagSearchRequest = { - query: string; - filters?: CompoundFilter | ComparisonFilter; - max_num_results?: number; - ranking_options?: { - ranker?: string; - score_threshold?: number; - }; - reranking?: { - enabled?: boolean; - model?: string; - }; - rewrite_query?: boolean; -}; -/** - * @deprecated AutoRAG has been replaced by AI Search. - * Use AiSearchChatCompletionsRequest with the new API instead. - * @see AiSearchChatCompletionsRequest - */ + query: string + filters?: CompoundFilter | ComparisonFilter + max_num_results?: number + ranking_options?: { + ranker?: string + score_threshold?: number + } + reranking?: { + enabled?: boolean + model?: string + } + rewrite_query?: boolean +} type AutoRagAiSearchRequest = AutoRagSearchRequest & { - stream?: boolean; - system_prompt?: string; -}; -/** - * @deprecated AutoRAG has been replaced by AI Search. - * Use AiSearchChatCompletionsRequest with stream: true instead. - * @see AiSearchChatCompletionsRequest - */ -type AutoRagAiSearchRequestStreaming = Omit & { - stream: true; -}; -/** - * @deprecated AutoRAG has been replaced by AI Search. - * Use AiSearchSearchResponse with the new API instead. - * @see AiSearchSearchResponse - */ + stream?: boolean + system_prompt?: string +} +type AutoRagAiSearchRequestStreaming = Omit< + AutoRagAiSearchRequest, + 'stream' +> & { + stream: true +} type AutoRagSearchResponse = { - object: 'vector_store.search_results.page'; - search_query: string; - data: { - file_id: string; - filename: string; - score: number; - attributes: Record; - content: { - type: 'text'; - text: string; - }[]; - }[]; - has_more: boolean; - next_page: string | null; -}; -/** - * @deprecated AutoRAG has been replaced by AI Search. - * Use AiSearchListResponse with the new API instead. - * @see AiSearchListResponse - */ + object: 'vector_store.search_results.page' + search_query: string + data: { + file_id: string + filename: string + score: number + attributes: Record + content: { + type: 'text' + text: string + }[] + }[] + has_more: boolean + next_page: string | null +} type AutoRagListResponse = { - id: string; - enable: boolean; - type: string; - source: string; - vectorize_name: string; - paused: boolean; - status: string; -}[]; -/** - * @deprecated AutoRAG has been replaced by AI Search. - * The new API returns different response formats for chat completions. - */ + id: string + enable: boolean + type: string + source: string + vectorize_name: string + paused: boolean + status: string +}[] type AutoRagAiSearchResponse = AutoRagSearchResponse & { - response: string; -}; -/** - * @deprecated AutoRAG has been replaced by AI Search. - * Use the new AI Search API instead: `env.AI.aiSearch` - * - * Migration guide: - * - `env.AI.autorag().list()` → `env.AI.aiSearch.list()` - * - `env.AI.autorag('id').search(...)` → `env.AI.aiSearch.get('id').search(...)` - * - `env.AI.autorag('id').aiSearch(...)` → `env.AI.aiSearch.get('id').chatCompletions(...)` - * - * @see AiSearchAccountService - * @see AiSearchInstanceService - */ + response: string +} declare abstract class AutoRAG { - /** - * @deprecated Use `env.AI.aiSearch.list()` instead. - * @see AiSearchAccountService.list - */ - list(): Promise; - /** - * @deprecated Use `env.AI.aiSearch.get(id).search(...)` instead. - * Note: The new API uses a messages array instead of a query string. - * @see AiSearchInstanceService.search - */ - search(params: AutoRagSearchRequest): Promise; - /** - * @deprecated Use `env.AI.aiSearch.get(id).chatCompletions(...)` instead. - * @see AiSearchInstanceService.chatCompletions - */ - aiSearch(params: AutoRagAiSearchRequestStreaming): Promise; - /** - * @deprecated Use `env.AI.aiSearch.get(id).chatCompletions(...)` instead. - * @see AiSearchInstanceService.chatCompletions - */ - aiSearch(params: AutoRagAiSearchRequest): Promise; - /** - * @deprecated Use `env.AI.aiSearch.get(id).chatCompletions(...)` instead. - * @see AiSearchInstanceService.chatCompletions - */ - aiSearch(params: AutoRagAiSearchRequest): Promise; + list(): Promise + search(params: AutoRagSearchRequest): Promise + aiSearch(params: AutoRagAiSearchRequestStreaming): Promise + aiSearch(params: AutoRagAiSearchRequest): Promise + aiSearch( + params: AutoRagAiSearchRequest, + ): Promise } interface BasicImageTransformations { - /** - * Maximum width in image pixels. The value must be an integer. - */ - width?: number; - /** - * Maximum height in image pixels. The value must be an integer. - */ - height?: number; - /** - * Resizing mode as a string. It affects interpretation of width and height - * options: - * - scale-down: Similar to contain, but the image is never enlarged. If - * the image is larger than given width or height, it will be resized. - * Otherwise its original size will be kept. - * - contain: Resizes to maximum size that fits within the given width and - * height. If only a single dimension is given (e.g. only width), the - * image will be shrunk or enlarged to exactly match that dimension. - * Aspect ratio is always preserved. - * - cover: Resizes (shrinks or enlarges) to fill the entire area of width - * and height. If the image has an aspect ratio different from the ratio - * of width and height, it will be cropped to fit. - * - crop: The image will be shrunk and cropped to fit within the area - * specified by width and height. The image will not be enlarged. For images - * smaller than the given dimensions it's the same as scale-down. For - * images larger than the given dimensions, it's the same as cover. - * See also trim. - * - pad: Resizes to the maximum size that fits within the given width and - * height, and then fills the remaining area with a background color - * (white by default). Use of this mode is not recommended, as the same - * effect can be more efficiently achieved with the contain mode and the - * CSS object-fit: contain property. - * - squeeze: Stretches and deforms to the width and height given, even if it - * breaks aspect ratio - */ - fit?: "scale-down" | "contain" | "cover" | "crop" | "pad" | "squeeze"; - /** - * Image segmentation using artificial intelligence models. Sets pixels not - * within selected segment area to transparent e.g "foreground" sets every - * background pixel as transparent. - */ - segment?: "foreground"; - /** - * When cropping with fit: "cover", this defines the side or point that should - * be left uncropped. The value is either a string - * "left", "right", "top", "bottom", "auto", or "center" (the default), - * or an object {x, y} containing focal point coordinates in the original - * image expressed as fractions ranging from 0.0 (top or left) to 1.0 - * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will - * crop bottom or left and right sides as necessary, but won’t crop anything - * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to - * preserve as much as possible around a point at 20% of the height of the - * source image. - */ - gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | BasicImageTransformationsGravityCoordinates; - /** - * Background color to add underneath the image. Applies only to images with - * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), - * hsl(…), etc.) - */ - background?: string; - /** - * Number of degrees (90, 180, 270) to rotate the image by. width and height - * options refer to axes after rotation. - */ - rotate?: 0 | 90 | 180 | 270 | 360; + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + * - squeeze: Stretches and deforms to the width and height given, even if it + * breaks aspect ratio + */ + fit?: 'scale-down' | 'contain' | 'cover' | 'crop' | 'pad' | 'squeeze' + /** + * Image segmentation using artificial intelligence models. Sets pixels not + * within selected segment area to transparent e.g "foreground" sets every + * background pixel as transparent. + */ + segment?: 'foreground' + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: + | 'face' + | 'left' + | 'right' + | 'top' + | 'bottom' + | 'center' + | 'auto' + | 'entropy' + | BasicImageTransformationsGravityCoordinates + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360 } interface BasicImageTransformationsGravityCoordinates { - x?: number; - y?: number; - mode?: 'remainder' | 'box-center'; + x?: number + y?: number + mode?: 'remainder' | 'box-center' } /** * In addition to the properties you can set in the RequestInit dict @@ -9092,755 +7755,1027 @@ interface BasicImageTransformationsGravityCoordinates { * playground. */ interface RequestInitCfProperties extends Record { - cacheEverything?: boolean; - /** - * A request's cache key is what determines if two requests are - * "the same" for caching purposes. If a request has the same cache key - * as some previous request, then we can serve the same cached response for - * both. (e.g. 'some-key') - * - * Only available for Enterprise customers. - */ - cacheKey?: string; - /** - * This allows you to append additional Cache-Tag response headers - * to the origin response without modifications to the origin server. - * This will allow for greater control over the Purge by Cache Tag feature - * utilizing changes only in the Workers process. - * - * Only available for Enterprise customers. - */ - cacheTags?: string[]; - /** - * Force response to be cached for a given number of seconds. (e.g. 300) - */ - cacheTtl?: number; - /** - * Force response to be cached for a given number of seconds based on the Origin status code. - * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) - */ - cacheTtlByStatus?: Record; - scrapeShield?: boolean; - apps?: boolean; - image?: RequestInitCfPropertiesImage; - minify?: RequestInitCfPropertiesImageMinify; - mirage?: boolean; - polish?: "lossy" | "lossless" | "off"; - r2?: RequestInitCfPropertiesR2; - /** - * Redirects the request to an alternate origin server. You can use this, - * for example, to implement load balancing across several origins. - * (e.g.us-east.example.com) - * - * Note - For security reasons, the hostname set in resolveOverride must - * be proxied on the same Cloudflare zone of the incoming request. - * Otherwise, the setting is ignored. CNAME hosts are allowed, so to - * resolve to a host under a different domain or a DNS only domain first - * declare a CNAME record within your own zone’s DNS mapping to the - * external hostname, set proxy on Cloudflare, then set resolveOverride - * to point to that CNAME record. - */ - resolveOverride?: string; + cacheEverything?: boolean + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[] + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record + scrapeShield?: boolean + apps?: boolean + image?: RequestInitCfPropertiesImage + minify?: RequestInitCfPropertiesImageMinify + mirage?: boolean + polish?: 'lossy' | 'lossless' | 'off' + r2?: RequestInitCfPropertiesR2 + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string } interface RequestInitCfPropertiesImageDraw extends BasicImageTransformations { - /** - * Absolute URL of the image file to use for the drawing. It can be any of - * the supported file formats. For drawing of watermarks or non-rectangular - * overlays we recommend using PNG or WebP images. - */ - url: string; - /** - * Floating-point number between 0 (transparent) and 1 (opaque). - * For example, opacity: 0.5 makes overlay semitransparent. - */ - opacity?: number; - /** - * - If set to true, the overlay image will be tiled to cover the entire - * area. This is useful for stock-photo-like watermarks. - * - If set to "x", the overlay image will be tiled horizontally only - * (form a line). - * - If set to "y", the overlay image will be tiled vertically only - * (form a line). - */ - repeat?: true | "x" | "y"; - /** - * Position of the overlay image relative to a given edge. Each property is - * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 - * positions left side of the overlay 10 pixels from the left edge of the - * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom - * of the background image. - * - * Setting both left & right, or both top & bottom is an error. - * - * If no position is specified, the image will be centered. - */ - top?: number; - left?: number; - bottom?: number; - right?: number; + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | 'x' | 'y' + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number + left?: number + bottom?: number + right?: number } interface RequestInitCfPropertiesImage extends BasicImageTransformations { - /** - * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it - * easier to specify higher-DPI sizes in . - */ - dpr?: number; - /** - * Allows you to trim your image. Takes dpr into account and is performed before - * resizing or rotation. - * - * It can be used as: - * - left, top, right, bottom - it will specify the number of pixels to cut - * off each side - * - width, height - the width/height you'd like to end up with - can be used - * in combination with the properties above - * - border - this will automatically trim the surroundings of an image based on - * it's color. It consists of three properties: - * - color: rgb or hex representation of the color you wish to trim (todo: verify the rgba bit) - * - tolerance: difference from color to treat as color - * - keep: the number of pixels of border to keep - */ - trim?: "border" | { - top?: number; - bottom?: number; - left?: number; - right?: number; - width?: number; - height?: number; - border?: boolean | { - color?: string; - tolerance?: number; - keep?: number; - }; - }; - /** - * Quality setting from 1-100 (useful values are in 60-90 range). Lower values - * make images look worse, but load faster. The default is 85. It applies only - * to JPEG and WebP images. It doesn’t have any effect on PNG. - */ - quality?: number | "low" | "medium-low" | "medium-high" | "high"; - /** - * Output format to generate. It can be: - * - avif: generate images in AVIF format. - * - webp: generate images in Google WebP format. Set quality to 100 to get - * the WebP-lossless format. - * - json: instead of generating an image, outputs information about the - * image, in JSON format. The JSON object will contain image size - * (before and after resizing), source image’s MIME type, file size, etc. - * - jpeg: generate images in JPEG format. - * - png: generate images in PNG format. - */ - format?: "avif" | "webp" | "json" | "jpeg" | "png" | "baseline-jpeg" | "png-force" | "svg"; - /** - * Whether to preserve animation frames from input files. Default is true. - * Setting it to false reduces animations to still images. This setting is - * recommended when enlarging images or processing arbitrary user content, - * because large GIF animations can weigh tens or even hundreds of megabytes. - * It is also useful to set anim:false when using format:"json" to get the - * response quicker without the number of frames. - */ - anim?: boolean; - /** - * What EXIF data should be preserved in the output image. Note that EXIF - * rotation and embedded color profiles are always applied ("baked in" into - * the image), and aren't affected by this option. Note that if the Polish - * feature is enabled, all metadata may have been removed already and this - * option may have no effect. - * - keep: Preserve most of EXIF metadata, including GPS location if there's - * any. - * - copyright: Only keep the copyright tag, and discard everything else. - * This is the default behavior for JPEG files. - * - none: Discard all invisible EXIF metadata. Currently WebP and PNG - * output formats always discard metadata. - */ - metadata?: "keep" | "copyright" | "none"; - /** - * Strength of sharpening filter to apply to the image. Floating-point - * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a - * recommended value for downscaled images. - */ - sharpen?: number; - /** - * Radius of a blur filter (approximate gaussian). Maximum supported radius - * is 250. - */ - blur?: number; - /** - * Overlays are drawn in the order they appear in the array (last array - * entry is the topmost layer). - */ - draw?: RequestInitCfPropertiesImageDraw[]; - /** - * Fetching image from authenticated origin. Setting this property will - * pass authentication headers (Authorization, Cookie, etc.) through to - * the origin. - */ - "origin-auth"?: "share-publicly"; - /** - * Adds a border around the image. The border is added after resizing. Border - * width takes dpr into account, and can be specified either using a single - * width property, or individually for each side. - */ - border?: { - color: string; - width: number; - } | { - color: string; - top: number; - right: number; - bottom: number; - left: number; - }; - /** - * Increase brightness by a factor. A value of 1.0 equals no change, a value - * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. - * 0 is ignored. - */ - brightness?: number; - /** - * Increase contrast by a factor. A value of 1.0 equals no change, a value of - * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is - * ignored. - */ - contrast?: number; - /** - * Increase exposure by a factor. A value of 1.0 equals no change, a value of - * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. - */ - gamma?: number; - /** - * Increase contrast by a factor. A value of 1.0 equals no change, a value of - * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is - * ignored. - */ - saturation?: number; - /** - * Flips the images horizontally, vertically, or both. Flipping is applied before - * rotation, so if you apply flip=h,rotate=90 then the image will be flipped - * horizontally, then rotated by 90 degrees. - */ - flip?: 'h' | 'v' | 'hv'; - /** - * Slightly reduces latency on a cache miss by selecting a - * quickest-to-compress file format, at a cost of increased file size and - * lower image quality. It will usually override the format option and choose - * JPEG over WebP or AVIF. We do not recommend using this option, except in - * unusual circumstances like resizing uncacheable dynamically-generated - * images. - */ - compression?: "fast"; + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in . + */ + dpr?: number + /** + * Allows you to trim your image. Takes dpr into account and is performed before + * resizing or rotation. + * + * It can be used as: + * - left, top, right, bottom - it will specify the number of pixels to cut + * off each side + * - width, height - the width/height you'd like to end up with - can be used + * in combination with the properties above + * - border - this will automatically trim the surroundings of an image based on + * it's color. It consists of three properties: + * - color: rgb or hex representation of the color you wish to trim (todo: verify the rgba bit) + * - tolerance: difference from color to treat as color + * - keep: the number of pixels of border to keep + */ + trim?: + | 'border' + | { + top?: number + bottom?: number + left?: number + right?: number + width?: number + height?: number + border?: + | boolean + | { + color?: string + tolerance?: number + keep?: number + } + } + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number | 'low' | 'medium-low' | 'medium-high' | 'high' + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: + | 'avif' + | 'webp' + | 'json' + | 'jpeg' + | 'png' + | 'baseline-jpeg' + | 'png-force' + | 'svg' + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: 'keep' | 'copyright' | 'none' + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[] + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + 'origin-auth'?: 'share-publicly' + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: + | { + color: string + width: number + } + | { + color: string + top: number + right: number + bottom: number + left: number + } + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + saturation?: number + /** + * Flips the images horizontally, vertically, or both. Flipping is applied before + * rotation, so if you apply flip=h,rotate=90 then the image will be flipped + * horizontally, then rotated by 90 degrees. + */ + flip?: 'h' | 'v' | 'hv' + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: 'fast' } interface RequestInitCfPropertiesImageMinify { - javascript?: boolean; - css?: boolean; - html?: boolean; + javascript?: boolean + css?: boolean + html?: boolean } interface RequestInitCfPropertiesR2 { - /** - * Colo id of bucket that an object is stored in - */ - bucketColoId?: number; + /** + * Colo id of bucket that an object is stored in + */ + bucketColoId?: number } /** * Request metadata provided by Cloudflare's edge. */ -type IncomingRequestCfProperties = IncomingRequestCfPropertiesBase & IncomingRequestCfPropertiesBotManagementEnterprise & IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & IncomingRequestCfPropertiesGeographicInformation & IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +type IncomingRequestCfProperties = + IncomingRequestCfPropertiesBase & + IncomingRequestCfPropertiesBotManagementEnterprise & + IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & + IncomingRequestCfPropertiesGeographicInformation & + IncomingRequestCfPropertiesCloudflareAccessOrApiShield interface IncomingRequestCfPropertiesBase extends Record { - /** - * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. - * - * @example 395747 - */ - asn?: number; - /** - * The organization which owns the ASN of the incoming request. - * - * @example "Google Cloud" - */ - asOrganization?: string; - /** - * The original value of the `Accept-Encoding` header if Cloudflare modified it. - * - * @example "gzip, deflate, br" - */ - clientAcceptEncoding?: string; - /** - * The number of milliseconds it took for the request to reach your worker. - * - * @example 22 - */ - clientTcpRtt?: number; - /** - * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) - * airport code of the data center that the request hit. - * - * @example "DFW" - */ - colo: string; - /** - * Represents the upstream's response to a - * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) - * from cloudflare. - * - * For workers with no upstream, this will always be `1`. - * - * @example 3 - */ - edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; - /** - * The HTTP Protocol the request used. - * - * @example "HTTP/2" - */ - httpProtocol: string; - /** - * The browser-requested prioritization information in the request object. - * - * If no information was set, defaults to the empty string `""` - * - * @example "weight=192;exclusive=0;group=3;group-weight=127" - * @default "" - */ - requestPriority: string; - /** - * The TLS version of the connection to Cloudflare. - * In requests served over plaintext (without TLS), this property is the empty string `""`. - * - * @example "TLSv1.3" - */ - tlsVersion: string; - /** - * The cipher for the connection to Cloudflare. - * In requests served over plaintext (without TLS), this property is the empty string `""`. - * - * @example "AEAD-AES128-GCM-SHA256" - */ - tlsCipher: string; - /** - * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. - * - * If the incoming request was served over plaintext (without TLS) this field is undefined. - */ - tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn?: number + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization?: string + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string + /** + * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata } interface IncomingRequestCfPropertiesBotManagementBase { - /** - * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, - * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). - * - * @example 54 - */ - score: number; - /** - * A boolean value that is true if the request comes from a good bot, like Google or Bing. - * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). - */ - verifiedBot: boolean; - /** - * A boolean value that is true if the request originates from a - * Cloudflare-verified proxy service. - */ - corporateProxy: boolean; - /** - * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. - */ - staticResource: boolean; - /** - * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). - */ - detectionIds: number[]; + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). + */ + verifiedBot: boolean + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean + /** + * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. + */ + staticResource: boolean + /** + * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). + */ + detectionIds: number[] } interface IncomingRequestCfPropertiesBotManagement { - /** - * Results of Cloudflare's Bot Management analysis - */ - botManagement: IncomingRequestCfPropertiesBotManagementBase; - /** - * Duplicate of `botManagement.score`. - * - * @deprecated - */ - clientTrustScore: number; + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number } -interface IncomingRequestCfPropertiesBotManagementEnterprise extends IncomingRequestCfPropertiesBotManagement { +interface IncomingRequestCfPropertiesBotManagementEnterprise + extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { /** - * Results of Cloudflare's Bot Management analysis + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. */ - botManagement: IncomingRequestCfPropertiesBotManagementBase & { - /** - * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients - * across different destination IPs, Ports, and X509 certificates. - */ - ja3Hash: string; - }; + ja3Hash: string + } } interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise { - /** - * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). - * - * This field is only present if you have Cloudflare for SaaS enabled on your account - * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). - */ - hostMetadata?: HostMetadata; + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata?: HostMetadata } interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { - /** - * Information about the client certificate presented to Cloudflare. - * - * This is populated when the incoming request is served over TLS using - * either Cloudflare Access or API Shield (mTLS) - * and the presented SSL certificate has a valid - * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) - * (i.e., not `null` or `""`). - * - * Otherwise, a set of placeholder values are used. - * - * The property `certPresented` will be set to `"1"` when - * the object is populated (i.e. the above conditions were met). - */ - tlsClientAuth: IncomingRequestCfPropertiesTLSClientAuth | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: + | IncomingRequestCfPropertiesTLSClientAuth + | IncomingRequestCfPropertiesTLSClientAuthPlaceholder } /** * Metadata about the request's TLS handshake */ interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { - /** - * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal - * - * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" - */ - clientHandshake: string; - /** - * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal - * - * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" - */ - serverHandshake: string; - /** - * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal - * - * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" - */ - clientFinished: string; - /** - * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal - * - * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" - */ - serverFinished: string; + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string } /** * Geographic data about the request's origin. */ interface IncomingRequestCfPropertiesGeographicInformation { - /** - * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. - * - * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. - * - * If Cloudflare is unable to determine where the request originated this property is omitted. - * - * The country code `"T1"` is used for requests originating on TOR. - * - * @example "GB" - */ - country?: Iso3166Alpha2Code | "T1"; - /** - * If present, this property indicates that the request originated in the EU - * - * @example "1" - */ - isEUCountry?: "1"; - /** - * A two-letter code indicating the continent the request originated from. - * - * @example "AN" - */ - continent?: ContinentCode; - /** - * The city the request originated from - * - * @example "Austin" - */ - city?: string; - /** - * Postal code of the incoming request - * - * @example "78701" - */ - postalCode?: string; - /** - * Latitude of the incoming request - * - * @example "30.27130" - */ - latitude?: string; - /** - * Longitude of the incoming request - * - * @example "-97.74260" - */ - longitude?: string; - /** - * Timezone of the incoming request - * - * @example "America/Chicago" - */ - timezone?: string; - /** - * If known, the ISO 3166-2 name for the first level region associated with - * the IP address of the incoming request - * - * @example "Texas" - */ - region?: string; - /** - * If known, the ISO 3166-2 code for the first-level region associated with - * the IP address of the incoming request - * - * @example "TX" - */ - regionCode?: string; - /** - * Metro code (DMA) of the incoming request - * - * @example "635" - */ - metroCode?: string; + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | 'T1' + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: '1' + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string } /** Data about the incoming request's TLS certificate */ interface IncomingRequestCfPropertiesTLSClientAuth { - /** Always `"1"`, indicating that the certificate was presented */ - certPresented: "1"; - /** - * Result of certificate verification. - * - * @example "FAILED:self signed certificate" - */ - certVerified: Exclude; - /** The presented certificate's revokation status. - * - * - A value of `"1"` indicates the certificate has been revoked - * - A value of `"0"` indicates the certificate has not been revoked - */ - certRevoked: "1" | "0"; - /** - * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) - * - * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" - */ - certIssuerDN: string; - /** - * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) - * - * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" - */ - certSubjectDN: string; - /** - * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) - * - * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" - */ - certIssuerDNRFC2253: string; - /** - * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) - * - * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" - */ - certSubjectDNRFC2253: string; - /** The certificate issuer's distinguished name (legacy policies) */ - certIssuerDNLegacy: string; - /** The certificate subject's distinguished name (legacy policies) */ - certSubjectDNLegacy: string; - /** - * The certificate's serial number - * - * @example "00936EACBE07F201DF" - */ - certSerial: string; - /** - * The certificate issuer's serial number - * - * @example "2489002934BDFEA34" - */ - certIssuerSerial: string; - /** - * The certificate's Subject Key Identifier - * - * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" - */ - certSKI: string; - /** - * The certificate issuer's Subject Key Identifier - * - * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" - */ - certIssuerSKI: string; - /** - * The certificate's SHA-1 fingerprint - * - * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" - */ - certFingerprintSHA1: string; - /** - * The certificate's SHA-256 fingerprint - * - * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" - */ - certFingerprintSHA256: string; - /** - * The effective starting date of the certificate - * - * @example "Dec 22 19:39:00 2018 GMT" - */ - certNotBefore: string; - /** - * The effective expiration date of the certificate - * - * @example "Dec 22 19:39:00 2018 GMT" - */ - certNotAfter: string; + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: '1' + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: '1' | '0' + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string } /** Placeholder values for TLS Client Authorization */ interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { - certPresented: "0"; - certVerified: "NONE"; - certRevoked: "0"; - certIssuerDN: ""; - certSubjectDN: ""; - certIssuerDNRFC2253: ""; - certSubjectDNRFC2253: ""; - certIssuerDNLegacy: ""; - certSubjectDNLegacy: ""; - certSerial: ""; - certIssuerSerial: ""; - certSKI: ""; - certIssuerSKI: ""; - certFingerprintSHA1: ""; - certFingerprintSHA256: ""; - certNotBefore: ""; - certNotAfter: ""; + certPresented: '0' + certVerified: 'NONE' + certRevoked: '0' + certIssuerDN: '' + certSubjectDN: '' + certIssuerDNRFC2253: '' + certSubjectDNRFC2253: '' + certIssuerDNLegacy: '' + certSubjectDNLegacy: '' + certSerial: '' + certIssuerSerial: '' + certSKI: '' + certIssuerSKI: '' + certFingerprintSHA1: '' + certFingerprintSHA256: '' + certNotBefore: '' + certNotAfter: '' } /** Possible outcomes of TLS verification */ -declare type CertVerificationStatus = -/** Authentication succeeded */ -"SUCCESS" -/** No certificate was presented */ - | "NONE" -/** Failed because the certificate was self-signed */ - | "FAILED:self signed certificate" -/** Failed because the certificate failed a trust chain check */ - | "FAILED:unable to verify the first certificate" -/** Failed because the certificate not yet valid */ - | "FAILED:certificate is not yet valid" -/** Failed because the certificate is expired */ - | "FAILED:certificate has expired" -/** Failed for another unspecified reason */ - | "FAILED"; +declare type CertVerificationStatus = + /** Authentication succeeded */ + | 'SUCCESS' + /** No certificate was presented */ + | 'NONE' + /** Failed because the certificate was self-signed */ + | 'FAILED:self signed certificate' + /** Failed because the certificate failed a trust chain check */ + | 'FAILED:unable to verify the first certificate' + /** Failed because the certificate not yet valid */ + | 'FAILED:certificate is not yet valid' + /** Failed because the certificate is expired */ + | 'FAILED:certificate has expired' + /** Failed for another unspecified reason */ + | 'FAILED' /** * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. */ -declare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = 0 /** Unknown */ | 1 /** no keepalives (not found) */ | 2 /** no connection re-use, opening keepalive connection failed */ | 3 /** no connection re-use, keepalive accepted and saved */ | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ | 5; /** connection re-use, accepted by the origin server */ +declare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = + | 0 /** Unknown */ + | 1 /** no keepalives (not found) */ + | 2 /** no connection re-use, opening keepalive connection failed */ + | 3 /** no connection re-use, keepalive accepted and saved */ + | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ + | 5 /** connection re-use, accepted by the origin server */ /** ISO 3166-1 Alpha-2 codes */ -declare type Iso3166Alpha2Code = "AD" | "AE" | "AF" | "AG" | "AI" | "AL" | "AM" | "AO" | "AQ" | "AR" | "AS" | "AT" | "AU" | "AW" | "AX" | "AZ" | "BA" | "BB" | "BD" | "BE" | "BF" | "BG" | "BH" | "BI" | "BJ" | "BL" | "BM" | "BN" | "BO" | "BQ" | "BR" | "BS" | "BT" | "BV" | "BW" | "BY" | "BZ" | "CA" | "CC" | "CD" | "CF" | "CG" | "CH" | "CI" | "CK" | "CL" | "CM" | "CN" | "CO" | "CR" | "CU" | "CV" | "CW" | "CX" | "CY" | "CZ" | "DE" | "DJ" | "DK" | "DM" | "DO" | "DZ" | "EC" | "EE" | "EG" | "EH" | "ER" | "ES" | "ET" | "FI" | "FJ" | "FK" | "FM" | "FO" | "FR" | "GA" | "GB" | "GD" | "GE" | "GF" | "GG" | "GH" | "GI" | "GL" | "GM" | "GN" | "GP" | "GQ" | "GR" | "GS" | "GT" | "GU" | "GW" | "GY" | "HK" | "HM" | "HN" | "HR" | "HT" | "HU" | "ID" | "IE" | "IL" | "IM" | "IN" | "IO" | "IQ" | "IR" | "IS" | "IT" | "JE" | "JM" | "JO" | "JP" | "KE" | "KG" | "KH" | "KI" | "KM" | "KN" | "KP" | "KR" | "KW" | "KY" | "KZ" | "LA" | "LB" | "LC" | "LI" | "LK" | "LR" | "LS" | "LT" | "LU" | "LV" | "LY" | "MA" | "MC" | "MD" | "ME" | "MF" | "MG" | "MH" | "MK" | "ML" | "MM" | "MN" | "MO" | "MP" | "MQ" | "MR" | "MS" | "MT" | "MU" | "MV" | "MW" | "MX" | "MY" | "MZ" | "NA" | "NC" | "NE" | "NF" | "NG" | "NI" | "NL" | "NO" | "NP" | "NR" | "NU" | "NZ" | "OM" | "PA" | "PE" | "PF" | "PG" | "PH" | "PK" | "PL" | "PM" | "PN" | "PR" | "PS" | "PT" | "PW" | "PY" | "QA" | "RE" | "RO" | "RS" | "RU" | "RW" | "SA" | "SB" | "SC" | "SD" | "SE" | "SG" | "SH" | "SI" | "SJ" | "SK" | "SL" | "SM" | "SN" | "SO" | "SR" | "SS" | "ST" | "SV" | "SX" | "SY" | "SZ" | "TC" | "TD" | "TF" | "TG" | "TH" | "TJ" | "TK" | "TL" | "TM" | "TN" | "TO" | "TR" | "TT" | "TV" | "TW" | "TZ" | "UA" | "UG" | "UM" | "US" | "UY" | "UZ" | "VA" | "VC" | "VE" | "VG" | "VI" | "VN" | "VU" | "WF" | "WS" | "YE" | "YT" | "ZA" | "ZM" | "ZW"; +declare type Iso3166Alpha2Code = + | 'AD' + | 'AE' + | 'AF' + | 'AG' + | 'AI' + | 'AL' + | 'AM' + | 'AO' + | 'AQ' + | 'AR' + | 'AS' + | 'AT' + | 'AU' + | 'AW' + | 'AX' + | 'AZ' + | 'BA' + | 'BB' + | 'BD' + | 'BE' + | 'BF' + | 'BG' + | 'BH' + | 'BI' + | 'BJ' + | 'BL' + | 'BM' + | 'BN' + | 'BO' + | 'BQ' + | 'BR' + | 'BS' + | 'BT' + | 'BV' + | 'BW' + | 'BY' + | 'BZ' + | 'CA' + | 'CC' + | 'CD' + | 'CF' + | 'CG' + | 'CH' + | 'CI' + | 'CK' + | 'CL' + | 'CM' + | 'CN' + | 'CO' + | 'CR' + | 'CU' + | 'CV' + | 'CW' + | 'CX' + | 'CY' + | 'CZ' + | 'DE' + | 'DJ' + | 'DK' + | 'DM' + | 'DO' + | 'DZ' + | 'EC' + | 'EE' + | 'EG' + | 'EH' + | 'ER' + | 'ES' + | 'ET' + | 'FI' + | 'FJ' + | 'FK' + | 'FM' + | 'FO' + | 'FR' + | 'GA' + | 'GB' + | 'GD' + | 'GE' + | 'GF' + | 'GG' + | 'GH' + | 'GI' + | 'GL' + | 'GM' + | 'GN' + | 'GP' + | 'GQ' + | 'GR' + | 'GS' + | 'GT' + | 'GU' + | 'GW' + | 'GY' + | 'HK' + | 'HM' + | 'HN' + | 'HR' + | 'HT' + | 'HU' + | 'ID' + | 'IE' + | 'IL' + | 'IM' + | 'IN' + | 'IO' + | 'IQ' + | 'IR' + | 'IS' + | 'IT' + | 'JE' + | 'JM' + | 'JO' + | 'JP' + | 'KE' + | 'KG' + | 'KH' + | 'KI' + | 'KM' + | 'KN' + | 'KP' + | 'KR' + | 'KW' + | 'KY' + | 'KZ' + | 'LA' + | 'LB' + | 'LC' + | 'LI' + | 'LK' + | 'LR' + | 'LS' + | 'LT' + | 'LU' + | 'LV' + | 'LY' + | 'MA' + | 'MC' + | 'MD' + | 'ME' + | 'MF' + | 'MG' + | 'MH' + | 'MK' + | 'ML' + | 'MM' + | 'MN' + | 'MO' + | 'MP' + | 'MQ' + | 'MR' + | 'MS' + | 'MT' + | 'MU' + | 'MV' + | 'MW' + | 'MX' + | 'MY' + | 'MZ' + | 'NA' + | 'NC' + | 'NE' + | 'NF' + | 'NG' + | 'NI' + | 'NL' + | 'NO' + | 'NP' + | 'NR' + | 'NU' + | 'NZ' + | 'OM' + | 'PA' + | 'PE' + | 'PF' + | 'PG' + | 'PH' + | 'PK' + | 'PL' + | 'PM' + | 'PN' + | 'PR' + | 'PS' + | 'PT' + | 'PW' + | 'PY' + | 'QA' + | 'RE' + | 'RO' + | 'RS' + | 'RU' + | 'RW' + | 'SA' + | 'SB' + | 'SC' + | 'SD' + | 'SE' + | 'SG' + | 'SH' + | 'SI' + | 'SJ' + | 'SK' + | 'SL' + | 'SM' + | 'SN' + | 'SO' + | 'SR' + | 'SS' + | 'ST' + | 'SV' + | 'SX' + | 'SY' + | 'SZ' + | 'TC' + | 'TD' + | 'TF' + | 'TG' + | 'TH' + | 'TJ' + | 'TK' + | 'TL' + | 'TM' + | 'TN' + | 'TO' + | 'TR' + | 'TT' + | 'TV' + | 'TW' + | 'TZ' + | 'UA' + | 'UG' + | 'UM' + | 'US' + | 'UY' + | 'UZ' + | 'VA' + | 'VC' + | 'VE' + | 'VG' + | 'VI' + | 'VN' + | 'VU' + | 'WF' + | 'WS' + | 'YE' + | 'YT' + | 'ZA' + | 'ZM' + | 'ZW' /** The 2-letter continent codes Cloudflare uses */ -declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; -type CfProperties = IncomingRequestCfProperties | RequestInitCfProperties; +declare type ContinentCode = 'AF' | 'AN' | 'AS' | 'EU' | 'NA' | 'OC' | 'SA' +type CfProperties = + | IncomingRequestCfProperties + | RequestInitCfProperties interface D1Meta { - duration: number; - size_after: number; - rows_read: number; - rows_written: number; - last_row_id: number; - changed_db: boolean; - changes: number; + duration: number + size_after: number + rows_read: number + rows_written: number + last_row_id: number + changed_db: boolean + changes: number + /** + * The region of the database instance that executed the query. + */ + served_by_region?: string + /** + * True if-and-only-if the database instance that executed the query was the primary. + */ + served_by_primary?: boolean + timings?: { /** - * The region of the database instance that executed the query. + * The duration of the SQL query execution by the database instance. It doesn't include any network time. */ - served_by_region?: string; - /** - * The three letters airport code of the colo that executed the query. - */ - served_by_colo?: string; - /** - * True if-and-only-if the database instance that executed the query was the primary. - */ - served_by_primary?: boolean; - timings?: { - /** - * The duration of the SQL query execution by the database instance. It doesn't include any network time. - */ - sql_duration_ms: number; - }; - /** - * Number of total attempts to execute the query, due to automatic retries. - * Note: All other fields in the response like `timings` only apply to the last attempt. - */ - total_attempts?: number; + sql_duration_ms: number + } + /** + * Number of total attempts to execute the query, due to automatic retries. + * Note: All other fields in the response like `timings` only apply to the last attempt. + */ + total_attempts?: number } interface D1Response { - success: true; - meta: D1Meta & Record; - error?: never; + success: true + meta: D1Meta & Record + error?: never } type D1Result = D1Response & { - results: T[]; -}; -interface D1ExecResult { - count: number; - duration: number; + results: T[] } -type D1SessionConstraint = -// Indicates that the first query should go to the primary, and the rest queries -// using the same D1DatabaseSession will go to any replica that is consistent with -// the bookmark maintained by the session (returned by the first query). -'first-primary' -// Indicates that the first query can go anywhere (primary or replica), and the rest queries -// using the same D1DatabaseSession will go to any replica that is consistent with -// the bookmark maintained by the session (returned by the first query). - | 'first-unconstrained'; -type D1SessionBookmark = string; +interface D1ExecResult { + count: number + duration: number +} +type D1SessionConstraint = + // Indicates that the first query should go to the primary, and the rest queries + // using the same D1DatabaseSession will go to any replica that is consistent with + // the bookmark maintained by the session (returned by the first query). + | 'first-primary' + // Indicates that the first query can go anywhere (primary or replica), and the rest queries + // using the same D1DatabaseSession will go to any replica that is consistent with + // the bookmark maintained by the session (returned by the first query). + | 'first-unconstrained' +type D1SessionBookmark = string declare abstract class D1Database { - prepare(query: string): D1PreparedStatement; - batch(statements: D1PreparedStatement[]): Promise[]>; - exec(query: string): Promise; - /** - * Creates a new D1 Session anchored at the given constraint or the bookmark. - * All queries executed using the created session will have sequential consistency, - * meaning that all writes done through the session will be visible in subsequent reads. - * - * @param constraintOrBookmark Either the session constraint or the explicit bookmark to anchor the created session. - */ - withSession(constraintOrBookmark?: D1SessionBookmark | D1SessionConstraint): D1DatabaseSession; - /** - * @deprecated dump() will be removed soon, only applies to deprecated alpha v1 databases. - */ - dump(): Promise; + prepare(query: string): D1PreparedStatement + batch(statements: D1PreparedStatement[]): Promise[]> + exec(query: string): Promise + /** + * Creates a new D1 Session anchored at the given constraint or the bookmark. + * All queries executed using the created session will have sequential consistency, + * meaning that all writes done through the session will be visible in subsequent reads. + * + * @param constraintOrBookmark Either the session constraint or the explicit bookmark to anchor the created session. + */ + withSession( + constraintOrBookmark?: D1SessionBookmark | D1SessionConstraint, + ): D1DatabaseSession + /** + * @deprecated dump() will be removed soon, only applies to deprecated alpha v1 databases. + */ + dump(): Promise } declare abstract class D1DatabaseSession { - prepare(query: string): D1PreparedStatement; - batch(statements: D1PreparedStatement[]): Promise[]>; - /** - * @returns The latest session bookmark across all executed queries on the session. - * If no query has been executed yet, `null` is returned. - */ - getBookmark(): D1SessionBookmark | null; + prepare(query: string): D1PreparedStatement + batch(statements: D1PreparedStatement[]): Promise[]> + /** + * @returns The latest session bookmark across all executed queries on the session. + * If no query has been executed yet, `null` is returned. + */ + getBookmark(): D1SessionBookmark | null } declare abstract class D1PreparedStatement { - bind(...values: unknown[]): D1PreparedStatement; - first(colName: string): Promise; - first>(): Promise; - run>(): Promise>; - all>(): Promise>; - raw(options: { - columnNames: true; - }): Promise<[ - string[], - ...T[] - ]>; - raw(options?: { - columnNames?: false; - }): Promise; + bind(...values: unknown[]): D1PreparedStatement + first(colName: string): Promise + first>(): Promise + run>(): Promise> + all>(): Promise> + raw(options: { + columnNames: true + }): Promise<[string[], ...T[]]> + raw(options?: { columnNames?: false }): Promise } // `Disposable` was added to TypeScript's standard lib types in version 5.2. // To support older TypeScript versions, define an empty `Disposable` interface. @@ -9848,1846 +8783,1138 @@ declare abstract class D1PreparedStatement { // but this will ensure type checking on older versions still passes. // TypeScript's interface merging will ensure our empty interface is effectively // ignored when `Disposable` is included in the standard lib. -interface Disposable { -} -/** - * The returned data after sending an email - */ -interface EmailSendResult { - /** - * The Email Message ID - */ - messageId: string; -} +interface Disposable {} /** * An email message that can be sent from a Worker. */ interface EmailMessage { - /** - * Envelope From attribute of the email message. - */ - readonly from: string; - /** - * Envelope To attribute of the email message. - */ - readonly to: string; + /** + * Envelope From attribute of the email message. + */ + readonly from: string + /** + * Envelope To attribute of the email message. + */ + readonly to: string } /** * An email message that is sent to a consumer Worker and can be rejected/forwarded. */ interface ForwardableEmailMessage extends EmailMessage { - /** - * Stream of the email message content. - */ - readonly raw: ReadableStream; - /** - * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). - */ - readonly headers: Headers; - /** - * Size of the email message content. - */ - readonly rawSize: number; - /** - * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. - * @param reason The reject reason. - * @returns void - */ - setReject(reason: string): void; - /** - * Forward this email message to a verified destination address of the account. - * @param rcptTo Verified destination address. - * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). - * @returns A promise that resolves when the email message is forwarded. - */ - forward(rcptTo: string, headers?: Headers): Promise; - /** - * Reply to the sender of this email message with a new EmailMessage object. - * @param message The reply message. - * @returns A promise that resolves when the email message is replied. - */ - reply(message: EmailMessage): Promise; -} -/** A file attachment for an email message */ -type EmailAttachment = { - disposition: 'inline'; - contentId: string; - filename: string; - type: string; - content: string | ArrayBuffer | ArrayBufferView; -} | { - disposition: 'attachment'; - contentId?: undefined; - filename: string; - type: string; - content: string | ArrayBuffer | ArrayBufferView; -}; -/** An Email Address */ -interface EmailAddress { - name: string; - email: string; + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers + /** + * Size of the email message content. + */ + readonly rawSize: number + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise + /** + * Reply to the sender of this email message with a new EmailMessage object. + * @param message The reply message. + * @returns A promise that resolves when the email message is replied. + */ + reply(message: EmailMessage): Promise } /** * A binding that allows a Worker to send email messages. */ interface SendEmail { - send(message: EmailMessage): Promise; - send(builder: { - from: string | EmailAddress; - to: string | string[]; - subject: string; - replyTo?: string | EmailAddress; - cc?: string | string[]; - bcc?: string | string[]; - headers?: Record; - text?: string; - html?: string; - attachments?: EmailAttachment[]; - }): Promise; + send(message: EmailMessage): Promise } declare abstract class EmailEvent extends ExtendableEvent { - readonly message: ForwardableEmailMessage; + readonly message: ForwardableEmailMessage } -declare type EmailExportedHandler = (message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext) => void | Promise; -declare module "cloudflare:email" { - let _EmailMessage: { - prototype: EmailMessage; - new (from: string, to: string, raw: ReadableStream | string): EmailMessage; - }; - export { _EmailMessage as EmailMessage }; +declare type EmailExportedHandler = ( + message: ForwardableEmailMessage, + env: Env, + ctx: ExecutionContext, +) => void | Promise +declare module 'cloudflare:email' { + let _EmailMessage: { + prototype: EmailMessage + new (from: string, to: string, raw: ReadableStream | string): EmailMessage + } + export { _EmailMessage as EmailMessage } } /** * Hello World binding to serve as an explanatory example. DO NOT USE */ interface HelloWorldBinding { - /** - * Retrieve the current stored value - */ - get(): Promise<{ - value: string; - ms?: number; - }>; - /** - * Set a new stored value - */ - set(value: string): Promise; + /** + * Retrieve the current stored value + */ + get(): Promise<{ + value: string + ms?: number + }> + /** + * Set a new stored value + */ + set(value: string): Promise } interface Hyperdrive { - /** - * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. - * - * Calling this method returns an identical socket to if you call - * `connect("host:port")` using the `host` and `port` fields from this object. - * Pick whichever approach works better with your preferred DB client library. - * - * Note that this socket is not yet authenticated -- it's expected that your - * code (or preferably, the client library of your choice) will authenticate - * using the information in this class's readonly fields. - */ - connect(): Socket; - /** - * A valid DB connection string that can be passed straight into the typical - * client library/driver/ORM. This will typically be the easiest way to use - * Hyperdrive. - */ - readonly connectionString: string; - /* - * A randomly generated hostname that is only valid within the context of the - * currently running Worker which, when passed into `connect()` function from - * the "cloudflare:sockets" module, will connect to the Hyperdrive instance - * for your database. - */ - readonly host: string; - /* - * The port that must be paired the the host field when connecting. - */ - readonly port: number; - /* - * The username to use when authenticating to your database via Hyperdrive. - * Unlike the host and password, this will be the same every time - */ - readonly user: string; - /* - * The randomly generated password to use when authenticating to your - * database via Hyperdrive. Like the host field, this password is only valid - * within the context of the currently running Worker instance from which - * it's read. - */ - readonly password: string; - /* - * The name of the database to connect to. - */ - readonly database: string; + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: number + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string + /* + * The name of the database to connect to. + */ + readonly database: string } // Copyright (c) 2024 Cloudflare, Inc. // Licensed under the Apache 2.0 license found in the LICENSE file or at: // https://opensource.org/licenses/Apache-2.0 -type ImageInfoResponse = { - format: 'image/svg+xml'; -} | { - format: string; - fileSize: number; - width: number; - height: number; -}; +type ImageInfoResponse = + | { + format: 'image/svg+xml' + } + | { + format: string + fileSize: number + width: number + height: number + } type ImageTransform = { - width?: number; - height?: number; - background?: string; - blur?: number; - border?: { - color?: string; - width?: number; - } | { - top?: number; - bottom?: number; - left?: number; - right?: number; - }; - brightness?: number; - contrast?: number; - fit?: 'scale-down' | 'contain' | 'pad' | 'squeeze' | 'cover' | 'crop'; - flip?: 'h' | 'v' | 'hv'; - gamma?: number; - segment?: 'foreground'; - gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | { - x?: number; - y?: number; - mode: 'remainder' | 'box-center'; - }; - rotate?: 0 | 90 | 180 | 270; - saturation?: number; - sharpen?: number; - trim?: 'border' | { - top?: number; - bottom?: number; - left?: number; - right?: number; - width?: number; - height?: number; - border?: boolean | { - color?: string; - tolerance?: number; - keep?: number; - }; - }; -}; + width?: number + height?: number + background?: string + blur?: number + border?: + | { + color?: string + width?: number + } + | { + top?: number + bottom?: number + left?: number + right?: number + } + brightness?: number + contrast?: number + fit?: 'scale-down' | 'contain' | 'pad' | 'squeeze' | 'cover' | 'crop' + flip?: 'h' | 'v' | 'hv' + gamma?: number + segment?: 'foreground' + gravity?: + | 'face' + | 'left' + | 'right' + | 'top' + | 'bottom' + | 'center' + | 'auto' + | 'entropy' + | { + x?: number + y?: number + mode: 'remainder' | 'box-center' + } + rotate?: 0 | 90 | 180 | 270 + saturation?: number + sharpen?: number + trim?: + | 'border' + | { + top?: number + bottom?: number + left?: number + right?: number + width?: number + height?: number + border?: + | boolean + | { + color?: string + tolerance?: number + keep?: number + } + } +} type ImageDrawOptions = { - opacity?: number; - repeat?: boolean | string; - top?: number; - left?: number; - bottom?: number; - right?: number; -}; + opacity?: number + repeat?: boolean | string + top?: number + left?: number + bottom?: number + right?: number +} type ImageInputOptions = { - encoding?: 'base64'; -}; + encoding?: 'base64' +} type ImageOutputOptions = { - format: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp' | 'image/avif' | 'rgb' | 'rgba'; - quality?: number; - background?: string; - anim?: boolean; -}; -interface ImageMetadata { - id: string; - filename?: string; - uploaded?: string; - requireSignedURLs: boolean; - meta?: Record; - variants: string[]; - draft?: boolean; - creator?: string; -} -interface ImageUploadOptions { - id?: string; - filename?: string; - requireSignedURLs?: boolean; - metadata?: Record; - creator?: string; - encoding?: 'base64'; -} -interface ImageUpdateOptions { - requireSignedURLs?: boolean; - metadata?: Record; - creator?: string; -} -interface ImageListOptions { - limit?: number; - cursor?: string; - sortOrder?: 'asc' | 'desc'; - creator?: string; -} -interface ImageList { - images: ImageMetadata[]; - cursor?: string; - listComplete: boolean; -} -interface HostedImagesBinding { - /** - * Get detailed metadata for a hosted image - * @param imageId The ID of the image (UUID or custom ID) - * @returns Image metadata, or null if not found - */ - details(imageId: string): Promise; - /** - * Get the raw image data for a hosted image - * @param imageId The ID of the image (UUID or custom ID) - * @returns ReadableStream of image bytes, or null if not found - */ - image(imageId: string): Promise | null>; - /** - * Upload a new hosted image - * @param image The image file to upload - * @param options Upload configuration - * @returns Metadata for the uploaded image - * @throws {@link ImagesError} if upload fails - */ - upload(image: ReadableStream | ArrayBuffer, options?: ImageUploadOptions): Promise; - /** - * Update hosted image metadata - * @param imageId The ID of the image - * @param options Properties to update - * @returns Updated image metadata - * @throws {@link ImagesError} if update fails - */ - update(imageId: string, options: ImageUpdateOptions): Promise; - /** - * Delete a hosted image - * @param imageId The ID of the image - * @returns True if deleted, false if not found - */ - delete(imageId: string): Promise; - /** - * List hosted images with pagination - * @param options List configuration - * @returns List of images with pagination info - * @throws {@link ImagesError} if list fails - */ - list(options?: ImageListOptions): Promise; + format: + | 'image/jpeg' + | 'image/png' + | 'image/gif' + | 'image/webp' + | 'image/avif' + | 'rgb' + | 'rgba' + quality?: number + background?: string + anim?: boolean } interface ImagesBinding { - /** - * Get image metadata (type, width and height) - * @throws {@link ImagesError} with code 9412 if input is not an image - * @param stream The image bytes - */ - info(stream: ReadableStream, options?: ImageInputOptions): Promise; - /** - * Begin applying a series of transformations to an image - * @param stream The image bytes - * @returns A transform handle - */ - input(stream: ReadableStream, options?: ImageInputOptions): ImageTransformer; - /** - * Access hosted images CRUD operations - */ - readonly hosted: HostedImagesBinding; + /** + * Get image metadata (type, width and height) + * @throws {@link ImagesError} with code 9412 if input is not an image + * @param stream The image bytes + */ + info( + stream: ReadableStream, + options?: ImageInputOptions, + ): Promise + /** + * Begin applying a series of transformations to an image + * @param stream The image bytes + * @returns A transform handle + */ + input( + stream: ReadableStream, + options?: ImageInputOptions, + ): ImageTransformer } interface ImageTransformer { - /** - * Apply transform next, returning a transform handle. - * You can then apply more transformations, draw, or retrieve the output. - * @param transform - */ - transform(transform: ImageTransform): ImageTransformer; - /** - * Draw an image on this transformer, returning a transform handle. - * You can then apply more transformations, draw, or retrieve the output. - * @param image The image (or transformer that will give the image) to draw - * @param options The options configuring how to draw the image - */ - draw(image: ReadableStream | ImageTransformer, options?: ImageDrawOptions): ImageTransformer; - /** - * Retrieve the image that results from applying the transforms to the - * provided input - * @param options Options that apply to the output e.g. output format - */ - output(options: ImageOutputOptions): Promise; + /** + * Apply transform next, returning a transform handle. + * You can then apply more transformations, draw, or retrieve the output. + * @param transform + */ + transform(transform: ImageTransform): ImageTransformer + /** + * Draw an image on this transformer, returning a transform handle. + * You can then apply more transformations, draw, or retrieve the output. + * @param image The image (or transformer that will give the image) to draw + * @param options The options configuring how to draw the image + */ + draw( + image: ReadableStream | ImageTransformer, + options?: ImageDrawOptions, + ): ImageTransformer + /** + * Retrieve the image that results from applying the transforms to the + * provided input + * @param options Options that apply to the output e.g. output format + */ + output(options: ImageOutputOptions): Promise } type ImageTransformationOutputOptions = { - encoding?: 'base64'; -}; + encoding?: 'base64' +} interface ImageTransformationResult { - /** - * The image as a response, ready to store in cache or return to users - */ - response(): Response; - /** - * The content type of the returned image - */ - contentType(): string; - /** - * The bytes of the response - */ - image(options?: ImageTransformationOutputOptions): ReadableStream; + /** + * The image as a response, ready to store in cache or return to users + */ + response(): Response + /** + * The content type of the returned image + */ + contentType(): string + /** + * The bytes of the response + */ + image(options?: ImageTransformationOutputOptions): ReadableStream } interface ImagesError extends Error { - readonly code: number; - readonly message: string; - readonly stack?: string; + readonly code: number + readonly message: string + readonly stack?: string } /** * Media binding for transforming media streams. * Provides the entry point for media transformation operations. */ interface MediaBinding { - /** - * Creates a media transformer from an input stream. - * @param media - The input media bytes - * @returns A MediaTransformer instance for applying transformations - */ - input(media: ReadableStream): MediaTransformer; + /** + * Creates a media transformer from an input stream. + * @param media - The input media bytes + * @returns A MediaTransformer instance for applying transformations + */ + input(media: ReadableStream): MediaTransformer } /** * Media transformer for applying transformation operations to media content. * Handles sizing, fitting, and other input transformation parameters. */ interface MediaTransformer { - /** - * Applies transformation options to the media content. - * @param transform - Configuration for how the media should be transformed - * @returns A generator for producing the transformed media output - */ - transform(transform?: MediaTransformationInputOptions): MediaTransformationGenerator; - /** - * Generates the final media output with specified options. - * @param output - Configuration for the output format and parameters - * @returns The final transformation result containing the transformed media - */ - output(output?: MediaTransformationOutputOptions): MediaTransformationResult; + /** + * Applies transformation options to the media content. + * @param transform - Configuration for how the media should be transformed + * @returns A generator for producing the transformed media output + */ + transform( + transform: MediaTransformationInputOptions, + ): MediaTransformationGenerator } /** * Generator for producing media transformation results. * Configures the output format and parameters for the transformed media. */ interface MediaTransformationGenerator { - /** - * Generates the final media output with specified options. - * @param output - Configuration for the output format and parameters - * @returns The final transformation result containing the transformed media - */ - output(output?: MediaTransformationOutputOptions): MediaTransformationResult; + /** + * Generates the final media output with specified options. + * @param output - Configuration for the output format and parameters + * @returns The final transformation result containing the transformed media + */ + output(output: MediaTransformationOutputOptions): MediaTransformationResult } /** * Result of a media transformation operation. * Provides multiple ways to access the transformed media content. */ interface MediaTransformationResult { - /** - * Returns the transformed media as a readable stream of bytes. - * @returns A promise containing a readable stream with the transformed media - */ - media(): Promise>; - /** - * Returns the transformed media as an HTTP response object. - * @returns The transformed media as a Promise, ready to store in cache or return to users - */ - response(): Promise; - /** - * Returns the MIME type of the transformed media. - * @returns A promise containing the content type string (e.g., 'image/jpeg', 'video/mp4') - */ - contentType(): Promise; + /** + * Returns the transformed media as a readable stream of bytes. + * @returns A stream containing the transformed media data + */ + media(): ReadableStream + /** + * Returns the transformed media as an HTTP response object. + * @returns The transformed media as a Response, ready to store in cache or return to users + */ + response(): Response + /** + * Returns the MIME type of the transformed media. + * @returns The content type string (e.g., 'image/jpeg', 'video/mp4') + */ + contentType(): string } /** * Configuration options for transforming media input. * Controls how the media should be resized and fitted. */ type MediaTransformationInputOptions = { - /** How the media should be resized to fit the specified dimensions */ - fit?: 'contain' | 'cover' | 'scale-down'; - /** Target width in pixels */ - width?: number; - /** Target height in pixels */ - height?: number; -}; + /** How the media should be resized to fit the specified dimensions */ + fit?: 'contain' | 'cover' | 'scale-down' + /** Target width in pixels */ + width?: number + /** Target height in pixels */ + height?: number +} /** * Configuration options for Media Transformations output. * Controls the format, timing, and type of the generated output. */ type MediaTransformationOutputOptions = { - /** - * Output mode determining the type of media to generate - */ - mode?: 'video' | 'spritesheet' | 'frame' | 'audio'; - /** Whether to include audio in the output */ - audio?: boolean; - /** - * Starting timestamp for frame extraction or start time for clips. (e.g. '2s'). - */ - time?: string; - /** - * Duration for video clips, audio extraction, and spritesheet generation (e.g. '5s'). - */ - duration?: string; - /** - * Number of frames in the spritesheet. - */ - imageCount?: number; - /** - * Output format for the generated media. - */ - format?: 'jpg' | 'png' | 'm4a'; -}; + /** + * Output mode determining the type of media to generate + */ + mode?: 'video' | 'spritesheet' | 'frame' | 'audio' + /** Whether to include audio in the output */ + audio?: boolean + /** + * Starting timestamp for frame extraction or start time for clips. (e.g. '2s'). + */ + time?: string + /** + * Duration for video clips, audio extraction, and spritesheet generation (e.g. '5s'). + */ + duration?: string + /** + * Number of frames in the spritesheet. + */ + imageCount?: number + /** + * Output format for the generated media. + */ + format?: 'jpg' | 'png' | 'm4a' +} /** * Error object for media transformation operations. * Extends the standard Error interface with additional media-specific information. */ interface MediaError extends Error { - readonly code: number; - readonly message: string; - readonly stack?: string; + readonly code: number + readonly message: string + readonly stack?: string } declare module 'cloudflare:node' { - interface NodeStyleServer { - listen(...args: unknown[]): this; - address(): { - port?: number | null | undefined; - }; + interface NodeStyleServer { + listen(...args: unknown[]): this + address(): { + port?: number | null | undefined } - export function httpServerHandler(port: number): ExportedHandler; - export function httpServerHandler(options: { - port: number; - }): ExportedHandler; - export function httpServerHandler(server: NodeStyleServer): ExportedHandler; + } + export function httpServerHandler(port: number): ExportedHandler + export function httpServerHandler(options: { port: number }): ExportedHandler + export function httpServerHandler(server: NodeStyleServer): ExportedHandler } -type Params

= Record; +type Params

= Record type EventContext = { - request: Request>; - functionPath: string; - waitUntil: (promise: Promise) => void; - passThroughOnException: () => void; - next: (input?: Request | string, init?: RequestInit) => Promise; - env: Env & { - ASSETS: { - fetch: typeof fetch; - }; - }; - params: Params

; - data: Data; -}; -type PagesFunction = Record> = (context: EventContext) => Response | Promise; + request: Request> + functionPath: string + waitUntil: (promise: Promise) => void + passThroughOnException: () => void + next: (input?: Request | string, init?: RequestInit) => Promise + env: Env & { + ASSETS: { + fetch: typeof fetch + } + } + params: Params

+ data: Data +} +type PagesFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, +> = (context: EventContext) => Response | Promise type EventPluginContext = { - request: Request>; - functionPath: string; - waitUntil: (promise: Promise) => void; - passThroughOnException: () => void; - next: (input?: Request | string, init?: RequestInit) => Promise; - env: Env & { - ASSETS: { - fetch: typeof fetch; - }; - }; - params: Params

; - data: Data; - pluginArgs: PluginArgs; -}; -type PagesPluginFunction = Record, PluginArgs = unknown> = (context: EventPluginContext) => Response | Promise; -declare module "assets:*" { - export const onRequest: PagesFunction; + request: Request> + functionPath: string + waitUntil: (promise: Promise) => void + passThroughOnException: () => void + next: (input?: Request | string, init?: RequestInit) => Promise + env: Env & { + ASSETS: { + fetch: typeof fetch + } + } + params: Params

) => Result> : Result>; - // Type for the callable part of an `Provider` if `T` is callable. - // This is intersected with methods/properties. - type MaybeCallableProvider = T extends (...args: any[]) => any ? MethodOrProperty : unknown; - // Base type for all other types providing RPC-like interfaces. - // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. - // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. - export type Provider = MaybeCallableProvider & Pick<{ - [K in keyof T]: MethodOrProperty; - }, Exclude>>; + type UnstubifyAll = { + [I in keyof A]: Unstubify + } + // Utility type for adding `Provider`/`Disposable`s to `object` types only. + // Note `unknown & T` is equivalent to `T`. + type MaybeProvider = T extends object ? Provider : unknown + type MaybeDisposable = T extends object ? Disposable : unknown + // Type for method return or property on an RPC interface. + // - Stubable types are replaced by stubs. + // - Serializable types are passed by value, with stubable types replaced by stubs + // and a top-level `Disposer`. + // Everything else can't be passed over PRC. + // Technically, we use custom thenables here, but they quack like `Promise`s. + // Intersecting with `(Maybe)Provider` allows pipelining. + // prettier-ignore + type Result = R extends Stubable ? Promise> & Provider : R extends Serializable ? Promise & MaybeDisposable> & MaybeProvider : never; + // Type for method or property on an RPC interface. + // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. + // Unwrapping `Stub`s allows calling with `Stubable` arguments. + // For properties, rewrite types to be `Result`s. + // In each case, unwrap `Promise`s. + type MethodOrProperty = V extends (...args: infer P) => infer R + ? (...args: UnstubifyAll

) => Result> + : Result> + // Type for the callable part of an `Provider` if `T` is callable. + // This is intersected with methods/properties. + type MaybeCallableProvider = T extends (...args: any[]) => any + ? MethodOrProperty + : unknown + // Base type for all other types providing RPC-like interfaces. + // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. + // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. + export type Provider< + T extends object, + Reserved extends string = never, + > = MaybeCallableProvider & { + [K in Exclude< + keyof T, + Reserved | symbol | keyof StubBase + >]: MethodOrProperty + } } declare namespace Cloudflare { - // Type of `env`. - // - // The specific project can extend `Env` by redeclaring it in project-specific files. Typescript - // will merge all declarations. - // - // You can use `wrangler types` to generate the `Env` type automatically. - interface Env { - } - // Project-specific parameters used to inform types. - // - // This interface is, again, intended to be declared in project-specific files, and then that - // declaration will be merged with this one. - // - // A project should have a declaration like this: - // - // interface GlobalProps { - // // Declares the main module's exports. Used to populate Cloudflare.Exports aka the type - // // of `ctx.exports`. - // mainModule: typeof import("my-main-module"); - // - // // Declares which of the main module's exports are configured with durable storage, and - // // thus should behave as Durable Object namsepace bindings. - // durableNamespaces: "MyDurableObject" | "AnotherDurableObject"; - // } - // - // You can use `wrangler types` to generate `GlobalProps` automatically. - interface GlobalProps { - } - // Evaluates to the type of a property in GlobalProps, defaulting to `Default` if it is not - // present. - type GlobalProp = K extends keyof GlobalProps ? GlobalProps[K] : Default; - // The type of the program's main module exports, if known. Requires `GlobalProps` to declare the - // `mainModule` property. - type MainModule = GlobalProp<"mainModule", {}>; - // The type of ctx.exports, which contains loopback bindings for all top-level exports. - type Exports = { - [K in keyof MainModule]: LoopbackForExport - // If the export is listed in `durableNamespaces`, then it is also a - // DurableObjectNamespace. - & (K extends GlobalProp<"durableNamespaces", never> ? MainModule[K] extends new (...args: any[]) => infer DoInstance ? DoInstance extends Rpc.DurableObjectBranded ? DurableObjectNamespace : DurableObjectNamespace : DurableObjectNamespace : {}); - }; + // Type of `env`. + // + // The specific project can extend `Env` by redeclaring it in project-specific files. Typescript + // will merge all declarations. + // + // You can use `wrangler types` to generate the `Env` type automatically. + interface Env {} + // Project-specific parameters used to inform types. + // + // This interface is, again, intended to be declared in project-specific files, and then that + // declaration will be merged with this one. + // + // A project should have a declaration like this: + // + // interface GlobalProps { + // // Declares the main module's exports. Used to populate Cloudflare.Exports aka the type + // // of `ctx.exports`. + // mainModule: typeof import("my-main-module"); + // + // // Declares which of the main module's exports are configured with durable storage, and + // // thus should behave as Durable Object namsepace bindings. + // durableNamespaces: "MyDurableObject" | "AnotherDurableObject"; + // } + // + // You can use `wrangler types` to generate `GlobalProps` automatically. + interface GlobalProps {} + // Evaluates to the type of a property in GlobalProps, defaulting to `Default` if it is not + // present. + type GlobalProp = K extends keyof GlobalProps + ? GlobalProps[K] + : Default + // The type of the program's main module exports, if known. Requires `GlobalProps` to declare the + // `mainModule` property. + type MainModule = GlobalProp<'mainModule', {}> + // The type of ctx.exports, which contains loopback bindings for all top-level exports. + type Exports = { + [K in keyof MainModule]: LoopbackForExport & + // If the export is listed in `durableNamespaces`, then it is also a + // DurableObjectNamespace. + (K extends GlobalProp<'durableNamespaces', never> + ? MainModule[K] extends new (...args: any[]) => infer DoInstance + ? DoInstance extends Rpc.DurableObjectBranded + ? DurableObjectNamespace + : DurableObjectNamespace + : DurableObjectNamespace + : {}) + } } declare namespace CloudflareWorkersModule { - export type RpcStub = Rpc.Stub; - export const RpcStub: { - new (value: T): Rpc.Stub; - }; - export abstract class RpcTarget implements Rpc.RpcTargetBranded { - [Rpc.__RPC_TARGET_BRAND]: never; + export type RpcStub = Rpc.Stub + export const RpcStub: { + new (value: T): Rpc.Stub + } + export abstract class RpcTarget implements Rpc.RpcTargetBranded { + [Rpc.__RPC_TARGET_BRAND]: never + } + // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC + export abstract class WorkerEntrypoint + implements Rpc.WorkerEntrypointBranded + { + [Rpc.__WORKER_ENTRYPOINT_BRAND]: never + protected ctx: ExecutionContext + protected env: Env + constructor(ctx: ExecutionContext, env: Env) + email?(message: ForwardableEmailMessage): void | Promise + fetch?(request: Request): Response | Promise + queue?(batch: MessageBatch): void | Promise + scheduled?(controller: ScheduledController): void | Promise + tail?(events: TraceItem[]): void | Promise + tailStream?( + event: TailStream.TailEvent, + ): + | TailStream.TailEventHandlerType + | Promise + test?(controller: TestController): void | Promise + trace?(traces: TraceItem[]): void | Promise + } + export abstract class DurableObject + implements Rpc.DurableObjectBranded + { + [Rpc.__DURABLE_OBJECT_BRAND]: never + protected ctx: DurableObjectState + protected env: Env + constructor(ctx: DurableObjectState, env: Env) + alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise + fetch?(request: Request): Response | Promise + webSocketMessage?( + ws: WebSocket, + message: string | ArrayBuffer, + ): void | Promise + webSocketClose?( + ws: WebSocket, + code: number, + reason: string, + wasClean: boolean, + ): void | Promise + webSocketError?(ws: WebSocket, error: unknown): void | Promise + } + export type WorkflowDurationLabel = + | 'second' + | 'minute' + | 'hour' + | 'day' + | 'week' + | 'month' + | 'year' + export type WorkflowSleepDuration = + | `${number} ${WorkflowDurationLabel}${'s' | ''}` + | number + export type WorkflowDelayDuration = WorkflowSleepDuration + export type WorkflowTimeoutDuration = WorkflowSleepDuration + export type WorkflowRetentionDuration = WorkflowSleepDuration + export type WorkflowBackoff = 'constant' | 'linear' | 'exponential' + export type WorkflowStepConfig = { + retries?: { + limit: number + delay: WorkflowDelayDuration | number + backoff?: WorkflowBackoff } - // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC - export abstract class WorkerEntrypoint implements Rpc.WorkerEntrypointBranded { - [Rpc.__WORKER_ENTRYPOINT_BRAND]: never; - protected ctx: ExecutionContext; - protected env: Env; - constructor(ctx: ExecutionContext, env: Env); - email?(message: ForwardableEmailMessage): void | Promise; - fetch?(request: Request): Response | Promise; - queue?(batch: MessageBatch): void | Promise; - scheduled?(controller: ScheduledController): void | Promise; - tail?(events: TraceItem[]): void | Promise; - tailStream?(event: TailStream.TailEvent): TailStream.TailEventHandlerType | Promise; - test?(controller: TestController): void | Promise; - trace?(traces: TraceItem[]): void | Promise; - } - export abstract class DurableObject implements Rpc.DurableObjectBranded { - [Rpc.__DURABLE_OBJECT_BRAND]: never; - protected ctx: DurableObjectState; - protected env: Env; - constructor(ctx: DurableObjectState, env: Env); - alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; - fetch?(request: Request): Response | Promise; - webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; - webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise; - webSocketError?(ws: WebSocket, error: unknown): void | Promise; - } - export type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; - export type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number; - export type WorkflowDelayDuration = WorkflowSleepDuration; - export type WorkflowTimeoutDuration = WorkflowSleepDuration; - export type WorkflowRetentionDuration = WorkflowSleepDuration; - export type WorkflowBackoff = 'constant' | 'linear' | 'exponential'; - export type WorkflowStepConfig = { - retries?: { - limit: number; - delay: WorkflowDelayDuration | number; - backoff?: WorkflowBackoff; - }; - timeout?: WorkflowTimeoutDuration | number; - }; - export type WorkflowEvent = { - payload: Readonly; - timestamp: Date; - instanceId: string; - }; - export type WorkflowStepEvent = { - payload: Readonly; - timestamp: Date; - type: string; - }; - export type WorkflowStepContext = { - attempt: number; - }; - export abstract class WorkflowStep { - do>(name: string, callback: (ctx: WorkflowStepContext) => Promise): Promise; - do>(name: string, config: WorkflowStepConfig, callback: (ctx: WorkflowStepContext) => Promise): Promise; - sleep: (name: string, duration: WorkflowSleepDuration) => Promise; - sleepUntil: (name: string, timestamp: Date | number) => Promise; - waitForEvent>(name: string, options: { - type: string; - timeout?: WorkflowTimeoutDuration | number; - }): Promise>; - } - export type WorkflowInstanceStatus = 'queued' | 'running' | 'paused' | 'errored' | 'terminated' | 'complete' | 'waiting' | 'waitingForPause' | 'unknown'; - export abstract class WorkflowEntrypoint | unknown = unknown> implements Rpc.WorkflowEntrypointBranded { - [Rpc.__WORKFLOW_ENTRYPOINT_BRAND]: never; - protected ctx: ExecutionContext; - protected env: Env; - constructor(ctx: ExecutionContext, env: Env); - run(event: Readonly>, step: WorkflowStep): Promise; - } - export function waitUntil(promise: Promise): void; - export function withEnv(newEnv: unknown, fn: () => unknown): unknown; - export function withExports(newExports: unknown, fn: () => unknown): unknown; - export function withEnvAndExports(newEnv: unknown, newExports: unknown, fn: () => unknown): unknown; - export const env: Cloudflare.Env; - export const exports: Cloudflare.Exports; + timeout?: WorkflowTimeoutDuration | number + } + export type WorkflowEvent = { + payload: Readonly + timestamp: Date + instanceId: string + } + export type WorkflowStepEvent = { + payload: Readonly + timestamp: Date + type: string + } + export abstract class WorkflowStep { + do>( + name: string, + callback: () => Promise, + ): Promise + do>( + name: string, + config: WorkflowStepConfig, + callback: () => Promise, + ): Promise + sleep: (name: string, duration: WorkflowSleepDuration) => Promise + sleepUntil: (name: string, timestamp: Date | number) => Promise + waitForEvent>( + name: string, + options: { + type: string + timeout?: WorkflowTimeoutDuration | number + }, + ): Promise> + } + export abstract class WorkflowEntrypoint< + Env = unknown, + T extends Rpc.Serializable | unknown = unknown, + > implements Rpc.WorkflowEntrypointBranded + { + [Rpc.__WORKFLOW_ENTRYPOINT_BRAND]: never + protected ctx: ExecutionContext + protected env: Env + constructor(ctx: ExecutionContext, env: Env) + run(event: Readonly>, step: WorkflowStep): Promise + } + export function waitUntil(promise: Promise): void + export const env: Cloudflare.Env } declare module 'cloudflare:workers' { - export = CloudflareWorkersModule; + export = CloudflareWorkersModule } interface SecretsStoreSecret { - /** - * Get a secret from the Secrets Store, returning a string of the secret value - * if it exists, or throws an error if it does not exist - */ - get(): Promise; + /** + * Get a secret from the Secrets Store, returning a string of the secret value + * if it exists, or throws an error if it does not exist + */ + get(): Promise } -declare module "cloudflare:sockets" { - function _connect(address: string | SocketAddress, options?: SocketOptions): Socket; - export { _connect as connect }; -} -/** - * Binding entrypoint for Cloudflare Stream. - * - * Usage: - * - Binding-level operations: - * `await env.STREAM.videos.upload` - * `await env.STREAM.videos.createDirectUpload` - * `await env.STREAM.videos.*` - * `await env.STREAM.watermarks.*` - * - Per-video operations: - * `await env.STREAM.video(id).downloads.*` - * `await env.STREAM.video(id).captions.*` - * - * Example usage: - * ```ts - * await env.STREAM.video(id).downloads.generate(); - * - * const video = env.STREAM.video(id) - * const captions = video.captions.list(); - * const videoDetails = video.details() - * ``` - */ -interface StreamBinding { - /** - * Returns a handle scoped to a single video for per-video operations. - * @param id The unique identifier for the video. - * @returns A handle for per-video operations. - */ - video(id: string): StreamVideoHandle; - /** - * Uploads a new video from a File. - * @param file The video file to upload. - * @returns The uploaded video details. - * @throws {BadRequestError} if the upload parameter is invalid - * @throws {QuotaReachedError} if the account storage capacity is exceeded - * @throws {MaxFileSizeError} if the file size is too large - * @throws {RateLimitedError} if the server received too many requests - * @throws {InternalError} if an unexpected error occurs - */ - upload(file: File): Promise; - /** - * Uploads a new video from a provided URL. - * @param url The URL to upload from. - * @param params Optional upload parameters. - * @returns The uploaded video details. - * @throws {BadRequestError} if the upload parameter is invalid or the URL is invalid - * @throws {QuotaReachedError} if the account storage capacity is exceeded - * @throws {MaxFileSizeError} if the file size is too large - * @throws {RateLimitedError} if the server received too many requests - * @throws {AlreadyUploadedError} if a video was already uploaded to this URL - * @throws {InternalError} if an unexpected error occurs - */ - upload(url: string, params?: StreamUrlUploadParams): Promise; - /** - * Creates a direct upload that allows video uploads without an API key. - * @param params Parameters for the direct upload - * @returns The direct upload details. - * @throws {BadRequestError} if the parameters are invalid - * @throws {RateLimitedError} if the server received too many requests - * @throws {InternalError} if an unexpected error occurs - */ - createDirectUpload(params: StreamDirectUploadCreateParams): Promise; - videos: StreamVideos; - watermarks: StreamWatermarks; -} -/** - * Handle for operations scoped to a single Stream video. - */ -interface StreamVideoHandle { - /** - * The unique identifier for the video. - */ - id: string; - /** - * Get a full videos details - * @returns The full video details. - * @throws {NotFoundError} if the video is not found - * @throws {InternalError} if an unexpected error occurs - */ - details(): Promise; - /** - * Update details for a single video. - * @param params The fields to update for the video. - * @returns The updated video details. - * @throws {NotFoundError} if the video is not found - * @throws {BadRequestError} if the parameters are invalid - * @throws {InternalError} if an unexpected error occurs - */ - update(params: StreamUpdateVideoParams): Promise; - /** - * Deletes a video and its copies from Cloudflare Stream. - * @returns A promise that resolves when deletion completes. - * @throws {NotFoundError} if the video is not found - * @throws {InternalError} if an unexpected error occurs - */ - delete(): Promise; - /** - * Creates a signed URL token for a video. - * @returns The signed token that was created. - * @throws {InternalError} if the signing key cannot be retrieved or the token cannot be signed - */ - generateToken(): Promise; - downloads: StreamScopedDownloads; - captions: StreamScopedCaptions; -} -interface StreamVideo { - /** - * The unique identifier for the video. - */ - id: string; - /** - * A user-defined identifier for the media creator. - */ - creator: string | null; - /** - * The thumbnail URL for the video. - */ - thumbnail: string; - /** - * The thumbnail timestamp percentage. - */ - thumbnailTimestampPct: number; - /** - * Indicates whether the video is ready to stream. - */ - readyToStream: boolean; - /** - * The date and time the video became ready to stream. - */ - readyToStreamAt: string | null; - /** - * Processing status information. - */ - status: StreamVideoStatus; - /** - * A user modifiable key-value store. - */ - meta: Record; - /** - * The date and time the video was created. - */ - created: string; - /** - * The date and time the video was last modified. - */ - modified: string; - /** - * The date and time at which the video will be deleted. - */ - scheduledDeletion: string | null; - /** - * The size of the video in bytes. - */ - size: number; - /** - * The preview URL for the video. - */ - preview?: string; - /** - * Origins allowed to display the video. - */ - allowedOrigins: Array; - /** - * Indicates whether signed URLs are required. - */ - requireSignedURLs: boolean | null; - /** - * The date and time the video was uploaded. - */ - uploaded: string | null; - /** - * The date and time when the upload URL expires. - */ - uploadExpiry: string | null; - /** - * The maximum size in bytes for direct uploads. - */ - maxSizeBytes: number | null; - /** - * The maximum duration in seconds for direct uploads. - */ - maxDurationSeconds: number | null; - /** - * The video duration in seconds. -1 indicates unknown. - */ - duration: number; - /** - * Input metadata for the original upload. - */ - input: StreamVideoInput; - /** - * Playback URLs for the video. - */ - hlsPlaybackUrl: string; - dashPlaybackUrl: string; - /** - * The watermark applied to the video, if any. - */ - watermark: StreamWatermark | null; - /** - * The live input id associated with the video, if any. - */ - liveInputId?: string | null; - /** - * The source video id if this is a clip. - */ - clippedFromId: string | null; - /** - * Public details associated with the video. - */ - publicDetails: StreamPublicDetails | null; -} -type StreamVideoStatus = { - /** - * The current processing state. - */ - state: string; - /** - * The current processing step. - */ - step?: string; - /** - * The percent complete as a string. - */ - pctComplete?: string; - /** - * An error reason code, if applicable. - */ - errorReasonCode: string; - /** - * An error reason text, if applicable. - */ - errorReasonText: string; -}; -type StreamVideoInput = { - /** - * The input width in pixels. - */ - width: number; - /** - * The input height in pixels. - */ - height: number; -}; -type StreamPublicDetails = { - /** - * The public title for the video. - */ - title: string | null; - /** - * The public share link. - */ - share_link: string | null; - /** - * The public channel link. - */ - channel_link: string | null; - /** - * The public logo URL. - */ - logo: string | null; -}; -type StreamDirectUpload = { - /** - * The URL an unauthenticated upload can use for a single multipart request. - */ - uploadURL: string; - /** - * A Cloudflare-generated unique identifier for a media item. - */ - id: string; - /** - * The watermark profile applied to the upload. - */ - watermark: StreamWatermark | null; - /** - * The scheduled deletion time, if any. - */ - scheduledDeletion: string | null; -}; -type StreamDirectUploadCreateParams = { - /** - * The maximum duration in seconds for a video upload. - */ - maxDurationSeconds: number; - /** - * The date and time after upload when videos will not be accepted. - */ - expiry?: string; - /** - * A user-defined identifier for the media creator. - */ - creator?: string; - /** - * A user modifiable key-value store used to reference other systems of record for - * managing videos. - */ - meta?: Record; - /** - * Lists the origins allowed to display the video. - */ - allowedOrigins?: Array; - /** - * Indicates whether the video can be accessed using the id. When set to `true`, - * a signed token must be generated with a signing key to view the video. - */ - requireSignedURLs?: boolean; - /** - * The thumbnail timestamp percentage. - */ - thumbnailTimestampPct?: number; - /** - * The date and time at which the video will be deleted. Include `null` to remove - * a scheduled deletion. - */ - scheduledDeletion?: string | null; - /** - * The watermark profile to apply. - */ - watermark?: StreamDirectUploadWatermark; -}; -type StreamDirectUploadWatermark = { - /** - * The unique identifier for the watermark profile. - */ - id: string; -}; -type StreamUrlUploadParams = { - /** - * Lists the origins allowed to display the video. Enter allowed origin - * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the - * video to be viewed on any origin. - */ - allowedOrigins?: Array; - /** - * A user-defined identifier for the media creator. - */ - creator?: string; - /** - * A user modifiable key-value store used to reference other systems of - * record for managing videos. - */ - meta?: Record; - /** - * Indicates whether the video can be a accessed using the id. When - * set to `true`, a signed token must be generated with a signing key to view the - * video. - */ - requireSignedURLs?: boolean; - /** - * Indicates the date and time at which the video will be deleted. Omit - * the field to indicate no change, or include with a `null` value to remove an - * existing scheduled deletion. If specified, must be at least 30 days from upload - * time. - */ - scheduledDeletion?: string | null; - /** - * The timestamp for a thumbnail image calculated as a percentage value - * of the video's duration. To convert from a second-wise timestamp to a - * percentage, divide the desired timestamp by the total duration of the video. If - * this value is not set, the default thumbnail image is taken from 0s of the - * video. - */ - thumbnailTimestampPct?: number; - /** - * The identifier for the watermark profile - */ - watermarkId?: string; -}; -interface StreamScopedCaptions { - /** - * Uploads the caption or subtitle file to the endpoint for a specific BCP47 language. - * One caption or subtitle file per language is allowed. - * @param language The BCP 47 language tag for the caption or subtitle. - * @param file The caption or subtitle file to upload. - * @returns The created caption entry. - * @throws {NotFoundError} if the video is not found - * @throws {BadRequestError} if the language or file is invalid - * @throws {MaxFileSizeError} if the file size is too large - * @throws {InternalError} if an unexpected error occurs - */ - upload(language: string, file: File): Promise; - /** - * Generate captions or subtitles for the provided language via AI. - * @param language The BCP 47 language tag to generate. - * @returns The generated caption entry. - * @throws {NotFoundError} if the video is not found - * @throws {BadRequestError} if the language is invalid - * @throws {StreamError} if a generated caption already exists - * @throws {StreamError} if the video duration is too long - * @throws {StreamError} if the video is missing audio - * @throws {StreamError} if the requested language is not supported - * @throws {InternalError} if an unexpected error occurs - */ - generate(language: string): Promise; - /** - * Lists the captions or subtitles. - * Use the language parameter to filter by a specific language. - * @param language The optional BCP 47 language tag to filter by. - * @returns The list of captions or subtitles. - * @throws {NotFoundError} if the video or caption is not found - * @throws {InternalError} if an unexpected error occurs - */ - list(language?: string): Promise; - /** - * Removes the captions or subtitles from a video. - * @param language The BCP 47 language tag to remove. - * @returns A promise that resolves when deletion completes. - * @throws {NotFoundError} if the video or caption is not found - * @throws {InternalError} if an unexpected error occurs - */ - delete(language: string): Promise; -} -interface StreamScopedDownloads { - /** - * Generates a download for a video when a video is ready to view. Available - * types are `default` and `audio`. Defaults to `default` when omitted. - * @param downloadType The download type to create. - * @returns The current downloads for the video. - * @throws {NotFoundError} if the video is not found - * @throws {BadRequestError} if the download type is invalid - * @throws {StreamError} if the video duration is too long to generate a download - * @throws {StreamError} if the video is not ready to stream - * @throws {InternalError} if an unexpected error occurs - */ - generate(downloadType?: StreamDownloadType): Promise; - /** - * Lists the downloads created for a video. - * @returns The current downloads for the video. - * @throws {NotFoundError} if the video or downloads are not found - * @throws {InternalError} if an unexpected error occurs - */ - get(): Promise; - /** - * Delete the downloads for a video. Available types are `default` and `audio`. - * Defaults to `default` when omitted. - * @param downloadType The download type to delete. - * @returns A promise that resolves when deletion completes. - * @throws {NotFoundError} if the video or downloads are not found - * @throws {InternalError} if an unexpected error occurs - */ - delete(downloadType?: StreamDownloadType): Promise; -} -interface StreamVideos { - /** - * Lists all videos in a users account. - * @returns The list of videos. - * @throws {BadRequestError} if the parameters are invalid - * @throws {InternalError} if an unexpected error occurs - */ - list(params?: StreamVideosListParams): Promise; -} -interface StreamWatermarks { - /** - * Generate a new watermark profile - * @param file The image file to upload - * @param params The watermark creation parameters. - * @returns The created watermark profile. - * @throws {BadRequestError} if the parameters are invalid - * @throws {InvalidURLError} if the URL is invalid - * @throws {MaxFileSizeError} if the file size is too large - * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached - * @throws {InternalError} if an unexpected error occurs - */ - generate(file: File, params: StreamWatermarkCreateParams): Promise; - /** - * Generate a new watermark profile - * @param url The image url to upload - * @param params The watermark creation parameters. - * @returns The created watermark profile. - * @throws {BadRequestError} if the parameters are invalid - * @throws {InvalidURLError} if the URL is invalid - * @throws {MaxFileSizeError} if the file size is too large - * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached - * @throws {InternalError} if an unexpected error occurs - */ - generate(url: string, params: StreamWatermarkCreateParams): Promise; - /** - * Lists all watermark profiles for an account. - * @returns The list of watermark profiles. - * @throws {InternalError} if an unexpected error occurs - */ - list(): Promise; - /** - * Retrieves details for a single watermark profile. - * @param watermarkId The watermark profile identifier. - * @returns The watermark profile details. - * @throws {NotFoundError} if the watermark is not found - * @throws {InternalError} if an unexpected error occurs - */ - get(watermarkId: string): Promise; - /** - * Deletes a watermark profile. - * @param watermarkId The watermark profile identifier. - * @returns A promise that resolves when deletion completes. - * @throws {NotFoundError} if the watermark is not found - * @throws {InternalError} if an unexpected error occurs - */ - delete(watermarkId: string): Promise; -} -type StreamUpdateVideoParams = { - /** - * Lists the origins allowed to display the video. Enter allowed origin - * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the - * video to be viewed on any origin. - */ - allowedOrigins?: Array; - /** - * A user-defined identifier for the media creator. - */ - creator?: string; - /** - * The maximum duration in seconds for a video upload. Can be set for a - * video that is not yet uploaded to limit its duration. Uploads that exceed the - * specified duration will fail during processing. A value of `-1` means the value - * is unknown. - */ - maxDurationSeconds?: number; - /** - * A user modifiable key-value store used to reference other systems of - * record for managing videos. - */ - meta?: Record; - /** - * Indicates whether the video can be a accessed using the id. When - * set to `true`, a signed token must be generated with a signing key to view the - * video. - */ - requireSignedURLs?: boolean; - /** - * Indicates the date and time at which the video will be deleted. Omit - * the field to indicate no change, or include with a `null` value to remove an - * existing scheduled deletion. If specified, must be at least 30 days from upload - * time. - */ - scheduledDeletion?: string | null; - /** - * The timestamp for a thumbnail image calculated as a percentage value - * of the video's duration. To convert from a second-wise timestamp to a - * percentage, divide the desired timestamp by the total duration of the video. If - * this value is not set, the default thumbnail image is taken from 0s of the - * video. - */ - thumbnailTimestampPct?: number; -}; -type StreamCaption = { - /** - * Whether the caption was generated via AI. - */ - generated?: boolean; - /** - * The language label displayed in the native language to users. - */ - label: string; - /** - * The language tag in BCP 47 format. - */ - language: string; - /** - * The status of a generated caption. - */ - status?: 'ready' | 'inprogress' | 'error'; -}; -type StreamDownloadStatus = 'ready' | 'inprogress' | 'error'; -type StreamDownloadType = 'default' | 'audio'; -type StreamDownload = { - /** - * Indicates the progress as a percentage between 0 and 100. - */ - percentComplete: number; - /** - * The status of a generated download. - */ - status: StreamDownloadStatus; - /** - * The URL to access the generated download. - */ - url?: string; -}; -/** - * An object with download type keys. Each key is optional and only present if that - * download type has been created. - */ -type StreamDownloadGetResponse = { - /** - * The audio-only download. Only present if this download type has been created. - */ - audio?: StreamDownload; - /** - * The default video download. Only present if this download type has been created. - */ - default?: StreamDownload; -}; -type StreamWatermarkPosition = 'upperRight' | 'upperLeft' | 'lowerLeft' | 'lowerRight' | 'center'; -type StreamWatermark = { - /** - * The unique identifier for a watermark profile. - */ - id: string; - /** - * The size of the image in bytes. - */ - size: number; - /** - * The height of the image in pixels. - */ - height: number; - /** - * The width of the image in pixels. - */ - width: number; - /** - * The date and a time a watermark profile was created. - */ - created: string; - /** - * The source URL for a downloaded image. If the watermark profile was created via - * direct upload, this field is null. - */ - downloadedFrom: string | null; - /** - * A short description of the watermark profile. - */ - name: string; - /** - * The translucency of the image. A value of `0.0` makes the image completely - * transparent, and `1.0` makes the image completely opaque. Note that if the image - * is already semi-transparent, setting this to `1.0` will not make the image - * completely opaque. - */ - opacity: number; - /** - * The whitespace between the adjacent edges (determined by position) of the video - * and the image. `0.0` indicates no padding, and `1.0` indicates a fully padded - * video width or length, as determined by the algorithm. - */ - padding: number; - /** - * The size of the image relative to the overall size of the video. This parameter - * will adapt to horizontal and vertical videos automatically. `0.0` indicates no - * scaling (use the size of the image as-is), and `1.0 `fills the entire video. - */ - scale: number; - /** - * The location of the image. Valid positions are: `upperRight`, `upperLeft`, - * `lowerLeft`, `lowerRight`, and `center`. Note that `center` ignores the - * `padding` parameter. - */ - position: StreamWatermarkPosition; -}; -type StreamWatermarkCreateParams = { - /** - * A short description of the watermark profile. - */ - name?: string; - /** - * The translucency of the image. A value of `0.0` makes the image completely - * transparent, and `1.0` makes the image completely opaque. Note that if the - * image is already semi-transparent, setting this to `1.0` will not make the - * image completely opaque. - */ - opacity?: number; - /** - * The whitespace between the adjacent edges (determined by position) of the - * video and the image. `0.0` indicates no padding, and `1.0` indicates a fully - * padded video width or length, as determined by the algorithm. - */ - padding?: number; - /** - * The size of the image relative to the overall size of the video. This - * parameter will adapt to horizontal and vertical videos automatically. `0.0` - * indicates no scaling (use the size of the image as-is), and `1.0 `fills the - * entire video. - */ - scale?: number; - /** - * The location of the image. - */ - position?: StreamWatermarkPosition; -}; -type StreamVideosListParams = { - /** - * The maximum number of videos to return. - */ - limit?: number; - /** - * Return videos created before this timestamp. - * (RFC3339/RFC3339Nano) - */ - before?: string; - /** - * Comparison operator for the `before` field. - * @default 'lt' - */ - beforeComp?: StreamPaginationComparison; - /** - * Return videos created after this timestamp. - * (RFC3339/RFC3339Nano) - */ - after?: string; - /** - * Comparison operator for the `after` field. - * @default 'gte' - */ - afterComp?: StreamPaginationComparison; -}; -type StreamPaginationComparison = 'eq' | 'gt' | 'gte' | 'lt' | 'lte'; -/** - * Error object for Stream binding operations. - */ -interface StreamError extends Error { - readonly code: number; - readonly statusCode: number; - readonly message: string; - readonly stack?: string; -} -interface InternalError extends StreamError { - name: 'InternalError'; -} -interface BadRequestError extends StreamError { - name: 'BadRequestError'; -} -interface NotFoundError extends StreamError { - name: 'NotFoundError'; -} -interface ForbiddenError extends StreamError { - name: 'ForbiddenError'; -} -interface RateLimitedError extends StreamError { - name: 'RateLimitedError'; -} -interface QuotaReachedError extends StreamError { - name: 'QuotaReachedError'; -} -interface MaxFileSizeError extends StreamError { - name: 'MaxFileSizeError'; -} -interface InvalidURLError extends StreamError { - name: 'InvalidURLError'; -} -interface AlreadyUploadedError extends StreamError { - name: 'AlreadyUploadedError'; -} -interface TooManyWatermarksError extends StreamError { - name: 'TooManyWatermarksError'; +declare module 'cloudflare:sockets' { + function _connect( + address: string | SocketAddress, + options?: SocketOptions, + ): Socket + export { _connect as connect } } type MarkdownDocument = { - name: string; - blob: Blob; -}; -type ConversionResponse = { - id: string; - name: string; - mimeType: string; - format: 'markdown'; - tokens: number; - data: string; -} | { - id: string; - name: string; - mimeType: string; - format: 'error'; - error: string; -}; + name: string + blob: Blob +} +type ConversionResponse = + | { + name: string + mimeType: string + format: 'markdown' + tokens: number + data: string + } + | { + name: string + mimeType: string + format: 'error' + error: string + } type ImageConversionOptions = { - descriptionLanguage?: 'en' | 'es' | 'fr' | 'it' | 'pt' | 'de'; -}; + descriptionLanguage?: 'en' | 'es' | 'fr' | 'it' | 'pt' | 'de' +} type EmbeddedImageConversionOptions = ImageConversionOptions & { - convert?: boolean; - maxConvertedImages?: number; -}; + convert?: boolean + maxConvertedImages?: number +} type ConversionOptions = { - html?: { - images?: EmbeddedImageConversionOptions & { - convertOGImage?: boolean; - }; - hostname?: string; - cssSelector?: string; - }; - docx?: { - images?: EmbeddedImageConversionOptions; - }; - image?: ImageConversionOptions; - pdf?: { - images?: EmbeddedImageConversionOptions; - metadata?: boolean; - }; -}; + html?: { + images?: EmbeddedImageConversionOptions & { + convertOGImage?: boolean + } + } + docx?: { + images?: EmbeddedImageConversionOptions + } + image?: ImageConversionOptions + pdf?: { + images?: EmbeddedImageConversionOptions + metadata?: boolean + } +} type ConversionRequestOptions = { - gateway?: GatewayOptions; - extraHeaders?: object; - conversionOptions?: ConversionOptions; -}; + gateway?: GatewayOptions + extraHeaders?: object + conversionOptions?: ConversionOptions +} type SupportedFileFormat = { - mimeType: string; - extension: string; -}; + mimeType: string + extension: string +} declare abstract class ToMarkdownService { - transform(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise; - transform(files: MarkdownDocument, options?: ConversionRequestOptions): Promise; - supported(): Promise; + transform( + files: MarkdownDocument[], + options?: ConversionRequestOptions, + ): Promise + transform( + files: MarkdownDocument, + options?: ConversionRequestOptions, + ): Promise + supported(): Promise } declare namespace TailStream { - interface Header { - readonly name: string; - readonly value: string; - } - interface FetchEventInfo { - readonly type: "fetch"; - readonly method: string; - readonly url: string; - readonly cfJson?: object; - readonly headers: Header[]; - } - interface JsRpcEventInfo { - readonly type: "jsrpc"; - } - interface ScheduledEventInfo { - readonly type: "scheduled"; - readonly scheduledTime: Date; - readonly cron: string; - } - interface AlarmEventInfo { - readonly type: "alarm"; - readonly scheduledTime: Date; - } - interface QueueEventInfo { - readonly type: "queue"; - readonly queueName: string; - readonly batchSize: number; - } - interface EmailEventInfo { - readonly type: "email"; - readonly mailFrom: string; - readonly rcptTo: string; - readonly rawSize: number; - } - interface TraceEventInfo { - readonly type: "trace"; - readonly traces: (string | null)[]; - } - interface HibernatableWebSocketEventInfoMessage { - readonly type: "message"; - } - interface HibernatableWebSocketEventInfoError { - readonly type: "error"; - } - interface HibernatableWebSocketEventInfoClose { - readonly type: "close"; - readonly code: number; - readonly wasClean: boolean; - } - interface HibernatableWebSocketEventInfo { - readonly type: "hibernatableWebSocket"; - readonly info: HibernatableWebSocketEventInfoClose | HibernatableWebSocketEventInfoError | HibernatableWebSocketEventInfoMessage; - } - interface CustomEventInfo { - readonly type: "custom"; - } - interface FetchResponseInfo { - readonly type: "fetch"; - readonly statusCode: number; - } - type EventOutcome = "ok" | "canceled" | "exception" | "unknown" | "killSwitch" | "daemonDown" | "exceededCpu" | "exceededMemory" | "loadShed" | "responseStreamDisconnected" | "scriptNotFound"; - interface ScriptVersion { - readonly id: string; - readonly tag?: string; - readonly message?: string; - } - interface Onset { - readonly type: "onset"; - readonly attributes: Attribute[]; - // id for the span being opened by this Onset event. - readonly spanId: string; - readonly dispatchNamespace?: string; - readonly entrypoint?: string; - readonly executionModel: string; - readonly scriptName?: string; - readonly scriptTags?: string[]; - readonly scriptVersion?: ScriptVersion; - readonly info: FetchEventInfo | JsRpcEventInfo | ScheduledEventInfo | AlarmEventInfo | QueueEventInfo | EmailEventInfo | TraceEventInfo | HibernatableWebSocketEventInfo | CustomEventInfo; - } - interface Outcome { - readonly type: "outcome"; - readonly outcome: EventOutcome; - readonly cpuTime: number; - readonly wallTime: number; - } - interface SpanOpen { - readonly type: "spanOpen"; - readonly name: string; - // id for the span being opened by this SpanOpen event. - readonly spanId: string; - readonly info?: FetchEventInfo | JsRpcEventInfo | Attributes; - } - interface SpanClose { - readonly type: "spanClose"; - readonly outcome: EventOutcome; - } - interface DiagnosticChannelEvent { - readonly type: "diagnosticChannel"; - readonly channel: string; - readonly message: any; - } - interface Exception { - readonly type: "exception"; - readonly name: string; - readonly message: string; - readonly stack?: string; - } - interface Log { - readonly type: "log"; - readonly level: "debug" | "error" | "info" | "log" | "warn"; - readonly message: object; - } - interface DroppedEventsDiagnostic { - readonly diagnosticsType: "droppedEvents"; - readonly count: number; - } - interface StreamDiagnostic { - readonly type: 'streamDiagnostic'; - // To add new diagnostic types, define a new interface and add it to this union type. - readonly diagnostic: DroppedEventsDiagnostic; - } - // This marks the worker handler return information. - // This is separate from Outcome because the worker invocation can live for a long time after - // returning. For example - Websockets that return an http upgrade response but then continue - // streaming information or SSE http connections. - interface Return { - readonly type: "return"; - readonly info?: FetchResponseInfo; - } - interface Attribute { - readonly name: string; - readonly value: string | string[] | boolean | boolean[] | number | number[] | bigint | bigint[]; - } - interface Attributes { - readonly type: "attributes"; - readonly info: Attribute[]; - } - type EventType = Onset | Outcome | SpanOpen | SpanClose | DiagnosticChannelEvent | Exception | Log | StreamDiagnostic | Return | Attributes; - // Context in which this trace event lives. - interface SpanContext { - // Single id for the entire top-level invocation - // This should be a new traceId for the first worker stage invoked in the eyeball request and then - // same-account service-bindings should reuse the same traceId but cross-account service-bindings - // should use a new traceId. - readonly traceId: string; - // spanId in which this event is handled - // for Onset and SpanOpen events this would be the parent span id - // for Outcome and SpanClose these this would be the span id of the opening Onset and SpanOpen events - // For Hibernate and Mark this would be the span under which they were emitted. - // spanId is not set ONLY if: - // 1. This is an Onset event - // 2. We are not inheriting any SpanContext. (e.g. this is a cross-account service binding or a new top-level invocation) - readonly spanId?: string; - } - interface TailEvent { - // invocation id of the currently invoked worker stage. - // invocation id will always be unique to every Onset event and will be the same until the Outcome event. - readonly invocationId: string; - // Inherited spanContext for this event. - readonly spanContext: SpanContext; - readonly timestamp: Date; - readonly sequence: number; - readonly event: Event; - } - type TailEventHandler = (event: TailEvent) => void | Promise; - type TailEventHandlerObject = { - outcome?: TailEventHandler; - spanOpen?: TailEventHandler; - spanClose?: TailEventHandler; - diagnosticChannel?: TailEventHandler; - exception?: TailEventHandler; - log?: TailEventHandler; - return?: TailEventHandler; - attributes?: TailEventHandler; - }; - type TailEventHandlerType = TailEventHandler | TailEventHandlerObject; + interface Header { + readonly name: string + readonly value: string + } + interface FetchEventInfo { + readonly type: 'fetch' + readonly method: string + readonly url: string + readonly cfJson?: object + readonly headers: Header[] + } + interface JsRpcEventInfo { + readonly type: 'jsrpc' + } + interface ScheduledEventInfo { + readonly type: 'scheduled' + readonly scheduledTime: Date + readonly cron: string + } + interface AlarmEventInfo { + readonly type: 'alarm' + readonly scheduledTime: Date + } + interface QueueEventInfo { + readonly type: 'queue' + readonly queueName: string + readonly batchSize: number + } + interface EmailEventInfo { + readonly type: 'email' + readonly mailFrom: string + readonly rcptTo: string + readonly rawSize: number + } + interface TraceEventInfo { + readonly type: 'trace' + readonly traces: (string | null)[] + } + interface HibernatableWebSocketEventInfoMessage { + readonly type: 'message' + } + interface HibernatableWebSocketEventInfoError { + readonly type: 'error' + } + interface HibernatableWebSocketEventInfoClose { + readonly type: 'close' + readonly code: number + readonly wasClean: boolean + } + interface HibernatableWebSocketEventInfo { + readonly type: 'hibernatableWebSocket' + readonly info: + | HibernatableWebSocketEventInfoClose + | HibernatableWebSocketEventInfoError + | HibernatableWebSocketEventInfoMessage + } + interface CustomEventInfo { + readonly type: 'custom' + } + interface FetchResponseInfo { + readonly type: 'fetch' + readonly statusCode: number + } + type EventOutcome = + | 'ok' + | 'canceled' + | 'exception' + | 'unknown' + | 'killSwitch' + | 'daemonDown' + | 'exceededCpu' + | 'exceededMemory' + | 'loadShed' + | 'responseStreamDisconnected' + | 'scriptNotFound' + interface ScriptVersion { + readonly id: string + readonly tag?: string + readonly message?: string + } + interface Onset { + readonly type: 'onset' + readonly attributes: Attribute[] + // id for the span being opened by this Onset event. + readonly spanId: string + readonly dispatchNamespace?: string + readonly entrypoint?: string + readonly executionModel: string + readonly scriptName?: string + readonly scriptTags?: string[] + readonly scriptVersion?: ScriptVersion + readonly info: + | FetchEventInfo + | JsRpcEventInfo + | ScheduledEventInfo + | AlarmEventInfo + | QueueEventInfo + | EmailEventInfo + | TraceEventInfo + | HibernatableWebSocketEventInfo + | CustomEventInfo + } + interface Outcome { + readonly type: 'outcome' + readonly outcome: EventOutcome + readonly cpuTime: number + readonly wallTime: number + } + interface SpanOpen { + readonly type: 'spanOpen' + readonly name: string + // id for the span being opened by this SpanOpen event. + readonly spanId: string + readonly info?: FetchEventInfo | JsRpcEventInfo | Attributes + } + interface SpanClose { + readonly type: 'spanClose' + readonly outcome: EventOutcome + } + interface DiagnosticChannelEvent { + readonly type: 'diagnosticChannel' + readonly channel: string + readonly message: any + } + interface Exception { + readonly type: 'exception' + readonly name: string + readonly message: string + readonly stack?: string + } + interface Log { + readonly type: 'log' + readonly level: 'debug' | 'error' | 'info' | 'log' | 'warn' + readonly message: object + } + // This marks the worker handler return information. + // This is separate from Outcome because the worker invocation can live for a long time after + // returning. For example - Websockets that return an http upgrade response but then continue + // streaming information or SSE http connections. + interface Return { + readonly type: 'return' + readonly info?: FetchResponseInfo + } + interface Attribute { + readonly name: string + readonly value: + | string + | string[] + | boolean + | boolean[] + | number + | number[] + | bigint + | bigint[] + } + interface Attributes { + readonly type: 'attributes' + readonly info: Attribute[] + } + type EventType = + | Onset + | Outcome + | SpanOpen + | SpanClose + | DiagnosticChannelEvent + | Exception + | Log + | Return + | Attributes + // Context in which this trace event lives. + interface SpanContext { + // Single id for the entire top-level invocation + // This should be a new traceId for the first worker stage invoked in the eyeball request and then + // same-account service-bindings should reuse the same traceId but cross-account service-bindings + // should use a new traceId. + readonly traceId: string + // spanId in which this event is handled + // for Onset and SpanOpen events this would be the parent span id + // for Outcome and SpanClose these this would be the span id of the opening Onset and SpanOpen events + // For Hibernate and Mark this would be the span under which they were emitted. + // spanId is not set ONLY if: + // 1. This is an Onset event + // 2. We are not inherting any SpanContext. (e.g. this is a cross-account service binding or a new top-level invocation) + readonly spanId?: string + } + interface TailEvent { + // invocation id of the currently invoked worker stage. + // invocation id will always be unique to every Onset event and will be the same until the Outcome event. + readonly invocationId: string + // Inherited spanContext for this event. + readonly spanContext: SpanContext + readonly timestamp: Date + readonly sequence: number + readonly event: Event + } + type TailEventHandler = ( + event: TailEvent, + ) => void | Promise + type TailEventHandlerObject = { + outcome?: TailEventHandler + spanOpen?: TailEventHandler + spanClose?: TailEventHandler + diagnosticChannel?: TailEventHandler + exception?: TailEventHandler + log?: TailEventHandler + return?: TailEventHandler + attributes?: TailEventHandler + } + type TailEventHandlerType = TailEventHandler | TailEventHandlerObject } // Copyright (c) 2022-2023 Cloudflare, Inc. // Licensed under the Apache 2.0 license found in the LICENSE file or at: @@ -11695,38 +9922,56 @@ declare namespace TailStream { /** * Data types supported for holding vector metadata. */ -type VectorizeVectorMetadataValue = string | number | boolean | string[]; +type VectorizeVectorMetadataValue = string | number | boolean | string[] /** * Additional information to associate with a vector. */ -type VectorizeVectorMetadata = VectorizeVectorMetadataValue | Record; -type VectorFloatArray = Float32Array | Float64Array; +type VectorizeVectorMetadata = + | VectorizeVectorMetadataValue + | Record +type VectorFloatArray = Float32Array | Float64Array interface VectorizeError { - code?: number; - error: string; + code?: number + error: string } /** * Comparison logic/operation to use for metadata filtering. * * This list is expected to grow as support for more operations are released. */ -type VectorizeVectorMetadataFilterOp = '$eq' | '$ne' | '$lt' | '$lte' | '$gt' | '$gte'; -type VectorizeVectorMetadataFilterCollectionOp = '$in' | '$nin'; +type VectorizeVectorMetadataFilterOp = + | '$eq' + | '$ne' + | '$lt' + | '$lte' + | '$gt' + | '$gte' +type VectorizeVectorMetadataFilterCollectionOp = '$in' | '$nin' /** * Filter criteria for vector metadata used to limit the retrieved query result set. */ type VectorizeVectorMetadataFilter = { - [field: string]: Exclude | null | { - [Op in VectorizeVectorMetadataFilterOp]?: Exclude | null; - } | { - [Op in VectorizeVectorMetadataFilterCollectionOp]?: Exclude[]; - }; -}; + [field: string]: + | Exclude + | null + | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude< + VectorizeVectorMetadataValue, + string[] + > | null + } + | { + [Op in VectorizeVectorMetadataFilterCollectionOp]?: Exclude< + VectorizeVectorMetadataValue, + string[] + >[] + } +} /** * Supported distance metrics for an index. * Distance metrics determine how other "similar" vectors are determined. */ -type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +type VectorizeDistanceMetric = 'euclidean' | 'cosine' | 'dot-product' /** * Metadata return levels for a Vectorize query. * @@ -11736,23 +9981,25 @@ type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; * @property indexed Return all metadata fields configured for indexing in the vector return set. This level of retrieval is "free" in that no additional overhead is incurred returning this data. However, note that indexed metadata is subject to truncation (especially for larger strings). * @property none No indexed metadata will be returned. */ -type VectorizeMetadataRetrievalLevel = "all" | "indexed" | "none"; +type VectorizeMetadataRetrievalLevel = 'all' | 'indexed' | 'none' interface VectorizeQueryOptions { - topK?: number; - namespace?: string; - returnValues?: boolean; - returnMetadata?: boolean | VectorizeMetadataRetrievalLevel; - filter?: VectorizeVectorMetadataFilter; + topK?: number + namespace?: string + returnValues?: boolean + returnMetadata?: boolean | VectorizeMetadataRetrievalLevel + filter?: VectorizeVectorMetadataFilter } /** * Information about the configuration of an index. */ -type VectorizeIndexConfig = { - dimensions: number; - metric: VectorizeDistanceMetric; -} | { - preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity -}; +type VectorizeIndexConfig = + | { + dimensions: number + metric: VectorizeDistanceMetric + } + | { + preset: string // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity + } /** * Metadata about an existing index. * @@ -11760,56 +10007,57 @@ type VectorizeIndexConfig = { * See {@link VectorizeIndexInfo} for its post-beta equivalent. */ interface VectorizeIndexDetails { - /** The unique ID of the index */ - readonly id: string; - /** The name of the index. */ - name: string; - /** (optional) A human readable description for the index. */ - description?: string; - /** The index configuration, including the dimension size and distance metric. */ - config: VectorizeIndexConfig; - /** The number of records containing vectors within the index. */ - vectorsCount: number; + /** The unique ID of the index */ + readonly id: string + /** The name of the index. */ + name: string + /** (optional) A human readable description for the index. */ + description?: string + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig + /** The number of records containing vectors within the index. */ + vectorsCount: number } /** * Metadata about an existing index. */ interface VectorizeIndexInfo { - /** The number of records containing vectors within the index. */ - vectorCount: number; - /** Number of dimensions the index has been configured for. */ - dimensions: number; - /** ISO 8601 datetime of the last processed mutation on in the index. All changes before this mutation will be reflected in the index state. */ - processedUpToDatetime: number; - /** UUIDv4 of the last mutation processed by the index. All changes before this mutation will be reflected in the index state. */ - processedUpToMutation: number; + /** The number of records containing vectors within the index. */ + vectorCount: number + /** Number of dimensions the index has been configured for. */ + dimensions: number + /** ISO 8601 datetime of the last processed mutation on in the index. All changes before this mutation will be reflected in the index state. */ + processedUpToDatetime: number + /** UUIDv4 of the last mutation processed by the index. All changes before this mutation will be reflected in the index state. */ + processedUpToMutation: number } /** * Represents a single vector value set along with its associated metadata. */ interface VectorizeVector { - /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ - id: string; - /** The vector values */ - values: VectorFloatArray | number[]; - /** The namespace this vector belongs to. */ - namespace?: string; - /** Metadata associated with the vector. Includes the values of other fields and potentially additional details. */ - metadata?: Record; + /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ + id: string + /** The vector values */ + values: VectorFloatArray | number[] + /** The namespace this vector belongs to. */ + namespace?: string + /** Metadata associated with the vector. Includes the values of other fields and potentially additional details. */ + metadata?: Record } /** * Represents a matched vector for a query along with its score and (if specified) the matching vector information. */ -type VectorizeMatch = Pick, "values"> & Omit & { +type VectorizeMatch = Pick, 'values'> & + Omit & { /** The score or rank for similarity, when returned as a result */ - score: number; -}; + score: number + } /** * A set of matching {@link VectorizeMatch} for a particular query. */ interface VectorizeMatches { - matches: VectorizeMatch[]; - count: number; + matches: VectorizeMatch[] + count: number } /** * Results of an operation that performed a mutation on a set of vectors. @@ -11819,18 +10067,18 @@ interface VectorizeMatches { * See {@link VectorizeAsyncMutation} for its post-beta equivalent. */ interface VectorizeVectorMutation { - /* List of ids of vectors that were successfully processed. */ - ids: string[]; - /* Total count of the number of processed vectors. */ - count: number; + /* List of ids of vectors that were successfully processed. */ + ids: string[] + /* Total count of the number of processed vectors. */ + count: number } /** * Result type indicating a mutation on the Vectorize Index. * Actual mutations are processed async where the `mutationId` is the unique identifier for the operation. */ interface VectorizeAsyncMutation { - /** The unique identifier for the async mutation operation containing the changeset. */ - mutationId: string; + /** The unique identifier for the async mutation operation containing the changeset. */ + mutationId: string } /** * A Vectorize Vector Search Index for querying vectors/embeddings. @@ -11839,42 +10087,45 @@ interface VectorizeAsyncMutation { * See {@link Vectorize} for its new implementation. */ declare abstract class VectorizeIndex { - /** - * Get information about the currently bound index. - * @returns A promise that resolves with information about the current index. - */ - public describe(): Promise; - /** - * Use the provided vector to perform a similarity search across the index. - * @param vector Input vector that will be used to drive the similarity search. - * @param options Configuration options to massage the returned data. - * @returns A promise that resolves with matched and scored vectors. - */ - public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise; - /** - * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. - * @param vectors List of vectors that will be inserted. - * @returns A promise that resolves with the ids & count of records that were successfully processed. - */ - public insert(vectors: VectorizeVector[]): Promise; - /** - * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. - * @param vectors List of vectors that will be upserted. - * @returns A promise that resolves with the ids & count of records that were successfully processed. - */ - public upsert(vectors: VectorizeVector[]): Promise; - /** - * Delete a list of vectors with a matching id. - * @param ids List of vector ids that should be deleted. - * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). - */ - public deleteByIds(ids: string[]): Promise; - /** - * Get a list of vectors with a matching id. - * @param ids List of vector ids that should be returned. - * @returns A promise that resolves with the raw unscored vectors matching the id set. - */ - public getByIds(ids: string[]): Promise; + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options?: VectorizeQueryOptions, + ): Promise + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise } /** * A Vectorize Vector Search Index for querying vectors/embeddings. @@ -11882,190 +10133,218 @@ declare abstract class VectorizeIndex { * Mutations in this version are async, returning a mutation id. */ declare abstract class Vectorize { - /** - * Get information about the currently bound index. - * @returns A promise that resolves with information about the current index. - */ - public describe(): Promise; - /** - * Use the provided vector to perform a similarity search across the index. - * @param vector Input vector that will be used to drive the similarity search. - * @param options Configuration options to massage the returned data. - * @returns A promise that resolves with matched and scored vectors. - */ - public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise; - /** - * Use the provided vector-id to perform a similarity search across the index. - * @param vectorId Id for a vector in the index against which the index should be queried. - * @param options Configuration options to massage the returned data. - * @returns A promise that resolves with matched and scored vectors. - */ - public queryById(vectorId: string, options?: VectorizeQueryOptions): Promise; - /** - * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. - * @param vectors List of vectors that will be inserted. - * @returns A promise that resolves with a unique identifier of a mutation containing the insert changeset. - */ - public insert(vectors: VectorizeVector[]): Promise; - /** - * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. - * @param vectors List of vectors that will be upserted. - * @returns A promise that resolves with a unique identifier of a mutation containing the upsert changeset. - */ - public upsert(vectors: VectorizeVector[]): Promise; - /** - * Delete a list of vectors with a matching id. - * @param ids List of vector ids that should be deleted. - * @returns A promise that resolves with a unique identifier of a mutation containing the delete changeset. - */ - public deleteByIds(ids: string[]): Promise; - /** - * Get a list of vectors with a matching id. - * @param ids List of vector ids that should be returned. - * @returns A promise that resolves with the raw unscored vectors matching the id set. - */ - public getByIds(ids: string[]): Promise; + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query( + vector: VectorFloatArray | number[], + options?: VectorizeQueryOptions, + ): Promise + /** + * Use the provided vector-id to perform a similarity search across the index. + * @param vectorId Id for a vector in the index against which the index should be queried. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public queryById( + vectorId: string, + options?: VectorizeQueryOptions, + ): Promise + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with a unique identifier of a mutation containing the insert changeset. + */ + public insert(vectors: VectorizeVector[]): Promise + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with a unique identifier of a mutation containing the upsert changeset. + */ + public upsert(vectors: VectorizeVector[]): Promise + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with a unique identifier of a mutation containing the delete changeset. + */ + public deleteByIds(ids: string[]): Promise + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise } /** * The interface for "version_metadata" binding * providing metadata about the Worker Version using this binding. */ type WorkerVersionMetadata = { - /** The ID of the Worker Version using this binding */ - id: string; - /** The tag of the Worker Version using this binding */ - tag: string; - /** The timestamp of when the Worker Version was uploaded */ - timestamp: string; -}; + /** The ID of the Worker Version using this binding */ + id: string + /** The tag of the Worker Version using this binding */ + tag: string + /** The timestamp of when the Worker Version was uploaded */ + timestamp: string +} interface DynamicDispatchLimits { - /** - * Limit CPU time in milliseconds. - */ - cpuMs?: number; - /** - * Limit number of subrequests. - */ - subRequests?: number; + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number + /** + * Limit number of subrequests. + */ + subRequests?: number } interface DynamicDispatchOptions { - /** - * Limit resources of invoked Worker script. - */ - limits?: DynamicDispatchLimits; - /** - * Arguments for outbound Worker script, if configured. - */ - outbound?: { - [key: string]: any; - }; + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any + } } interface DispatchNamespace { - /** - * @param name Name of the Worker script. - * @param args Arguments to Worker script. - * @param options Options for Dynamic Dispatch invocation. - * @returns A Fetcher object that allows you to send requests to the Worker script. - * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. - */ - get(name: string, args?: { - [key: string]: any; - }, options?: DynamicDispatchOptions): Fetcher; + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get( + name: string, + args?: { + [key: string]: any + }, + options?: DynamicDispatchOptions, + ): Fetcher } declare module 'cloudflare:workflows' { - /** - * NonRetryableError allows for a user to throw a fatal error - * that makes a Workflow instance fail immediately without triggering a retry - */ - export class NonRetryableError extends Error { - public constructor(message: string, name?: string); - } + /** + * NonRetryableError allows for a user to throw a fatal error + * that makes a Workflow instance fail immediately without triggering a retry + */ + export class NonRetryableError extends Error { + public constructor(message: string, name?: string) + } } declare abstract class Workflow { - /** - * Get a handle to an existing instance of the Workflow. - * @param id Id for the instance of this Workflow - * @returns A promise that resolves with a handle for the Instance - */ - public get(id: string): Promise; - /** - * Create a new instance and return a handle to it. If a provided id exists, an error will be thrown. - * @param options Options when creating an instance including id and params - * @returns A promise that resolves with a handle for the Instance - */ - public create(options?: WorkflowInstanceCreateOptions): Promise; - /** - * Create a batch of instances and return handle for all of them. If a provided id exists, an error will be thrown. - * `createBatch` is limited at 100 instances at a time or when the RPC limit for the batch (1MiB) is reached. - * @param batch List of Options when creating an instance including name and params - * @returns A promise that resolves with a list of handles for the created instances. - */ - public createBatch(batch: WorkflowInstanceCreateOptions[]): Promise; + /** + * Get a handle to an existing instance of the Workflow. + * @param id Id for the instance of this Workflow + * @returns A promise that resolves with a handle for the Instance + */ + public get(id: string): Promise + /** + * Create a new instance and return a handle to it. If a provided id exists, an error will be thrown. + * @param options Options when creating an instance including id and params + * @returns A promise that resolves with a handle for the Instance + */ + public create( + options?: WorkflowInstanceCreateOptions, + ): Promise + /** + * Create a batch of instances and return handle for all of them. If a provided id exists, an error will be thrown. + * `createBatch` is limited at 100 instances at a time or when the RPC limit for the batch (1MiB) is reached. + * @param batch List of Options when creating an instance including name and params + * @returns A promise that resolves with a list of handles for the created instances. + */ + public createBatch( + batch: WorkflowInstanceCreateOptions[], + ): Promise } -type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; -type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number; -type WorkflowRetentionDuration = WorkflowSleepDuration; +type WorkflowDurationLabel = + | 'second' + | 'minute' + | 'hour' + | 'day' + | 'week' + | 'month' + | 'year' +type WorkflowSleepDuration = + | `${number} ${WorkflowDurationLabel}${'s' | ''}` + | number +type WorkflowRetentionDuration = WorkflowSleepDuration interface WorkflowInstanceCreateOptions { - /** - * An id for your Workflow instance. Must be unique within the Workflow. - */ - id?: string; - /** - * The event payload the Workflow instance is triggered with - */ - params?: PARAMS; - /** - * The retention policy for Workflow instance. - * Defaults to the maximum retention period available for the owner's account. - */ - retention?: { - successRetention?: WorkflowRetentionDuration; - errorRetention?: WorkflowRetentionDuration; - }; + /** + * An id for your Workflow instance. Must be unique within the Workflow. + */ + id?: string + /** + * The event payload the Workflow instance is triggered with + */ + params?: PARAMS + /** + * The retention policy for Workflow instance. + * Defaults to the maximum retention period available for the owner's account. + */ + retention?: { + successRetention?: WorkflowRetentionDuration + errorRetention?: WorkflowRetentionDuration + } } type InstanceStatus = { - status: 'queued' // means that instance is waiting to be started (see concurrency limits) - | 'running' | 'paused' | 'errored' | 'terminated' // user terminated the instance while it was running - | 'complete' | 'waiting' // instance is hibernating and waiting for sleep or event to finish - | 'waitingForPause' // instance is finishing the current work to pause - | 'unknown'; - error?: { - name: string; - message: string; - }; - output?: unknown; -}; + status: + | 'queued' // means that instance is waiting to be started (see concurrency limits) + | 'running' + | 'paused' + | 'errored' + | 'terminated' // user terminated the instance while it was running + | 'complete' + | 'waiting' // instance is hibernating and waiting for sleep or event to finish + | 'waitingForPause' // instance is finishing the current work to pause + | 'unknown' + error?: string + output?: object +} interface WorkflowError { - code?: number; - message: string; + code?: number + message: string } declare abstract class WorkflowInstance { - public id: string; - /** - * Pause the instance. - */ - public pause(): Promise; - /** - * Resume the instance. If it is already running, an error will be thrown. - */ - public resume(): Promise; - /** - * Terminate the instance. If it is errored, terminated or complete, an error will be thrown. - */ - public terminate(): Promise; - /** - * Restart the instance. - */ - public restart(): Promise; - /** - * Returns the current status of the instance. - */ - public status(): Promise; - /** - * Send an event to this instance. - */ - public sendEvent({ type, payload, }: { - type: string; - payload: unknown; - }): Promise; + public id: string + /** + * Pause the instance. + */ + public pause(): Promise + /** + * Resume the instance. If it is already running, an error will be thrown. + */ + public resume(): Promise + /** + * Terminate the instance. If it is errored, terminated or complete, an error will be thrown. + */ + public terminate(): Promise + /** + * Restart the instance. + */ + public restart(): Promise + /** + * Returns the current status of the instance. + */ + public status(): Promise + /** + * Send an event to this instance. + */ + public sendEvent({ + type, + payload, + }: { + type: string + payload: unknown + }): Promise } diff --git a/e2e/vue-start/basic-tsr-config/.devcontainer/devcontainer.json b/e2e/vue-start/basic-tsr-config/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-start/basic-tsr-config/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-start/basic-tsr-config/package.json b/e2e/vue-start/basic-tsr-config/package.json index 828dce5b2a..f707d39ef9 100644 --- a/e2e/vue-start/basic-tsr-config/package.json +++ b/e2e/vue-start/basic-tsr-config/package.json @@ -8,23 +8,22 @@ "dev:e2e": "vite dev", "build": "rimraf ./count.txt && vite build && tsc --noEmit", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", + "vite": "^7.3.1", "vue": "^3.5.25" }, "devDependencies": { "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", - "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", - "rimraf": "catalog:" + "srvx": "^0.11.2", + "typescript": "^5.7.2", + "@vitejs/plugin-vue": "^6.0.3", + "@vitejs/plugin-vue-jsx": "^5.1.2", + "vite-tsconfig-paths": "^5.1.4" } } diff --git a/e2e/vue-start/basic-tsr-config/playwright.config.ts b/e2e/vue-start/basic-tsr-config/playwright.config.ts index e6b92ce385..f6dd61ba6c 100644 --- a/e2e/vue-start/basic-tsr-config/playwright.config.ts +++ b/e2e/vue-start/basic-tsr-config/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/basic-tsr-config/src/app/routes/index.tsx b/e2e/vue-start/basic-tsr-config/src/app/routes/index.tsx index b4b520e8af..feaff21c25 100644 --- a/e2e/vue-start/basic-tsr-config/src/app/routes/index.tsx +++ b/e2e/vue-start/basic-tsr-config/src/app/routes/index.tsx @@ -1,4 +1,3 @@ -import { defineComponent } from 'vue' import * as fs from 'node:fs' import { createFileRoute, useRouter } from '@tanstack/vue-router' import { createServerFn } from '@tanstack/vue-start' @@ -13,31 +12,30 @@ const getCount = createServerFn({ }) const updateCount = createServerFn({ method: 'POST' }) - .validator((d: number) => d) + .inputValidator((d: number) => d) .handler(async ({ data }) => { 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-tsr-config/tsconfig.json b/e2e/vue-start/basic-tsr-config/tsconfig.json index e8f3ecf0c9..010db955bf 100644 --- a/e2e/vue-start/basic-tsr-config/tsconfig.json +++ b/e2e/vue-start/basic-tsr-config/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/app/*"] }, diff --git a/e2e/vue-start/basic-tsr-config/vite.config.ts b/e2e/vue-start/basic-tsr-config/vite.config.ts index 3abd7d269c..9ee2806bfe 100644 --- a/e2e/vue-start/basic-tsr-config/vite.config.ts +++ b/e2e/vue-start/basic-tsr-config/vite.config.ts @@ -1,14 +1,17 @@ import { defineConfig } from 'vite' +import tsConfigPaths from 'vite-tsconfig-paths' 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 }, server: { port: 3000, }, plugins: [ + tsConfigPaths({ + projects: ['./tsconfig.json'], + }), tanstackStart({ srcDirectory: './src/app', }), diff --git a/e2e/vue-start/basic-vue-query/.devcontainer/devcontainer.json b/e2e/vue-start/basic-vue-query/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-start/basic-vue-query/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-start/basic-vue-query/package.json b/e2e/vue-start/basic-vue-query/package.json index ab9589376d..d075ce6488 100644 --- a/e2e/vue-start/basic-vue-query/package.json +++ b/e2e/vue-start/basic-vue-query/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-query": "^5.92.1", @@ -18,22 +18,22 @@ "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-router-ssr-query": "workspace:^", "@tanstack/vue-start": "workspace:^", - "redaxios": "catalog:", - "tailwind-merge": "^3.6.0", + "redaxios": "^0.5.1", + "tailwind-merge": "^2.6.0", + "vite": "^7.3.1", "vue": "^3.5.25", - "zod": "^4.4.3" + "zod": "^4.1.12" }, "devDependencies": { - "@playwright/test": "^1.61.0", - "@tailwindcss/vite": "^4.2.2", + "@playwright/test": "^1.50.1", + "@tailwindcss/vite": "^4.1.18", "@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", - "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "srvx": "^0.11.2", + "tailwindcss": "^4.1.18", + "typescript": "^5.7.2", + "@vitejs/plugin-vue": "^6.0.3", + "@vitejs/plugin-vue-jsx": "^5.1.2", + "vite-tsconfig-paths": "^5.1.4" } } diff --git a/e2e/vue-start/basic-vue-query/playwright.config.ts b/e2e/vue-start/basic-vue-query/playwright.config.ts index 0618b7272a..84636ab0f9 100644 --- a/e2e/vue-start/basic-vue-query/playwright.config.ts +++ b/e2e/vue-start/basic-vue-query/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` @@ -11,18 +16,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { baseURL, }, webServer: { - command: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', - env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, - }, }, projects: [ diff --git a/e2e/vue-start/basic-vue-query/src/routeTree.gen.ts b/e2e/vue-start/basic-vue-query/src/routeTree.gen.ts index 10e8a56450..588ab8b52d 100644 --- a/e2e/vue-start/basic-vue-query/src/routeTree.gen.ts +++ b/e2e/vue-start/basic-vue-query/src/routeTree.gen.ts @@ -9,41 +9,27 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as LayoutRouteImport } from './routes/_layout' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as SuspenseTransitionRouteImport } from './routes/suspense-transition' 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 PostsIndexRouteImport } from './routes/posts.index' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as SuspenseTransitionRouteImport } from './routes/suspense-transition' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as IndexRouteImport } from './routes/index' import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' -import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as ApiUsersRouteImport } from './routes/api.users' +import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' import { Route as TransitionCountQueryRouteImport } from './routes/transition/count/query' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' +import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const SuspenseTransitionRoute = SuspenseTransitionRouteImport.update({ @@ -51,64 +37,78 @@ const SuspenseTransitionRoute = SuspenseTransitionRouteImport.update({ path: '/suspense-transition', getParentRoute: () => rootRouteImport, } as any) -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const LayoutLayout2Route = LayoutLayout2RouteImport.update({ - id: '/_layout-2', - getParentRoute: () => LayoutRoute, -} as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => PostsRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, + getParentRoute: () => rootRouteImport, } as any) const UsersIndexRoute = UsersIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => UsersRoute, } as any) +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) const UsersUserIdRoute = UsersUserIdRouteImport.update({ id: '/$userId', path: '/$userId', getParentRoute: () => UsersRoute, } as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, } as any) -const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ - id: '/layout-b', - path: '/layout-b', - getParentRoute: () => LayoutLayout2Route, +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', + getParentRoute: () => rootRouteImport, } as any) -const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => ApiUsersRoute, +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, +} as any) +const TransitionCountQueryRoute = TransitionCountQueryRouteImport.update({ + id: '/transition/count/query', + path: '/transition/count/query', + getParentRoute: () => rootRouteImport, } as any) const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ id: '/posts_/$postId/deep', path: '/posts/$postId/deep', getParentRoute: () => rootRouteImport, } as any) -const TransitionCountQueryRoute = TransitionCountQueryRouteImport.update({ - id: '/transition/count/query', - path: '/transition/count/query', - getParentRoute: () => rootRouteImport, +const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => ApiUsersRoute, +} as any) +const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ + id: '/layout-b', + path: '/layout-b', + getParentRoute: () => LayoutLayout2Route, +} as any) +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, } as any) export interface FileRoutesByFullPath { @@ -231,32 +231,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout': { - id: '/_layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/suspense-transition': { @@ -266,40 +245,33 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof SuspenseTransitionRouteImport parentRoute: typeof rootRouteImport } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } - '/_layout/_layout-2': { - id: '/_layout/_layout-2' + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout': { + id: '/_layout' path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute - } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + fullPath: '' + preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' + '/': { + id: '/' path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/users/': { id: '/users/' @@ -308,6 +280,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof UsersIndexRouteImport parentRoute: typeof UsersRoute } + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute + } '/users/$userId': { id: '/users/$userId' path: '/$userId' @@ -315,26 +294,33 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof UsersUserIdRouteImport parentRoute: typeof UsersRoute } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute } - '/_layout/_layout-2/layout-b': { - id: '/_layout/_layout-2/layout-b' - path: '/layout-b' - fullPath: '/layout-b' - preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport - parentRoute: typeof LayoutLayout2Route + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport + parentRoute: typeof rootRouteImport } - '/api/users/$id': { - id: '/api/users/$id' - path: '/$id' - fullPath: '/api/users/$id' - preLoaderRoute: typeof ApiUsersIdRouteImport - parentRoute: typeof ApiUsersRoute + '/_layout/_layout-2': { + id: '/_layout/_layout-2' + path: '' + fullPath: '' + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute + } + '/transition/count/query': { + id: '/transition/count/query' + path: '/transition/count/query' + fullPath: '/transition/count/query' + preLoaderRoute: typeof TransitionCountQueryRouteImport + parentRoute: typeof rootRouteImport } '/posts_/$postId/deep': { id: '/posts_/$postId/deep' @@ -343,12 +329,26 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsPostIdDeepRouteImport parentRoute: typeof rootRouteImport } - '/transition/count/query': { - id: '/transition/count/query' - path: '/transition/count/query' - fullPath: '/transition/count/query' - preLoaderRoute: typeof TransitionCountQueryRouteImport - parentRoute: typeof rootRouteImport + '/api/users/$id': { + id: '/api/users/$id' + path: '/$id' + fullPath: '/api/users/$id' + preLoaderRoute: typeof ApiUsersIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/_layout/_layout-2/layout-b': { + id: '/_layout/_layout-2/layout-b' + path: '/layout-b' + fullPath: '/layout-b' + preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport + parentRoute: typeof LayoutLayout2Route + } + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route } } } diff --git a/e2e/vue-start/basic-vue-query/src/routes/api.users.ts b/e2e/vue-start/basic-vue-query/src/routes/api.users.ts index f9330a87db..cab4cafc3f 100644 --- a/e2e/vue-start/basic-vue-query/src/routes/api.users.ts +++ b/e2e/vue-start/basic-vue-query/src/routes/api.users.ts @@ -2,7 +2,11 @@ import { createFileRoute } from '@tanstack/vue-router' import axios from 'redaxios' import type { User } from '../utils/users' -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const Route = createFileRoute('/api/users')({ server: { diff --git a/e2e/vue-start/basic-vue-query/src/routes/api/users.$id.ts b/e2e/vue-start/basic-vue-query/src/routes/api/users.$id.ts index d138746730..4cc4b33a0b 100644 --- a/e2e/vue-start/basic-vue-query/src/routes/api/users.$id.ts +++ b/e2e/vue-start/basic-vue-query/src/routes/api/users.$id.ts @@ -2,7 +2,11 @@ import { createFileRoute } from '@tanstack/vue-router' import axios from 'redaxios' import type { User } from '../../utils/users' -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const Route = createFileRoute('/api/users/$id')({ server: { diff --git a/e2e/vue-start/basic-vue-query/src/routes/posts.$postId.tsx b/e2e/vue-start/basic-vue-query/src/routes/posts.$postId.tsx index fd8deaf291..5ec224eb2d 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,10 +1,9 @@ -import { defineComponent } from 'vue' import { useQuery } from '@tanstack/vue-query' import { ErrorComponent, Link, createFileRoute, - ErrorComponentProps, + type ErrorComponentProps, } from '@tanstack/vue-router' import { postQueryOptions } from '~/utils/posts' @@ -12,30 +11,27 @@ export function PostErrorComponent(props: ErrorComponentProps) { return } -const PostComponent = defineComponent({ - setup() { - const params = Route.useParams() - const postQuery = useQuery(() => postQueryOptions(params.value.postId)) - return () => ( -

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

{postQuery.data.value?.title}

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

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

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

{postQuery.data.value?.title}

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

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

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

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

+
{userQuery.data.value?.email ?? ''}
+
+ ) +} export const Route = createFileRoute('/users/$userId')({ loader: async ({ context, params: { userId } }) => { diff --git a/e2e/vue-start/basic-vue-query/src/utils/posts.tsx b/e2e/vue-start/basic-vue-query/src/utils/posts.tsx index c6b5e70a0b..7f1f564645 100644 --- a/e2e/vue-start/basic-vue-query/src/utils/posts.tsx +++ b/e2e/vue-start/basic-vue-query/src/utils/posts.tsx @@ -7,8 +7,6 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' - export const postsQueryOptions = () => queryOptions({ queryKey: ['posts'], @@ -16,7 +14,7 @@ export const postsQueryOptions = () => console.info('Fetching posts...') await new Promise((r) => setTimeout(r, 500)) return axios - .get>(`${queryURL}/posts`) + .get>('https://jsonplaceholder.typicode.com/posts') .then((r) => r.data.slice(0, 10)) }, }) @@ -29,7 +27,7 @@ export const postQueryOptions = (postId: string) => await new Promise((r) => setTimeout(r, 500)) return axios - .get(`${queryURL}/posts/${postId}`) + .get(`https://jsonplaceholder.typicode.com/posts/${postId}`) .then((r) => r.data) }, }) diff --git a/e2e/vue-start/basic-vue-query/src/utils/users.tsx b/e2e/vue-start/basic-vue-query/src/utils/users.tsx index fe7a902fa2..29bf08c315 100644 --- a/e2e/vue-start/basic-vue-query/src/utils/users.tsx +++ b/e2e/vue-start/basic-vue-query/src/utils/users.tsx @@ -1,6 +1,4 @@ import { queryOptions } from '@tanstack/vue-query' -import { createIsomorphicFn } from '@tanstack/vue-start' -import { getRequestUrl } from '@tanstack/vue-start/server' import axios from 'redaxios' export type User = { @@ -9,16 +7,17 @@ export type User = { email: string } -const getOrigin = createIsomorphicFn() - .server(() => getRequestUrl().origin) - .client(() => window.location.origin) +const PORT = + import.meta.env.VITE_SERVER_PORT || process.env.VITE_SERVER_PORT || 3000 + +export const DEPLOY_URL = `http://localhost:${PORT}` export const usersQueryOptions = () => queryOptions({ queryKey: ['users'], queryFn: () => axios - .get>(getOrigin() + '/api/users') + .get>(DEPLOY_URL + '/api/users') .then((r) => r.data) .catch(() => { throw new Error('Failed to fetch users') @@ -30,7 +29,7 @@ export const userQueryOptions = (id: string) => queryKey: ['users', id], queryFn: () => axios - .get(getOrigin() + '/api/users/' + id) + .get(DEPLOY_URL + '/api/users/' + id) .then((r) => r.data) .catch(() => { throw new Error('Failed to fetch user') diff --git a/e2e/react-start/i18n-paraglide/test-results/.last-run.json b/e2e/vue-start/basic-vue-query/test-results/.last-run.json similarity index 100% rename from e2e/react-start/i18n-paraglide/test-results/.last-run.json rename to e2e/vue-start/basic-vue-query/test-results/.last-run.json diff --git a/e2e/vue-start/basic-vue-query/tests/app.spec.ts b/e2e/vue-start/basic-vue-query/tests/app.spec.ts index 4ce5c20ef7..ab2469f68d 100644 --- a/e2e/vue-start/basic-vue-query/tests/app.spec.ts +++ b/e2e/vue-start/basic-vue-query/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test('Navigating to post', async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-start/basic-vue-query/tests/setup/global.setup.ts b/e2e/vue-start/basic-vue-query/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-start/basic-vue-query/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/basic-vue-query/tests/setup/global.teardown.ts b/e2e/vue-start/basic-vue-query/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-start/basic-vue-query/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/basic-vue-query/tests/transition.spec.ts b/e2e/vue-start/basic-vue-query/tests/transition.spec.ts index a0f3bf0964..2c28fc72a2 100644 --- a/e2e/vue-start/basic-vue-query/tests/transition.spec.ts +++ b/e2e/vue-start/basic-vue-query/tests/transition.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test('transitions/count/query should keep old values visible during navigation', async ({ page, diff --git a/e2e/vue-start/basic-vue-query/tsconfig.json b/e2e/vue-start/basic-vue-query/tsconfig.json index 572d840872..8bf3d33789 100644 --- a/e2e/vue-start/basic-vue-query/tsconfig.json +++ b/e2e/vue-start/basic-vue-query/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/basic-vue-query/vite.config.ts b/e2e/vue-start/basic-vue-query/vite.config.ts index 563e212077..e0b4a0e909 100644 --- a/e2e/vue-start/basic-vue-query/vite.config.ts +++ b/e2e/vue-start/basic-vue-query/vite.config.ts @@ -1,13 +1,21 @@ import { defineConfig } from 'vite' +import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import tailwindcss from '@tailwindcss/vite' export default defineConfig({ - resolve: { tsconfigPaths: true }, server: { port: 3000, }, - plugins: [tailwindcss(), tanstackStart(), vue(), vueJsx()], + plugins: [ + tailwindcss(), + tsConfigPaths({ + projects: ['./tsconfig.json'], + }), + tanstackStart(), + vue(), + vueJsx(), + ], }) diff --git a/e2e/vue-start/basic/.devcontainer/devcontainer.json b/e2e/vue-start/basic/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-start/basic/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-start/basic/.gitignore b/e2e/vue-start/basic/.gitignore index b9c2c7e5f6..a79d5cf129 100644 --- a/e2e/vue-start/basic/.gitignore +++ b/e2e/vue-start/basic/.gitignore @@ -18,4 +18,3 @@ yarn.lock /playwright-report/ /blob-report/ /playwright/.cache/ -/dist-vite-*/ diff --git a/e2e/vue-start/basic/package.json b/e2e/vue-start/basic/package.json index 2ff8329543..62e03a3389 100644 --- a/e2e/vue-start/basic/package.json +++ b/e2e/vue-start/basic/package.json @@ -6,73 +6,44 @@ "scripts": { "dev": "vite dev --port 3000", "dev:e2e": "vite dev", - "build": "pnpm build:vite", + "build": "vite build && tsc --noEmit", + "build:spa": "MODE=spa vite build && tsc --noEmit", + "build:prerender": "MODE=prerender vite build && tsc --noEmit", "preview": "vite preview", "start": "node server.js", - "test:e2e:local": "playwright test --project=chromium", - "build:vite": "vite build && tsc --noEmit", - "build:rsbuild": "rsbuild build && tsc --noEmit" + "test:e2e:startDummyServer": "node -e 'import(\"./tests/setup/global.setup.ts\").then(m => m.default())' &", + "test:e2e:stopDummyServer": "node -e 'import(\"./tests/setup/global.teardown.ts\").then(m => m.default())'", + "test:e2e:spaMode": "rm -rf port*.txt; MODE=spa playwright test --project=chromium", + "test:e2e:ssrMode": "rm -rf port*.txt; playwright test --project=chromium", + "test:e2e:prerender": "rm -rf port*.txt; MODE=prerender playwright test --project=chromium", + "test:e2e:preview": "rm -rf port*.txt; MODE=preview playwright test --project=chromium", + "test:e2e": "pnpm run test:e2e:spaMode && pnpm run test:e2e:ssrMode && pnpm run test:e2e:prerender && pnpm run test:e2e:preview" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", - "express": "^5.2.1", + "express": "^5.1.0", "http-proxy-middleware": "^3.0.5", "js-cookie": "^3.0.5", - "redaxios": "catalog:", - "tailwind-merge": "^3.6.0", + "redaxios": "^0.5.1", "vue": "^3.5.16", - "zod": "^4.4.3" + "tailwind-merge": "^2.6.0", + "vite": "^7.3.1", + "zod": "^3.24.2" }, "devDependencies": { - "@playwright/test": "^1.61.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", - "@tailwindcss/postcss": "^4.2.2", - "@tailwindcss/vite": "^4.2.2", + "@playwright/test": "^1.50.1", + "@tailwindcss/vite": "^4.1.18", "@tanstack/router-e2e-utils": "workspace:^", "@types/js-cookie": "^3.0.6", "@types/node": "^22.10.2", - "@vitejs/plugin-vue": "^6.0.5", - "@vitejs/plugin-vue-jsx": "^5.1.5", + "@vitejs/plugin-vue": "^5.2.4", + "@vitejs/plugin-vue-jsx": "^4.1.2", "combinate": "^1.1.11", - "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": { - "metadata": { - "playwrightModes": [ - { - "toolchain": "vite", - "mode": "ssr", - "shards": 4 - }, - { - "toolchain": "vite", - "mode": "spa" - }, - { - "toolchain": "vite", - "mode": "prerender", - "env": { - "NODE_OPTIONS": "--import=@tanstack/router-e2e-utils/mock-api" - } - }, - { - "toolchain": "vite", - "mode": "preview" - }, - { - "toolchain": "rsbuild", - "mode": "ssr" - } - ] - } + "srvx": "^0.11.2", + "tailwindcss": "^4.1.18", + "typescript": "^5.7.2", + "vite-tsconfig-paths": "^5.1.4" } } diff --git a/e2e/vue-start/basic/playwright.config.ts b/e2e/vue-start/basic/playwright.config.ts index 9322874f3a..86c58bc1ce 100644 --- a/e2e/vue-start/basic/playwright.config.ts +++ b/e2e/vue-start/basic/playwright.config.ts @@ -1,37 +1,63 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import { isSpaMode } from './tests/utils/isSpaMode' +import { isPrerender } from './tests/utils/isPrerender' +import { isPreview } from './tests/utils/isPreview' +import packageJson from './package.json' with { type: 'json' } -const mode = process.env.MODE ?? 'ssr' - -const distDir = process.env.E2E_DIST_DIR ?? 'dist' - -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort( + `${packageJson.name}${isSpaMode ? '_spa' : ''}${isPreview ? '_preview' : ''}`, +) +const START_PORT = await getTestServerPort( + `${packageJson.name}${isSpaMode ? '_spa_start' : ''}`, +) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` -const commandByMode = - mode === 'preview' - ? `pnpm preview --host 0.0.0.0 --outDir ${distDir} --port ${PORT}` - : `pnpm start` +const spaModeCommand = `pnpm build:spa && pnpm start` +const ssrModeCommand = `pnpm build && pnpm start` +const prerenderModeCommand = `pnpm run test:e2e:startDummyServer && pnpm build:prerender && pnpm run test:e2e:stopDummyServer && pnpm start` +const previewModeCommand = `pnpm build && pnpm preview --port ${PORT}` +const getCommand = () => { + if (isSpaMode) return spaModeCommand + if (isPrerender) return prerenderModeCommand + if (isPreview) return previewModeCommand + return ssrModeCommand +} +console.log('running in spa mode: ', isSpaMode.toString()) +console.log('running in prerender mode: ', isPrerender.toString()) +console.log('running in preview mode: ', isPreview.toString()) +/** + * See https://playwright.dev/docs/test-configuration. + */ export default defineConfig({ testDir: './tests', 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: commandByMode, - wait: appServerReady, - reuseExistingServer: false, + command: getCommand(), + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, - MODE: mode, - START_PORT: '0', + MODE: process.env.MODE || '', + VITE_NODE_ENV: 'test', + VITE_EXTERNAL_PORT: String(EXTERNAL_PORT), + VITE_SERVER_PORT: String(PORT), + START_PORT: String(START_PORT), PORT: String(PORT), - E2E_DIST_DIR: distDir, }, }, diff --git a/e2e/vue-start/basic/postcss.config.mjs b/e2e/vue-start/basic/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/vue-start/basic/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/vue-start/basic/rsbuild.config.ts b/e2e/vue-start/basic/rsbuild.config.ts deleted file mode 100644 index aad3a76e73..0000000000 --- a/e2e/vue-start/basic/rsbuild.config.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { defineConfig } from '@rsbuild/core' -import { pluginBabel } from '@rsbuild/plugin-babel' -import { pluginVue } from '@rsbuild/plugin-vue' -import { pluginVueJsx } from '@rsbuild/plugin-vue-jsx' -import { tanstackStart } from '@tanstack/vue-start/plugin/rsbuild' -import { isPrerender } from './tests/utils/isPrerender' - -const outDir = process.env.E2E_DIST_DIR ?? 'dist' - -export default defineConfig({ - plugins: [ - pluginBabel({ - include: /\.(?:jsx|tsx)$/, - }), - pluginVue(), - pluginVueJsx(), - tanstackStart(), - ], - source: { - define: { - __TSR_PRERENDER__: JSON.stringify(isPrerender), - }, - }, - output: { - distPath: { - root: outDir, - }, - }, -}) diff --git a/e2e/vue-start/basic/server.js b/e2e/vue-start/basic/server.js index 3e1ddab400..83f5ff0079 100644 --- a/e2e/vue-start/basic/server.js +++ b/e2e/vue-start/basic/server.js @@ -1,42 +1,24 @@ -import fs from 'node:fs' -import path from 'node:path' import { toNodeHandler } from 'srvx/node' +import path from 'node:path' import express from 'express' import { createProxyMiddleware } from 'http-proxy-middleware' -const port = Number(process.env.PORT ?? 3000) +const port = process.env.PORT || 3000 -const startPort = Number(process.env.START_PORT ?? 0) +const startPort = process.env.START_PORT || 3001 const isSpaMode = process.env.MODE === 'spa' const isPrerender = process.env.MODE === 'prerender' -const distDir = process.env.E2E_DIST_DIR || 'dist' -const distClientDir = path.resolve(distDir, 'client') - -function resolveDistServerEntryPath() { - const serverJsPath = path.resolve(distDir, 'server', 'server.js') - if (fs.existsSync(serverJsPath)) { - return serverJsPath - } - - const indexJsPath = path.resolve(distDir, 'server', 'index.js') - if (fs.existsSync(indexJsPath)) { - return indexJsPath - } - - return serverJsPath -} export async function createStartServer() { - const distServerEntryPath = resolveDistServerEntryPath() - const server = (await import(distServerEntryPath)).default + const server = (await import('./dist/server/server.js')).default const nodeHandler = toNodeHandler(server.fetch) const app = express() // to keep testing uniform stop express from redirecting /posts to /posts/ // when serving pre-rendered pages - app.use(express.static(distClientDir, { redirect: !isPrerender })) + app.use(express.static('./dist/client', { redirect: !isPrerender })) app.use(async (req, res, next) => { try { @@ -49,13 +31,13 @@ export async function createStartServer() { return { app } } -export async function createSpaServer(backendPort) { +export async function createSpaServer() { const app = express() app.use( '/api', createProxyMiddleware({ - target: `http://localhost:${backendPort}/api`, // Replace with your target server's URL + target: `http://localhost:${startPort}/api`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) @@ -63,36 +45,36 @@ export async function createSpaServer(backendPort) { app.use( '/_serverFn', createProxyMiddleware({ - target: `http://localhost:${backendPort}/_serverFn`, // Replace with your target server's URL + target: `http://localhost:${startPort}/_serverFn`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) - app.use(express.static(distClientDir)) + app.use(express.static('./dist/client')) app.get('/{*splat}', (req, res) => { - res.sendFile('index.html', { root: distClientDir }) + res.sendFile(path.resolve('./dist/client/index.html')) }) return { app } } -// Bind the backend first so the SPA proxy receives the port actually held by it. -const { app: startApp } = await createStartServer() -const backend = startApp.listen(isSpaMode ? startPort : port, async (error) => { - if (error) { - throw error - } - const backendPort = backend.address().port - if (isSpaMode) { - const { app } = await createSpaServer(backendPort) - const frontend = app.listen(port, (frontendError) => { - if (frontendError) { - throw frontendError - } - console.info(`E2E app: http://localhost:${frontend.address().port}`) - }) - } else { - console.info(`E2E app: http://localhost:${backendPort}`) - } -}) +if (isSpaMode) { + createSpaServer().then(async ({ app }) => + app.listen(port, () => { + console.info(`Client Server: http://localhost:${port}`) + }), + ) + + createStartServer().then(async ({ app }) => + app.listen(startPort, () => { + console.info(`Start Server: http://localhost:${startPort}`) + }), + ) +} else { + createStartServer().then(async ({ app }) => + app.listen(port, () => { + console.info(`Start Server: http://localhost:${port}`) + }), + ) +} diff --git a/e2e/vue-start/basic/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/basic/src/components/DefaultCatchBoundary.tsx index cd0fa98fc7..fe99cf62f3 100644 --- a/e2e/vue-start/basic/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/basic/src/components/DefaultCatchBoundary.tsx @@ -1,9 +1,11 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/vue-router' +import type { ErrorComponentProps } from '@tanstack/vue-router' import { defineComponent } from 'vue' export const DefaultCatchBoundary = defineComponent({ @@ -15,8 +17,9 @@ export const DefaultCatchBoundary = defineComponent({ }, setup(props) { const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) console.error(props.error) diff --git a/e2e/vue-start/basic/src/components/throwRedirect.ts b/e2e/vue-start/basic/src/components/throwRedirect.ts index 7d7265e214..187687192b 100644 --- a/e2e/vue-start/basic/src/components/throwRedirect.ts +++ b/e2e/vue-start/basic/src/components/throwRedirect.ts @@ -2,7 +2,7 @@ import { redirect } from '@tanstack/vue-router' import { createServerFn } from '@tanstack/vue-start' export const throwRedirect = createServerFn() - .validator( + .inputValidator( (opts: { target: 'internal' | 'external' reloadDocument?: boolean diff --git a/e2e/vue-start/basic/src/routeTree.gen.ts b/e2e/vue-start/basic/src/routeTree.gen.ts index 7fbcd192b6..77a84e6eca 100644 --- a/e2e/vue-start/basic/src/routeTree.gen.ts +++ b/e2e/vue-start/basic/src/routeTree.gen.ts @@ -9,116 +9,64 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as LayoutRouteImport } from './routes/_layout' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as InlineScriptsRouteImport } from './routes/inline-scripts' -import { Route as LinksRouteImport } from './routes/links' -import { Route as NotFoundRouteRouteImport } from './routes/not-found/route' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as RawStreamRouteImport } from './routes/raw-stream' -import { Route as ScriptsRouteImport } from './routes/scripts' -import { Route as SearchParamsRouteRouteImport } from './routes/search-params/route' -import { Route as SpecialCharsRouteRouteImport } from './routes/specialChars/route' -import { Route as StreamRouteImport } from './routes/stream' 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 MultiCookieRedirectIndexRouteImport } from './routes/multi-cookie-redirect/index' -import { Route as MultiCookieRedirectTargetRouteImport } from './routes/multi-cookie-redirect/target' -import { Route as NotFoundIndexRouteImport } from './routes/not-found/index' -import { Route as NotFoundParentBoundaryRouteRouteImport } from './routes/not-found/parent-boundary/route' -import { Route as NotFoundViaBeforeLoadRouteImport } from './routes/not-found/via-beforeLoad' -import { Route as NotFoundViaBeforeLoadTargetRootRouteImport } from './routes/not-found/via-beforeLoad-target-root' -import { Route as NotFoundViaLoaderRouteImport } from './routes/not-found/via-loader' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as RawStreamIndexRouteImport } from './routes/raw-stream/index' -import { Route as RawStreamClientCallRouteImport } from './routes/raw-stream/client-call' -import { Route as RawStreamSsrBinaryHintRouteImport } from './routes/raw-stream/ssr-binary-hint' -import { Route as RawStreamSsrMixedRouteImport } from './routes/raw-stream/ssr-mixed' -import { Route as RawStreamSsrMultipleRouteImport } from './routes/raw-stream/ssr-multiple' -import { Route as RawStreamSsrSingleRouteImport } from './routes/raw-stream/ssr-single' -import { Route as RawStreamSsrTextHintRouteImport } from './routes/raw-stream/ssr-text-hint' -import { Route as RedirectIndexRouteImport } from './routes/redirect/index' -import { Route as RedirectTargetRouteImport } from './routes/redirect/$target' -import { Route as SearchParamsIndexRouteImport } from './routes/search-params/index' -import { Route as SearchParamsDefaultRouteImport } from './routes/search-params/default' -import { Route as SearchParamsLoaderThrowsRedirectRouteImport } from './routes/search-params/loader-throws-redirect' -import { Route as SpecialCharsParamRouteImport } from './routes/specialChars/$param' -import { Route as SpecialCharsHashRouteImport } from './routes/specialChars/hash' -import { Route as SpecialCharsMalformedRouteRouteImport } from './routes/specialChars/malformed/route' -import { Route as SpecialCharsSearchRouteImport } from './routes/specialChars/search' -import { Route as SpecialCharsChar45824Char54620Char48124Char44397RouteImport } from './routes/specialChars/대한민국' +import { Route as StreamRouteImport } from './routes/stream' +import { Route as ScriptsRouteImport } from './routes/scripts' +import { Route as RawStreamRouteImport } from './routes/raw-stream' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as LinksRouteImport } from './routes/links' +import { Route as InlineScriptsRouteImport } from './routes/inline-scripts' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as SpecialCharsRouteRouteImport } from './routes/specialChars/route' +import { Route as SearchParamsRouteRouteImport } from './routes/search-params/route' +import { Route as NotFoundRouteRouteImport } from './routes/not-found/route' +import { Route as IndexRouteImport } from './routes/index' import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as SearchParamsIndexRouteImport } from './routes/search-params/index' +import { Route as RedirectIndexRouteImport } from './routes/redirect/index' +import { Route as RawStreamIndexRouteImport } from './routes/raw-stream/index' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as NotFoundIndexRouteImport } from './routes/not-found/index' +import { Route as MultiCookieRedirectIndexRouteImport } from './routes/multi-cookie-redirect/index' import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' -import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' -import { Route as NotFoundParentBoundaryViaBeforeLoadRouteImport } from './routes/not-found/parent-boundary/via-beforeLoad' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' +import { Route as SpecialCharsChar45824Char54620Char48124Char44397RouteImport } from './routes/specialChars/대한민국' +import { Route as SpecialCharsSearchRouteImport } from './routes/specialChars/search' +import { Route as SpecialCharsHashRouteImport } from './routes/specialChars/hash' +import { Route as SpecialCharsParamRouteImport } from './routes/specialChars/$param' +import { Route as SearchParamsLoaderThrowsRedirectRouteImport } from './routes/search-params/loader-throws-redirect' +import { Route as SearchParamsDefaultRouteImport } from './routes/search-params/default' +import { Route as RedirectTargetRouteImport } from './routes/redirect/$target' +import { Route as RawStreamSsrTextHintRouteImport } from './routes/raw-stream/ssr-text-hint' +import { Route as RawStreamSsrSingleRouteImport } from './routes/raw-stream/ssr-single' +import { Route as RawStreamSsrMultipleRouteImport } from './routes/raw-stream/ssr-multiple' +import { Route as RawStreamSsrMixedRouteImport } from './routes/raw-stream/ssr-mixed' +import { Route as RawStreamSsrBinaryHintRouteImport } from './routes/raw-stream/ssr-binary-hint' +import { Route as RawStreamClientCallRouteImport } from './routes/raw-stream/client-call' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as NotFoundViaLoaderRouteImport } from './routes/not-found/via-loader' +import { Route as NotFoundViaBeforeLoadRouteImport } from './routes/not-found/via-beforeLoad' +import { Route as MultiCookieRedirectTargetRouteImport } from './routes/multi-cookie-redirect/target' +import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' +import { Route as SpecialCharsMalformedRouteRouteImport } from './routes/specialChars/malformed/route' import { Route as RedirectTargetIndexRouteImport } from './routes/redirect/$target/index' -import { Route as RedirectTargetViaBeforeLoadRouteImport } from './routes/redirect/$target/via-beforeLoad' -import { Route as RedirectTargetViaLoaderRouteImport } from './routes/redirect/$target/via-loader' -import { Route as SpecialCharsMalformedParamRouteImport } from './routes/specialChars/malformed/$param' import { Route as SpecialCharsMalformedSearchRouteImport } from './routes/specialChars/malformed/search' +import { Route as SpecialCharsMalformedParamRouteImport } from './routes/specialChars/malformed/$param' +import { Route as RedirectTargetViaLoaderRouteImport } from './routes/redirect/$target/via-loader' +import { Route as RedirectTargetViaBeforeLoadRouteImport } from './routes/redirect/$target/via-beforeLoad' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' +import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' import { Route as RedirectTargetServerFnIndexRouteImport } from './routes/redirect/$target/serverFn/index' -import { Route as RedirectTargetServerFnViaBeforeLoadRouteImport } from './routes/redirect/$target/serverFn/via-beforeLoad' -import { Route as RedirectTargetServerFnViaLoaderRouteImport } from './routes/redirect/$target/serverFn/via-loader' import { Route as RedirectTargetServerFnViaUseServerFnRouteImport } from './routes/redirect/$target/serverFn/via-useServerFn' +import { Route as RedirectTargetServerFnViaLoaderRouteImport } from './routes/redirect/$target/serverFn/via-loader' +import { Route as RedirectTargetServerFnViaBeforeLoadRouteImport } from './routes/redirect/$target/serverFn/via-beforeLoad' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', - getParentRoute: () => rootRouteImport, -} as any) -const InlineScriptsRoute = InlineScriptsRouteImport.update({ - id: '/inline-scripts', - path: '/inline-scripts', - getParentRoute: () => rootRouteImport, -} as any) -const LinksRoute = LinksRouteImport.update({ - id: '/links', - path: '/links', - getParentRoute: () => rootRouteImport, -} as any) -const NotFoundRouteRoute = NotFoundRouteRouteImport.update({ - id: '/not-found', - path: '/not-found', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const RawStreamRoute = RawStreamRouteImport.update({ - id: '/raw-stream', - path: '/raw-stream', - getParentRoute: () => rootRouteImport, -} as any) -const ScriptsRoute = ScriptsRouteImport.update({ - id: '/scripts', - path: '/scripts', - getParentRoute: () => rootRouteImport, -} as any) -const SearchParamsRouteRoute = SearchParamsRouteRouteImport.update({ - id: '/search-params', - path: '/search-params', - getParentRoute: () => rootRouteImport, -} as any) -const SpecialCharsRouteRoute = SpecialCharsRouteRouteImport.update({ - id: '/specialChars', - path: '/specialChars', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const StreamRoute = StreamRouteImport.update({ @@ -126,150 +74,100 @@ const StreamRoute = StreamRouteImport.update({ path: '/stream', getParentRoute: () => rootRouteImport, } as any) -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const ScriptsRoute = ScriptsRouteImport.update({ + id: '/scripts', + path: '/scripts', getParentRoute: () => rootRouteImport, } as any) -const LayoutLayout2Route = LayoutLayout2RouteImport.update({ - id: '/_layout-2', - getParentRoute: () => LayoutRoute, -} as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const RawStreamRoute = RawStreamRouteImport.update({ + id: '/raw-stream', + path: '/raw-stream', getParentRoute: () => rootRouteImport, } as any) +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) +const LinksRoute = LinksRouteImport.update({ + id: '/links', + path: '/links', + getParentRoute: () => rootRouteImport, +} as any) +const InlineScriptsRoute = InlineScriptsRouteImport.update({ + id: '/inline-scripts', + path: '/inline-scripts', + getParentRoute: () => rootRouteImport, +} as any) +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', + getParentRoute: () => rootRouteImport, +} as any) +const SpecialCharsRouteRoute = SpecialCharsRouteRouteImport.update({ + id: '/specialChars', + path: '/specialChars', + getParentRoute: () => rootRouteImport, +} as any) +const SearchParamsRouteRoute = SearchParamsRouteRouteImport.update({ + id: '/search-params', + path: '/search-params', + getParentRoute: () => rootRouteImport, +} as any) +const NotFoundRouteRoute = NotFoundRouteRouteImport.update({ + id: '/not-found', + path: '/not-found', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, +} as any) +const SearchParamsIndexRoute = SearchParamsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SearchParamsRouteRoute, +} as any) +const RedirectIndexRoute = RedirectIndexRouteImport.update({ + id: '/redirect/', + path: '/redirect/', + getParentRoute: () => rootRouteImport, +} as any) +const RawStreamIndexRoute = RawStreamIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => RawStreamRoute, +} as any) +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) +const NotFoundIndexRoute = NotFoundIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => NotFoundRouteRoute, +} as any) const MultiCookieRedirectIndexRoute = MultiCookieRedirectIndexRouteImport.update({ id: '/multi-cookie-redirect/', path: '/multi-cookie-redirect/', getParentRoute: () => rootRouteImport, } as any) -const MultiCookieRedirectTargetRoute = - MultiCookieRedirectTargetRouteImport.update({ - id: '/multi-cookie-redirect/target', - path: '/multi-cookie-redirect/target', - getParentRoute: () => rootRouteImport, - } as any) -const NotFoundIndexRoute = NotFoundIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => NotFoundRouteRoute, -} as any) -const NotFoundParentBoundaryRouteRoute = - NotFoundParentBoundaryRouteRouteImport.update({ - id: '/parent-boundary', - path: '/parent-boundary', - getParentRoute: () => NotFoundRouteRoute, - } as any) -const NotFoundViaBeforeLoadRoute = NotFoundViaBeforeLoadRouteImport.update({ - id: '/via-beforeLoad', - path: '/via-beforeLoad', - getParentRoute: () => NotFoundRouteRoute, -} as any) -const NotFoundViaBeforeLoadTargetRootRoute = - NotFoundViaBeforeLoadTargetRootRouteImport.update({ - id: '/via-beforeLoad-target-root', - path: '/via-beforeLoad-target-root', - getParentRoute: () => NotFoundRouteRoute, - } as any) -const NotFoundViaLoaderRoute = NotFoundViaLoaderRouteImport.update({ - id: '/via-loader', - path: '/via-loader', - getParentRoute: () => NotFoundRouteRoute, -} as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const RawStreamIndexRoute = RawStreamIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => RawStreamRoute, -} as any) -const RawStreamClientCallRoute = RawStreamClientCallRouteImport.update({ - id: '/client-call', - path: '/client-call', - getParentRoute: () => RawStreamRoute, -} as any) -const RawStreamSsrBinaryHintRoute = RawStreamSsrBinaryHintRouteImport.update({ - id: '/ssr-binary-hint', - path: '/ssr-binary-hint', - getParentRoute: () => RawStreamRoute, -} as any) -const RawStreamSsrMixedRoute = RawStreamSsrMixedRouteImport.update({ - id: '/ssr-mixed', - path: '/ssr-mixed', - getParentRoute: () => RawStreamRoute, -} as any) -const RawStreamSsrMultipleRoute = RawStreamSsrMultipleRouteImport.update({ - id: '/ssr-multiple', - path: '/ssr-multiple', - getParentRoute: () => RawStreamRoute, -} as any) -const RawStreamSsrSingleRoute = RawStreamSsrSingleRouteImport.update({ - id: '/ssr-single', - path: '/ssr-single', - getParentRoute: () => RawStreamRoute, -} as any) -const RawStreamSsrTextHintRoute = RawStreamSsrTextHintRouteImport.update({ - id: '/ssr-text-hint', - path: '/ssr-text-hint', - getParentRoute: () => RawStreamRoute, -} as any) -const RedirectIndexRoute = RedirectIndexRouteImport.update({ - id: '/redirect/', - path: '/redirect/', - getParentRoute: () => rootRouteImport, -} as any) -const RedirectTargetRoute = RedirectTargetRouteImport.update({ - id: '/redirect/$target', - path: '/redirect/$target', - getParentRoute: () => rootRouteImport, -} as any) -const SearchParamsIndexRoute = SearchParamsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SearchParamsRouteRoute, -} as any) -const SearchParamsDefaultRoute = SearchParamsDefaultRouteImport.update({ - id: '/default', - path: '/default', - getParentRoute: () => SearchParamsRouteRoute, -} as any) -const SearchParamsLoaderThrowsRedirectRoute = - SearchParamsLoaderThrowsRedirectRouteImport.update({ - id: '/loader-throws-redirect', - path: '/loader-throws-redirect', - getParentRoute: () => SearchParamsRouteRoute, - } as any) -const SpecialCharsParamRoute = SpecialCharsParamRouteImport.update({ - id: '/$param', - path: '/$param', - getParentRoute: () => SpecialCharsRouteRoute, -} as any) -const SpecialCharsHashRoute = SpecialCharsHashRouteImport.update({ - id: '/hash', - path: '/hash', - getParentRoute: () => SpecialCharsRouteRoute, -} as any) -const SpecialCharsMalformedRouteRoute = - SpecialCharsMalformedRouteRouteImport.update({ - id: '/malformed', - path: '/malformed', - getParentRoute: () => SpecialCharsRouteRoute, - } as any) -const SpecialCharsSearchRoute = SpecialCharsSearchRouteImport.update({ - id: '/search', - path: '/search', - getParentRoute: () => SpecialCharsRouteRoute, +const UsersUserIdRoute = UsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => UsersRoute, } as any) const SpecialCharsChar45824Char54620Char48124Char44397Route = SpecialCharsChar45824Char54620Char48124Char44397RouteImport.update({ @@ -277,80 +175,161 @@ const SpecialCharsChar45824Char54620Char48124Char44397Route = path: '/대한민국', getParentRoute: () => SpecialCharsRouteRoute, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, +const SpecialCharsSearchRoute = SpecialCharsSearchRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => SpecialCharsRouteRoute, } as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, +const SpecialCharsHashRoute = SpecialCharsHashRouteImport.update({ + id: '/hash', + path: '/hash', + getParentRoute: () => SpecialCharsRouteRoute, } as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, +const SpecialCharsParamRoute = SpecialCharsParamRouteImport.update({ + id: '/$param', + path: '/$param', + getParentRoute: () => SpecialCharsRouteRoute, } as any) -const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ - id: '/layout-b', - path: '/layout-b', - getParentRoute: () => LayoutLayout2Route, -} as any) -const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => ApiUsersRoute, -} as any) -const NotFoundParentBoundaryViaBeforeLoadRoute = - NotFoundParentBoundaryViaBeforeLoadRouteImport.update({ - id: '/via-beforeLoad', - path: '/via-beforeLoad', - getParentRoute: () => NotFoundParentBoundaryRouteRoute, +const SearchParamsLoaderThrowsRedirectRoute = + SearchParamsLoaderThrowsRedirectRouteImport.update({ + id: '/loader-throws-redirect', + path: '/loader-throws-redirect', + getParentRoute: () => SearchParamsRouteRoute, } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', +const SearchParamsDefaultRoute = SearchParamsDefaultRouteImport.update({ + id: '/default', + path: '/default', + getParentRoute: () => SearchParamsRouteRoute, +} as any) +const RedirectTargetRoute = RedirectTargetRouteImport.update({ + id: '/redirect/$target', + path: '/redirect/$target', getParentRoute: () => rootRouteImport, } as any) +const RawStreamSsrTextHintRoute = RawStreamSsrTextHintRouteImport.update({ + id: '/ssr-text-hint', + path: '/ssr-text-hint', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrSingleRoute = RawStreamSsrSingleRouteImport.update({ + id: '/ssr-single', + path: '/ssr-single', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrMultipleRoute = RawStreamSsrMultipleRouteImport.update({ + id: '/ssr-multiple', + path: '/ssr-multiple', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrMixedRoute = RawStreamSsrMixedRouteImport.update({ + id: '/ssr-mixed', + path: '/ssr-mixed', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrBinaryHintRoute = RawStreamSsrBinaryHintRouteImport.update({ + id: '/ssr-binary-hint', + path: '/ssr-binary-hint', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamClientCallRoute = RawStreamClientCallRouteImport.update({ + id: '/client-call', + path: '/client-call', + getParentRoute: () => RawStreamRoute, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const NotFoundViaLoaderRoute = NotFoundViaLoaderRouteImport.update({ + id: '/via-loader', + path: '/via-loader', + getParentRoute: () => NotFoundRouteRoute, +} as any) +const NotFoundViaBeforeLoadRoute = NotFoundViaBeforeLoadRouteImport.update({ + id: '/via-beforeLoad', + path: '/via-beforeLoad', + getParentRoute: () => NotFoundRouteRoute, +} as any) +const MultiCookieRedirectTargetRoute = + MultiCookieRedirectTargetRouteImport.update({ + id: '/multi-cookie-redirect/target', + path: '/multi-cookie-redirect/target', + getParentRoute: () => rootRouteImport, + } as any) +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, +} as any) +const SpecialCharsMalformedRouteRoute = + SpecialCharsMalformedRouteRouteImport.update({ + id: '/malformed', + path: '/malformed', + getParentRoute: () => SpecialCharsRouteRoute, + } as any) const RedirectTargetIndexRoute = RedirectTargetIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => RedirectTargetRoute, } as any) +const SpecialCharsMalformedSearchRoute = + SpecialCharsMalformedSearchRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => SpecialCharsMalformedRouteRoute, + } as any) +const SpecialCharsMalformedParamRoute = + SpecialCharsMalformedParamRouteImport.update({ + id: '/$param', + path: '/$param', + getParentRoute: () => SpecialCharsMalformedRouteRoute, + } as any) +const RedirectTargetViaLoaderRoute = RedirectTargetViaLoaderRouteImport.update({ + id: '/via-loader', + path: '/via-loader', + getParentRoute: () => RedirectTargetRoute, +} as any) const RedirectTargetViaBeforeLoadRoute = RedirectTargetViaBeforeLoadRouteImport.update({ id: '/via-beforeLoad', path: '/via-beforeLoad', getParentRoute: () => RedirectTargetRoute, } as any) -const RedirectTargetViaLoaderRoute = RedirectTargetViaLoaderRouteImport.update({ - id: '/via-loader', - path: '/via-loader', - getParentRoute: () => RedirectTargetRoute, +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) +const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => ApiUsersRoute, +} as any) +const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ + id: '/layout-b', + path: '/layout-b', + getParentRoute: () => LayoutLayout2Route, +} as any) +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, } as any) -const SpecialCharsMalformedParamRoute = - SpecialCharsMalformedParamRouteImport.update({ - id: '/$param', - path: '/$param', - getParentRoute: () => SpecialCharsMalformedRouteRoute, - } as any) -const SpecialCharsMalformedSearchRoute = - SpecialCharsMalformedSearchRouteImport.update({ - id: '/search', - path: '/search', - getParentRoute: () => SpecialCharsMalformedRouteRoute, - } as any) const RedirectTargetServerFnIndexRoute = RedirectTargetServerFnIndexRouteImport.update({ id: '/serverFn/', path: '/serverFn/', getParentRoute: () => RedirectTargetRoute, } as any) -const RedirectTargetServerFnViaBeforeLoadRoute = - RedirectTargetServerFnViaBeforeLoadRouteImport.update({ - id: '/serverFn/via-beforeLoad', - path: '/serverFn/via-beforeLoad', +const RedirectTargetServerFnViaUseServerFnRoute = + RedirectTargetServerFnViaUseServerFnRouteImport.update({ + id: '/serverFn/via-useServerFn', + path: '/serverFn/via-useServerFn', getParentRoute: () => RedirectTargetRoute, } as any) const RedirectTargetServerFnViaLoaderRoute = @@ -359,10 +338,10 @@ const RedirectTargetServerFnViaLoaderRoute = path: '/serverFn/via-loader', getParentRoute: () => RedirectTargetRoute, } as any) -const RedirectTargetServerFnViaUseServerFnRoute = - RedirectTargetServerFnViaUseServerFnRouteImport.update({ - id: '/serverFn/via-useServerFn', - path: '/serverFn/via-useServerFn', +const RedirectTargetServerFnViaBeforeLoadRoute = + RedirectTargetServerFnViaBeforeLoadRouteImport.update({ + id: '/serverFn/via-beforeLoad', + path: '/serverFn/via-beforeLoad', getParentRoute: () => RedirectTargetRoute, } as any) @@ -379,12 +358,10 @@ export interface FileRoutesByFullPath { '/scripts': typeof ScriptsRoute '/stream': typeof StreamRoute '/users': typeof UsersRouteWithChildren - '/not-found/parent-boundary': typeof NotFoundParentBoundaryRouteRouteWithChildren '/specialChars/malformed': typeof SpecialCharsMalformedRouteRouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren '/multi-cookie-redirect/target': typeof MultiCookieRedirectTargetRoute '/not-found/via-beforeLoad': typeof NotFoundViaBeforeLoadRoute - '/not-found/via-beforeLoad-target-root': typeof NotFoundViaBeforeLoadTargetRootRoute '/not-found/via-loader': typeof NotFoundViaLoaderRoute '/posts/$postId': typeof PostsPostIdRoute '/raw-stream/client-call': typeof RawStreamClientCallRoute @@ -411,7 +388,6 @@ export interface FileRoutesByFullPath { '/layout-a': typeof LayoutLayout2LayoutARoute '/layout-b': typeof LayoutLayout2LayoutBRoute '/api/users/$userId': typeof ApiUsersUserIdRoute - '/not-found/parent-boundary/via-beforeLoad': typeof NotFoundParentBoundaryViaBeforeLoadRoute '/posts/$postId/deep': typeof PostsPostIdDeepRoute '/redirect/$target/via-beforeLoad': typeof RedirectTargetViaBeforeLoadRoute '/redirect/$target/via-loader': typeof RedirectTargetViaLoaderRoute @@ -431,12 +407,10 @@ export interface FileRoutesByTo { '/links': typeof LinksRoute '/scripts': typeof ScriptsRoute '/stream': typeof StreamRoute - '/not-found/parent-boundary': typeof NotFoundParentBoundaryRouteRouteWithChildren '/specialChars/malformed': typeof SpecialCharsMalformedRouteRouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren '/multi-cookie-redirect/target': typeof MultiCookieRedirectTargetRoute '/not-found/via-beforeLoad': typeof NotFoundViaBeforeLoadRoute - '/not-found/via-beforeLoad-target-root': typeof NotFoundViaBeforeLoadTargetRootRoute '/not-found/via-loader': typeof NotFoundViaLoaderRoute '/posts/$postId': typeof PostsPostIdRoute '/raw-stream/client-call': typeof RawStreamClientCallRoute @@ -462,7 +436,6 @@ export interface FileRoutesByTo { '/layout-a': typeof LayoutLayout2LayoutARoute '/layout-b': typeof LayoutLayout2LayoutBRoute '/api/users/$userId': typeof ApiUsersUserIdRoute - '/not-found/parent-boundary/via-beforeLoad': typeof NotFoundParentBoundaryViaBeforeLoadRoute '/posts/$postId/deep': typeof PostsPostIdDeepRoute '/redirect/$target/via-beforeLoad': typeof RedirectTargetViaBeforeLoadRoute '/redirect/$target/via-loader': typeof RedirectTargetViaLoaderRoute @@ -489,13 +462,11 @@ export interface FileRoutesById { '/scripts': typeof ScriptsRoute '/stream': typeof StreamRoute '/users': typeof UsersRouteWithChildren - '/not-found/parent-boundary': typeof NotFoundParentBoundaryRouteRouteWithChildren '/specialChars/malformed': typeof SpecialCharsMalformedRouteRouteWithChildren '/_layout/_layout-2': typeof LayoutLayout2RouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren '/multi-cookie-redirect/target': typeof MultiCookieRedirectTargetRoute '/not-found/via-beforeLoad': typeof NotFoundViaBeforeLoadRoute - '/not-found/via-beforeLoad-target-root': typeof NotFoundViaBeforeLoadTargetRootRoute '/not-found/via-loader': typeof NotFoundViaLoaderRoute '/posts/$postId': typeof PostsPostIdRoute '/raw-stream/client-call': typeof RawStreamClientCallRoute @@ -522,7 +493,6 @@ export interface FileRoutesById { '/_layout/_layout-2/layout-a': typeof LayoutLayout2LayoutARoute '/_layout/_layout-2/layout-b': typeof LayoutLayout2LayoutBRoute '/api/users/$userId': typeof ApiUsersUserIdRoute - '/not-found/parent-boundary/via-beforeLoad': typeof NotFoundParentBoundaryViaBeforeLoadRoute '/posts_/$postId/deep': typeof PostsPostIdDeepRoute '/redirect/$target/via-beforeLoad': typeof RedirectTargetViaBeforeLoadRoute '/redirect/$target/via-loader': typeof RedirectTargetViaLoaderRoute @@ -549,12 +519,10 @@ export interface FileRouteTypes { | '/scripts' | '/stream' | '/users' - | '/not-found/parent-boundary' | '/specialChars/malformed' | '/api/users' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' - | '/not-found/via-beforeLoad-target-root' | '/not-found/via-loader' | '/posts/$postId' | '/raw-stream/client-call' @@ -581,7 +549,6 @@ export interface FileRouteTypes { | '/layout-a' | '/layout-b' | '/api/users/$userId' - | '/not-found/parent-boundary/via-beforeLoad' | '/posts/$postId/deep' | '/redirect/$target/via-beforeLoad' | '/redirect/$target/via-loader' @@ -601,12 +568,10 @@ export interface FileRouteTypes { | '/links' | '/scripts' | '/stream' - | '/not-found/parent-boundary' | '/specialChars/malformed' | '/api/users' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' - | '/not-found/via-beforeLoad-target-root' | '/not-found/via-loader' | '/posts/$postId' | '/raw-stream/client-call' @@ -632,7 +597,6 @@ export interface FileRouteTypes { | '/layout-a' | '/layout-b' | '/api/users/$userId' - | '/not-found/parent-boundary/via-beforeLoad' | '/posts/$postId/deep' | '/redirect/$target/via-beforeLoad' | '/redirect/$target/via-loader' @@ -658,13 +622,11 @@ export interface FileRouteTypes { | '/scripts' | '/stream' | '/users' - | '/not-found/parent-boundary' | '/specialChars/malformed' | '/_layout/_layout-2' | '/api/users' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' - | '/not-found/via-beforeLoad-target-root' | '/not-found/via-loader' | '/posts/$postId' | '/raw-stream/client-call' @@ -691,7 +653,6 @@ export interface FileRouteTypes { | '/_layout/_layout-2/layout-a' | '/_layout/_layout-2/layout-b' | '/api/users/$userId' - | '/not-found/parent-boundary/via-beforeLoad' | '/posts_/$postId/deep' | '/redirect/$target/via-beforeLoad' | '/redirect/$target/via-loader' @@ -728,81 +689,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout': { - id: '/_layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/inline-scripts': { - id: '/inline-scripts' - path: '/inline-scripts' - fullPath: '/inline-scripts' - preLoaderRoute: typeof InlineScriptsRouteImport - parentRoute: typeof rootRouteImport - } - '/links': { - id: '/links' - path: '/links' - fullPath: '/links' - preLoaderRoute: typeof LinksRouteImport - parentRoute: typeof rootRouteImport - } - '/not-found': { - id: '/not-found' - path: '/not-found' - fullPath: '/not-found' - preLoaderRoute: typeof NotFoundRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/raw-stream': { - id: '/raw-stream' - path: '/raw-stream' - fullPath: '/raw-stream' - preLoaderRoute: typeof RawStreamRouteImport - parentRoute: typeof rootRouteImport - } - '/scripts': { - id: '/scripts' - path: '/scripts' - fullPath: '/scripts' - preLoaderRoute: typeof ScriptsRouteImport - parentRoute: typeof rootRouteImport - } - '/search-params': { - id: '/search-params' - path: '/search-params' - fullPath: '/search-params' - preLoaderRoute: typeof SearchParamsRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/specialChars': { - id: '/specialChars' - path: '/specialChars' - fullPath: '/specialChars' - preLoaderRoute: typeof SpecialCharsRouteRouteImport + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/stream': { @@ -812,152 +703,89 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof StreamRouteImport parentRoute: typeof rootRouteImport } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/scripts': { + id: '/scripts' + path: '/scripts' + fullPath: '/scripts' + preLoaderRoute: typeof ScriptsRouteImport parentRoute: typeof rootRouteImport } - '/_layout/_layout-2': { - id: '/_layout/_layout-2' + '/raw-stream': { + id: '/raw-stream' + path: '/raw-stream' + fullPath: '/raw-stream' + preLoaderRoute: typeof RawStreamRouteImport + parentRoute: typeof rootRouteImport + } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/links': { + id: '/links' + path: '/links' + fullPath: '/links' + preLoaderRoute: typeof LinksRouteImport + parentRoute: typeof rootRouteImport + } + '/inline-scripts': { + id: '/inline-scripts' + path: '/inline-scripts' + fullPath: '/inline-scripts' + preLoaderRoute: typeof InlineScriptsRouteImport + parentRoute: typeof rootRouteImport + } + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout': { + id: '/_layout' path: '' fullPath: '/' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute - } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/multi-cookie-redirect/': { - id: '/multi-cookie-redirect/' - path: '/multi-cookie-redirect' - fullPath: '/multi-cookie-redirect/' - preLoaderRoute: typeof MultiCookieRedirectIndexRouteImport + '/specialChars': { + id: '/specialChars' + path: '/specialChars' + fullPath: '/specialChars' + preLoaderRoute: typeof SpecialCharsRouteRouteImport parentRoute: typeof rootRouteImport } - '/multi-cookie-redirect/target': { - id: '/multi-cookie-redirect/target' - path: '/multi-cookie-redirect/target' - fullPath: '/multi-cookie-redirect/target' - preLoaderRoute: typeof MultiCookieRedirectTargetRouteImport + '/search-params': { + id: '/search-params' + path: '/search-params' + fullPath: '/search-params' + preLoaderRoute: typeof SearchParamsRouteRouteImport parentRoute: typeof rootRouteImport } - '/not-found/': { - id: '/not-found/' + '/not-found': { + id: '/not-found' + path: '/not-found' + fullPath: '/not-found' + preLoaderRoute: typeof NotFoundRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' path: '/' - fullPath: '/not-found/' - preLoaderRoute: typeof NotFoundIndexRouteImport - parentRoute: typeof NotFoundRouteRoute - } - '/not-found/parent-boundary': { - id: '/not-found/parent-boundary' - path: '/parent-boundary' - fullPath: '/not-found/parent-boundary' - preLoaderRoute: typeof NotFoundParentBoundaryRouteRouteImport - parentRoute: typeof NotFoundRouteRoute - } - '/not-found/via-beforeLoad': { - id: '/not-found/via-beforeLoad' - path: '/via-beforeLoad' - fullPath: '/not-found/via-beforeLoad' - preLoaderRoute: typeof NotFoundViaBeforeLoadRouteImport - parentRoute: typeof NotFoundRouteRoute - } - '/not-found/via-beforeLoad-target-root': { - id: '/not-found/via-beforeLoad-target-root' - path: '/via-beforeLoad-target-root' - fullPath: '/not-found/via-beforeLoad-target-root' - preLoaderRoute: typeof NotFoundViaBeforeLoadTargetRootRouteImport - parentRoute: typeof NotFoundRouteRoute - } - '/not-found/via-loader': { - id: '/not-found/via-loader' - path: '/via-loader' - fullPath: '/not-found/via-loader' - preLoaderRoute: typeof NotFoundViaLoaderRouteImport - parentRoute: typeof NotFoundRouteRoute - } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/raw-stream/': { - id: '/raw-stream/' - path: '/' - fullPath: '/raw-stream/' - preLoaderRoute: typeof RawStreamIndexRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/client-call': { - id: '/raw-stream/client-call' - path: '/client-call' - fullPath: '/raw-stream/client-call' - preLoaderRoute: typeof RawStreamClientCallRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/ssr-binary-hint': { - id: '/raw-stream/ssr-binary-hint' - path: '/ssr-binary-hint' - fullPath: '/raw-stream/ssr-binary-hint' - preLoaderRoute: typeof RawStreamSsrBinaryHintRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/ssr-mixed': { - id: '/raw-stream/ssr-mixed' - path: '/ssr-mixed' - fullPath: '/raw-stream/ssr-mixed' - preLoaderRoute: typeof RawStreamSsrMixedRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/ssr-multiple': { - id: '/raw-stream/ssr-multiple' - path: '/ssr-multiple' - fullPath: '/raw-stream/ssr-multiple' - preLoaderRoute: typeof RawStreamSsrMultipleRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/ssr-single': { - id: '/raw-stream/ssr-single' - path: '/ssr-single' - fullPath: '/raw-stream/ssr-single' - preLoaderRoute: typeof RawStreamSsrSingleRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/ssr-text-hint': { - id: '/raw-stream/ssr-text-hint' - path: '/ssr-text-hint' - fullPath: '/raw-stream/ssr-text-hint' - preLoaderRoute: typeof RawStreamSsrTextHintRouteImport - parentRoute: typeof RawStreamRoute - } - '/redirect/': { - id: '/redirect/' - path: '/redirect' - fullPath: '/redirect/' - preLoaderRoute: typeof RedirectIndexRouteImport + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/redirect/$target': { - id: '/redirect/$target' - path: '/redirect/$target' - fullPath: '/redirect/$target' - preLoaderRoute: typeof RedirectTargetRouteImport - parentRoute: typeof rootRouteImport + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute } '/search-params/': { id: '/search-params/' @@ -966,39 +794,53 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof SearchParamsIndexRouteImport parentRoute: typeof SearchParamsRouteRoute } - '/search-params/default': { - id: '/search-params/default' - path: '/default' - fullPath: '/search-params/default' - preLoaderRoute: typeof SearchParamsDefaultRouteImport - parentRoute: typeof SearchParamsRouteRoute + '/redirect/': { + id: '/redirect/' + path: '/redirect' + fullPath: '/redirect/' + preLoaderRoute: typeof RedirectIndexRouteImport + parentRoute: typeof rootRouteImport } - '/search-params/loader-throws-redirect': { - id: '/search-params/loader-throws-redirect' - path: '/loader-throws-redirect' - fullPath: '/search-params/loader-throws-redirect' - preLoaderRoute: typeof SearchParamsLoaderThrowsRedirectRouteImport - parentRoute: typeof SearchParamsRouteRoute + '/raw-stream/': { + id: '/raw-stream/' + path: '/' + fullPath: '/raw-stream/' + preLoaderRoute: typeof RawStreamIndexRouteImport + parentRoute: typeof RawStreamRoute } - '/specialChars/$param': { - id: '/specialChars/$param' - path: '/$param' - fullPath: '/specialChars/$param' - preLoaderRoute: typeof SpecialCharsParamRouteImport - parentRoute: typeof SpecialCharsRouteRoute + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute } - '/specialChars/hash': { - id: '/specialChars/hash' - path: '/hash' - fullPath: '/specialChars/hash' - preLoaderRoute: typeof SpecialCharsHashRouteImport - parentRoute: typeof SpecialCharsRouteRoute + '/not-found/': { + id: '/not-found/' + path: '/' + fullPath: '/not-found/' + preLoaderRoute: typeof NotFoundIndexRouteImport + parentRoute: typeof NotFoundRouteRoute } - '/specialChars/malformed': { - id: '/specialChars/malformed' - path: '/malformed' - fullPath: '/specialChars/malformed' - preLoaderRoute: typeof SpecialCharsMalformedRouteRouteImport + '/multi-cookie-redirect/': { + id: '/multi-cookie-redirect/' + path: '/multi-cookie-redirect' + fullPath: '/multi-cookie-redirect/' + preLoaderRoute: typeof MultiCookieRedirectIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/users/$userId': { + id: '/users/$userId' + path: '/$userId' + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute + } + '/specialChars/대한민국': { + id: '/specialChars/대한민국' + path: '/대한민국' + fullPath: '/specialChars/대한민국' + preLoaderRoute: typeof SpecialCharsChar45824Char54620Char48124Char44397RouteImport parentRoute: typeof SpecialCharsRouteRoute } '/specialChars/search': { @@ -1008,62 +850,132 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof SpecialCharsSearchRouteImport parentRoute: typeof SpecialCharsRouteRoute } - '/specialChars/대한민국': { - id: '/specialChars/대한민국' - path: '/대한민국' - fullPath: '/specialChars/대한민국' - preLoaderRoute: typeof SpecialCharsChar45824Char54620Char48124Char44397RouteImport + '/specialChars/hash': { + id: '/specialChars/hash' + path: '/hash' + fullPath: '/specialChars/hash' + preLoaderRoute: typeof SpecialCharsHashRouteImport parentRoute: typeof SpecialCharsRouteRoute } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute + '/specialChars/$param': { + id: '/specialChars/$param' + path: '/$param' + fullPath: '/specialChars/$param' + preLoaderRoute: typeof SpecialCharsParamRouteImport + parentRoute: typeof SpecialCharsRouteRoute } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute + '/search-params/loader-throws-redirect': { + id: '/search-params/loader-throws-redirect' + path: '/loader-throws-redirect' + fullPath: '/search-params/loader-throws-redirect' + preLoaderRoute: typeof SearchParamsLoaderThrowsRedirectRouteImport + parentRoute: typeof SearchParamsRouteRoute } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route + '/search-params/default': { + id: '/search-params/default' + path: '/default' + fullPath: '/search-params/default' + preLoaderRoute: typeof SearchParamsDefaultRouteImport + parentRoute: typeof SearchParamsRouteRoute } - '/_layout/_layout-2/layout-b': { - id: '/_layout/_layout-2/layout-b' - path: '/layout-b' - fullPath: '/layout-b' - preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport - parentRoute: typeof LayoutLayout2Route - } - '/api/users/$userId': { - id: '/api/users/$userId' - path: '/$userId' - fullPath: '/api/users/$userId' - preLoaderRoute: typeof ApiUsersUserIdRouteImport - parentRoute: typeof ApiUsersRoute - } - '/not-found/parent-boundary/via-beforeLoad': { - id: '/not-found/parent-boundary/via-beforeLoad' - path: '/via-beforeLoad' - fullPath: '/not-found/parent-boundary/via-beforeLoad' - preLoaderRoute: typeof NotFoundParentBoundaryViaBeforeLoadRouteImport - parentRoute: typeof NotFoundParentBoundaryRouteRoute - } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport + '/redirect/$target': { + id: '/redirect/$target' + path: '/redirect/$target' + fullPath: '/redirect/$target' + preLoaderRoute: typeof RedirectTargetRouteImport parentRoute: typeof rootRouteImport } + '/raw-stream/ssr-text-hint': { + id: '/raw-stream/ssr-text-hint' + path: '/ssr-text-hint' + fullPath: '/raw-stream/ssr-text-hint' + preLoaderRoute: typeof RawStreamSsrTextHintRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-single': { + id: '/raw-stream/ssr-single' + path: '/ssr-single' + fullPath: '/raw-stream/ssr-single' + preLoaderRoute: typeof RawStreamSsrSingleRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-multiple': { + id: '/raw-stream/ssr-multiple' + path: '/ssr-multiple' + fullPath: '/raw-stream/ssr-multiple' + preLoaderRoute: typeof RawStreamSsrMultipleRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-mixed': { + id: '/raw-stream/ssr-mixed' + path: '/ssr-mixed' + fullPath: '/raw-stream/ssr-mixed' + preLoaderRoute: typeof RawStreamSsrMixedRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-binary-hint': { + id: '/raw-stream/ssr-binary-hint' + path: '/ssr-binary-hint' + fullPath: '/raw-stream/ssr-binary-hint' + preLoaderRoute: typeof RawStreamSsrBinaryHintRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/client-call': { + id: '/raw-stream/client-call' + path: '/client-call' + fullPath: '/raw-stream/client-call' + preLoaderRoute: typeof RawStreamClientCallRouteImport + parentRoute: typeof RawStreamRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute + } + '/not-found/via-loader': { + id: '/not-found/via-loader' + path: '/via-loader' + fullPath: '/not-found/via-loader' + preLoaderRoute: typeof NotFoundViaLoaderRouteImport + parentRoute: typeof NotFoundRouteRoute + } + '/not-found/via-beforeLoad': { + id: '/not-found/via-beforeLoad' + path: '/via-beforeLoad' + fullPath: '/not-found/via-beforeLoad' + preLoaderRoute: typeof NotFoundViaBeforeLoadRouteImport + parentRoute: typeof NotFoundRouteRoute + } + '/multi-cookie-redirect/target': { + id: '/multi-cookie-redirect/target' + path: '/multi-cookie-redirect/target' + fullPath: '/multi-cookie-redirect/target' + preLoaderRoute: typeof MultiCookieRedirectTargetRouteImport + parentRoute: typeof rootRouteImport + } + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout/_layout-2': { + id: '/_layout/_layout-2' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute + } + '/specialChars/malformed': { + id: '/specialChars/malformed' + path: '/malformed' + fullPath: '/specialChars/malformed' + preLoaderRoute: typeof SpecialCharsMalformedRouteRouteImport + parentRoute: typeof SpecialCharsRouteRoute + } '/redirect/$target/': { id: '/redirect/$target/' path: '/' @@ -1071,6 +983,27 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof RedirectTargetIndexRouteImport parentRoute: typeof RedirectTargetRoute } + '/specialChars/malformed/search': { + id: '/specialChars/malformed/search' + path: '/search' + fullPath: '/specialChars/malformed/search' + preLoaderRoute: typeof SpecialCharsMalformedSearchRouteImport + parentRoute: typeof SpecialCharsMalformedRouteRoute + } + '/specialChars/malformed/$param': { + id: '/specialChars/malformed/$param' + path: '/$param' + fullPath: '/specialChars/malformed/$param' + preLoaderRoute: typeof SpecialCharsMalformedParamRouteImport + parentRoute: typeof SpecialCharsMalformedRouteRoute + } + '/redirect/$target/via-loader': { + id: '/redirect/$target/via-loader' + path: '/via-loader' + fullPath: '/redirect/$target/via-loader' + preLoaderRoute: typeof RedirectTargetViaLoaderRouteImport + parentRoute: typeof RedirectTargetRoute + } '/redirect/$target/via-beforeLoad': { id: '/redirect/$target/via-beforeLoad' path: '/via-beforeLoad' @@ -1078,26 +1011,33 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof RedirectTargetViaBeforeLoadRouteImport parentRoute: typeof RedirectTargetRoute } - '/redirect/$target/via-loader': { - id: '/redirect/$target/via-loader' - path: '/via-loader' - fullPath: '/redirect/$target/via-loader' - preLoaderRoute: typeof RedirectTargetViaLoaderRouteImport - parentRoute: typeof RedirectTargetRoute + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport } - '/specialChars/malformed/$param': { - id: '/specialChars/malformed/$param' - path: '/$param' - fullPath: '/specialChars/malformed/$param' - preLoaderRoute: typeof SpecialCharsMalformedParamRouteImport - parentRoute: typeof SpecialCharsMalformedRouteRoute + '/api/users/$userId': { + id: '/api/users/$userId' + path: '/$userId' + fullPath: '/api/users/$userId' + preLoaderRoute: typeof ApiUsersUserIdRouteImport + parentRoute: typeof ApiUsersRoute } - '/specialChars/malformed/search': { - id: '/specialChars/malformed/search' - path: '/search' - fullPath: '/specialChars/malformed/search' - preLoaderRoute: typeof SpecialCharsMalformedSearchRouteImport - parentRoute: typeof SpecialCharsMalformedRouteRoute + '/_layout/_layout-2/layout-b': { + id: '/_layout/_layout-2/layout-b' + path: '/layout-b' + fullPath: '/layout-b' + preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport + parentRoute: typeof LayoutLayout2Route + } + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route } '/redirect/$target/serverFn/': { id: '/redirect/$target/serverFn/' @@ -1106,20 +1046,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof RedirectTargetServerFnIndexRouteImport parentRoute: typeof RedirectTargetRoute } - '/redirect/$target/serverFn/via-beforeLoad': { - id: '/redirect/$target/serverFn/via-beforeLoad' - path: '/serverFn/via-beforeLoad' - fullPath: '/redirect/$target/serverFn/via-beforeLoad' - preLoaderRoute: typeof RedirectTargetServerFnViaBeforeLoadRouteImport - parentRoute: typeof RedirectTargetRoute - } - '/redirect/$target/serverFn/via-loader': { - id: '/redirect/$target/serverFn/via-loader' - path: '/serverFn/via-loader' - fullPath: '/redirect/$target/serverFn/via-loader' - preLoaderRoute: typeof RedirectTargetServerFnViaLoaderRouteImport - parentRoute: typeof RedirectTargetRoute - } '/redirect/$target/serverFn/via-useServerFn': { id: '/redirect/$target/serverFn/via-useServerFn' path: '/serverFn/via-useServerFn' @@ -1127,37 +1053,31 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof RedirectTargetServerFnViaUseServerFnRouteImport parentRoute: typeof RedirectTargetRoute } + '/redirect/$target/serverFn/via-loader': { + id: '/redirect/$target/serverFn/via-loader' + path: '/serverFn/via-loader' + fullPath: '/redirect/$target/serverFn/via-loader' + preLoaderRoute: typeof RedirectTargetServerFnViaLoaderRouteImport + parentRoute: typeof RedirectTargetRoute + } + '/redirect/$target/serverFn/via-beforeLoad': { + id: '/redirect/$target/serverFn/via-beforeLoad' + path: '/serverFn/via-beforeLoad' + fullPath: '/redirect/$target/serverFn/via-beforeLoad' + preLoaderRoute: typeof RedirectTargetServerFnViaBeforeLoadRouteImport + parentRoute: typeof RedirectTargetRoute + } } } -interface NotFoundParentBoundaryRouteRouteChildren { - NotFoundParentBoundaryViaBeforeLoadRoute: typeof NotFoundParentBoundaryViaBeforeLoadRoute -} - -const NotFoundParentBoundaryRouteRouteChildren: NotFoundParentBoundaryRouteRouteChildren = - { - NotFoundParentBoundaryViaBeforeLoadRoute: - NotFoundParentBoundaryViaBeforeLoadRoute, - } - -const NotFoundParentBoundaryRouteRouteWithChildren = - NotFoundParentBoundaryRouteRoute._addFileChildren( - NotFoundParentBoundaryRouteRouteChildren, - ) - interface NotFoundRouteRouteChildren { - NotFoundParentBoundaryRouteRoute: typeof NotFoundParentBoundaryRouteRouteWithChildren NotFoundViaBeforeLoadRoute: typeof NotFoundViaBeforeLoadRoute - NotFoundViaBeforeLoadTargetRootRoute: typeof NotFoundViaBeforeLoadTargetRootRoute NotFoundViaLoaderRoute: typeof NotFoundViaLoaderRoute NotFoundIndexRoute: typeof NotFoundIndexRoute } const NotFoundRouteRouteChildren: NotFoundRouteRouteChildren = { - NotFoundParentBoundaryRouteRoute: - NotFoundParentBoundaryRouteRouteWithChildren, NotFoundViaBeforeLoadRoute: NotFoundViaBeforeLoadRoute, - NotFoundViaBeforeLoadTargetRootRoute: NotFoundViaBeforeLoadTargetRootRoute, NotFoundViaLoaderRoute: NotFoundViaLoaderRoute, NotFoundIndexRoute: NotFoundIndexRoute, } diff --git a/e2e/vue-start/basic/src/routes/__root.tsx b/e2e/vue-start/basic/src/routes/__root.tsx index 9da2c581fe..45b729c19c 100644 --- a/e2e/vue-start/basic/src/routes/__root.tsx +++ b/e2e/vue-start/basic/src/routes/__root.tsx @@ -1,135 +1,19 @@ /// -import { defineComponent } from 'vue' import { Body, - ClientOnly, HeadContent, Html, Link, Outlet, Scripts, createRootRoute, - useRouterState, } from '@tanstack/vue-router' import { TanStackRouterDevtoolsInProd } from '@tanstack/vue-router-devtools' import { NotFound } from '~/components/NotFound' -import '~/styles/app.css' +import appCss from '~/styles/app.css?url' 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: [ @@ -144,6 +28,7 @@ export const Route = createRootRoute({ }), ], links: [ + { rel: 'stylesheet', href: appCss }, { rel: 'apple-touch-icon', sizes: '180x180', @@ -176,11 +61,107 @@ export const Route = createRootRoute({ }, ], }), - errorComponent: (props) => ( -

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

- ), + errorComponent: (props) =>

{props.error.stack}

, notFoundComponent: () => , component: RootComponent, }) + +function RootComponent() { + return ( + + + + + +
+ + Home + {' '} + + Posts + {' '} + + Users + {' '} + + Layout + {' '} + + Scripts + {' '} + + Inline Scripts + {' '} + + Deferred + {' '} + + redirect + {' '} + + Raw Stream + {' '} + + This Route Does Not Exist + +
+ +
This is an inline styled div
+ + + + + ) +} diff --git a/e2e/vue-start/basic/src/routes/api/users.$userId.ts b/e2e/vue-start/basic/src/routes/api/users.$userId.ts index 24938d51c2..50b9ca995a 100644 --- a/e2e/vue-start/basic/src/routes/api/users.$userId.ts +++ b/e2e/vue-start/basic/src/routes/api/users.$userId.ts @@ -1,15 +1,19 @@ import { createFileRoute } from '@tanstack/vue-router' import type { User } from '~/utils/users' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} + export const Route = createFileRoute('/api/users/$userId')({ server: { handlers: { GET: async ({ params, request }) => { console.info(`Fetching users by id=${params.userId}... @`, request.url) try { - const res = await fetch( - `https://jsonplaceholder.typicode.com/users/${params.userId}`, - ) + const res = await fetch(`${queryURL}/users/${params.userId}`) if (!res.ok) { throw new Error('Failed to fetch user') } diff --git a/e2e/vue-start/basic/src/routes/api/users.ts b/e2e/vue-start/basic/src/routes/api/users.ts index c6045977b8..97989b93ca 100644 --- a/e2e/vue-start/basic/src/routes/api/users.ts +++ b/e2e/vue-start/basic/src/routes/api/users.ts @@ -38,13 +38,19 @@ const testMiddleware = createMiddleware() return result }) +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} + export const Route = createFileRoute('/api/users')({ server: { middleware: [testMiddleware, userLoggerMiddleware, testParentMiddleware], handlers: { GET: async ({ request }) => { console.info('Fetching users... @', request.url) - const res = await fetch('https://jsonplaceholder.typicode.com/users') + const res = await fetch(`${queryURL}/users`) if (!res.ok) { throw new Error('Failed to fetch users') } diff --git a/e2e/vue-start/basic/src/routes/deferred.tsx b/e2e/vue-start/basic/src/routes/deferred.tsx index 18aae161ab..4f8fcd600c 100644 --- a/e2e/vue-start/basic/src/routes/deferred.tsx +++ b/e2e/vue-start/basic/src/routes/deferred.tsx @@ -3,13 +3,13 @@ import { createServerFn } from '@tanstack/vue-start' import { Suspense, ref, defineComponent } from 'vue' const personServerFn = createServerFn({ method: 'GET' }) - .validator((data: { name: string }) => data) + .inputValidator((data: { name: string }) => data) .handler(({ data }) => { return { name: data.name, randomNumber: Math.floor(Math.random() * 100) } }) const slowServerFn = createServerFn({ method: 'GET' }) - .validator((data: { name: string }) => data) + .inputValidator((data: { name: string }) => data) .handler(async ({ data }) => { await new Promise((r) => setTimeout(r, 1000)) return { name: data.name, randomNumber: Math.floor(Math.random() * 100) } diff --git a/e2e/vue-start/basic/src/routes/not-found/index.tsx b/e2e/vue-start/basic/src/routes/not-found/index.tsx index ecd12d1dad..9f7e3b4b33 100644 --- a/e2e/vue-start/basic/src/routes/not-found/index.tsx +++ b/e2e/vue-start/basic/src/routes/not-found/index.tsx @@ -1,10 +1,9 @@ -import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' -const RouteComponent = defineComponent({ - setup() { +export const Route = createFileRoute('/not-found/')({ + component: () => { const preload = Route.useSearch({ select: (s) => s.preload }) - return () => ( + return (
( -
-
- {loaderData.value.parentLoaderData} -
-
- ) - }, -}) - -export const Route = createFileRoute('/not-found/parent-boundary')({ - loader: () => ({ - parentLoaderData: 'ready', - }), - component: RouteComponent, - notFoundComponent: ParentBoundaryNotFoundComponent, -}) - -function RouteComponent() { - return ( -
- -
- ) -} diff --git a/e2e/vue-start/basic/src/routes/not-found/parent-boundary/via-beforeLoad.tsx b/e2e/vue-start/basic/src/routes/not-found/parent-boundary/via-beforeLoad.tsx deleted file mode 100644 index b2c111a5ac..0000000000 --- a/e2e/vue-start/basic/src/routes/not-found/parent-boundary/via-beforeLoad.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import { createFileRoute, notFound } from '@tanstack/vue-router' -import { Route as ParentBoundaryRoute } from './route' - -export const Route = createFileRoute( - '/not-found/parent-boundary/via-beforeLoad', -)({ - beforeLoad: () => { - throw notFound({ routeId: ParentBoundaryRoute.id }) - }, - component: RouteComponent, -}) - -function RouteComponent() { - return ( -
- Hello "/not-found/parent-boundary/via-beforeLoad"! -
- ) -} diff --git a/e2e/vue-start/basic/src/routes/not-found/via-beforeLoad-target-root.tsx b/e2e/vue-start/basic/src/routes/not-found/via-beforeLoad-target-root.tsx deleted file mode 100644 index 1663bdc0af..0000000000 --- a/e2e/vue-start/basic/src/routes/not-found/via-beforeLoad-target-root.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute, notFound, rootRouteId } from '@tanstack/vue-router' - -export const Route = createFileRoute('/not-found/via-beforeLoad-target-root')({ - beforeLoad: () => { - throw notFound({ routeId: rootRouteId }) - }, - component: RouteComponent, -}) - -function RouteComponent() { - return ( -
- Hello "/not-found/via-beforeLoad-target-root"! -
- ) -} diff --git a/e2e/vue-start/basic/src/routes/posts.$postId.tsx b/e2e/vue-start/basic/src/routes/posts.$postId.tsx index edda7f0017..4d71080d64 100644 --- a/e2e/vue-start/basic/src/routes/posts.$postId.tsx +++ b/e2e/vue-start/basic/src/routes/posts.$postId.tsx @@ -1,32 +1,9 @@ -import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '~/utils/posts' import { NotFound } from '~/components/NotFound' import { PostErrorComponent } from '~/components/PostErrorComponent' -const PostComponent = defineComponent({ - setup() { - const post = Route.useLoaderData() - return () => ( -
-

{post.value.title}

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

{post.value.title}

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

{post.value.title}

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

{post.value.title}

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

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

SearchParams

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

SearchParams

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

{user.value.name}

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

{user.value.name}

+
{user.value.email}
+
+ ) +} diff --git a/e2e/vue-start/basic/src/routes/users.tsx b/e2e/vue-start/basic/src/routes/users.tsx index 3d8ef31598..1e0b297dd2 100644 --- a/e2e/vue-start/basic/src/routes/users.tsx +++ b/e2e/vue-start/basic/src/routes/users.tsx @@ -1,41 +1,9 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { getRouterInstance } from '@tanstack/vue-start' import axios from 'redaxios' import type { User } from '~/utils/users' -const UsersComponent = defineComponent({ - setup() { - const users = Route.useLoaderData() - return () => ( -
-
    - {[ - ...users.value, - { id: 'i-do-not-exist', name: 'Non-existent User', email: '' }, - ].map((user) => ( -
  • - -
    {user.name}
    - -
  • - ))} -
-
- -
- ) - }, -}) - export const Route = createFileRoute('/users')({ loader: async () => { const router = await getRouterInstance() @@ -48,3 +16,33 @@ export const Route = createFileRoute('/users')({ }, component: UsersComponent, }) + +function UsersComponent() { + const users = Route.useLoaderData() + + return ( +
+
    + {[ + ...users.value, + { id: 'i-do-not-exist', name: 'Non-existent User', email: '' }, + ].map((user) => ( +
  • + +
    {user.name}
    + +
  • + ))} +
+
+ +
+ ) +} diff --git a/e2e/vue-start/basic/src/utils/posts.tsx b/e2e/vue-start/basic/src/utils/posts.tsx index d8e2dc7450..a193bbc7af 100644 --- a/e2e/vue-start/basic/src/utils/posts.tsx +++ b/e2e/vue-start/basic/src/utils/posts.tsx @@ -8,12 +8,18 @@ export type PostType = { body: string } +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} + export const fetchPost = createServerFn({ method: 'GET' }) - .validator((postId: string) => postId) + .inputValidator((postId: string) => postId) .handler(async ({ data: postId }) => { console.info(`Fetching post with id ${postId}...`) const post = await axios - .get(`https://jsonplaceholder.typicode.com/posts/${postId}`) + .get(`${queryURL}/posts/${postId}`) .then((r) => r.data) .catch((err) => { console.error(err) @@ -30,7 +36,7 @@ export const fetchPosts = createServerFn({ method: 'GET' }).handler( async () => { console.info('Fetching posts...') return axios - .get>('https://jsonplaceholder.typicode.com/posts') + .get>(`${queryURL}/posts`) .then((r) => r.data.slice(0, 10)) }, ) diff --git a/e2e/vue-start/basic/src/utils/users.tsx b/e2e/vue-start/basic/src/utils/users.tsx index 7ba645b383..46be4b1580 100644 --- a/e2e/vue-start/basic/src/utils/users.tsx +++ b/e2e/vue-start/basic/src/utils/users.tsx @@ -3,3 +3,7 @@ export type User = { name: string email: string } + +const PORT = process.env.VITE_SERVER_PORT || 3000 + +export const DEPLOY_URL = `http://localhost:${PORT}` diff --git a/e2e/vue-start/basic/src/vite-env.d.ts b/e2e/vue-start/basic/src/vite-env.d.ts index 4da6234c8a..e8259b1e33 100644 --- a/e2e/vue-start/basic/src/vite-env.d.ts +++ b/e2e/vue-start/basic/src/vite-env.d.ts @@ -2,6 +2,7 @@ interface ImportMetaEnv { readonly VITE_NODE_ENV: string + readonly VITE_EXTERNAL_PORT: string readonly VITE_SERVER_PORT: string } diff --git a/e2e/vue-start/basic/tests/fixture-api.spec.ts b/e2e/vue-start/basic/tests/fixture-api.spec.ts deleted file mode 100644 index 6c9b26dc4c..0000000000 --- a/e2e/vue-start/basic/tests/fixture-api.spec.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { expect, test } from '@playwright/test' - -test('server API receives canned users without a fixture listener', async ({ - request, -}) => { - const response = await request.get('/api/users') - expect(response.ok()).toBe(true) - const users = await response.json() - expect(users).toHaveLength(10) - expect(users[0]).toMatchObject({ id: 1, name: 'Leanne Graham' }) -}) diff --git a/e2e/vue-start/basic/tests/not-found.spec.ts b/e2e/vue-start/basic/tests/not-found.spec.ts index cfc60fe5e4..9c6092c809 100644 --- a/e2e/vue-start/basic/tests/not-found.spec.ts +++ b/e2e/vue-start/basic/tests/not-found.spec.ts @@ -1,7 +1,7 @@ import { expect } from '@playwright/test' import combinateImport from 'combinate' import { test } from '@tanstack/router-e2e-utils' -import { isSpaMode } from './utils/isSpaMode' +import { isSpaMode } from '../tests/utils/isSpaMode' // somehow playwright does not correctly import default exports const combinate = (combinateImport as any).default as typeof combinateImport @@ -9,6 +9,7 @@ const combinate = (combinateImport as any).default as typeof combinateImport test.use({ whitelistErrors: [ 'Failed to load resource: the server responded with a status of 404', + 'NotFound error during hydration for routeId', ], }) test.describe('not-found', () => { @@ -24,7 +25,8 @@ test.describe('not-found', () => { test.describe('throw notFound()', () => { const navigationTestMatrix = combinate({ - thrower: ['beforeLoad', 'loader'] as const, + // TODO beforeLoad! + thrower: [/* 'beforeLoad',*/ 'loader'] as const, preload: [false, true] as const, }) @@ -53,7 +55,9 @@ test.describe('not-found', () => { }) }) const directVisitTestMatrix = combinate({ - thrower: ['beforeLoad', 'loader'] as const, + // TODO beforeLoad! + + thrower: [/* 'beforeLoad',*/ 'loader'] as const, }) directVisitTestMatrix.forEach(({ thrower }) => { @@ -68,34 +72,5 @@ test.describe('not-found', () => { ).not.toBeInViewport() }) }) - - test('direct visit: child beforeLoad notFound renders parent boundary with parent loader data', async ({ - page, - }) => { - await page.goto('/not-found/parent-boundary/via-beforeLoad') - await page.waitForLoadState('networkidle') - - await expect( - page.getByTestId('parent-boundary-notFound-component'), - ).toBeInViewport() - await expect(page.getByTestId('parent-loader-data')).toHaveText('ready') - await expect( - page.getByTestId('parent-boundary-child-route-component'), - ).not.toBeInViewport() - }) - - test('direct visit: beforeLoad notFound with routeId targets root boundary', async ({ - page, - }) => { - await page.goto('/not-found/via-beforeLoad-target-root') - await page.waitForLoadState('networkidle') - - await expect( - page.getByTestId('default-not-found-component'), - ).toBeInViewport() - await expect( - page.getByTestId('via-beforeLoad-target-root-route-component'), - ).not.toBeInViewport() - }) }) }) diff --git a/e2e/vue-start/basic/tests/prerendering.spec.ts b/e2e/vue-start/basic/tests/prerendering.spec.ts index ddcf720a4c..8506ff9b06 100644 --- a/e2e/vue-start/basic/tests/prerendering.spec.ts +++ b/e2e/vue-start/basic/tests/prerendering.spec.ts @@ -4,17 +4,13 @@ import { expect } from '@playwright/test' import { test } from '@tanstack/router-e2e-utils' import { isPrerender } from './utils/isPrerender' -const distDir = join( - process.cwd(), - process.env.E2E_DIST_DIR ?? 'dist', - 'client', -) - test.describe('Prerender Static Path Discovery', () => { test.skip(!isPrerender, 'Skipping since not in prerender mode') test.describe('Build Output Verification', () => { test('should automatically discover and prerender static routes', () => { // Check that static routes were automatically discovered and prerendered + const distDir = join(process.cwd(), 'dist', 'client') + // These static routes should be automatically discovered and prerendered expect(existsSync(join(distDir, 'index.html'))).toBe(true) expect(existsSync(join(distDir, 'posts/index.html'))).toBe(true) @@ -38,6 +34,7 @@ test.describe('Prerender Static Path Discovery', () => { test.describe('Static Files Verification', () => { test('should contain prerendered content in posts.html', () => { + const distDir = join(process.cwd(), 'dist', 'client') expect(existsSync(join(distDir, 'posts/index.html'))).toBe(true) // "Select a post." should be in the prerendered HTML diff --git a/e2e/vue-start/basic/tests/redirect.spec.ts b/e2e/vue-start/basic/tests/redirect.spec.ts index 8e6ceba5b9..b52ce026af 100644 --- a/e2e/vue-start/basic/tests/redirect.spec.ts +++ b/e2e/vue-start/basic/tests/redirect.spec.ts @@ -1,27 +1,22 @@ import queryString from 'node:querystring' import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' import combinateImport from 'combinate' -import type { Page } from '@playwright/test' +import { + getDummyServerPort, + getTestServerPort, + test, +} from '@tanstack/router-e2e-utils' +import packageJson from '../package.json' with { type: 'json' } +import { isSpaMode } from '../tests/utils/isSpaMode' +import { isPreview } from '../tests/utils/isPreview' // somehow playwright does not correctly import default exports const combinate = (combinateImport as any).default as typeof combinateImport -const PORT = Number(process.env.E2E_APP_PORT ?? 0) -const EXTERNAL_ORIGIN = `http://127.0.0.1:${PORT}` -const POSTS_URL = `http://localhost:${PORT}/posts` - -async function waitForRouterIdle(page: Page) { - await expect(page.getByTestId('router-isLoading')).toHaveText('false') - await expect(page.getByTestId('router-status')).toHaveText('idle') -} - -async function waitForPostsIndex(page: Page) { - await page.waitForURL(POSTS_URL) - expect(page.url()).toBe(POSTS_URL) - await waitForRouterIdle(page) - await expect(page.getByTestId('PostsIndexComponent')).toBeInViewport() -} +const PORT = await getTestServerPort( + `${packageJson.name}${isSpaMode ? '_spa' : ''}${isPreview ? '_preview' : ''}`, +) +const EXTERNAL_HOST_PORT = await getDummyServerPort(packageJson.name) test.describe('redirects', () => { const internalNavigationTestMatrix = combinate({ @@ -42,7 +37,7 @@ test.describe('redirects', () => { `via-${thrower}${reloadDocument ? '-reloadDocument' : ''}`, ) - await waitForRouterIdle(page) + await page.waitForLoadState('networkidle') let requestHappened = false const requestPromise = new Promise((resolve) => { @@ -70,7 +65,11 @@ test.describe('redirects', () => { await link.click() - await waitForPostsIndex(page) + const url = `http://localhost:${PORT}/posts` + + await page.waitForURL(url) + expect(page.url()).toBe(url) + await expect(page.getByTestId('PostsIndexComponent')).toBeInViewport() expect(fullPageLoad).toBe(reloadDocument) }) }, @@ -87,7 +86,12 @@ test.describe('redirects', () => { }) => { await page.goto(`/redirect/internal/via-${thrower}`) - await waitForPostsIndex(page) + const url = `http://localhost:${PORT}/posts` + + await page.waitForURL(url) + expect(page.url()).toBe(url) + await page.waitForLoadState('networkidle') + await expect(page.getByTestId('PostsIndexComponent')).toBeInViewport() }) }) @@ -101,12 +105,12 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, }) if (scenario === 'navigate') { await page.goto(`/redirect/external?${q}`) - await waitForRouterIdle(page) + await page.waitForLoadState('networkidle') const link = page.getByTestId(`via-${thrower}`) await link.focus() await link.click() @@ -114,7 +118,7 @@ test.describe('redirects', () => { await page.goto(`/redirect/external/via-${thrower}?${q}`) } - const url = `${EXTERNAL_ORIGIN}/` + const url = `http://localhost:${EXTERNAL_HOST_PORT}/` await page.waitForURL(url) expect(page.url()).toBe(url) @@ -135,13 +139,13 @@ test.describe('redirects', () => { }) => { let fullPageLoad = false const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, reloadDocument, }) if (scenario === 'navigate') { await page.goto(`/redirect/${target}/serverFn?${q}`) - await waitForRouterIdle(page) + await page.waitForLoadState('networkidle') const link = page.getByTestId( `via-${thrower}${reloadDocument ? '-reloadDocument' : ''}`, ) @@ -154,11 +158,13 @@ test.describe('redirects', () => { await page.goto(`/redirect/${target}/serverFn/via-${thrower}?${q}`) } - const url = target === 'internal' ? POSTS_URL : `${EXTERNAL_ORIGIN}/` + const url = + target === 'internal' + ? `http://localhost:${PORT}/posts` + : `http://localhost:${EXTERNAL_HOST_PORT}/` await page.waitForURL(url) expect(page.url()).toBe(url) if (target === 'internal' && scenario === 'navigate') { - await waitForRouterIdle(page) await expect(page.getByTestId('PostsIndexComponent')).toBeInViewport() expect(fullPageLoad).toBe(reloadDocument) } @@ -176,13 +182,13 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, reloadDocument, }) await page.goto(`/redirect/${target}/serverFn/via-useServerFn?${q}`) - await waitForRouterIdle(page) + await page.waitForLoadState('networkidle') const button = page.getByTestId('redirect-on-click') @@ -193,11 +199,13 @@ test.describe('redirects', () => { await button.click() - const url = target === 'internal' ? POSTS_URL : `${EXTERNAL_ORIGIN}/` + const url = + target === 'internal' + ? `http://localhost:${PORT}/posts` + : `http://localhost:${EXTERNAL_HOST_PORT}/` await page.waitForURL(url) expect(page.url()).toBe(url) if (target === 'internal') { - await waitForRouterIdle(page) await expect(page.getByTestId('PostsIndexComponent')).toBeInViewport() expect(fullPageLoad).toBe(reloadDocument) } diff --git a/e2e/vue-start/basic/tests/search-params.spec.ts b/e2e/vue-start/basic/tests/search-params.spec.ts index cdf5a21b4a..74c1aa54dc 100644 --- a/e2e/vue-start/basic/tests/search-params.spec.ts +++ b/e2e/vue-start/basic/tests/search-params.spec.ts @@ -1,6 +1,6 @@ import { expect } from '@playwright/test' import { test } from '@tanstack/router-e2e-utils' -import { isSpaMode } from './utils/isSpaMode' +import { isSpaMode } from 'tests/utils/isSpaMode' import { isPrerender } from './utils/isPrerender' import type { Response } from '@playwright/test' diff --git a/e2e/vue-start/basic/tests/setup/global.setup.ts b/e2e/vue-start/basic/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-start/basic/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/basic/tests/setup/global.teardown.ts b/e2e/vue-start/basic/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-start/basic/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/basic/tests/special-characters.spec.ts b/e2e/vue-start/basic/tests/special-characters.spec.ts index 284097d72b..6bbb240a84 100644 --- a/e2e/vue-start/basic/tests/special-characters.spec.ts +++ b/e2e/vue-start/basic/tests/special-characters.spec.ts @@ -175,12 +175,6 @@ test.describe('Unicode route rendering', () => { }) test.describe('malformed paths', () => { - const malformedPathnames = [ - '/specialChars/malformed/%E0%A4', - '/specialChars/malformed/%80', - '/specialChars/malformed/%FF', - ] - test.use({ whitelistErrors: [ 'Failed to load resource: the server responded with a status of 404', @@ -188,22 +182,24 @@ test.describe('Unicode route rendering', () => { ], }) - for (const pathname of malformedPathnames) { - test(`un-matched malformed path "${pathname}" should return bad request on direct navigation`, async ({ - page, - }) => { - const res = await page.goto(pathname) + test('un-matched malformed paths should return not found on direct navigation', async ({ + page, + }) => { + const res = await page.goto('/specialChars/malformed/%E0%A4') - await page.waitForLoadState(`load`) + await page.waitForLoadState(`load`) - // in spa mode this is caught and handled at server level - if (!isSpaMode) { - expect(res!.status()).toBe(400) - } else { - expect(res!.status()).toBe(400) - } - }) - } + // in spa mode this is caught and handled at server level + if (!isSpaMode) { + expect(res!.status()).toBe(404) + + await expect( + page.getByTestId('default-not-found-component'), + ).toBeInViewport() + } else { + expect(res!.status()).toBe(400) + } + }) test('malformed path params should return not found on router link', async ({ page, diff --git a/e2e/vue-start/basic/tests/utils/getPackageName.ts b/e2e/vue-start/basic/tests/utils/getPackageName.ts deleted file mode 100644 index 6bd2e0499e..0000000000 --- a/e2e/vue-start/basic/tests/utils/getPackageName.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' - -let packageName: string | undefined - -export function getPackageName() { - if (!packageName) { - const packageJson = JSON.parse( - readFileSync(join(process.cwd(), 'package.json'), 'utf-8'), - ) as { name: string } - - packageName = packageJson.name - } - - return packageName -} diff --git a/e2e/vue-start/basic/tsconfig.json b/e2e/vue-start/basic/tsconfig.json index 1b2ac7b943..6d933a5b2c 100644 --- a/e2e/vue-start/basic/tsconfig.json +++ b/e2e/vue-start/basic/tsconfig.json @@ -9,12 +9,12 @@ "moduleResolution": "Bundler", "lib": ["DOM", "DOM.Iterable", "ES2022"], "isolatedModules": true, - "allowImportingTsExtensions": true, "resolveJsonModule": true, "skipLibCheck": true, "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/basic/vite.config.ts b/e2e/vue-start/basic/vite.config.ts index 6fe8d5d194..7fa09b226c 100644 --- a/e2e/vue-start/basic/vite.config.ts +++ b/e2e/vue-start/basic/vite.config.ts @@ -1,4 +1,5 @@ import { defineConfig } from 'vite' +import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' import { isSpaMode } from './tests/utils/isSpaMode' @@ -19,7 +20,8 @@ const prerenderConfiguration = { '/this-route-does-not-exist', '/redirect', '/i-do-not-exist', - '/not-found', + '/not-found/via-beforeLoad', + '/not-found/via-loader', '/specialChars/search', '/specialChars/hash', '/specialChars/malformed', @@ -30,13 +32,7 @@ const prerenderConfiguration = { maxRedirects: 100, } -const outDir = process.env.E2E_DIST_DIR ?? 'dist' - export default defineConfig({ - resolve: { tsconfigPaths: true }, - build: { - outDir, - }, server: { port: 3000, }, @@ -45,6 +41,9 @@ export default defineConfig({ }, plugins: [ tailwindcss(), + tsConfigPaths({ + projects: ['./tsconfig.json'], + }), tanstackStart({ spa: isSpaMode ? spaModeConfiguration : undefined, prerender: isPrerender ? prerenderConfiguration : undefined, diff --git a/e2e/vue-start/css-modules/.devcontainer/devcontainer.json b/e2e/vue-start/css-modules/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-start/css-modules/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-start/css-modules/package.json b/e2e/vue-start/css-modules/package.json index 3671774644..63270632cc 100644 --- a/e2e/vue-start/css-modules/package.json +++ b/e2e/vue-start/css-modules/package.json @@ -11,7 +11,7 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js", "test:e2e:dev": "MODE=dev playwright test --project=chromium", "test:e2e:prod": "playwright test --project=chromium", - "test:e2e": "pnpm run test:e2e:dev" + "test:e2e": "rm -rf port*.txt; pnpm run test:e2e:dev" }, "dependencies": { "@tanstack/vue-router": "workspace:*", @@ -19,14 +19,14 @@ "vue": "^3.5.16" }, "devDependencies": { - "@playwright/test": "^1.61.0", + "@playwright/test": "^1.50.1", "@tanstack/router-e2e-utils": "workspace:*", "@types/node": "^22.10.2", - "@vitejs/plugin-vue-jsx": "^5.1.5", + "@vitejs/plugin-vue-jsx": "^4.1.2", "sass": "^1.97.2", - "srvx": "^1.0.0", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "srvx": "^0.11.2", + "typescript": "^5.7.2", + "vite": "^7.3.1", + "vite-tsconfig-paths": "^5.1.4" } } diff --git a/e2e/vue-start/css-modules/playwright.config.ts b/e2e/vue-start/css-modules/playwright.config.ts index a50ac5ae63..0b810d5372 100644 --- a/e2e/vue-start/css-modules/playwright.config.ts +++ b/e2e/vue-start/css-modules/playwright.config.ts @@ -1,9 +1,10 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } const mode = process.env.MODE ?? 'prod' const isDev = mode === 'dev' -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -12,17 +13,16 @@ export default defineConfig({ reporter: [['line']], globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', use: { baseURL, }, webServer: { - command: isDev - ? `pnpm dev:e2e --port 0` - : `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: isDev ? `pnpm dev:e2e` : `pnpm build && PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { VITE_NODE_ENV: 'test', diff --git a/e2e/vue-start/css-modules/tests/css.spec.ts b/e2e/vue-start/css-modules/tests/css.spec.ts index 7646eb750e..f3d06bcb1c 100644 --- a/e2e/vue-start/css-modules/tests/css.spec.ts +++ b/e2e/vue-start/css-modules/tests/css.spec.ts @@ -14,6 +14,28 @@ const whitelistErrors = [ test.describe('CSS styles in SSR (dev mode)', () => { test.use({ whitelistErrors }) + // Warmup: trigger Vite's dependency optimization before running tests + // This prevents "optimized dependencies changed. reloading" during actual tests + // We use a real browser context since dep optimization happens on JS load, not HTTP requests + test.beforeAll(async ({ browser, baseURL }) => { + const context = await browser.newContext() + const page = await context.newPage() + try { + // Load both pages to trigger dependency optimization + await page.goto(baseURL!) + await page.waitForTimeout(2000) // Wait for deps to optimize + await page.goto(`${baseURL}/modules`) + await page.waitForTimeout(2000) + // Load again after optimization completes + await page.goto(baseURL!) + await page.waitForTimeout(1000) + } catch { + // Ignore errors during warmup + } finally { + await context.close() + } + }) + // Helper to build full URL from baseURL and path // Playwright's goto with absolute paths (like '/modules') ignores baseURL's path portion // So we need to manually construct the full URL @@ -175,35 +197,44 @@ test.describe('CSS styles in SSR (dev mode)', () => { // Start from home await page.goto(buildUrl(baseURL!, '/')) - // Verify initial styles + // Verify initial styles with retry to handle potential Vite dep optimization reload const globalElement = page.getByTestId('global-styled') - await expect(globalElement).toBeVisible() - let backgroundColor = await globalElement.evaluate( - (el) => getComputedStyle(el).backgroundColor, - ) - expect(backgroundColor).toBe('rgb(59, 130, 246)') + await expect(async () => { + await expect(globalElement).toBeVisible() + const backgroundColor = await globalElement.evaluate( + (el) => getComputedStyle(el).backgroundColor, + ) + expect(backgroundColor).toBe('rgb(59, 130, 246)') + }).toPass({ timeout: 10000 }) // Navigate to modules page await page.getByTestId('nav-modules').click() + // Use glob pattern to match with or without basepath await page.waitForURL('**/modules') - // Verify CSS modules styles + // Verify CSS modules styles with retry to handle potential Vite dep optimization reload const card = page.getByTestId('module-card') - await expect(card).toBeVisible() - backgroundColor = await card.evaluate( - (el) => getComputedStyle(el).backgroundColor, - ) - expect(backgroundColor).toBe('rgb(240, 253, 244)') + await expect(async () => { + await expect(card).toBeVisible() + const backgroundColor = await card.evaluate( + (el) => getComputedStyle(el).backgroundColor, + ) + expect(backgroundColor).toBe('rgb(240, 253, 244)') + }).toPass({ timeout: 10000 }) // Navigate back to home await page.getByTestId('nav-home').click() + // Match home URL with or without trailing slash and optional query string + // Matches: /, /?, /my-app, /my-app/, /my-app?foo=bar await page.waitForURL(/\/([^/]*)(\/)?($|\?)/) - // Verify global styles still work - await expect(globalElement).toBeVisible() - backgroundColor = await globalElement.evaluate( - (el) => getComputedStyle(el).backgroundColor, - ) - expect(backgroundColor).toBe('rgb(59, 130, 246)') + // Verify global styles still work with retry + await expect(async () => { + await expect(globalElement).toBeVisible() + const backgroundColor = await globalElement.evaluate( + (el) => getComputedStyle(el).backgroundColor, + ) + expect(backgroundColor).toBe('rgb(59, 130, 246)') + }).toPass({ timeout: 10000 }) }) }) diff --git a/e2e/vue-start/css-modules/tests/setup/global.setup.ts b/e2e/vue-start/css-modules/tests/setup/global.setup.ts index 17be637f77..3593d10ab9 100644 --- a/e2e/vue-start/css-modules/tests/setup/global.setup.ts +++ b/e2e/vue-start/css-modules/tests/setup/global.setup.ts @@ -1,39 +1,6 @@ -import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } 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: 'global-styled', - warmup: async (page) => { - await page.goto(`${baseURL}/modules`, { waitUntil: 'domcontentloaded' }) - await page.getByTestId('module-card').waitFor({ state: 'visible' }) - await page.waitForLoadState('networkidle') - - await page.goto(`${baseURL}/sass-mixin`, { - waitUntil: 'domcontentloaded', - }) - await page.getByTestId('mixin-styled').waitFor({ state: 'visible' }) - await page.waitForLoadState('networkidle') - - await page.goto(`${baseURL}/`, { waitUntil: 'domcontentloaded' }) - await page.getByTestId('global-styled').waitFor({ state: 'visible' }) - await page.waitForLoadState('networkidle') - - await page.getByTestId('nav-modules').click() - await page.waitForURL('**/modules') - await page.getByTestId('module-card').waitFor({ state: 'visible' }) - await page.waitForLoadState('networkidle') - - await page.getByTestId('nav-home').click() - await page.waitForURL(/\/([^/]*)(\/)?($|\?)/) - await page.getByTestId('global-styled').waitFor({ state: 'visible' }) - await page.waitForLoadState('networkidle') - }, - }) + await e2eStartDummyServer(packageJson.name) } diff --git a/e2e/vue-start/css-modules/tests/setup/global.teardown.ts b/e2e/vue-start/css-modules/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-start/css-modules/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/css-modules/tsconfig.json b/e2e/vue-start/css-modules/tsconfig.json index 572d840872..8bf3d33789 100644 --- a/e2e/vue-start/css-modules/tsconfig.json +++ b/e2e/vue-start/css-modules/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/css-modules/vite.config.ts b/e2e/vue-start/css-modules/vite.config.ts index 36e10f551e..d7b96c1c2f 100644 --- a/e2e/vue-start/css-modules/vite.config.ts +++ b/e2e/vue-start/css-modules/vite.config.ts @@ -1,11 +1,17 @@ import { defineConfig } from 'vite' +import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' export default defineConfig({ - resolve: { tsconfigPaths: true }, server: { port: 3000, }, - plugins: [tanstackStart(), vueJsx()], + plugins: [ + tsConfigPaths({ + projects: ['./tsconfig.json'], + }), + tanstackStart(), + vueJsx(), + ], }) diff --git a/e2e/vue-start/custom-basepath/.devcontainer/devcontainer.json b/e2e/vue-start/custom-basepath/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-start/custom-basepath/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-start/custom-basepath/express-server.ts b/e2e/vue-start/custom-basepath/express-server.ts index b9bf393466..87dcfb50da 100644 --- a/e2e/vue-start/custom-basepath/express-server.ts +++ b/e2e/vue-start/custom-basepath/express-server.ts @@ -1,6 +1,5 @@ import express from 'express' import { toNodeHandler } from 'srvx/node' -import type { AddressInfo } from 'node:net' import type { NodeHttp1Handler } from 'srvx' const DEVELOPMENT = process.env.NODE_ENV === 'development' @@ -41,11 +40,6 @@ if (DEVELOPMENT) { }) } -const httpServer = app.listen(PORT, (error) => { - if (error) { - throw error - } - console.log( - `E2E app: http://localhost:${(httpServer.address() as AddressInfo).port}`, - ) +app.listen(PORT, () => { + console.log(`Server is running on http://localhost:${PORT}`) }) diff --git a/e2e/vue-start/custom-basepath/package.json b/e2e/vue-start/custom-basepath/package.json index c1032ea88b..9910391a93 100644 --- a/e2e/vue-start/custom-basepath/package.json +++ b/e2e/vue-start/custom-basepath/package.json @@ -8,30 +8,30 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "tsx express-server.ts", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", - "express": "^5.2.1", - "redaxios": "catalog:", + "express": "^4.21.2", + "redaxios": "^0.5.1", "vue": "^3.5.25" }, "devDependencies": { - "@playwright/test": "^1.61.0", - "@tailwindcss/vite": "^4.2.2", + "@playwright/test": "^1.50.1", + "@tailwindcss/vite": "^4.1.18", "@tanstack/router-e2e-utils": "workspace:^", - "@types/express": "^5.0.6", + "@types/express": "^5.0.3", "@types/node": "^22.10.2", "cross-env": "^10.0.0", - "srvx": "^1.0.0", - "tailwindcss": "^4.2.2", + "srvx": "^0.11.2", + "tailwindcss": "^4.1.18", "tsx": "^4.20.3", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "@vitejs/plugin-vue": "^6.0.5", - "@vitejs/plugin-vue-jsx": "^5.1.5" + "typescript": "^5.7.2", + "vite": "^7.3.1", + "@vitejs/plugin-vue": "^6.0.3", + "@vitejs/plugin-vue-jsx": "^5.1.2", + "vite-tsconfig-paths": "^5.1.4" } } diff --git a/e2e/vue-start/custom-basepath/playwright.config.ts b/e2e/vue-start/custom-basepath/playwright.config.ts index e113ce64ad..5095425f47 100644 --- a/e2e/vue-start/custom-basepath/playwright.config.ts +++ b/e2e/vue-start/custom-basepath/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}/custom/basepath` /** @@ -13,19 +18,19 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', - env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, - }, }, projects: [ diff --git a/e2e/vue-start/custom-basepath/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/custom-basepath/src/components/DefaultCatchBoundary.tsx index 77c03c5afa..b1f818dd74 100644 --- a/e2e/vue-start/custom-basepath/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/custom-basepath/src/components/DefaultCatchBoundary.tsx @@ -1,61 +1,53 @@ -import { defineComponent } from 'vue' -import type { PropType } from 'vue' import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -export const DefaultCatchBoundary = defineComponent({ - props: { - error: { - type: Object as PropType, - required: true, - }, - }, - setup(props) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - return () => { - console.error(props.error) - return ( -
- -
- - {isRoot.value ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) - } - }, -}) +export function DefaultCatchBoundary({ error }: ErrorComponentProps) { + const router = useRouter() + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, + }) + + console.error(error) + + return ( +
+ +
+ + {isRoot.value ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
+
+ ) +} diff --git a/e2e/vue-start/custom-basepath/src/routeTree.gen.ts b/e2e/vue-start/custom-basepath/src/routeTree.gen.ts index 605193fbec..2aa189fd3c 100644 --- a/e2e/vue-start/custom-basepath/src/routeTree.gen.ts +++ b/e2e/vue-start/custom-basepath/src/routeTree.gen.ts @@ -9,34 +9,24 @@ // 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 DeferredRouteImport } from './routes/deferred' -import { Route as LogoutRouteImport } from './routes/logout' -import { Route as PostsRouteImport } from './routes/posts' import { Route as UsersRouteImport } from './routes/users' -import { Route as ApiUsersRouteImport } from './routes/api/users' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as RedirectIndexRouteImport } from './routes/redirect.index' -import { Route as RedirectThrowItRouteImport } from './routes/redirect.throw-it' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as LogoutRouteImport } from './routes/logout' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as IndexRouteImport } from './routes/index' import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as RedirectIndexRouteImport } from './routes/redirect.index' +import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' +import { Route as RedirectThrowItRouteImport } from './routes/redirect.throw-it' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as ApiUsersRouteImport } from './routes/api/users' import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' +import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', - getParentRoute: () => rootRouteImport, -} as any) -const LogoutRoute = LogoutRouteImport.update({ - id: '/logout', - path: '/logout', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const PostsRoute = PostsRouteImport.update({ @@ -44,34 +34,19 @@ const PostsRoute = PostsRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const LogoutRoute = LogoutRouteImport.update({ + id: '/logout', + path: '/logout', getParentRoute: () => rootRouteImport, } as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ +const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => PostsRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const RedirectIndexRoute = RedirectIndexRouteImport.update({ - id: '/redirect/', - path: '/redirect/', - getParentRoute: () => rootRouteImport, -} as any) -const RedirectThrowItRoute = RedirectThrowItRouteImport.update({ - id: '/redirect/throw-it', - path: '/redirect/throw-it', getParentRoute: () => rootRouteImport, } as any) const UsersIndexRoute = UsersIndexRouteImport.update({ @@ -79,21 +54,46 @@ const UsersIndexRoute = UsersIndexRouteImport.update({ path: '/', getParentRoute: () => UsersRoute, } as any) +const RedirectIndexRoute = RedirectIndexRouteImport.update({ + id: '/redirect/', + path: '/redirect/', + getParentRoute: () => rootRouteImport, +} as any) +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) const UsersUserIdRoute = UsersUserIdRouteImport.update({ id: '/$userId', path: '/$userId', getParentRoute: () => UsersRoute, } as any) -const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => ApiUsersRoute, +const RedirectThrowItRoute = RedirectThrowItRouteImport.update({ + id: '/redirect/throw-it', + path: '/redirect/throw-it', + getParentRoute: () => rootRouteImport, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', + getParentRoute: () => rootRouteImport, } as any) const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ id: '/posts_/$postId/deep', path: '/posts/$postId/deep', getParentRoute: () => rootRouteImport, } as any) +const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => ApiUsersRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -106,7 +106,7 @@ export interface FileRoutesByFullPath { '/redirect/throw-it': typeof RedirectThrowItRoute '/users/$userId': typeof UsersUserIdRoute '/posts/': typeof PostsIndexRoute - '/redirect/': typeof RedirectIndexRoute + '/redirect': typeof RedirectIndexRoute '/users/': typeof UsersIndexRoute '/api/users/$userId': typeof ApiUsersUserIdRoute '/posts/$postId/deep': typeof PostsPostIdDeepRoute @@ -155,7 +155,7 @@ export interface FileRouteTypes { | '/redirect/throw-it' | '/users/$userId' | '/posts/' - | '/redirect/' + | '/redirect' | '/users/' | '/api/users/$userId' | '/posts/$postId/deep' @@ -205,25 +205,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/logout': { - id: '/logout' - path: '/logout' - fullPath: '/logout' - preLoaderRoute: typeof LogoutRouteImport + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/posts': { @@ -233,46 +219,25 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/logout': { + id: '/logout' + path: '/logout' + fullPath: '/logout' + preLoaderRoute: typeof LogoutRouteImport parentRoute: typeof rootRouteImport } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' + '/': { + id: '/' path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/redirect/': { - id: '/redirect/' - path: '/redirect' - fullPath: '/redirect/' - preLoaderRoute: typeof RedirectIndexRouteImport - parentRoute: typeof rootRouteImport - } - '/redirect/throw-it': { - id: '/redirect/throw-it' - path: '/redirect/throw-it' - fullPath: '/redirect/throw-it' - preLoaderRoute: typeof RedirectThrowItRouteImport + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/users/': { @@ -282,6 +247,20 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof UsersIndexRouteImport parentRoute: typeof UsersRoute } + '/redirect/': { + id: '/redirect/' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute + } '/users/$userId': { id: '/users/$userId' path: '/$userId' @@ -289,12 +268,26 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof UsersUserIdRouteImport parentRoute: typeof UsersRoute } - '/api/users/$userId': { - id: '/api/users/$userId' - path: '/$userId' - fullPath: '/api/users/$userId' - preLoaderRoute: typeof ApiUsersUserIdRouteImport - parentRoute: typeof ApiUsersRoute + '/redirect/throw-it': { + id: '/redirect/throw-it' + path: '/redirect/throw-it' + fullPath: '/redirect/throw-it' + preLoaderRoute: typeof RedirectThrowItRouteImport + parentRoute: typeof rootRouteImport + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute + } + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport + parentRoute: typeof rootRouteImport } '/posts_/$postId/deep': { id: '/posts_/$postId/deep' @@ -303,6 +296,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsPostIdDeepRouteImport parentRoute: typeof rootRouteImport } + '/api/users/$userId': { + id: '/api/users/$userId' + path: '/$userId' + fullPath: '/api/users/$userId' + preLoaderRoute: typeof ApiUsersUserIdRouteImport + parentRoute: typeof ApiUsersRoute + } } } diff --git a/e2e/vue-start/custom-basepath/src/routes/__root.tsx b/e2e/vue-start/custom-basepath/src/routes/__root.tsx index c6d1eb197c..8bc947b03a 100644 --- a/e2e/vue-start/custom-basepath/src/routes/__root.tsx +++ b/e2e/vue-start/custom-basepath/src/routes/__root.tsx @@ -49,11 +49,7 @@ export const Route = createRootRoute({ { rel: 'icon', href: '/favicon.ico' }, ], }), - errorComponent: (props) => ( -

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

- ), + errorComponent: (props) =>

{props.error.stack}

, 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 7e3f528d68..50b9ca995a 100644 --- a/e2e/vue-start/custom-basepath/src/routes/api/users.$userId.ts +++ b/e2e/vue-start/custom-basepath/src/routes/api/users.$userId.ts @@ -1,7 +1,11 @@ import { createFileRoute } from '@tanstack/vue-router' import type { User } from '~/utils/users' -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const Route = createFileRoute('/api/users/$userId')({ server: { diff --git a/e2e/vue-start/custom-basepath/src/routes/api/users.ts b/e2e/vue-start/custom-basepath/src/routes/api/users.ts index dfdb5cd844..97989b93ca 100644 --- a/e2e/vue-start/custom-basepath/src/routes/api/users.ts +++ b/e2e/vue-start/custom-basepath/src/routes/api/users.ts @@ -38,7 +38,11 @@ const testMiddleware = createMiddleware() return result }) -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const Route = createFileRoute('/api/users')({ server: { diff --git a/e2e/vue-start/custom-basepath/src/routes/deferred.tsx b/e2e/vue-start/custom-basepath/src/routes/deferred.tsx index 8db75401e9..7dbd50b030 100644 --- a/e2e/vue-start/custom-basepath/src/routes/deferred.tsx +++ b/e2e/vue-start/custom-basepath/src/routes/deferred.tsx @@ -3,13 +3,13 @@ import { createServerFn } from '@tanstack/vue-start' import { Suspense, defineComponent, ref } from 'vue' const personServerFn = createServerFn({ method: 'GET' }) - .validator((data: { name: string }) => data) + .inputValidator((data: { name: string }) => data) .handler(({ data }) => { return { name: data.name, randomNumber: Math.floor(Math.random() * 100) } }) const slowServerFn = createServerFn({ method: 'GET' }) - .validator((data: { name: string }) => data) + .inputValidator((data: { name: string }) => data) .handler(async ({ data }) => { await new Promise((r) => setTimeout(r, 1000)) return { name: data.name, randomNumber: Math.floor(Math.random() * 100) } diff --git a/e2e/vue-start/custom-basepath/src/routes/posts.$postId.tsx b/e2e/vue-start/custom-basepath/src/routes/posts.$postId.tsx index 599e0f046e..b4e5a8a6a2 100644 --- a/e2e/vue-start/custom-basepath/src/routes/posts.$postId.tsx +++ b/e2e/vue-start/custom-basepath/src/routes/posts.$postId.tsx @@ -1,32 +1,9 @@ -import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '~/utils/posts' import { NotFound } from '~/components/NotFound' import { PostErrorComponent } from '~/components/PostErrorComponent' -const PostComponent = defineComponent({ - setup() { - const post = Route.useLoaderData() - return () => ( -
-

{post.value.title}

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

{post.value.title}

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

{post.value.title}

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

{post.value.title}

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

{user.value.name}

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

{user.value.name}

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

Vue Dev SSR Styles Test

- -
- ) -} diff --git a/e2e/vue-start/dev-ssr-styles/src/styles/app.css b/e2e/vue-start/dev-ssr-styles/src/styles/app.css deleted file mode 100644 index 9a67f9b153..0000000000 --- a/e2e/vue-start/dev-ssr-styles/src/styles/app.css +++ /dev/null @@ -1,5 +0,0 @@ -body { - font-family: sans-serif; - margin: 0; - padding: 20px; -} diff --git a/e2e/vue-start/dev-ssr-styles/src/vue-shim.d.ts b/e2e/vue-start/dev-ssr-styles/src/vue-shim.d.ts deleted file mode 100644 index fe00a856b2..0000000000 --- a/e2e/vue-start/dev-ssr-styles/src/vue-shim.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -declare module '*.vue' { - import type { DefineComponent } from 'vue' - - const component: DefineComponent - export default component -} diff --git a/e2e/vue-start/dev-ssr-styles/tests/app.spec.ts b/e2e/vue-start/dev-ssr-styles/tests/app.spec.ts deleted file mode 100644 index 0e052441b7..0000000000 --- a/e2e/vue-start/dev-ssr-styles/tests/app.spec.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { expect } from '@playwright/test' -import { DEV_STYLES_ATTR } from '@tanstack/router-core' -import { test } from '@tanstack/router-e2e-utils' - -const whitelistErrors = [ - 'Failed to load resource: net::ERR_NAME_NOT_RESOLVED', - 'Failed to load resource: the server responded with a status of 504', -] - -test.describe('dev SSR styles', () => { - test.use({ whitelistErrors }) - - test.describe('with JavaScript disabled', () => { - test.use({ javaScriptEnabled: false, whitelistErrors }) - - test('includes a Vue SFC style block during SSR', async ({ page }) => { - await page.goto('/') - - const element = page.getByTestId('styled-box') - await expect(element).toBeVisible() - await expect(element).toHaveCSS('background-color', 'rgb(126, 34, 206)') - - const href = await page - .locator(`link[${DEV_STYLES_ATTR}]`) - .getAttribute('href') - expect(href).toBeTruthy() - - const response = await page.request.get(new URL(href!, page.url()).href) - expect(response.ok()).toBeTruthy() - const css = await response.text() - expect(css).toContain('--vue-sfc-style-marker') - expect(css).toMatch( - /\/src\/components\/SfcStyledBox\.vue\?vue&type=style[^\n]*&lang\.css/, - ) - }) - }) - - test('keeps CSS output stable after client modules load', async ({ - page, - }) => { - const initialResponsePromise = page.waitForResponse((response) => - new URL(response.url()).pathname.endsWith('/@tanstack-start/styles.css'), - ) - await page.goto('/') - await expect(page.getByTestId('styled-box')).toBeVisible() - const initialResponse = await initialResponsePromise - expect(initialResponse.ok()).toBeTruthy() - const initialCss = await initialResponse.text() - - const reloadedResponsePromise = page.waitForResponse((response) => - new URL(response.url()).pathname.endsWith('/@tanstack-start/styles.css'), - ) - await page.reload() - await expect(page.getByTestId('styled-box')).toBeVisible() - const reloadedResponse = await reloadedResponsePromise - expect(reloadedResponse.ok()).toBeTruthy() - const reloadedCss = await reloadedResponse.text() - - expect(reloadedCss).toBe(initialCss) - }) -}) diff --git a/e2e/vue-start/dev-ssr-styles/tests/setup/global.setup.ts b/e2e/vue-start/dev-ssr-styles/tests/setup/global.setup.ts deleted file mode 100644 index b03b6485c8..0000000000 --- a/e2e/vue-start/dev-ssr-styles/tests/setup/global.setup.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' - -export default async function setup() { - if (process.env.MODE !== 'dev') { - return - } - - const port = Number(process.env.E2E_APP_PORT ?? 0) - const baseURL = `http://localhost:${port}` - await waitForServer(baseURL) - await preOptimizeDevServer({ - baseURL, - readyTestId: 'home-heading', - }) -} diff --git a/e2e/vue-start/dev-ssr-styles/tsconfig.json b/e2e/vue-start/dev-ssr-styles/tsconfig.json deleted file mode 100644 index 898ea214b1..0000000000 --- a/e2e/vue-start/dev-ssr-styles/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "include": ["**/*.ts", "**/*.tsx", "**/*.vue"], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "preserve", - "jsxImportSource": "vue", - "module": "ESNext", - "moduleResolution": "Bundler", - "lib": ["DOM", "DOM.Iterable", "ES2022"], - "isolatedModules": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "target": "ES2022", - "allowJs": true, - "forceConsistentCasingInFileNames": true, - "paths": { - "~/*": ["./src/*"] - }, - "noEmit": true, - "types": ["vite/client"] - } -} diff --git a/e2e/vue-start/dev-ssr-styles/vite.config.ts b/e2e/vue-start/dev-ssr-styles/vite.config.ts deleted file mode 100644 index f8b7293af9..0000000000 --- a/e2e/vue-start/dev-ssr-styles/vite.config.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { defineConfig } from 'vite' -import { tanstackStart } from '@tanstack/vue-start/plugin/vite' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' - -export default defineConfig({ - resolve: { tsconfigPaths: true }, - experimental: - process.env.E2E_VITE_BUNDLED_DEV === 'true' - ? { bundledDev: true } - : undefined, - server: { port: 3000 }, - plugins: [tanstackStart(), vue(), vueJsx()], -}) diff --git a/e2e/vue-start/query-integration/.devcontainer/devcontainer.json b/e2e/vue-start/query-integration/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-start/query-integration/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-start/query-integration/package.json b/e2e/vue-start/query-integration/package.json index 617ce4f430..e13023b4ae 100644 --- a/e2e/vue-start/query-integration/package.json +++ b/e2e/vue-start/query-integration/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-query": "^5.90.0", @@ -18,20 +18,20 @@ "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-router-ssr-query": "workspace:^", "@tanstack/vue-start": "workspace:^", - "tailwind-merge": "^3.6.0", "vue": "^3.5.16", - "zod": "^4.4.3" + "tailwind-merge": "^2.6.0", + "vite": "^6.3.5", + "zod": "^3.24.2" }, "devDependencies": { - "@playwright/test": "^1.61.0", - "@tailwindcss/vite": "^4.2.2", + "@playwright/test": "^1.50.1", + "@tailwindcss/vite": "^4.1.18", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", - "@vitejs/plugin-vue": "^6.0.5", - "@vitejs/plugin-vue-jsx": "^5.1.5", - "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-vue": "^5.2.4", + "@vitejs/plugin-vue-jsx": "^4.1.2", + "tailwindcss": "^4.1.18", + "typescript": "^5.7.2", + "vite-tsconfig-paths": "^5.1.4" } } diff --git a/e2e/vue-start/query-integration/playwright.config.ts b/e2e/vue-start/query-integration/playwright.config.ts index 82678ac00b..4d86a1dbe7 100644 --- a/e2e/vue-start/query-integration/playwright.config.ts +++ b/e2e/vue-start/query-integration/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { derivePort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await derivePort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/query-integration/src/routeTree.gen.ts b/e2e/vue-start/query-integration/src/routeTree.gen.ts index c5a9f02a7a..d4d30083a0 100644 --- a/e2e/vue-start/query-integration/src/routeTree.gen.ts +++ b/e2e/vue-start/query-integration/src/routeTree.gen.ts @@ -9,20 +9,20 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' import { Route as UseQueryRouteImport } from './routes/useQuery' +import { Route as IndexRouteImport } from './routes/index' import { Route as LoaderFetchQueryTypeRouteImport } from './routes/loader-fetchQuery/$type' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const UseQueryRoute = UseQueryRouteImport.update({ id: '/useQuery', path: '/useQuery', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const LoaderFetchQueryTypeRoute = LoaderFetchQueryTypeRouteImport.update({ id: '/loader-fetchQuery/$type', path: '/loader-fetchQuery/$type', @@ -61,13 +61,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/useQuery': { id: '/useQuery' path: '/useQuery' @@ -75,6 +68,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof UseQueryRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/loader-fetchQuery/$type': { id: '/loader-fetchQuery/$type' path: '/loader-fetchQuery/$type' diff --git a/e2e/vue-start/query-integration/src/routes/loader-fetchQuery/$type.tsx b/e2e/vue-start/query-integration/src/routes/loader-fetchQuery/$type.tsx index 38f1e209dc..9e928feafe 100644 --- a/e2e/vue-start/query-integration/src/routes/loader-fetchQuery/$type.tsx +++ b/e2e/vue-start/query-integration/src/routes/loader-fetchQuery/$type.tsx @@ -1,29 +1,8 @@ -import { defineComponent } from 'vue' import { useQuery } from '@tanstack/vue-query' import { createFileRoute } from '@tanstack/vue-router' import z from 'zod' import { makeQueryOptions } from '~/queryOptions' -const RouteComponent = defineComponent({ - setup() { - const loaderData = Route.useLoaderData() - const context = Route.useRouteContext() - const query = useQuery(() => context.value.queryOptions) - return () => ( -
-
- loader data:{' '} -
{loaderData.value ?? 'undefined'}
-
-
- query data:{' '} -
{query.data.value ?? 'loading...'}
-
-
- ) - }, -}) - export const Route = createFileRoute('/loader-fetchQuery/$type')({ component: RouteComponent, params: { @@ -45,3 +24,21 @@ export const Route = createFileRoute('/loader-fetchQuery/$type')({ }, ssr: 'data-only', }) + +function RouteComponent() { + const loaderData = Route.useLoaderData() + const context = Route.useRouteContext() + const query = useQuery(context.value.queryOptions) + return ( +
+
+ loader data:{' '} +
{loaderData.value ?? 'undefined'}
+
+
+ query data:{' '} +
{query.data.value ?? 'loading...'}
+
+
+ ) +} diff --git a/e2e/vue-start/query-integration/tsconfig.json b/e2e/vue-start/query-integration/tsconfig.json index 390dad84c0..f9f5aab3da 100644 --- a/e2e/vue-start/query-integration/tsconfig.json +++ b/e2e/vue-start/query-integration/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/query-integration/vite.config.ts b/e2e/vue-start/query-integration/vite.config.ts index 6d0bbb229e..0c5b29b394 100644 --- a/e2e/vue-start/query-integration/vite.config.ts +++ b/e2e/vue-start/query-integration/vite.config.ts @@ -1,9 +1,16 @@ import { defineConfig } from 'vite' +import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' import tailwindcss from '@tailwindcss/vite' export default defineConfig({ - resolve: { tsconfigPaths: true }, - plugins: [tailwindcss(), tanstackStart(), vueJsx()], + plugins: [ + tailwindcss(), + tsConfigPaths({ + projects: ['./tsconfig.json'], + }), + tanstackStart(), + vueJsx(), + ], }) diff --git a/e2e/vue-start/scroll-restoration/.devcontainer/devcontainer.json b/e2e/vue-start/scroll-restoration/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-start/scroll-restoration/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-start/scroll-restoration/package.json b/e2e/vue-start/scroll-restoration/package.json index 025b0225be..19ea7f65be 100644 --- a/e2e/vue-start/scroll-restoration/package.json +++ b/e2e/vue-start/scroll-restoration/package.json @@ -9,29 +9,30 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", - "redaxios": "catalog:", - "tailwind-merge": "^3.6.0", + "@tanstack/zod-adapter": "workspace:^", + "redaxios": "^0.5.1", + "tailwind-merge": "^2.6.0", + "vite": "^7.3.1", "vue": "^3.5.25", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@playwright/test": "^1.61.0", - "@tailwindcss/vite": "^4.2.2", + "@playwright/test": "^1.50.1", + "@tailwindcss/vite": "^4.1.18", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", - "@vitejs/plugin-vue": "^6.0.5", - "@vitejs/plugin-vue-jsx": "^5.1.5", "combinate": "^1.1.11", - "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" + "srvx": "^0.11.2", + "tailwindcss": "^4.1.18", + "typescript": "^5.7.2", + "@vitejs/plugin-vue": "^6.0.3", + "@vitejs/plugin-vue-jsx": "^5.1.2", + "vite-tsconfig-paths": "^5.1.4" } } diff --git a/e2e/vue-start/scroll-restoration/playwright.config.ts b/e2e/vue-start/scroll-restoration/playwright.config.ts index 1862174905..b0c365f8bd 100644 --- a/e2e/vue-start/scroll-restoration/playwright.config.ts +++ b/e2e/vue-start/scroll-restoration/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,19 +18,19 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', - env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, - }, }, projects: [ diff --git a/e2e/vue-start/scroll-restoration/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/scroll-restoration/src/components/DefaultCatchBoundary.tsx index 77c03c5afa..b1f818dd74 100644 --- a/e2e/vue-start/scroll-restoration/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/scroll-restoration/src/components/DefaultCatchBoundary.tsx @@ -1,61 +1,53 @@ -import { defineComponent } from 'vue' -import type { PropType } from 'vue' import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -export const DefaultCatchBoundary = defineComponent({ - props: { - error: { - type: Object as PropType, - required: true, - }, - }, - setup(props) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - return () => { - console.error(props.error) - return ( -
- -
- - {isRoot.value ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) - } - }, -}) +export function DefaultCatchBoundary({ error }: ErrorComponentProps) { + const router = useRouter() + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, + }) + + console.error(error) + + return ( +
+ +
+ + {isRoot.value ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
+
+ ) +} diff --git a/e2e/vue-start/scroll-restoration/src/routeTree.gen.ts b/e2e/vue-start/scroll-restoration/src/routeTree.gen.ts index 49b34fc68f..86dc966e78 100644 --- a/e2e/vue-start/scroll-restoration/src/routeTree.gen.ts +++ b/e2e/vue-start/scroll-restoration/src/routeTree.gen.ts @@ -10,18 +10,18 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as testsNormalPageRouteImport } from './routes/(tests)/normal-page' -import { Route as testsWithLoaderRouteImport } from './routes/(tests)/with-loader' import { Route as testsWithSearchRouteImport } from './routes/(tests)/with-search' +import { Route as testsWithLoaderRouteImport } from './routes/(tests)/with-loader' +import { Route as testsNormalPageRouteImport } from './routes/(tests)/normal-page' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const testsNormalPageRoute = testsNormalPageRouteImport.update({ - id: '/(tests)/normal-page', - path: '/normal-page', +const testsWithSearchRoute = testsWithSearchRouteImport.update({ + id: '/(tests)/with-search', + path: '/with-search', getParentRoute: () => rootRouteImport, } as any) const testsWithLoaderRoute = testsWithLoaderRouteImport.update({ @@ -29,9 +29,9 @@ const testsWithLoaderRoute = testsWithLoaderRouteImport.update({ path: '/with-loader', getParentRoute: () => rootRouteImport, } as any) -const testsWithSearchRoute = testsWithSearchRouteImport.update({ - id: '/(tests)/with-search', - path: '/with-search', +const testsNormalPageRoute = testsNormalPageRouteImport.update({ + id: '/(tests)/normal-page', + path: '/normal-page', getParentRoute: () => rootRouteImport, } as any) @@ -83,11 +83,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/(tests)/normal-page': { - id: '/(tests)/normal-page' - path: '/normal-page' - fullPath: '/normal-page' - preLoaderRoute: typeof testsNormalPageRouteImport + '/(tests)/with-search': { + id: '/(tests)/with-search' + path: '/with-search' + fullPath: '/with-search' + preLoaderRoute: typeof testsWithSearchRouteImport parentRoute: typeof rootRouteImport } '/(tests)/with-loader': { @@ -97,11 +97,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof testsWithLoaderRouteImport parentRoute: typeof rootRouteImport } - '/(tests)/with-search': { - id: '/(tests)/with-search' - path: '/with-search' - fullPath: '/with-search' - preLoaderRoute: typeof testsWithSearchRouteImport + '/(tests)/normal-page': { + id: '/(tests)/normal-page' + path: '/normal-page' + fullPath: '/normal-page' + preLoaderRoute: typeof testsNormalPageRouteImport parentRoute: typeof rootRouteImport } } diff --git a/e2e/vue-start/scroll-restoration/src/routes/(tests)/with-loader.tsx b/e2e/vue-start/scroll-restoration/src/routes/(tests)/with-loader.tsx index 50c2f2a47f..23630b8ae4 100644 --- a/e2e/vue-start/scroll-restoration/src/routes/(tests)/with-loader.tsx +++ b/e2e/vue-start/scroll-restoration/src/routes/(tests)/with-loader.tsx @@ -1,5 +1,5 @@ import { createFileRoute } from '@tanstack/vue-router' -import { sleep } from '../../utils/posts' +import { sleep } from 'src/utils/posts' import { ScrollBlock } from '../-components/scroll-block' export const Route = createFileRoute('/(tests)/with-loader')({ diff --git a/e2e/vue-start/scroll-restoration/src/routes/(tests)/with-search.tsx b/e2e/vue-start/scroll-restoration/src/routes/(tests)/with-search.tsx index f19c280d80..4edc141440 100644 --- a/e2e/vue-start/scroll-restoration/src/routes/(tests)/with-search.tsx +++ b/e2e/vue-start/scroll-restoration/src/routes/(tests)/with-search.tsx @@ -1,9 +1,10 @@ import { createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' +import { zodValidator } from '@tanstack/zod-adapter' import { ScrollBlock } from '../-components/scroll-block' export const Route = createFileRoute('/(tests)/with-search')({ - validateSearch: z.object({ where: z.string() }), + validateSearch: zodValidator(z.object({ where: z.string() })), component: Component, }) diff --git a/e2e/vue-start/scroll-restoration/src/routes/__root.tsx b/e2e/vue-start/scroll-restoration/src/routes/__root.tsx index cd8a558359..a28ab59f79 100644 --- a/e2e/vue-start/scroll-restoration/src/routes/__root.tsx +++ b/e2e/vue-start/scroll-restoration/src/routes/__root.tsx @@ -53,11 +53,7 @@ export const Route = createRootRoute({ ], }), errorComponent: (props) => { - return ( -

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

- ) + return

{props.error.stack}

}, 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 c4a2d0dcca..e45ef52969 100644 --- a/e2e/vue-start/scroll-restoration/src/utils/posts.tsx +++ b/e2e/vue-start/scroll-restoration/src/utils/posts.tsx @@ -10,7 +10,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export class PostNotFoundError extends Error {} diff --git a/e2e/vue-start/scroll-restoration/src/utils/users.tsx b/e2e/vue-start/scroll-restoration/src/utils/users.tsx index 7ba645b383..46be4b1580 100644 --- a/e2e/vue-start/scroll-restoration/src/utils/users.tsx +++ b/e2e/vue-start/scroll-restoration/src/utils/users.tsx @@ -3,3 +3,7 @@ export type User = { name: string email: string } + +const PORT = process.env.VITE_SERVER_PORT || 3000 + +export const DEPLOY_URL = `http://localhost:${PORT}` diff --git a/e2e/vue-start/scroll-restoration/src/vite-env.d.ts b/e2e/vue-start/scroll-restoration/src/vite-env.d.ts index d0b512cd80..0b2af560d6 100644 --- a/e2e/vue-start/scroll-restoration/src/vite-env.d.ts +++ b/e2e/vue-start/scroll-restoration/src/vite-env.d.ts @@ -1,5 +1,3 @@ -/// - declare module '*?url' { const url: string export default url diff --git a/e2e/vue-start/scroll-restoration/tests/scroll-restoration-lifecycle.spec.ts b/e2e/vue-start/scroll-restoration/tests/scroll-restoration-lifecycle.spec.ts deleted file mode 100644 index df75cba73c..0000000000 --- a/e2e/vue-start/scroll-restoration/tests/scroll-restoration-lifecycle.spec.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { test } from '@tanstack/router-e2e-utils' -import { scrollRestorationLifecycleTests } from '../../../scroll-restoration-lifecycle' - -scrollRestorationLifecycleTests(test) diff --git a/e2e/vue-start/scroll-restoration/tests/setup/global.setup.ts b/e2e/vue-start/scroll-restoration/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-start/scroll-restoration/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/scroll-restoration/tests/setup/global.teardown.ts b/e2e/vue-start/scroll-restoration/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-start/scroll-restoration/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/scroll-restoration/tsconfig.json b/e2e/vue-start/scroll-restoration/tsconfig.json index 6f99c0f49a..6d933a5b2c 100644 --- a/e2e/vue-start/scroll-restoration/tsconfig.json +++ b/e2e/vue-start/scroll-restoration/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/scroll-restoration/vite.config.ts b/e2e/vue-start/scroll-restoration/vite.config.ts index 563e212077..e0b4a0e909 100644 --- a/e2e/vue-start/scroll-restoration/vite.config.ts +++ b/e2e/vue-start/scroll-restoration/vite.config.ts @@ -1,13 +1,21 @@ import { defineConfig } from 'vite' +import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import tailwindcss from '@tailwindcss/vite' export default defineConfig({ - resolve: { tsconfigPaths: true }, server: { port: 3000, }, - plugins: [tailwindcss(), tanstackStart(), vue(), vueJsx()], + plugins: [ + tailwindcss(), + tsConfigPaths({ + projects: ['./tsconfig.json'], + }), + tanstackStart(), + vue(), + vueJsx(), + ], }) diff --git a/e2e/vue-start/selective-ssr/.devcontainer/devcontainer.json b/e2e/vue-start/selective-ssr/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-start/selective-ssr/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-start/selective-ssr/package.json b/e2e/vue-start/selective-ssr/package.json index b555a01c26..ff082cc638 100644 --- a/e2e/vue-start/selective-ssr/package.json +++ b/e2e/vue-start/selective-ssr/package.json @@ -9,24 +9,24 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-start": "workspace:^", "vue": "^3.5.25", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@tailwindcss/vite": "^4.2.2", + "@tailwindcss/vite": "^4.1.18", "@tanstack/router-e2e-utils": "workspace:^", - "@vitejs/plugin-vue": "^6.0.5", - "@vitejs/plugin-vue-jsx": "^5.1.5", - "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", - "vue-tsc": "^3.3.8" + "srvx": "^0.11.2", + "tailwindcss": "^4.1.18", + "typescript": "^5.7.2", + "vite": "^7.3.1", + "@vitejs/plugin-vue": "^6.0.3", + "@vitejs/plugin-vue-jsx": "^5.1.2", + "vite-tsconfig-paths": "^5.1.4", + "vue-tsc": "^3.1.8" } } diff --git a/e2e/vue-start/selective-ssr/playwright.config.ts b/e2e/vue-start/selective-ssr/playwright.config.ts index 630989e41f..badd6db0eb 100644 --- a/e2e/vue-start/selective-ssr/playwright.config.ts +++ b/e2e/vue-start/selective-ssr/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/selective-ssr/src/routeTree.gen.ts b/e2e/vue-start/selective-ssr/src/routeTree.gen.ts index 0d44b648ee..474705b7e7 100644 --- a/e2e/vue-start/selective-ssr/src/routeTree.gen.ts +++ b/e2e/vue-start/selective-ssr/src/routeTree.gen.ts @@ -9,20 +9,20 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' import { Route as PostsRouteImport } from './routes/posts' +import { Route as IndexRouteImport } from './routes/index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PostsRoute = PostsRouteImport.update({ id: '/posts', path: '/posts', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const PostsPostIdRoute = PostsPostIdRouteImport.update({ id: '/$postId', path: '/$postId', @@ -60,13 +60,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/posts': { id: '/posts' path: '/posts' @@ -74,6 +67,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/posts/$postId': { id: '/posts/$postId' path: '/$postId' diff --git a/e2e/vue-start/selective-ssr/src/routes/__root.tsx b/e2e/vue-start/selective-ssr/src/routes/__root.tsx index 9319a0982a..a952abd4e0 100644 --- a/e2e/vue-start/selective-ssr/src/routes/__root.tsx +++ b/e2e/vue-start/selective-ssr/src/routes/__root.tsx @@ -1,5 +1,4 @@ /// -import { defineComponent } from 'vue' import { Body, ClientOnly, @@ -15,93 +14,6 @@ import { z } from 'zod' import { ssrSchema } from '~/search' import appCss from '~/styles/app.css?url' -const RootDocument = defineComponent({ - setup(_, { slots }) { - const routerState = useRouterState({ - select: (state) => ({ - isLoading: state.isLoading, - status: state.status, - }), - }) - return () => ( - - - - - -
-

Selective SSR E2E Test

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

root

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

root

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

Selective SSR E2E Test

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

postId

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

postId

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

posts

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

posts

+
+ ssr: {JSON.stringify(search.value.posts?.ssr ?? 'undefined')} +
+
+ expected data location execution:{' '} + + {search.value.posts?.expected?.data} + +
+
+ loader: {loaderData.value.posts} +
+
+ context: {context.value.posts} +
+
+ +
+ ) + }, }) diff --git a/e2e/vue-start/selective-ssr/tsconfig.json b/e2e/vue-start/selective-ssr/tsconfig.json index 390dad84c0..f9f5aab3da 100644 --- a/e2e/vue-start/selective-ssr/tsconfig.json +++ b/e2e/vue-start/selective-ssr/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/selective-ssr/vite.config.ts b/e2e/vue-start/selective-ssr/vite.config.ts index 563e212077..e0b4a0e909 100644 --- a/e2e/vue-start/selective-ssr/vite.config.ts +++ b/e2e/vue-start/selective-ssr/vite.config.ts @@ -1,13 +1,21 @@ import { defineConfig } from 'vite' +import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import tailwindcss from '@tailwindcss/vite' export default defineConfig({ - resolve: { tsconfigPaths: true }, server: { port: 3000, }, - plugins: [tailwindcss(), tanstackStart(), vue(), vueJsx()], + plugins: [ + tailwindcss(), + tsConfigPaths({ + projects: ['./tsconfig.json'], + }), + tanstackStart(), + vue(), + vueJsx(), + ], }) diff --git a/e2e/vue-start/serialization-adapters/.devcontainer/devcontainer.json b/e2e/vue-start/serialization-adapters/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-start/serialization-adapters/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-start/serialization-adapters/package.json b/e2e/vue-start/serialization-adapters/package.json index a056e21da3..2be92888eb 100644 --- a/e2e/vue-start/serialization-adapters/package.json +++ b/e2e/vue-start/serialization-adapters/package.json @@ -9,25 +9,25 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", "vue": "^3.5.25", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@tailwindcss/vite": "^4.2.2", + "@tailwindcss/vite": "^4.1.18", "@tanstack/router-e2e-utils": "workspace:^", - "@vitejs/plugin-vue": "^6.0.5", - "@vitejs/plugin-vue-jsx": "^5.1.5", - "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", - "vue-tsc": "^3.3.8" + "srvx": "^0.11.2", + "tailwindcss": "^4.1.18", + "typescript": "^5.7.2", + "vite": "^7.3.1", + "@vitejs/plugin-vue": "^6.0.3", + "@vitejs/plugin-vue-jsx": "^5.1.2", + "vite-tsconfig-paths": "^5.1.4", + "vue-tsc": "^3.1.8" } } diff --git a/e2e/vue-start/serialization-adapters/playwright.config.ts b/e2e/vue-start/serialization-adapters/playwright.config.ts index 630989e41f..badd6db0eb 100644 --- a/e2e/vue-start/serialization-adapters/playwright.config.ts +++ b/e2e/vue-start/serialization-adapters/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/serialization-adapters/src/routeTree.gen.ts b/e2e/vue-start/serialization-adapters/src/routeTree.gen.ts index c684bbc82c..79b17ac82b 100644 --- a/e2e/vue-start/serialization-adapters/src/routeTree.gen.ts +++ b/e2e/vue-start/serialization-adapters/src/routeTree.gen.ts @@ -10,43 +10,43 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as ServerFunctionCustomErrorRouteImport } from './routes/server-function/custom-error' -import { Route as ServerFunctionNestedRouteImport } from './routes/server-function/nested' -import { Route as SsrDataOnlyRouteImport } from './routes/ssr/data-only' -import { Route as SsrNestedRouteImport } from './routes/ssr/nested' import { Route as SsrStreamRouteImport } from './routes/ssr/stream' +import { Route as SsrNestedRouteImport } from './routes/ssr/nested' +import { Route as SsrDataOnlyRouteImport } from './routes/ssr/data-only' +import { Route as ServerFunctionNestedRouteImport } from './routes/server-function/nested' +import { Route as ServerFunctionCustomErrorRouteImport } from './routes/server-function/custom-error' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const SsrStreamRoute = SsrStreamRouteImport.update({ + id: '/ssr/stream', + path: '/ssr/stream', + getParentRoute: () => rootRouteImport, +} as any) +const SsrNestedRoute = SsrNestedRouteImport.update({ + id: '/ssr/nested', + path: '/ssr/nested', + getParentRoute: () => rootRouteImport, +} as any) +const SsrDataOnlyRoute = SsrDataOnlyRouteImport.update({ + id: '/ssr/data-only', + path: '/ssr/data-only', + getParentRoute: () => rootRouteImport, +} as any) +const ServerFunctionNestedRoute = ServerFunctionNestedRouteImport.update({ + id: '/server-function/nested', + path: '/server-function/nested', + getParentRoute: () => rootRouteImport, +} as any) const ServerFunctionCustomErrorRoute = ServerFunctionCustomErrorRouteImport.update({ id: '/server-function/custom-error', path: '/server-function/custom-error', getParentRoute: () => rootRouteImport, } as any) -const ServerFunctionNestedRoute = ServerFunctionNestedRouteImport.update({ - id: '/server-function/nested', - path: '/server-function/nested', - getParentRoute: () => rootRouteImport, -} as any) -const SsrDataOnlyRoute = SsrDataOnlyRouteImport.update({ - id: '/ssr/data-only', - path: '/ssr/data-only', - getParentRoute: () => rootRouteImport, -} as any) -const SsrNestedRoute = SsrNestedRouteImport.update({ - id: '/ssr/nested', - path: '/ssr/nested', - getParentRoute: () => rootRouteImport, -} as any) -const SsrStreamRoute = SsrStreamRouteImport.update({ - id: '/ssr/stream', - path: '/ssr/stream', - getParentRoute: () => rootRouteImport, -} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -118,25 +118,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/server-function/custom-error': { - id: '/server-function/custom-error' - path: '/server-function/custom-error' - fullPath: '/server-function/custom-error' - preLoaderRoute: typeof ServerFunctionCustomErrorRouteImport - parentRoute: typeof rootRouteImport - } - '/server-function/nested': { - id: '/server-function/nested' - path: '/server-function/nested' - fullPath: '/server-function/nested' - preLoaderRoute: typeof ServerFunctionNestedRouteImport - parentRoute: typeof rootRouteImport - } - '/ssr/data-only': { - id: '/ssr/data-only' - path: '/ssr/data-only' - fullPath: '/ssr/data-only' - preLoaderRoute: typeof SsrDataOnlyRouteImport + '/ssr/stream': { + id: '/ssr/stream' + path: '/ssr/stream' + fullPath: '/ssr/stream' + preLoaderRoute: typeof SsrStreamRouteImport parentRoute: typeof rootRouteImport } '/ssr/nested': { @@ -146,11 +132,25 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof SsrNestedRouteImport parentRoute: typeof rootRouteImport } - '/ssr/stream': { - id: '/ssr/stream' - path: '/ssr/stream' - fullPath: '/ssr/stream' - preLoaderRoute: typeof SsrStreamRouteImport + '/ssr/data-only': { + id: '/ssr/data-only' + path: '/ssr/data-only' + fullPath: '/ssr/data-only' + preLoaderRoute: typeof SsrDataOnlyRouteImport + parentRoute: typeof rootRouteImport + } + '/server-function/nested': { + id: '/server-function/nested' + path: '/server-function/nested' + fullPath: '/server-function/nested' + preLoaderRoute: typeof ServerFunctionNestedRouteImport + parentRoute: typeof rootRouteImport + } + '/server-function/custom-error': { + id: '/server-function/custom-error' + path: '/server-function/custom-error' + fullPath: '/server-function/custom-error' + preLoaderRoute: typeof ServerFunctionCustomErrorRouteImport parentRoute: typeof rootRouteImport } } diff --git a/e2e/vue-start/serialization-adapters/src/routes/__root.tsx b/e2e/vue-start/serialization-adapters/src/routes/__root.tsx index 3ea36c7d46..96911d2500 100644 --- a/e2e/vue-start/serialization-adapters/src/routes/__root.tsx +++ b/e2e/vue-start/serialization-adapters/src/routes/__root.tsx @@ -1,5 +1,4 @@ /// -import { defineComponent } from 'vue' import { Body, ClientOnly, @@ -13,51 +12,6 @@ import { import { TanStackRouterDevtoolsInProd } from '@tanstack/vue-router-devtools' import appCss from '~/styles/app.css?url' -const RootDocument = defineComponent({ - setup(_, { slots }) { - const routerState = useRouterState({ - select: (state) => ({ isLoading: state.isLoading, status: state.status }), - }) - return () => ( - - - - - -
-

Serialization Adapters E2E Test

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

Serialization Adapters E2E Test

+ + Home + +
+
+ +
+ router isLoading:{' '} + + {routerState.value.isLoading ? 'true' : 'false'} + +
+
+ router status:{' '} + {routerState.value.status} +
+
+
+ {slots.default?.()} + + + + + ) +} diff --git a/e2e/vue-start/serialization-adapters/src/routes/index.tsx b/e2e/vue-start/serialization-adapters/src/routes/index.tsx index d6bacefdc0..2d90e4b073 100644 --- a/e2e/vue-start/serialization-adapters/src/routes/index.tsx +++ b/e2e/vue-start/serialization-adapters/src/routes/index.tsx @@ -2,9 +2,7 @@ import { Link, createFileRoute } from '@tanstack/vue-router' export const Route = createFileRoute('/')({ component: Home, - errorComponent: (e) => ( -
{e.error instanceof Error ? e.error.message : String(e.error)}
- ), + errorComponent: (e) =>
{e.error.message}
, }) function Home() { diff --git a/e2e/vue-start/serialization-adapters/src/routes/server-function/custom-error.tsx b/e2e/vue-start/serialization-adapters/src/routes/server-function/custom-error.tsx index d1cbdf6353..6bca8563d3 100644 --- a/e2e/vue-start/serialization-adapters/src/routes/server-function/custom-error.tsx +++ b/e2e/vue-start/serialization-adapters/src/routes/server-function/custom-error.tsx @@ -7,7 +7,7 @@ import { CustomError } from '~/CustomError' const schema = z.object({ hello: z.string() }) const serverFnThrowing = createServerFn() - .validator(schema) + .inputValidator(schema) .handler(async ({ data }) => { if (data.hello === 'world') { return 'Hello, world!' diff --git a/e2e/vue-start/serialization-adapters/src/routes/ssr/data-only.tsx b/e2e/vue-start/serialization-adapters/src/routes/ssr/data-only.tsx index e71906f03e..ecb35d0a55 100644 --- a/e2e/vue-start/serialization-adapters/src/routes/ssr/data-only.tsx +++ b/e2e/vue-start/serialization-adapters/src/routes/ssr/data-only.tsx @@ -1,47 +1,6 @@ -import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' import { RenderData, makeData } from '~/data' -const RouteComponent = defineComponent({ - setup() { - const context = Route.useRouteContext() - const loaderData = Route.useLoaderData() - return () => { - const localData = makeData() - const expectedHonkState = localData.car.singleInstance.honk() - const honkState = loaderData.value.car.singleInstance.honk() - return ( -
-

data-only

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

honk

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

data-only

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

honk

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

Stream

-
{loaderData.value.someString}
- - {{ - default: () => ( - ) => ( - - )} - /> - ), - fallback: () =>
Loading...
, - }} -
-
- ) - }, -}) - export const Route = createFileRoute('/ssr/stream')({ loader: () => { const dataPromise = new Promise>((r) => @@ -38,8 +13,29 @@ export const Route = createFileRoute('/ssr/stream')({ } }, - errorComponent: (e) => ( -
{e.error instanceof Error ? e.error.message : String(e.error)}
- ), + errorComponent: (e) =>
{e.error.message}
, component: RouteComponent, }) + +function RouteComponent() { + const loaderData = Route.useLoaderData() + return ( +
+

Stream

+
{loaderData.value.someString}
+ + {{ + default: () => ( + ) => ( + + )} + /> + ), + fallback: () =>
Loading...
, + }} +
+
+ ) +} diff --git a/e2e/vue-start/serialization-adapters/tsconfig.json b/e2e/vue-start/serialization-adapters/tsconfig.json index 390dad84c0..f9f5aab3da 100644 --- a/e2e/vue-start/serialization-adapters/tsconfig.json +++ b/e2e/vue-start/serialization-adapters/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/serialization-adapters/vite.config.ts b/e2e/vue-start/serialization-adapters/vite.config.ts index 563e212077..e0b4a0e909 100644 --- a/e2e/vue-start/serialization-adapters/vite.config.ts +++ b/e2e/vue-start/serialization-adapters/vite.config.ts @@ -1,13 +1,21 @@ import { defineConfig } from 'vite' +import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import tailwindcss from '@tailwindcss/vite' export default defineConfig({ - resolve: { tsconfigPaths: true }, server: { port: 3000, }, - plugins: [tailwindcss(), tanstackStart(), vue(), vueJsx()], + plugins: [ + tailwindcss(), + tsConfigPaths({ + projects: ['./tsconfig.json'], + }), + tanstackStart(), + vue(), + vueJsx(), + ], }) diff --git a/e2e/vue-start/server-functions/.devcontainer/devcontainer.json b/e2e/vue-start/server-functions/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-start/server-functions/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-start/server-functions/package.json b/e2e/vue-start/server-functions/package.json index dd1a7a9c6b..5f232aa8af 100644 --- a/e2e/vue-start/server-functions/package.json +++ b/e2e/vue-start/server-functions/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-query": "^5.90.9", @@ -18,24 +18,24 @@ "@tanstack/vue-router-ssr-query": "workspace:^", "@tanstack/vue-start": "workspace:^", "js-cookie": "^3.0.5", - "redaxios": "catalog:", - "tailwind-merge": "^3.6.0", + "redaxios": "^0.5.1", + "tailwind-merge": "^2.6.0", + "vite": "^7.3.1", "vue": "^3.5.25", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@playwright/test": "^1.61.0", - "@tailwindcss/vite": "^4.2.2", + "@playwright/test": "^1.50.1", + "@tailwindcss/vite": "^4.1.18", "@tanstack/router-e2e-utils": "workspace:^", "@types/js-cookie": "^3.0.6", "@types/node": "^22.10.2", - "@vitejs/plugin-vue": "^6.0.5", - "@vitejs/plugin-vue-jsx": "^5.1.5", "combinate": "^1.1.11", - "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" + "srvx": "^0.11.2", + "tailwindcss": "^4.1.18", + "typescript": "^5.7.2", + "@vitejs/plugin-vue": "^6.0.3", + "@vitejs/plugin-vue-jsx": "^5.1.2", + "vite-tsconfig-paths": "^5.1.4" } } diff --git a/e2e/vue-start/server-functions/playwright.config.ts b/e2e/vue-start/server-functions/playwright.config.ts index 48e14683f4..cb1da03b94 100644 --- a/e2e/vue-start/server-functions/playwright.config.ts +++ b/e2e/vue-start/server-functions/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -export const PORT = Number(process.env.E2E_APP_PORT ?? 0) +export const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/server-functions/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/server-functions/src/components/DefaultCatchBoundary.tsx index 77c03c5afa..b1f818dd74 100644 --- a/e2e/vue-start/server-functions/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/server-functions/src/components/DefaultCatchBoundary.tsx @@ -1,61 +1,53 @@ -import { defineComponent } from 'vue' -import type { PropType } from 'vue' import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -export const DefaultCatchBoundary = defineComponent({ - props: { - error: { - type: Object as PropType, - required: true, - }, - }, - setup(props) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - return () => { - console.error(props.error) - return ( -
- -
- - {isRoot.value ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) - } - }, -}) +export function DefaultCatchBoundary({ error }: ErrorComponentProps) { + const router = useRouter() + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, + }) + + console.error(error) + + return ( +
+ +
+ + {isRoot.value ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
+
+ ) +} diff --git a/e2e/vue-start/server-functions/src/routeTree.gen.ts b/e2e/vue-start/server-functions/src/routeTree.gen.ts index 96e5b7ba29..43a6eb4ae6 100644 --- a/e2e/vue-start/server-functions/src/routeTree.gen.ts +++ b/e2e/vue-start/server-functions/src/routeTree.gen.ts @@ -9,89 +9,39 @@ // 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 AbortSignalRouteImport } from './routes/abort-signal' -import { Route as ConsistentRouteImport } from './routes/consistent' -import { Route as DeadCodePreserveRouteImport } from './routes/dead-code-preserve' -import { Route as EnvOnlyRouteImport } from './routes/env-only' -import { Route as HeadersRouteImport } from './routes/headers' -import { Route as IsomorphicFnsRouteImport } from './routes/isomorphic-fns' -import { Route as MultipartRouteImport } from './routes/multipart' -import { Route as RawResponseRouteImport } from './routes/raw-response' -import { Route as ReturnNullRouteImport } from './routes/return-null' -import { Route as SerializeFormDataRouteImport } from './routes/serialize-form-data' -import { Route as StatusRouteImport } from './routes/status' import { Route as SubmitPostFormdataRouteImport } from './routes/submit-post-formdata' -import { Route as CookiesIndexRouteImport } from './routes/cookies/index' -import { Route as CookiesSetRouteImport } from './routes/cookies/set' -import { Route as FactoryIndexRouteImport } from './routes/factory/index' -import { Route as FormdataRedirectIndexRouteImport } from './routes/formdata-redirect/index' -import { Route as FunctionMetadataIndexRouteImport } from './routes/function-metadata/index' -import { Route as FunctionMethodIndexRouteImport } from './routes/function-method/index' -import { Route as MiddlewareIndexRouteImport } from './routes/middleware/index' -import { Route as MiddlewareClientMiddlewareRouterRouteImport } from './routes/middleware/client-middleware-router' -import { Route as MiddlewareRequestMiddlewareRouteImport } from './routes/middleware/request-middleware' -import { Route as MiddlewareSendServerFnRouteImport } from './routes/middleware/send-serverFn' -import { Route as PrimitivesIndexRouteImport } from './routes/primitives/index' -import { Route as RedirectTestSsrIndexRouteImport } from './routes/redirect-test-ssr/index' -import { Route as RedirectTestSsrTargetRouteImport } from './routes/redirect-test-ssr/target' +import { Route as StatusRouteImport } from './routes/status' +import { Route as SerializeFormDataRouteImport } from './routes/serialize-form-data' +import { Route as ReturnNullRouteImport } from './routes/return-null' +import { Route as RawResponseRouteImport } from './routes/raw-response' +import { Route as MultipartRouteImport } from './routes/multipart' +import { Route as IsomorphicFnsRouteImport } from './routes/isomorphic-fns' +import { Route as HeadersRouteImport } from './routes/headers' +import { Route as EnvOnlyRouteImport } from './routes/env-only' +import { Route as DeadCodePreserveRouteImport } from './routes/dead-code-preserve' +import { Route as ConsistentRouteImport } from './routes/consistent' +import { Route as AbortSignalRouteImport } from './routes/abort-signal' +import { Route as IndexRouteImport } from './routes/index' import { Route as RedirectTestIndexRouteImport } from './routes/redirect-test/index' +import { Route as RedirectTestSsrIndexRouteImport } from './routes/redirect-test-ssr/index' +import { Route as PrimitivesIndexRouteImport } from './routes/primitives/index' +import { Route as MiddlewareIndexRouteImport } from './routes/middleware/index' +import { Route as FunctionMethodIndexRouteImport } from './routes/function-method/index' +import { Route as FunctionMetadataIndexRouteImport } from './routes/function-metadata/index' +import { Route as FormdataRedirectIndexRouteImport } from './routes/formdata-redirect/index' +import { Route as FactoryIndexRouteImport } from './routes/factory/index' +import { Route as CookiesIndexRouteImport } from './routes/cookies/index' import { Route as RedirectTestTargetRouteImport } from './routes/redirect-test/target' +import { Route as RedirectTestSsrTargetRouteImport } from './routes/redirect-test-ssr/target' +import { Route as MiddlewareSendServerFnRouteImport } from './routes/middleware/send-serverFn' +import { Route as MiddlewareRequestMiddlewareRouteImport } from './routes/middleware/request-middleware' +import { Route as MiddlewareClientMiddlewareRouterRouteImport } from './routes/middleware/client-middleware-router' +import { Route as CookiesSetRouteImport } from './routes/cookies/set' import { Route as FormdataRedirectTargetNameRouteImport } from './routes/formdata-redirect/target.$name' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AbortSignalRoute = AbortSignalRouteImport.update({ - id: '/abort-signal', - path: '/abort-signal', - getParentRoute: () => rootRouteImport, -} as any) -const ConsistentRoute = ConsistentRouteImport.update({ - id: '/consistent', - path: '/consistent', - getParentRoute: () => rootRouteImport, -} as any) -const DeadCodePreserveRoute = DeadCodePreserveRouteImport.update({ - id: '/dead-code-preserve', - path: '/dead-code-preserve', - getParentRoute: () => rootRouteImport, -} as any) -const EnvOnlyRoute = EnvOnlyRouteImport.update({ - id: '/env-only', - path: '/env-only', - getParentRoute: () => rootRouteImport, -} as any) -const HeadersRoute = HeadersRouteImport.update({ - id: '/headers', - path: '/headers', - getParentRoute: () => rootRouteImport, -} as any) -const IsomorphicFnsRoute = IsomorphicFnsRouteImport.update({ - id: '/isomorphic-fns', - path: '/isomorphic-fns', - getParentRoute: () => rootRouteImport, -} as any) -const MultipartRoute = MultipartRouteImport.update({ - id: '/multipart', - path: '/multipart', - getParentRoute: () => rootRouteImport, -} as any) -const RawResponseRoute = RawResponseRouteImport.update({ - id: '/raw-response', - path: '/raw-response', - getParentRoute: () => rootRouteImport, -} as any) -const ReturnNullRoute = ReturnNullRouteImport.update({ - id: '/return-null', - path: '/return-null', - getParentRoute: () => rootRouteImport, -} as any) -const SerializeFormDataRoute = SerializeFormDataRouteImport.update({ - id: '/serialize-form-data', - path: '/serialize-form-data', +const SubmitPostFormdataRoute = SubmitPostFormdataRouteImport.update({ + id: '/submit-post-formdata', + path: '/submit-post-formdata', getParentRoute: () => rootRouteImport, } as any) const StatusRoute = StatusRouteImport.update({ @@ -99,76 +49,59 @@ const StatusRoute = StatusRouteImport.update({ path: '/status', getParentRoute: () => rootRouteImport, } as any) -const SubmitPostFormdataRoute = SubmitPostFormdataRouteImport.update({ - id: '/submit-post-formdata', - path: '/submit-post-formdata', +const SerializeFormDataRoute = SerializeFormDataRouteImport.update({ + id: '/serialize-form-data', + path: '/serialize-form-data', getParentRoute: () => rootRouteImport, } as any) -const CookiesIndexRoute = CookiesIndexRouteImport.update({ - id: '/cookies/', - path: '/cookies/', +const ReturnNullRoute = ReturnNullRouteImport.update({ + id: '/return-null', + path: '/return-null', getParentRoute: () => rootRouteImport, } as any) -const CookiesSetRoute = CookiesSetRouteImport.update({ - id: '/cookies/set', - path: '/cookies/set', +const RawResponseRoute = RawResponseRouteImport.update({ + id: '/raw-response', + path: '/raw-response', getParentRoute: () => rootRouteImport, } as any) -const FactoryIndexRoute = FactoryIndexRouteImport.update({ - id: '/factory/', - path: '/factory/', +const MultipartRoute = MultipartRouteImport.update({ + id: '/multipart', + path: '/multipart', getParentRoute: () => rootRouteImport, } as any) -const FormdataRedirectIndexRoute = FormdataRedirectIndexRouteImport.update({ - id: '/formdata-redirect/', - path: '/formdata-redirect/', +const IsomorphicFnsRoute = IsomorphicFnsRouteImport.update({ + id: '/isomorphic-fns', + path: '/isomorphic-fns', getParentRoute: () => rootRouteImport, } as any) -const FunctionMetadataIndexRoute = FunctionMetadataIndexRouteImport.update({ - id: '/function-metadata/', - path: '/function-metadata/', +const HeadersRoute = HeadersRouteImport.update({ + id: '/headers', + path: '/headers', getParentRoute: () => rootRouteImport, } as any) -const FunctionMethodIndexRoute = FunctionMethodIndexRouteImport.update({ - id: '/function-method/', - path: '/function-method/', +const EnvOnlyRoute = EnvOnlyRouteImport.update({ + id: '/env-only', + path: '/env-only', getParentRoute: () => rootRouteImport, } as any) -const MiddlewareIndexRoute = MiddlewareIndexRouteImport.update({ - id: '/middleware/', - path: '/middleware/', +const DeadCodePreserveRoute = DeadCodePreserveRouteImport.update({ + id: '/dead-code-preserve', + path: '/dead-code-preserve', getParentRoute: () => rootRouteImport, } as any) -const MiddlewareClientMiddlewareRouterRoute = - MiddlewareClientMiddlewareRouterRouteImport.update({ - id: '/middleware/client-middleware-router', - path: '/middleware/client-middleware-router', - getParentRoute: () => rootRouteImport, - } as any) -const MiddlewareRequestMiddlewareRoute = - MiddlewareRequestMiddlewareRouteImport.update({ - id: '/middleware/request-middleware', - path: '/middleware/request-middleware', - getParentRoute: () => rootRouteImport, - } as any) -const MiddlewareSendServerFnRoute = MiddlewareSendServerFnRouteImport.update({ - id: '/middleware/send-serverFn', - path: '/middleware/send-serverFn', +const ConsistentRoute = ConsistentRouteImport.update({ + id: '/consistent', + path: '/consistent', getParentRoute: () => rootRouteImport, } as any) -const PrimitivesIndexRoute = PrimitivesIndexRouteImport.update({ - id: '/primitives/', - path: '/primitives/', +const AbortSignalRoute = AbortSignalRouteImport.update({ + id: '/abort-signal', + path: '/abort-signal', getParentRoute: () => rootRouteImport, } as any) -const RedirectTestSsrIndexRoute = RedirectTestSsrIndexRouteImport.update({ - id: '/redirect-test-ssr/', - path: '/redirect-test-ssr/', - getParentRoute: () => rootRouteImport, -} as any) -const RedirectTestSsrTargetRoute = RedirectTestSsrTargetRouteImport.update({ - id: '/redirect-test-ssr/target', - path: '/redirect-test-ssr/target', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const RedirectTestIndexRoute = RedirectTestIndexRouteImport.update({ @@ -176,11 +109,78 @@ const RedirectTestIndexRoute = RedirectTestIndexRouteImport.update({ path: '/redirect-test/', getParentRoute: () => rootRouteImport, } as any) +const RedirectTestSsrIndexRoute = RedirectTestSsrIndexRouteImport.update({ + id: '/redirect-test-ssr/', + path: '/redirect-test-ssr/', + getParentRoute: () => rootRouteImport, +} as any) +const PrimitivesIndexRoute = PrimitivesIndexRouteImport.update({ + id: '/primitives/', + path: '/primitives/', + getParentRoute: () => rootRouteImport, +} as any) +const MiddlewareIndexRoute = MiddlewareIndexRouteImport.update({ + id: '/middleware/', + path: '/middleware/', + getParentRoute: () => rootRouteImport, +} as any) +const FunctionMethodIndexRoute = FunctionMethodIndexRouteImport.update({ + id: '/function-method/', + path: '/function-method/', + getParentRoute: () => rootRouteImport, +} as any) +const FunctionMetadataIndexRoute = FunctionMetadataIndexRouteImport.update({ + id: '/function-metadata/', + path: '/function-metadata/', + getParentRoute: () => rootRouteImport, +} as any) +const FormdataRedirectIndexRoute = FormdataRedirectIndexRouteImport.update({ + id: '/formdata-redirect/', + path: '/formdata-redirect/', + getParentRoute: () => rootRouteImport, +} as any) +const FactoryIndexRoute = FactoryIndexRouteImport.update({ + id: '/factory/', + path: '/factory/', + getParentRoute: () => rootRouteImport, +} as any) +const CookiesIndexRoute = CookiesIndexRouteImport.update({ + id: '/cookies/', + path: '/cookies/', + getParentRoute: () => rootRouteImport, +} as any) const RedirectTestTargetRoute = RedirectTestTargetRouteImport.update({ id: '/redirect-test/target', path: '/redirect-test/target', getParentRoute: () => rootRouteImport, } as any) +const RedirectTestSsrTargetRoute = RedirectTestSsrTargetRouteImport.update({ + id: '/redirect-test-ssr/target', + path: '/redirect-test-ssr/target', + getParentRoute: () => rootRouteImport, +} as any) +const MiddlewareSendServerFnRoute = MiddlewareSendServerFnRouteImport.update({ + id: '/middleware/send-serverFn', + path: '/middleware/send-serverFn', + getParentRoute: () => rootRouteImport, +} as any) +const MiddlewareRequestMiddlewareRoute = + MiddlewareRequestMiddlewareRouteImport.update({ + id: '/middleware/request-middleware', + path: '/middleware/request-middleware', + getParentRoute: () => rootRouteImport, + } as any) +const MiddlewareClientMiddlewareRouterRoute = + MiddlewareClientMiddlewareRouterRouteImport.update({ + id: '/middleware/client-middleware-router', + path: '/middleware/client-middleware-router', + getParentRoute: () => rootRouteImport, + } as any) +const CookiesSetRoute = CookiesSetRouteImport.update({ + id: '/cookies/set', + path: '/cookies/set', + getParentRoute: () => rootRouteImport, +} as any) const FormdataRedirectTargetNameRoute = FormdataRedirectTargetNameRouteImport.update({ id: '/formdata-redirect/target/$name', @@ -412,81 +412,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/abort-signal': { - id: '/abort-signal' - path: '/abort-signal' - fullPath: '/abort-signal' - preLoaderRoute: typeof AbortSignalRouteImport - parentRoute: typeof rootRouteImport - } - '/consistent': { - id: '/consistent' - path: '/consistent' - fullPath: '/consistent' - preLoaderRoute: typeof ConsistentRouteImport - parentRoute: typeof rootRouteImport - } - '/dead-code-preserve': { - id: '/dead-code-preserve' - path: '/dead-code-preserve' - fullPath: '/dead-code-preserve' - preLoaderRoute: typeof DeadCodePreserveRouteImport - parentRoute: typeof rootRouteImport - } - '/env-only': { - id: '/env-only' - path: '/env-only' - fullPath: '/env-only' - preLoaderRoute: typeof EnvOnlyRouteImport - parentRoute: typeof rootRouteImport - } - '/headers': { - id: '/headers' - path: '/headers' - fullPath: '/headers' - preLoaderRoute: typeof HeadersRouteImport - parentRoute: typeof rootRouteImport - } - '/isomorphic-fns': { - id: '/isomorphic-fns' - path: '/isomorphic-fns' - fullPath: '/isomorphic-fns' - preLoaderRoute: typeof IsomorphicFnsRouteImport - parentRoute: typeof rootRouteImport - } - '/multipart': { - id: '/multipart' - path: '/multipart' - fullPath: '/multipart' - preLoaderRoute: typeof MultipartRouteImport - parentRoute: typeof rootRouteImport - } - '/raw-response': { - id: '/raw-response' - path: '/raw-response' - fullPath: '/raw-response' - preLoaderRoute: typeof RawResponseRouteImport - parentRoute: typeof rootRouteImport - } - '/return-null': { - id: '/return-null' - path: '/return-null' - fullPath: '/return-null' - preLoaderRoute: typeof ReturnNullRouteImport - parentRoute: typeof rootRouteImport - } - '/serialize-form-data': { - id: '/serialize-form-data' - path: '/serialize-form-data' - fullPath: '/serialize-form-data' - preLoaderRoute: typeof SerializeFormDataRouteImport + '/submit-post-formdata': { + id: '/submit-post-formdata' + path: '/submit-post-formdata' + fullPath: '/submit-post-formdata' + preLoaderRoute: typeof SubmitPostFormdataRouteImport parentRoute: typeof rootRouteImport } '/status': { @@ -496,102 +426,81 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof StatusRouteImport parentRoute: typeof rootRouteImport } - '/submit-post-formdata': { - id: '/submit-post-formdata' - path: '/submit-post-formdata' - fullPath: '/submit-post-formdata' - preLoaderRoute: typeof SubmitPostFormdataRouteImport + '/serialize-form-data': { + id: '/serialize-form-data' + path: '/serialize-form-data' + fullPath: '/serialize-form-data' + preLoaderRoute: typeof SerializeFormDataRouteImport parentRoute: typeof rootRouteImport } - '/cookies/': { - id: '/cookies/' - path: '/cookies' - fullPath: '/cookies/' - preLoaderRoute: typeof CookiesIndexRouteImport + '/return-null': { + id: '/return-null' + path: '/return-null' + fullPath: '/return-null' + preLoaderRoute: typeof ReturnNullRouteImport parentRoute: typeof rootRouteImport } - '/cookies/set': { - id: '/cookies/set' - path: '/cookies/set' - fullPath: '/cookies/set' - preLoaderRoute: typeof CookiesSetRouteImport + '/raw-response': { + id: '/raw-response' + path: '/raw-response' + fullPath: '/raw-response' + preLoaderRoute: typeof RawResponseRouteImport parentRoute: typeof rootRouteImport } - '/factory/': { - id: '/factory/' - path: '/factory' - fullPath: '/factory/' - preLoaderRoute: typeof FactoryIndexRouteImport + '/multipart': { + id: '/multipart' + path: '/multipart' + fullPath: '/multipart' + preLoaderRoute: typeof MultipartRouteImport parentRoute: typeof rootRouteImport } - '/formdata-redirect/': { - id: '/formdata-redirect/' - path: '/formdata-redirect' - fullPath: '/formdata-redirect/' - preLoaderRoute: typeof FormdataRedirectIndexRouteImport + '/isomorphic-fns': { + id: '/isomorphic-fns' + path: '/isomorphic-fns' + fullPath: '/isomorphic-fns' + preLoaderRoute: typeof IsomorphicFnsRouteImport parentRoute: typeof rootRouteImport } - '/function-metadata/': { - id: '/function-metadata/' - path: '/function-metadata' - fullPath: '/function-metadata/' - preLoaderRoute: typeof FunctionMetadataIndexRouteImport + '/headers': { + id: '/headers' + path: '/headers' + fullPath: '/headers' + preLoaderRoute: typeof HeadersRouteImport parentRoute: typeof rootRouteImport } - '/function-method/': { - id: '/function-method/' - path: '/function-method' - fullPath: '/function-method/' - preLoaderRoute: typeof FunctionMethodIndexRouteImport + '/env-only': { + id: '/env-only' + path: '/env-only' + fullPath: '/env-only' + preLoaderRoute: typeof EnvOnlyRouteImport parentRoute: typeof rootRouteImport } - '/middleware/': { - id: '/middleware/' - path: '/middleware' - fullPath: '/middleware/' - preLoaderRoute: typeof MiddlewareIndexRouteImport + '/dead-code-preserve': { + id: '/dead-code-preserve' + path: '/dead-code-preserve' + fullPath: '/dead-code-preserve' + preLoaderRoute: typeof DeadCodePreserveRouteImport parentRoute: typeof rootRouteImport } - '/middleware/client-middleware-router': { - id: '/middleware/client-middleware-router' - path: '/middleware/client-middleware-router' - fullPath: '/middleware/client-middleware-router' - preLoaderRoute: typeof MiddlewareClientMiddlewareRouterRouteImport + '/consistent': { + id: '/consistent' + path: '/consistent' + fullPath: '/consistent' + preLoaderRoute: typeof ConsistentRouteImport parentRoute: typeof rootRouteImport } - '/middleware/request-middleware': { - id: '/middleware/request-middleware' - path: '/middleware/request-middleware' - fullPath: '/middleware/request-middleware' - preLoaderRoute: typeof MiddlewareRequestMiddlewareRouteImport + '/abort-signal': { + id: '/abort-signal' + path: '/abort-signal' + fullPath: '/abort-signal' + preLoaderRoute: typeof AbortSignalRouteImport parentRoute: typeof rootRouteImport } - '/middleware/send-serverFn': { - id: '/middleware/send-serverFn' - path: '/middleware/send-serverFn' - fullPath: '/middleware/send-serverFn' - preLoaderRoute: typeof MiddlewareSendServerFnRouteImport - parentRoute: typeof rootRouteImport - } - '/primitives/': { - id: '/primitives/' - path: '/primitives' - fullPath: '/primitives/' - preLoaderRoute: typeof PrimitivesIndexRouteImport - parentRoute: typeof rootRouteImport - } - '/redirect-test-ssr/': { - id: '/redirect-test-ssr/' - path: '/redirect-test-ssr' - fullPath: '/redirect-test-ssr/' - preLoaderRoute: typeof RedirectTestSsrIndexRouteImport - parentRoute: typeof rootRouteImport - } - '/redirect-test-ssr/target': { - id: '/redirect-test-ssr/target' - path: '/redirect-test-ssr/target' - fullPath: '/redirect-test-ssr/target' - preLoaderRoute: typeof RedirectTestSsrTargetRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/redirect-test/': { @@ -601,6 +510,62 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof RedirectTestIndexRouteImport parentRoute: typeof rootRouteImport } + '/redirect-test-ssr/': { + id: '/redirect-test-ssr/' + path: '/redirect-test-ssr' + fullPath: '/redirect-test-ssr/' + preLoaderRoute: typeof RedirectTestSsrIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/primitives/': { + id: '/primitives/' + path: '/primitives' + fullPath: '/primitives/' + preLoaderRoute: typeof PrimitivesIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/middleware/': { + id: '/middleware/' + path: '/middleware' + fullPath: '/middleware/' + preLoaderRoute: typeof MiddlewareIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/function-method/': { + id: '/function-method/' + path: '/function-method' + fullPath: '/function-method/' + preLoaderRoute: typeof FunctionMethodIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/function-metadata/': { + id: '/function-metadata/' + path: '/function-metadata' + fullPath: '/function-metadata/' + preLoaderRoute: typeof FunctionMetadataIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/formdata-redirect/': { + id: '/formdata-redirect/' + path: '/formdata-redirect' + fullPath: '/formdata-redirect/' + preLoaderRoute: typeof FormdataRedirectIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/factory/': { + id: '/factory/' + path: '/factory' + fullPath: '/factory/' + preLoaderRoute: typeof FactoryIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/cookies/': { + id: '/cookies/' + path: '/cookies' + fullPath: '/cookies/' + preLoaderRoute: typeof CookiesIndexRouteImport + parentRoute: typeof rootRouteImport + } '/redirect-test/target': { id: '/redirect-test/target' path: '/redirect-test/target' @@ -608,6 +573,41 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof RedirectTestTargetRouteImport parentRoute: typeof rootRouteImport } + '/redirect-test-ssr/target': { + id: '/redirect-test-ssr/target' + path: '/redirect-test-ssr/target' + fullPath: '/redirect-test-ssr/target' + preLoaderRoute: typeof RedirectTestSsrTargetRouteImport + parentRoute: typeof rootRouteImport + } + '/middleware/send-serverFn': { + id: '/middleware/send-serverFn' + path: '/middleware/send-serverFn' + fullPath: '/middleware/send-serverFn' + preLoaderRoute: typeof MiddlewareSendServerFnRouteImport + parentRoute: typeof rootRouteImport + } + '/middleware/request-middleware': { + id: '/middleware/request-middleware' + path: '/middleware/request-middleware' + fullPath: '/middleware/request-middleware' + preLoaderRoute: typeof MiddlewareRequestMiddlewareRouteImport + parentRoute: typeof rootRouteImport + } + '/middleware/client-middleware-router': { + id: '/middleware/client-middleware-router' + path: '/middleware/client-middleware-router' + fullPath: '/middleware/client-middleware-router' + preLoaderRoute: typeof MiddlewareClientMiddlewareRouterRouteImport + parentRoute: typeof rootRouteImport + } + '/cookies/set': { + id: '/cookies/set' + path: '/cookies/set' + fullPath: '/cookies/set' + preLoaderRoute: typeof CookiesSetRouteImport + parentRoute: typeof rootRouteImport + } '/formdata-redirect/target/$name': { id: '/formdata-redirect/target/$name' path: '/formdata-redirect/target/$name' diff --git a/e2e/vue-start/server-functions/src/routes/__root.tsx b/e2e/vue-start/server-functions/src/routes/__root.tsx index a52b12deae..342f7a79b3 100644 --- a/e2e/vue-start/server-functions/src/routes/__root.tsx +++ b/e2e/vue-start/server-functions/src/routes/__root.tsx @@ -25,11 +25,7 @@ export const Route = createRootRoute({ links: [{ rel: 'stylesheet', href: appCss }], }), errorComponent: (props) => { - return ( -

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

- ) + return

{props.error.stack}

}, notFoundComponent: () => , component: RootComponent, diff --git a/e2e/vue-start/server-functions/src/routes/consistent.tsx b/e2e/vue-start/server-functions/src/routes/consistent.tsx index 046f15f339..5e6b0a7e08 100644 --- a/e2e/vue-start/server-functions/src/routes/consistent.tsx +++ b/e2e/vue-start/server-functions/src/routes/consistent.tsx @@ -11,25 +11,25 @@ import { defineComponent, ref } from 'vue' */ const cons_getFn1 = createServerFn() - .validator((d: { username: string }) => d) + .inputValidator((d: { username: string }) => d) .handler(({ data }) => { return { payload: data } }) const cons_serverGetFn1 = createServerFn() - .validator((d: { username: string }) => d) + .inputValidator((d: { username: string }) => d) .handler(async ({ data }) => { return cons_getFn1({ data }) }) const cons_postFn1 = createServerFn({ method: 'POST' }) - .validator((d: { username: string }) => d) + .inputValidator((d: { username: string }) => d) .handler(({ data }) => { return { payload: data } }) const cons_serverPostFn1 = createServerFn({ method: 'POST' }) - .validator((d: { username: string }) => d) + .inputValidator((d: { username: string }) => d) .handler(({ data }) => { return cons_postFn1({ data }) }) diff --git a/e2e/vue-start/server-functions/src/routes/cookies/index.tsx b/e2e/vue-start/server-functions/src/routes/cookies/index.tsx index 90dddad0af..5da8860ac6 100644 --- a/e2e/vue-start/server-functions/src/routes/cookies/index.tsx +++ b/e2e/vue-start/server-functions/src/routes/cookies/index.tsx @@ -1,28 +1,24 @@ -import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' const cookieSchema = z - .object({ value: z.string().default(() => `CLIENT-${Date.now()}`) }) - .prefault({}) + .object({ value: z.string() }) .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/cookies/set.tsx b/e2e/vue-start/server-functions/src/routes/cookies/set.tsx index bcdad36ab9..39fd00b74e 100644 --- a/e2e/vue-start/server-functions/src/routes/cookies/set.tsx +++ b/e2e/vue-start/server-functions/src/routes/cookies/set.tsx @@ -8,14 +8,14 @@ import { defineComponent, ref, watch } from 'vue' const cookieSchema = z.object({ value: z.string() }) export const setCookieServerFn1 = createServerFn() - .validator(cookieSchema) + .inputValidator(cookieSchema) .handler(({ data }) => { setCookie(`cookie-1-${data.value}`, data.value) setCookie(`cookie-2-${data.value}`, data.value) }) export const setCookieServerFn2 = createServerFn() - .validator(cookieSchema) + .inputValidator(cookieSchema) .handler(({ data }) => { setCookie(`cookie-3-${data.value}`, data.value) setCookie(`cookie-4-${data.value}`, data.value) diff --git a/e2e/vue-start/server-functions/src/routes/formdata-redirect/index.tsx b/e2e/vue-start/server-functions/src/routes/formdata-redirect/index.tsx index 8bfcc55ca3..d23eb342b3 100644 --- a/e2e/vue-start/server-functions/src/routes/formdata-redirect/index.tsx +++ b/e2e/vue-start/server-functions/src/routes/formdata-redirect/index.tsx @@ -1,51 +1,7 @@ -import { defineComponent } from 'vue' import { createFileRoute, redirect } from '@tanstack/vue-router' import { createServerFn, useServerFn } from '@tanstack/vue-start' import { z } from 'zod' -const SubmitPostFormDataFn = defineComponent({ - setup() { - const mode = Route.useSearch({ select: (search) => search.mode }) - const greetUserFn = useServerFn(greetUser) - return () => ( -
-

Submit POST FormData Fn Call

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

Submit POST FormData Fn Call

+
+ It should return redirect to /formdata-redirect/target/{testValues.name}{' '} + and greet the user with their name: + +
+            {testValues.name}
+          
+
+
+
{ + if (mode.value === 'js') { + evt.preventDefault() + const data = new FormData(evt.currentTarget as HTMLFormElement) + await greetUserFn({ data }) + } + }} + > + + +
+
+ ) +} diff --git a/e2e/vue-start/server-functions/src/routes/formdata-redirect/target.$name.tsx b/e2e/vue-start/server-functions/src/routes/formdata-redirect/target.$name.tsx index 099a8665bf..958aeaf617 100644 --- a/e2e/vue-start/server-functions/src/routes/formdata-redirect/target.$name.tsx +++ b/e2e/vue-start/server-functions/src/routes/formdata-redirect/target.$name.tsx @@ -1,21 +1,18 @@ -import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' -const RouteComponent = defineComponent({ - setup() { - const params = Route.useParams() - return () => ( -
- Hello{' '} - - {params.value.name} - - ! -
- ) - }, -}) - export const Route = createFileRoute('/formdata-redirect/target/$name')({ component: RouteComponent, }) + +function RouteComponent() { + const params = Route.useParams() + return ( +
+ Hello{' '} + + {params.value.name} + + ! +
+ ) +} diff --git a/e2e/vue-start/server-functions/src/routes/isomorphic-fns.tsx b/e2e/vue-start/server-functions/src/routes/isomorphic-fns.tsx index 8764b558a2..6d0679e34d 100644 --- a/e2e/vue-start/server-functions/src/routes/isomorphic-fns.tsx +++ b/e2e/vue-start/server-functions/src/routes/isomorphic-fns.tsx @@ -13,7 +13,7 @@ const getEcho = createIsomorphicFn() .client((input) => 'client received ' + input) const getServerEcho = createServerFn() - .validator((input: string) => input) + .inputValidator((input: string) => input) .handler(({ data }) => getEcho(data)) const RouteComponent = defineComponent({ diff --git a/e2e/vue-start/server-functions/src/routes/multipart.tsx b/e2e/vue-start/server-functions/src/routes/multipart.tsx index 2157ed3922..c41fd8e4e5 100644 --- a/e2e/vue-start/server-functions/src/routes/multipart.tsx +++ b/e2e/vue-start/server-functions/src/routes/multipart.tsx @@ -3,7 +3,7 @@ import { createServerFn } from '@tanstack/vue-start' import { defineComponent, ref } from 'vue' const multipartFormDataServerFn = createServerFn({ method: 'POST' }) - .validator((x: unknown) => { + .inputValidator((x: unknown) => { if (!(x instanceof FormData)) { throw new Error('Invalid form data') } diff --git a/e2e/vue-start/server-functions/src/routes/primitives/index.tsx b/e2e/vue-start/server-functions/src/routes/primitives/index.tsx index 2f856bb7f3..561f7646eb 100644 --- a/e2e/vue-start/server-functions/src/routes/primitives/index.tsx +++ b/e2e/vue-start/server-functions/src/routes/primitives/index.tsx @@ -9,27 +9,27 @@ function stringify(data: any) { } const $stringPost = createServerFn({ method: 'POST' }) - .validator(z.string()) + .inputValidator(z.string()) .handler((ctx) => ctx.data) const $stringGet = createServerFn({ method: 'GET' }) - .validator(z.string()) + .inputValidator(z.string()) .handler((ctx) => ctx.data) const $undefinedPost = createServerFn({ method: 'POST' }) - .validator(z.undefined()) + .inputValidator(z.undefined()) .handler((ctx) => ctx.data) const $undefinedGet = createServerFn({ method: 'GET' }) - .validator(z.undefined()) + .inputValidator(z.undefined()) .handler((ctx) => ctx.data) const $nullPost = createServerFn({ method: 'POST' }) - .validator(z.null()) + .inputValidator(z.null()) .handler((ctx) => ctx.data) const $nullGet = createServerFn({ method: 'GET' }) - .validator(z.null()) + .inputValidator(z.null()) .handler((ctx) => ctx.data) interface PrimitiveComponentProps { diff --git a/e2e/vue-start/server-functions/src/routes/serialize-form-data.tsx b/e2e/vue-start/server-functions/src/routes/serialize-form-data.tsx index 4aaf8eec60..e2b117a9ad 100644 --- a/e2e/vue-start/server-functions/src/routes/serialize-form-data.tsx +++ b/e2e/vue-start/server-functions/src/routes/serialize-form-data.tsx @@ -11,7 +11,7 @@ const testValues = { } export const greetUser = createServerFn({ method: 'POST' }) - .validator((data: FormData) => { + .inputValidator((data: FormData) => { if (!(data instanceof FormData)) { throw new Error('Invalid! FormData is required') } diff --git a/e2e/vue-start/server-functions/src/routes/submit-post-formdata.tsx b/e2e/vue-start/server-functions/src/routes/submit-post-formdata.tsx index 3bbc85a163..35e083326d 100644 --- a/e2e/vue-start/server-functions/src/routes/submit-post-formdata.tsx +++ b/e2e/vue-start/server-functions/src/routes/submit-post-formdata.tsx @@ -10,7 +10,7 @@ const testValues = { } export const greetUser = createServerFn({ method: 'POST' }) - .validator((data: FormData) => { + .inputValidator((data: FormData) => { if (!(data instanceof FormData)) { throw new Error('Invalid! FormData is required') } diff --git a/e2e/vue-start/server-functions/src/vite-env.d.ts b/e2e/vue-start/server-functions/src/vite-env.d.ts index d0b512cd80..0b2af560d6 100644 --- a/e2e/vue-start/server-functions/src/vite-env.d.ts +++ b/e2e/vue-start/server-functions/src/vite-env.d.ts @@ -1,5 +1,3 @@ -/// - declare module '*?url' { const url: string export default url diff --git a/e2e/vue-start/server-functions/tsconfig.json b/e2e/vue-start/server-functions/tsconfig.json index d5b41741d2..a5ae5ae7e4 100644 --- a/e2e/vue-start/server-functions/tsconfig.json +++ b/e2e/vue-start/server-functions/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/server-functions/vite.config.ts b/e2e/vue-start/server-functions/vite.config.ts index 362cf4e122..d78d02d4c0 100644 --- a/e2e/vue-start/server-functions/vite.config.ts +++ b/e2e/vue-start/server-functions/vite.config.ts @@ -1,4 +1,5 @@ import { defineConfig } from 'vite' +import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' @@ -10,12 +11,14 @@ const FUNCTIONS_WITH_CONSTANT_ID = [ ] export default defineConfig({ - resolve: { tsconfigPaths: true }, server: { port: 3000, }, plugins: [ tailwindcss(), + tsConfigPaths({ + projects: ['./tsconfig.json'], + }), tanstackStart({ serverFns: { generateFunctionId: (opts) => { diff --git a/e2e/vue-start/server-routes/.devcontainer/devcontainer.json b/e2e/vue-start/server-routes/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-start/server-routes/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-start/server-routes/package.json b/e2e/vue-start/server-routes/package.json index 6a8e1babed..45a613a706 100644 --- a/e2e/vue-start/server-routes/package.json +++ b/e2e/vue-start/server-routes/package.json @@ -18,24 +18,24 @@ "@tanstack/vue-router-ssr-query": "workspace:^", "@tanstack/vue-start": "workspace:^", "js-cookie": "^3.0.5", - "redaxios": "catalog:", - "tailwind-merge": "^3.6.0", + "redaxios": "^0.5.1", + "tailwind-merge": "^2.6.0", + "vite": "^7.3.1", "vue": "^3.5.25", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@playwright/test": "^1.61.0", - "@tailwindcss/vite": "^4.2.2", + "@playwright/test": "^1.50.1", + "@tailwindcss/vite": "^4.1.18", "@tanstack/router-e2e-utils": "workspace:^", "@types/js-cookie": "^3.0.6", "@types/node": "^22.10.2", - "@vitejs/plugin-vue": "^6.0.5", - "@vitejs/plugin-vue-jsx": "^5.1.5", "combinate": "^1.1.11", - "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" + "srvx": "^0.11.2", + "tailwindcss": "^4.1.18", + "typescript": "^5.7.2", + "@vitejs/plugin-vue": "^6.0.3", + "@vitejs/plugin-vue-jsx": "^5.1.2", + "vite-tsconfig-paths": "^5.1.4" } } diff --git a/e2e/vue-start/server-routes/playwright.config.ts b/e2e/vue-start/server-routes/playwright.config.ts index 48e14683f4..cb1da03b94 100644 --- a/e2e/vue-start/server-routes/playwright.config.ts +++ b/e2e/vue-start/server-routes/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -export const PORT = Number(process.env.E2E_APP_PORT ?? 0) +export const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/server-routes/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/server-routes/src/components/DefaultCatchBoundary.tsx index 77c03c5afa..b1f818dd74 100644 --- a/e2e/vue-start/server-routes/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/server-routes/src/components/DefaultCatchBoundary.tsx @@ -1,61 +1,53 @@ -import { defineComponent } from 'vue' -import type { PropType } from 'vue' import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -export const DefaultCatchBoundary = defineComponent({ - props: { - error: { - type: Object as PropType, - required: true, - }, - }, - setup(props) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - return () => { - console.error(props.error) - return ( -
- -
- - {isRoot.value ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) - } - }, -}) +export function DefaultCatchBoundary({ error }: ErrorComponentProps) { + const router = useRouter() + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, + }) + + console.error(error) + + return ( +
+ +
+ + {isRoot.value ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
+
+ ) +} diff --git a/e2e/vue-start/server-routes/src/routeTree.gen.ts b/e2e/vue-start/server-routes/src/routeTree.gen.ts index 603560da2a..7d9d463772 100644 --- a/e2e/vue-start/server-routes/src/routeTree.gen.ts +++ b/e2e/vue-start/server-routes/src/routeTree.gen.ts @@ -9,21 +9,16 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' import { Route as MergeMiddlewareContextRouteImport } from './routes/merge-middleware-context' import { Route as MethodsRouteRouteImport } from './routes/methods/route' -import { Route as ApiMiddlewareContextRouteImport } from './routes/api/middleware-context' -import { Route as ApiOnlyAnyRouteImport } from './routes/api/only-any' +import { Route as IndexRouteImport } from './routes/index' import { Route as MethodsIndexRouteImport } from './routes/methods/index' import { Route as MethodsOnlyAnyRouteImport } from './routes/methods/only-any' +import { Route as ApiOnlyAnyRouteImport } from './routes/api/only-any' +import { Route as ApiMiddlewareContextRouteImport } from './routes/api/middleware-context' import { Route as ApiParamsFooRouteRouteImport } from './routes/api/params/$foo/route' import { Route as ApiParamsFooBarRouteImport } from './routes/api/params/$foo/$bar' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const MergeMiddlewareContextRoute = MergeMiddlewareContextRouteImport.update({ id: '/merge-middleware-context', path: '/merge-middleware-context', @@ -34,14 +29,9 @@ const MethodsRouteRoute = MethodsRouteRouteImport.update({ path: '/methods', getParentRoute: () => rootRouteImport, } as any) -const ApiMiddlewareContextRoute = ApiMiddlewareContextRouteImport.update({ - id: '/api/middleware-context', - path: '/api/middleware-context', - getParentRoute: () => rootRouteImport, -} as any) -const ApiOnlyAnyRoute = ApiOnlyAnyRouteImport.update({ - id: '/api/only-any', - path: '/api/only-any', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const MethodsIndexRoute = MethodsIndexRouteImport.update({ @@ -54,6 +44,16 @@ const MethodsOnlyAnyRoute = MethodsOnlyAnyRouteImport.update({ path: '/only-any', getParentRoute: () => MethodsRouteRoute, } as any) +const ApiOnlyAnyRoute = ApiOnlyAnyRouteImport.update({ + id: '/api/only-any', + path: '/api/only-any', + getParentRoute: () => rootRouteImport, +} as any) +const ApiMiddlewareContextRoute = ApiMiddlewareContextRouteImport.update({ + id: '/api/middleware-context', + path: '/api/middleware-context', + getParentRoute: () => rootRouteImport, +} as any) const ApiParamsFooRouteRoute = ApiParamsFooRouteRouteImport.update({ id: '/api/params/$foo', path: '/api/params/$foo', @@ -144,13 +144,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/merge-middleware-context': { id: '/merge-middleware-context' path: '/merge-middleware-context' @@ -165,18 +158,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof MethodsRouteRouteImport parentRoute: typeof rootRouteImport } - '/api/middleware-context': { - id: '/api/middleware-context' - path: '/api/middleware-context' - fullPath: '/api/middleware-context' - preLoaderRoute: typeof ApiMiddlewareContextRouteImport - parentRoute: typeof rootRouteImport - } - '/api/only-any': { - id: '/api/only-any' - path: '/api/only-any' - fullPath: '/api/only-any' - preLoaderRoute: typeof ApiOnlyAnyRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/methods/': { @@ -193,6 +179,20 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof MethodsOnlyAnyRouteImport parentRoute: typeof MethodsRouteRoute } + '/api/only-any': { + id: '/api/only-any' + path: '/api/only-any' + fullPath: '/api/only-any' + preLoaderRoute: typeof ApiOnlyAnyRouteImport + parentRoute: typeof rootRouteImport + } + '/api/middleware-context': { + id: '/api/middleware-context' + path: '/api/middleware-context' + fullPath: '/api/middleware-context' + preLoaderRoute: typeof ApiMiddlewareContextRouteImport + parentRoute: typeof rootRouteImport + } '/api/params/$foo': { id: '/api/params/$foo' path: '/api/params/$foo' diff --git a/e2e/vue-start/server-routes/src/routes/__root.tsx b/e2e/vue-start/server-routes/src/routes/__root.tsx index aa4b1f31fa..999d80fff1 100644 --- a/e2e/vue-start/server-routes/src/routes/__root.tsx +++ b/e2e/vue-start/server-routes/src/routes/__root.tsx @@ -25,11 +25,7 @@ export const Route = createRootRoute({ links: [{ rel: 'stylesheet', href: appCss }], }), errorComponent: (props) => { - return ( -

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

- ) + return

{props.error.stack}

}, notFoundComponent: () => , component: RootComponent, diff --git a/e2e/vue-start/server-routes/src/vite-env.d.ts b/e2e/vue-start/server-routes/src/vite-env.d.ts index d0b512cd80..0b2af560d6 100644 --- a/e2e/vue-start/server-routes/src/vite-env.d.ts +++ b/e2e/vue-start/server-routes/src/vite-env.d.ts @@ -1,5 +1,3 @@ -/// - declare module '*?url' { const url: string export default url diff --git a/e2e/vue-start/server-routes/tsconfig.json b/e2e/vue-start/server-routes/tsconfig.json index d5b41741d2..a5ae5ae7e4 100644 --- a/e2e/vue-start/server-routes/tsconfig.json +++ b/e2e/vue-start/server-routes/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/server-routes/vite.config.ts b/e2e/vue-start/server-routes/vite.config.ts index 563e212077..e0b4a0e909 100644 --- a/e2e/vue-start/server-routes/vite.config.ts +++ b/e2e/vue-start/server-routes/vite.config.ts @@ -1,13 +1,21 @@ import { defineConfig } from 'vite' +import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import tailwindcss from '@tailwindcss/vite' export default defineConfig({ - resolve: { tsconfigPaths: true }, server: { port: 3000, }, - plugins: [tailwindcss(), tanstackStart(), vue(), vueJsx()], + plugins: [ + tailwindcss(), + tsConfigPaths({ + projects: ['./tsconfig.json'], + }), + tanstackStart(), + vue(), + vueJsx(), + ], }) diff --git a/e2e/vue-start/spa-mode/.devcontainer/devcontainer.json b/e2e/vue-start/spa-mode/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-start/spa-mode/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-start/spa-mode/package.json b/e2e/vue-start/spa-mode/package.json index c4270cfccd..7a005ea2a4 100644 --- a/e2e/vue-start/spa-mode/package.json +++ b/e2e/vue-start/spa-mode/package.json @@ -9,23 +9,23 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "npx serve dist/client", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", "vue": "^3.5.25", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@tailwindcss/vite": "^4.2.2", + "@tailwindcss/vite": "^4.1.18", "@tanstack/router-e2e-utils": "workspace:^", - "@vitejs/plugin-vue": "^6.0.5", - "@vitejs/plugin-vue-jsx": "^5.1.5", - "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "tailwindcss": "^4.1.18", + "typescript": "^5.7.2", + "vite": "^7.3.1", + "@vitejs/plugin-vue": "^6.0.3", + "@vitejs/plugin-vue-jsx": "^5.1.2", + "vite-tsconfig-paths": "^5.1.4" } } diff --git a/e2e/vue-start/spa-mode/playwright.config.ts b/e2e/vue-start/spa-mode/playwright.config.ts index 630989e41f..badd6db0eb 100644 --- a/e2e/vue-start/spa-mode/playwright.config.ts +++ b/e2e/vue-start/spa-mode/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/spa-mode/src/routeTree.gen.ts b/e2e/vue-start/spa-mode/src/routeTree.gen.ts index 0d44b648ee..474705b7e7 100644 --- a/e2e/vue-start/spa-mode/src/routeTree.gen.ts +++ b/e2e/vue-start/spa-mode/src/routeTree.gen.ts @@ -9,20 +9,20 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' import { Route as PostsRouteImport } from './routes/posts' +import { Route as IndexRouteImport } from './routes/index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PostsRoute = PostsRouteImport.update({ id: '/posts', path: '/posts', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const PostsPostIdRoute = PostsPostIdRouteImport.update({ id: '/$postId', path: '/$postId', @@ -60,13 +60,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/posts': { id: '/posts' path: '/posts' @@ -74,6 +67,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/posts/$postId': { id: '/posts/$postId' path: '/$postId' diff --git a/e2e/vue-start/spa-mode/src/routes/__root.tsx b/e2e/vue-start/spa-mode/src/routes/__root.tsx index 45aee73c06..1e38664739 100644 --- a/e2e/vue-start/spa-mode/src/routes/__root.tsx +++ b/e2e/vue-start/spa-mode/src/routes/__root.tsx @@ -1,5 +1,4 @@ /// -import { defineComponent } from 'vue' import { Body, ClientOnly, @@ -14,71 +13,6 @@ import { import { TanStackRouterDevtools } from '@tanstack/vue-router-devtools' import appCss from '~/styles/app.css?url' -const RootDocument = defineComponent({ - setup(_, { slots }) { - const routerState = useRouterState({ - select: (state) => ({ isLoading: state.isLoading, status: state.status }), - }) - return () => ( - - - - - -
-

SPA Mode E2E Test

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

root

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

root

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

SPA Mode E2E Test

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

postId

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

postId

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

posts

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

posts

+
+ loader: {loaderData.value.posts} +
+
+ context: {context.value.posts} +
+
+ +
+ ) + }, pendingComponent: () =>
posts Loading...
, }) diff --git a/e2e/vue-start/spa-mode/tests/app.spec.ts b/e2e/vue-start/spa-mode/tests/app.spec.ts index ad437c0353..c18a0ff65d 100644 --- a/e2e/vue-start/spa-mode/tests/app.spec.ts +++ b/e2e/vue-start/spa-mode/tests/app.spec.ts @@ -5,16 +5,9 @@ import type { Page } from '@playwright/test' async function runTest( page: Page, expectedData: { - loader: { - root: 'server' | 'client' - posts: 'server' | 'client' - postId: 'server' | 'client' - } - context: { - root: 'server' | 'client' - posts: 'server' | 'client' - postId: 'server' | 'client' - } + root: 'server' | 'client' + posts: 'server' | 'client' + postId: 'server' | 'client' }, ) { // wait for page to be loaded by waiting for the leaf route to be rendered @@ -22,64 +15,36 @@ async function runTest( // check expectations await Promise.all( - Object.entries(expectedData.loader).map(async ([route, expectedLoader]) => { + Object.entries(expectedData).map(async ([route, expectedData]) => { await expect(page.getByTestId(`${route}-loader`)).toContainText( - expectedLoader, + expectedData, + ) + await expect(page.getByTestId(`${route}-context`)).toContainText( + expectedData, ) }), ) - await Promise.all( - Object.entries(expectedData.context).map( - async ([route, expectedContext]) => { - await expect(page.getByTestId(`${route}-context`)).toContainText( - expectedContext, - ) - }, - ), - ) await expect(page.getByTestId('router-isLoading')).toContainText('false') await expect(page.getByTestId('router-status')).toContainText('idle') } test.describe('SPA mode', () => { - test(`directly visiting prerendered /posts/1`, async ({ - page, - }: { - page: Page - }) => { + test(`directly visiting prerendered /posts/1`, async ({ page }) => { await page.goto('/posts/1') await runTest(page, { - loader: { - root: 'server', - posts: 'server', - postId: 'server', - }, - context: { - root: 'server', - posts: 'server', - postId: 'server', - }, + root: 'server', + posts: 'server', + postId: 'server', }) }) - test(`client-side navigation to /posts/1`, async ({ - page, - }: { - page: Page - }) => { + test(`client-side navigation to /posts/1`, async ({ page }) => { await page.goto('/') const testId = 'link-posts-1' await page.getByTestId(testId).click() await runTest(page, { - loader: { - root: 'server', - posts: 'client', - postId: 'client', - }, - context: { - root: 'client', - posts: 'client', - postId: 'client', - }, + root: 'client', + posts: 'client', + postId: 'client', }) }) }) diff --git a/e2e/vue-start/spa-mode/tsconfig.json b/e2e/vue-start/spa-mode/tsconfig.json index 390dad84c0..f9f5aab3da 100644 --- a/e2e/vue-start/spa-mode/tsconfig.json +++ b/e2e/vue-start/spa-mode/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/spa-mode/vite.config.ts b/e2e/vue-start/spa-mode/vite.config.ts index b0067bba4b..c7c7cc8baa 100644 --- a/e2e/vue-start/spa-mode/vite.config.ts +++ b/e2e/vue-start/spa-mode/vite.config.ts @@ -1,16 +1,19 @@ import { defineConfig } from 'vite' +import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import tailwindcss from '@tailwindcss/vite' export default defineConfig({ - resolve: { tsconfigPaths: true }, server: { port: 3000, }, plugins: [ tailwindcss(), + tsConfigPaths({ + projects: ['./tsconfig.json'], + }), tanstackStart({ spa: { enabled: true, diff --git a/e2e/vue-start/start-manifest/package.json b/e2e/vue-start/start-manifest/package.json deleted file mode 100644 index ae682f7a9d..0000000000 --- a/e2e/vue-start/start-manifest/package.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "tanstack-vue-start-e2e-start-manifest", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "build": "vite build && tsc --noEmit", - "preview": "vite preview", - "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "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-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": { - "test:e2e": { - "parallelism": false - } - } - } -} diff --git a/e2e/vue-start/start-manifest/playwright.config.ts b/e2e/vue-start/start-manifest/playwright.config.ts deleted file mode 100644 index 653e08253f..0000000000 --- a/e2e/vue-start/start-manifest/playwright.config.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' - -const PORT = Number(process.env.E2E_APP_PORT ?? 0) -const baseURL = `http://localhost:${PORT}` - -export default defineConfig({ - testDir: './tests', - workers: 1, - reporter: [['line']], - - use: { - baseURL, - }, - - webServer: { - command: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, - stdout: 'pipe', - }, - - projects: [ - { - name: 'chromium', - use: { ...devices['Desktop Chrome'] }, - }, - ], -}) diff --git a/e2e/vue-start/start-manifest/src/components/AppShell.tsx b/e2e/vue-start/start-manifest/src/components/AppShell.tsx deleted file mode 100644 index 0d57b2d0e3..0000000000 --- a/e2e/vue-start/start-manifest/src/components/AppShell.tsx +++ /dev/null @@ -1,38 +0,0 @@ -/// -import { ClientOnly, Link, Outlet, linkOptions } from '@tanstack/vue-router' -import styles from '~/styles/root-shell.module.css' - -const ROUTES = linkOptions([ - { to: '/', label: 'home' }, - { to: '/a', label: '/a' }, - { to: '/b', label: '/b' }, - { to: '/lazy-css-static', label: '/lazy-css-static' }, - { to: '/lazy-css-lazy', label: '/lazy-css-lazy' }, - { to: '/r1', label: '/r1' }, - { to: '/r2', label: '/r2' }, - { to: '/shared-a', label: '/shared-a' }, -]) - -export function AppShell() { - return ( -
- - -
-
- Start manifest CSS root shell -
- -
hydrated
-
- -
-
- ) -} diff --git a/e2e/vue-start/start-manifest/src/components/SharedCard.tsx b/e2e/vue-start/start-manifest/src/components/SharedCard.tsx deleted file mode 100644 index c82b2b0ea5..0000000000 --- a/e2e/vue-start/start-manifest/src/components/SharedCard.tsx +++ /dev/null @@ -1,10 +0,0 @@ -/// -import styles from '~/styles/shared-card.module.css' - -export function SharedCard({ label }: { label: string }) { - return ( -
- Shared card {label} -
- ) -} diff --git a/e2e/vue-start/start-manifest/src/components/SharedNestedLayout.tsx b/e2e/vue-start/start-manifest/src/components/SharedNestedLayout.tsx deleted file mode 100644 index 9c1f63f2f9..0000000000 --- a/e2e/vue-start/start-manifest/src/components/SharedNestedLayout.tsx +++ /dev/null @@ -1,34 +0,0 @@ -/// -import { Link, linkOptions } from '@tanstack/vue-router' -import { defineComponent } from 'vue' -import styles from '~/styles/shared-layout.module.css' - -const ROUTES = linkOptions([ - { to: '/shared-a', label: '/shared-a' }, - { to: '/shared-b', label: '/shared-b' }, - { to: '/shared-c', label: '/shared-c' }, -]) - -export const SharedNestedLayout = defineComponent({ - setup(_, { slots }) { - return () => ( -
-
- Shared nested layout CSS -
- - - -
- {slots.default?.()} -
-
- ) - }, -}) diff --git a/e2e/vue-start/start-manifest/src/components/SharedWidget.tsx b/e2e/vue-start/start-manifest/src/components/SharedWidget.tsx deleted file mode 100644 index 9074d5b2b0..0000000000 --- a/e2e/vue-start/start-manifest/src/components/SharedWidget.tsx +++ /dev/null @@ -1,15 +0,0 @@ -/// -import styles from '~/styles/shared-widget.module.css' - -export function SharedWidget() { - return ( -
-
- Shared widget styles -
-
- This widget uses CSS shared by a static route and a lazy route. -
-
- ) -} diff --git a/e2e/vue-start/start-manifest/src/components/SharedWidgetLazy.tsx b/e2e/vue-start/start-manifest/src/components/SharedWidgetLazy.tsx deleted file mode 100644 index 5f1f6410a5..0000000000 --- a/e2e/vue-start/start-manifest/src/components/SharedWidgetLazy.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { SharedWidget } from './SharedWidget' - -export default function SharedWidgetLazy() { - return -} diff --git a/e2e/vue-start/start-manifest/src/routeTree.gen.ts b/e2e/vue-start/start-manifest/src/routeTree.gen.ts deleted file mode 100644 index fc42a1e404..0000000000 --- a/e2e/vue-start/start-manifest/src/routeTree.gen.ts +++ /dev/null @@ -1,345 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as ARouteImport } from './routes/a' -import { Route as BRouteImport } from './routes/b' -import { Route as LazyCssLazyRouteImport } from './routes/lazy-css-lazy' -import { Route as LazyCssStaticRouteImport } from './routes/lazy-css-static' -import { Route as R1RouteImport } from './routes/r1' -import { Route as R2RouteImport } from './routes/r2' -import { Route as R3RouteImport } from './routes/r3' -import { Route as R4RouteImport } from './routes/r4' -import { Route as R5RouteImport } from './routes/r5' -import { Route as R6RouteImport } from './routes/r6' -import { Route as SharedARouteImport } from './routes/shared-a' -import { Route as SharedBRouteImport } from './routes/shared-b' -import { Route as SharedCRouteImport } from './routes/shared-c' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ARoute = ARouteImport.update({ - id: '/a', - path: '/a', - getParentRoute: () => rootRouteImport, -} as any) -const BRoute = BRouteImport.update({ - id: '/b', - path: '/b', - getParentRoute: () => rootRouteImport, -} as any) -const LazyCssLazyRoute = LazyCssLazyRouteImport.update({ - id: '/lazy-css-lazy', - path: '/lazy-css-lazy', - getParentRoute: () => rootRouteImport, -} as any) -const LazyCssStaticRoute = LazyCssStaticRouteImport.update({ - id: '/lazy-css-static', - path: '/lazy-css-static', - getParentRoute: () => rootRouteImport, -} as any) -const R1Route = R1RouteImport.update({ - id: '/r1', - path: '/r1', - getParentRoute: () => rootRouteImport, -} as any) -const R2Route = R2RouteImport.update({ - id: '/r2', - path: '/r2', - getParentRoute: () => rootRouteImport, -} as any) -const R3Route = R3RouteImport.update({ - id: '/r3', - path: '/r3', - getParentRoute: () => rootRouteImport, -} as any) -const R4Route = R4RouteImport.update({ - id: '/r4', - path: '/r4', - getParentRoute: () => rootRouteImport, -} as any) -const R5Route = R5RouteImport.update({ - id: '/r5', - path: '/r5', - getParentRoute: () => rootRouteImport, -} as any) -const R6Route = R6RouteImport.update({ - id: '/r6', - path: '/r6', - getParentRoute: () => rootRouteImport, -} as any) -const SharedARoute = SharedARouteImport.update({ - id: '/shared-a', - path: '/shared-a', - getParentRoute: () => rootRouteImport, -} as any) -const SharedBRoute = SharedBRouteImport.update({ - id: '/shared-b', - path: '/shared-b', - getParentRoute: () => rootRouteImport, -} as any) -const SharedCRoute = SharedCRouteImport.update({ - id: '/shared-c', - path: '/shared-c', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/a': typeof ARoute - '/b': typeof BRoute - '/lazy-css-lazy': typeof LazyCssLazyRoute - '/lazy-css-static': typeof LazyCssStaticRoute - '/r1': typeof R1Route - '/r2': typeof R2Route - '/r3': typeof R3Route - '/r4': typeof R4Route - '/r5': typeof R5Route - '/r6': typeof R6Route - '/shared-a': typeof SharedARoute - '/shared-b': typeof SharedBRoute - '/shared-c': typeof SharedCRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/a': typeof ARoute - '/b': typeof BRoute - '/lazy-css-lazy': typeof LazyCssLazyRoute - '/lazy-css-static': typeof LazyCssStaticRoute - '/r1': typeof R1Route - '/r2': typeof R2Route - '/r3': typeof R3Route - '/r4': typeof R4Route - '/r5': typeof R5Route - '/r6': typeof R6Route - '/shared-a': typeof SharedARoute - '/shared-b': typeof SharedBRoute - '/shared-c': typeof SharedCRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/a': typeof ARoute - '/b': typeof BRoute - '/lazy-css-lazy': typeof LazyCssLazyRoute - '/lazy-css-static': typeof LazyCssStaticRoute - '/r1': typeof R1Route - '/r2': typeof R2Route - '/r3': typeof R3Route - '/r4': typeof R4Route - '/r5': typeof R5Route - '/r6': typeof R6Route - '/shared-a': typeof SharedARoute - '/shared-b': typeof SharedBRoute - '/shared-c': typeof SharedCRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/a' - | '/b' - | '/lazy-css-lazy' - | '/lazy-css-static' - | '/r1' - | '/r2' - | '/r3' - | '/r4' - | '/r5' - | '/r6' - | '/shared-a' - | '/shared-b' - | '/shared-c' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/a' - | '/b' - | '/lazy-css-lazy' - | '/lazy-css-static' - | '/r1' - | '/r2' - | '/r3' - | '/r4' - | '/r5' - | '/r6' - | '/shared-a' - | '/shared-b' - | '/shared-c' - id: - | '__root__' - | '/' - | '/a' - | '/b' - | '/lazy-css-lazy' - | '/lazy-css-static' - | '/r1' - | '/r2' - | '/r3' - | '/r4' - | '/r5' - | '/r6' - | '/shared-a' - | '/shared-b' - | '/shared-c' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ARoute: typeof ARoute - BRoute: typeof BRoute - LazyCssLazyRoute: typeof LazyCssLazyRoute - LazyCssStaticRoute: typeof LazyCssStaticRoute - R1Route: typeof R1Route - R2Route: typeof R2Route - R3Route: typeof R3Route - R4Route: typeof R4Route - R5Route: typeof R5Route - R6Route: typeof R6Route - SharedARoute: typeof SharedARoute - SharedBRoute: typeof SharedBRoute - SharedCRoute: typeof SharedCRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/a': { - id: '/a' - path: '/a' - fullPath: '/a' - preLoaderRoute: typeof ARouteImport - parentRoute: typeof rootRouteImport - } - '/b': { - id: '/b' - path: '/b' - fullPath: '/b' - preLoaderRoute: typeof BRouteImport - parentRoute: typeof rootRouteImport - } - '/lazy-css-lazy': { - id: '/lazy-css-lazy' - path: '/lazy-css-lazy' - fullPath: '/lazy-css-lazy' - preLoaderRoute: typeof LazyCssLazyRouteImport - parentRoute: typeof rootRouteImport - } - '/lazy-css-static': { - id: '/lazy-css-static' - path: '/lazy-css-static' - fullPath: '/lazy-css-static' - preLoaderRoute: typeof LazyCssStaticRouteImport - parentRoute: typeof rootRouteImport - } - '/r1': { - id: '/r1' - path: '/r1' - fullPath: '/r1' - preLoaderRoute: typeof R1RouteImport - parentRoute: typeof rootRouteImport - } - '/r2': { - id: '/r2' - path: '/r2' - fullPath: '/r2' - preLoaderRoute: typeof R2RouteImport - parentRoute: typeof rootRouteImport - } - '/r3': { - id: '/r3' - path: '/r3' - fullPath: '/r3' - preLoaderRoute: typeof R3RouteImport - parentRoute: typeof rootRouteImport - } - '/r4': { - id: '/r4' - path: '/r4' - fullPath: '/r4' - preLoaderRoute: typeof R4RouteImport - parentRoute: typeof rootRouteImport - } - '/r5': { - id: '/r5' - path: '/r5' - fullPath: '/r5' - preLoaderRoute: typeof R5RouteImport - parentRoute: typeof rootRouteImport - } - '/r6': { - id: '/r6' - path: '/r6' - fullPath: '/r6' - preLoaderRoute: typeof R6RouteImport - parentRoute: typeof rootRouteImport - } - '/shared-a': { - id: '/shared-a' - path: '/shared-a' - fullPath: '/shared-a' - preLoaderRoute: typeof SharedARouteImport - parentRoute: typeof rootRouteImport - } - '/shared-b': { - id: '/shared-b' - path: '/shared-b' - fullPath: '/shared-b' - preLoaderRoute: typeof SharedBRouteImport - parentRoute: typeof rootRouteImport - } - '/shared-c': { - id: '/shared-c' - path: '/shared-c' - fullPath: '/shared-c' - preLoaderRoute: typeof SharedCRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ARoute: ARoute, - BRoute: BRoute, - LazyCssLazyRoute: LazyCssLazyRoute, - LazyCssStaticRoute: LazyCssStaticRoute, - R1Route: R1Route, - R2Route: R2Route, - R3Route: R3Route, - R4Route: R4Route, - R5Route: R5Route, - R6Route: R6Route, - SharedARoute: SharedARoute, - SharedBRoute: SharedBRoute, - SharedCRoute: SharedCRoute, -} -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/start-manifest/src/router.tsx b/e2e/vue-start/start-manifest/src/router.tsx deleted file mode 100644 index d7cd8e8284..0000000000 --- a/e2e/vue-start/start-manifest/src/router.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { createRouter } from '@tanstack/vue-router' -import { routeTree } from './routeTree.gen' - -export const getRouter = () => { - const router = createRouter({ - routeTree, - scrollRestoration: true, - defaultPreload: 'intent', - }) - - return router -} - -declare module '@tanstack/vue-router' { - interface Register { - router: ReturnType - } -} diff --git a/e2e/vue-start/start-manifest/src/routes/__root.tsx b/e2e/vue-start/start-manifest/src/routes/__root.tsx deleted file mode 100644 index b62d37c0f0..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/__root.tsx +++ /dev/null @@ -1,35 +0,0 @@ -/// -import { - Body, - HeadContent, - Html, - Scripts, - createRootRoute, -} from '@tanstack/vue-router' -import { AppShell } from '~/components/AppShell' - -export const Route = createRootRoute({ - head: () => ({ - meta: [ - { charSet: 'utf-8' }, - { name: 'viewport', content: 'width=device-width, initial-scale=1' }, - { title: 'TanStack Start Manifest Bloat E2E' }, - ], - }), - component: AppShell, - shellComponent: RootDocument, -}) - -function RootDocument(_: unknown, { slots }: { slots: any }) { - return ( - - - - - - {slots.default?.()} - - - - ) -} diff --git a/e2e/vue-start/start-manifest/src/routes/a.tsx b/e2e/vue-start/start-manifest/src/routes/a.tsx deleted file mode 100644 index e53399273d..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/a.tsx +++ /dev/null @@ -1,18 +0,0 @@ -/// -import { createFileRoute } from '@tanstack/vue-router' -import { SharedCard } from '~/components/SharedCard' -import styles from '~/styles/page-a.module.css' - -export const Route = createFileRoute('/a')({ - component: RouteComponent, -}) - -function RouteComponent() { - return ( -
-

Route /a

-

Route /a keeps the shared card styled.

- -
- ) -} diff --git a/e2e/vue-start/start-manifest/src/routes/b.tsx b/e2e/vue-start/start-manifest/src/routes/b.tsx deleted file mode 100644 index cb989a257f..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/b.tsx +++ /dev/null @@ -1,18 +0,0 @@ -/// -import { createFileRoute } from '@tanstack/vue-router' -import { SharedCard } from '~/components/SharedCard' -import styles from '~/styles/page-b.module.css' - -export const Route = createFileRoute('/b')({ - component: RouteComponent, -}) - -function RouteComponent() { - return ( -
-

Route /b

-

Route /b should keep the shared card stylesheet after nav.

- -
- ) -} diff --git a/e2e/vue-start/start-manifest/src/routes/index.tsx b/e2e/vue-start/start-manifest/src/routes/index.tsx deleted file mode 100644 index 728cc55e88..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/index.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' - -export const Route = createFileRoute('/')({ - component: HomeRoute, -}) - -function HomeRoute() { - return ( -
-

Start manifest fixture

-

- Use this page to navigate between CSS module routes. -

-
- ) -} diff --git a/e2e/vue-start/start-manifest/src/routes/lazy-css-lazy.tsx b/e2e/vue-start/start-manifest/src/routes/lazy-css-lazy.tsx deleted file mode 100644 index 0db0845425..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/lazy-css-lazy.tsx +++ /dev/null @@ -1,31 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' -import { Suspense, defineAsyncComponent } from 'vue' - -const LazySharedWidget = defineAsyncComponent( - () => import('~/components/SharedWidgetLazy'), -) - -export const Route = createFileRoute('/lazy-css-lazy')({ - component: LazyCssLazyRoute, -}) - -function LazyCssLazyRoute() { - return ( -
-

Lazy CSS Repro - Lazy Route

-

- This route renders the same widget through a lazy component so the CSS - only exists behind a dynamic import boundary. -

- - - {{ - default: () => , - fallback: () => ( -
Loading...
- ), - }} -
-
- ) -} diff --git a/e2e/vue-start/start-manifest/src/routes/lazy-css-static.tsx b/e2e/vue-start/start-manifest/src/routes/lazy-css-static.tsx deleted file mode 100644 index 2a8352e67e..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/lazy-css-static.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { ClientOnly, createFileRoute } from '@tanstack/vue-router' -import { SharedWidget } from '~/components/SharedWidget' - -export const Route = createFileRoute('/lazy-css-static')({ - component: LazyCssStaticRoute, -}) - -function LazyCssStaticRoute() { - return ( -
-

Lazy CSS Repro - Static Route

-

- This route statically imports the shared widget so its CSS is present in - the SSR head. -

- - -
hydrated
-
- - -
- ) -} diff --git a/e2e/vue-start/start-manifest/src/routes/r1.tsx b/e2e/vue-start/start-manifest/src/routes/r1.tsx deleted file mode 100644 index b35bec54e3..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/r1.tsx +++ /dev/null @@ -1,18 +0,0 @@ -/// -import { createFileRoute } from '@tanstack/vue-router' -import styles from '~/styles/route-one.module.css' - -export const Route = createFileRoute('/r1')({ - component: RouteComponent, -}) - -function RouteComponent() { - return ( -
-

Route /r1

-
- Route /r1 CSS module styling -
-
- ) -} diff --git a/e2e/vue-start/start-manifest/src/routes/r2.tsx b/e2e/vue-start/start-manifest/src/routes/r2.tsx deleted file mode 100644 index eadd952f98..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/r2.tsx +++ /dev/null @@ -1,18 +0,0 @@ -/// -import { createFileRoute } from '@tanstack/vue-router' -import styles from '~/styles/route-two.module.css' - -export const Route = createFileRoute('/r2')({ - component: RouteComponent, -}) - -function RouteComponent() { - return ( -
-

Route /r2

-
- Route /r2 CSS module styling -
-
- ) -} diff --git a/e2e/vue-start/start-manifest/src/routes/r3.tsx b/e2e/vue-start/start-manifest/src/routes/r3.tsx deleted file mode 100644 index a5a486cfaa..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/r3.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' - -export const Route = createFileRoute('/r3')({ - component: () =>
Route /r3
, -}) diff --git a/e2e/vue-start/start-manifest/src/routes/r4.tsx b/e2e/vue-start/start-manifest/src/routes/r4.tsx deleted file mode 100644 index 9739966d02..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/r4.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' - -export const Route = createFileRoute('/r4')({ - component: () =>
Route /r4
, -}) diff --git a/e2e/vue-start/start-manifest/src/routes/r5.tsx b/e2e/vue-start/start-manifest/src/routes/r5.tsx deleted file mode 100644 index 7c081e29a6..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/r5.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' - -export const Route = createFileRoute('/r5')({ - component: () =>
Route /r5
, -}) diff --git a/e2e/vue-start/start-manifest/src/routes/r6.tsx b/e2e/vue-start/start-manifest/src/routes/r6.tsx deleted file mode 100644 index c56c2afda3..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/r6.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' - -export const Route = createFileRoute('/r6')({ - component: () =>
Route /r6
, -}) diff --git a/e2e/vue-start/start-manifest/src/routes/shared-a.tsx b/e2e/vue-start/start-manifest/src/routes/shared-a.tsx deleted file mode 100644 index e7253a94ac..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/shared-a.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' -import { SharedNestedLayout } from '~/components/SharedNestedLayout' - -export const Route = createFileRoute('/shared-a')({ - component: RouteComponent, -}) - -function RouteComponent() { - return ( - -
Shared route A
-
- ) -} diff --git a/e2e/vue-start/start-manifest/src/routes/shared-b.tsx b/e2e/vue-start/start-manifest/src/routes/shared-b.tsx deleted file mode 100644 index ed02b3429b..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/shared-b.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' -import { SharedNestedLayout } from '~/components/SharedNestedLayout' - -export const Route = createFileRoute('/shared-b')({ - component: RouteComponent, -}) - -function RouteComponent() { - return ( - -
Shared route B
-
- ) -} diff --git a/e2e/vue-start/start-manifest/src/routes/shared-c.tsx b/e2e/vue-start/start-manifest/src/routes/shared-c.tsx deleted file mode 100644 index e395b33ed5..0000000000 --- a/e2e/vue-start/start-manifest/src/routes/shared-c.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' -import { SharedNestedLayout } from '~/components/SharedNestedLayout' - -export const Route = createFileRoute('/shared-c')({ - component: RouteComponent, -}) - -function RouteComponent() { - return ( - -
Shared route C
-
- ) -} diff --git a/e2e/vue-start/start-manifest/src/styles/page-a.module.css b/e2e/vue-start/start-manifest/src/styles/page-a.module.css deleted file mode 100644 index 7ed4301097..0000000000 --- a/e2e/vue-start/start-manifest/src/styles/page-a.module.css +++ /dev/null @@ -1,10 +0,0 @@ -.page { - padding: 1rem; - min-height: 12rem; - background: rgb(240, 253, 244); - border: 4px solid rgb(22, 163, 74); -} - -.title { - color: rgb(21, 128, 61); -} diff --git a/e2e/vue-start/start-manifest/src/styles/page-b.module.css b/e2e/vue-start/start-manifest/src/styles/page-b.module.css deleted file mode 100644 index 93d1d39a01..0000000000 --- a/e2e/vue-start/start-manifest/src/styles/page-b.module.css +++ /dev/null @@ -1,10 +0,0 @@ -.page { - padding: 1rem; - min-height: 12rem; - background: rgb(239, 246, 255); - border: 4px solid rgb(37, 99, 235); -} - -.title { - color: rgb(29, 78, 216); -} diff --git a/e2e/vue-start/start-manifest/src/styles/root-shell.module.css b/e2e/vue-start/start-manifest/src/styles/root-shell.module.css deleted file mode 100644 index e7bece8664..0000000000 --- a/e2e/vue-start/start-manifest/src/styles/root-shell.module.css +++ /dev/null @@ -1,37 +0,0 @@ -.shell { - font-family: - -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; - min-height: 100vh; - background: rgb(248, 250, 252); - color: rgb(15, 23, 42); -} - -.nav { - display: flex; - flex-wrap: wrap; - gap: 0.75rem; - padding: 1rem; - border-bottom: 1px solid rgb(226, 232, 240); - background: white; -} - -.nav a { - color: rgb(37, 99, 235); - text-decoration: none; -} - -.content { - max-width: 760px; - margin: 0 auto; - padding: 1.5rem 1rem 3rem; -} - -.rootBadge { - display: inline-block; - margin-bottom: 1rem; - padding: 0.375rem 0.75rem; - border-radius: 9999px; - background: rgb(220, 252, 231); - color: rgb(22, 101, 52); - font-weight: 700; -} diff --git a/e2e/vue-start/start-manifest/src/styles/route-one.module.css b/e2e/vue-start/start-manifest/src/styles/route-one.module.css deleted file mode 100644 index 623d03e6a3..0000000000 --- a/e2e/vue-start/start-manifest/src/styles/route-one.module.css +++ /dev/null @@ -1,7 +0,0 @@ -.card { - padding: 1rem; - border-radius: 0.75rem; - background: rgb(239, 246, 255); - color: rgb(30, 64, 175); - border: 2px solid rgb(96, 165, 250); -} diff --git a/e2e/vue-start/start-manifest/src/styles/route-two.module.css b/e2e/vue-start/start-manifest/src/styles/route-two.module.css deleted file mode 100644 index 66ed355711..0000000000 --- a/e2e/vue-start/start-manifest/src/styles/route-two.module.css +++ /dev/null @@ -1,7 +0,0 @@ -.card { - padding: 1rem; - border-radius: 0.75rem; - background: rgb(250, 245, 255); - color: rgb(126, 34, 206); - border: 2px solid rgb(192, 132, 252); -} diff --git a/e2e/vue-start/start-manifest/src/styles/shared-card.module.css b/e2e/vue-start/start-manifest/src/styles/shared-card.module.css deleted file mode 100644 index 2aa5a6ac17..0000000000 --- a/e2e/vue-start/start-manifest/src/styles/shared-card.module.css +++ /dev/null @@ -1,8 +0,0 @@ -.card { - margin-top: 1rem; - padding: 1.5rem; - border-radius: 0.75rem; - background: rgb(252, 231, 243); - border: 2px solid rgb(190, 24, 93); - color: rgb(157, 23, 77); -} diff --git a/e2e/vue-start/start-manifest/src/styles/shared-layout.module.css b/e2e/vue-start/start-manifest/src/styles/shared-layout.module.css deleted file mode 100644 index 6025a1da06..0000000000 --- a/e2e/vue-start/start-manifest/src/styles/shared-layout.module.css +++ /dev/null @@ -1,16 +0,0 @@ -.layout { - padding: 1rem; - border-radius: 0.75rem; - background: rgb(255, 251, 235); - border: 2px solid rgb(245, 158, 11); -} - -.heading { - color: rgb(180, 83, 9); - font-weight: 700; - margin-bottom: 0.5rem; -} - -.body { - color: rgb(146, 64, 14); -} diff --git a/e2e/vue-start/start-manifest/src/styles/shared-widget.module.css b/e2e/vue-start/start-manifest/src/styles/shared-widget.module.css deleted file mode 100644 index ed197cddb0..0000000000 --- a/e2e/vue-start/start-manifest/src/styles/shared-widget.module.css +++ /dev/null @@ -1,17 +0,0 @@ -.widget { - margin-top: 1rem; - padding: 1rem; - border-top: 4px solid rgb(249, 115, 22); - border-radius: 0.75rem; - background: rgb(255, 247, 237); -} - -.title { - font-weight: 700; - color: rgb(154, 52, 18); -} - -.content { - margin-top: 0.5rem; - color: rgb(124, 45, 18); -} diff --git a/e2e/vue-start/start-manifest/tests/start-manifest.spec.ts b/e2e/vue-start/start-manifest/tests/start-manifest.spec.ts deleted file mode 100644 index 4d5bea0a33..0000000000 --- a/e2e/vue-start/start-manifest/tests/start-manifest.spec.ts +++ /dev/null @@ -1,449 +0,0 @@ -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' -import type { Page } from '@playwright/test' -import { readdir } from 'node:fs/promises' -import path from 'node:path' -import { pathToFileURL } from 'node:url' - -const ROOT_SHELL_COLOR = 'rgb(22, 101, 52)' -const ROUTE_ONE_COLOR = 'rgb(30, 64, 175)' -const ROUTE_TWO_COLOR = 'rgb(126, 34, 206)' -const SHARED_CARD_BG = 'rgb(252, 231, 243)' -const SHARED_WIDGET_BG = 'rgb(255, 247, 237)' -const SHARED_WIDGET_BORDER = 'rgb(249, 115, 22)' - -const buildUrl = (baseURL: string, pathname: string) => - baseURL.replace(/\/$/, '') + pathname - -async function getColor(testId: string, page: Page) { - return page - .getByTestId(testId) - .evaluate((element) => getComputedStyle(element).color) -} - -async function getBackgroundColor(testId: string, page: Page) { - return page - .getByTestId(testId) - .evaluate((element) => getComputedStyle(element).backgroundColor) -} - -function getStylesheetHrefsFromHtml(html: string) { - return Array.from( - html.matchAll(/]+rel="stylesheet"[^>]+href="([^"]+)"/g), - (match) => match[1]!, - ) -} - -async function getHeadStylesheetHrefs(page: Page) { - return page.locator('head link[rel="stylesheet"]').evaluateAll((links) => { - return links.map( - (link) => (link as HTMLLinkElement).getAttribute('href') || '', - ) - }) -} - -function hasMatchingStylesheetHref(hrefs: Array, pattern: string) { - return hrefs.some((href) => href.includes(pattern)) -} - -function countMatchingStylesheetHrefs(hrefs: Array, pattern: string) { - return hrefs.filter((href) => href.includes(pattern)).length -} - -async function loadBuiltStartManifest() { - const serverDir = path.resolve(import.meta.dirname, '../dist/server/assets') - const entries = await readdir(serverDir) - const manifestFile = entries.find( - (entry) => - entry.startsWith('_tanstack-start-manifest_v-') && entry.endsWith('.js'), - ) - - expect(manifestFile).toBeTruthy() - - const moduleUrl = `${pathToFileURL(path.join(serverDir, manifestFile!)).href}?t=${Date.now()}` - const manifestModule = await import(moduleUrl) - - return manifestModule.tsrStartManifest() as { - routes: Record }> - } -} - -async function expectDirectEntry({ - page, - request, - baseURL, - pathname, - expectedVisibleTestId, - expectedAbsentTestId, - expectedStylesheetPattern, - unexpectedStylesheetPattern, - expectedColorTestId, - expectedColor, -}: { - page: Page - request: { - get: (url: string) => Promise<{ ok(): boolean; text(): Promise }> - } - baseURL: string - pathname: string - expectedVisibleTestId: string - expectedAbsentTestId: string - expectedStylesheetPattern: string - unexpectedStylesheetPattern: string - expectedColorTestId: string - expectedColor: string -}) { - const url = buildUrl(baseURL, pathname) - const response = await request.get(url) - const ssrHtml = await response.text() - - expect(response.ok()).toBe(true) - expect(ssrHtml).toContain('root-shell-marker') - expect(ssrHtml).toContain(expectedVisibleTestId) - expect(ssrHtml).not.toContain(expectedAbsentTestId) - - const stylesheetLinks = getStylesheetHrefsFromHtml(ssrHtml) - - expect( - countMatchingStylesheetHrefs(stylesheetLinks, expectedStylesheetPattern), - ).toBe(1) - expect( - countMatchingStylesheetHrefs(stylesheetLinks, unexpectedStylesheetPattern), - ).toBe(0) - expect(stylesheetLinks).toHaveLength(2) - - await page.goto(url) - await expect(page.getByTestId(expectedVisibleTestId)).toBeVisible() - await expect(page.getByTestId('hydration-marker')).toBeVisible() - - await expect - .poll(async () => { - const hrefs = await getHeadStylesheetHrefs(page) - return countMatchingStylesheetHrefs(hrefs, expectedStylesheetPattern) - }) - .toBe(1) - await expect - .poll(async () => { - const hrefs = await getHeadStylesheetHrefs(page) - return countMatchingStylesheetHrefs(hrefs, unexpectedStylesheetPattern) - }) - .toBe(0) - await expect - .poll(async () => { - const hrefs = await getHeadStylesheetHrefs(page) - return hrefs.length - }) - .toBe(2) - - await expect - .poll(() => getColor('root-shell-marker', page)) - .toBe(ROOT_SHELL_COLOR) - await expect - .poll(() => getColor(expectedColorTestId, page)) - .toBe(expectedColor) -} - -test('SSR and client navigation keep CSS module styles correct without hydration errors', async ({ - page, - baseURL, - request, -}) => { - const routeOneUrl = buildUrl(baseURL!, '/r1') - const response = await request.get(routeOneUrl) - const ssrHtml = await response.text() - - expect(response.ok()).toBe(true) - expect(ssrHtml).toContain('root-shell-marker') - expect(ssrHtml).toContain('route-r1-card') - expect(ssrHtml).not.toContain('route-r2-card') - - const stylesheetLinks = getStylesheetHrefsFromHtml(ssrHtml) - - expect(countMatchingStylesheetHrefs(stylesheetLinks, 'r1-')).toBe(1) - expect(countMatchingStylesheetHrefs(stylesheetLinks, 'r2-')).toBe(0) - expect(stylesheetLinks).toHaveLength(2) - - await page.goto(routeOneUrl) - - await expect(page.getByTestId('route-r1-card')).toBeVisible() - await expect(page.getByTestId('hydration-marker')).toBeVisible() - - await expect - .poll(async () => { - const hrefs = await getHeadStylesheetHrefs(page) - return hasMatchingStylesheetHref(hrefs, 'r1-') - }) - .toBe(true) - await expect - .poll(async () => { - const hrefs = await getHeadStylesheetHrefs(page) - return countMatchingStylesheetHrefs(hrefs, 'r2-') - }) - .toBe(0) - - await expect - .poll(() => getColor('root-shell-marker', page)) - .toBe(ROOT_SHELL_COLOR) - await expect.poll(() => getColor('route-r1-card', page)).toBe(ROUTE_ONE_COLOR) - - await page.getByTestId('nav-/r2').click() - await page.waitForURL('**/r2') - await expect(page.getByTestId('route-r2-card')).toBeVisible() - - await expect - .poll(async () => { - const hrefs = await getHeadStylesheetHrefs(page) - return hasMatchingStylesheetHref(hrefs, 'r2-') - }) - .toBe(true) - - await expect - .poll(() => getColor('root-shell-marker', page)) - .toBe(ROOT_SHELL_COLOR) - await expect.poll(() => getColor('route-r2-card', page)).toBe(ROUTE_TWO_COLOR) - - await page.getByTestId('nav-/r1').click() - await page.waitForURL('**/r1') - await expect(page.getByTestId('route-r1-card')).toBeVisible() - - await expect - .poll(async () => { - const hrefs = await getHeadStylesheetHrefs(page) - return hasMatchingStylesheetHref(hrefs, 'r1-') - }) - .toBe(true) - - await expect - .poll(() => getColor('root-shell-marker', page)) - .toBe(ROOT_SHELL_COLOR) - await expect.poll(() => getColor('route-r1-card', page)).toBe(ROUTE_ONE_COLOR) -}) - -test('direct SSR entry on /r2 only includes its stylesheet and hydrates cleanly', async ({ - page, - baseURL, - request, -}) => { - await expectDirectEntry({ - page, - request, - baseURL: baseURL!, - pathname: '/r2', - expectedVisibleTestId: 'route-r2-card', - expectedAbsentTestId: 'route-r1-card', - expectedStylesheetPattern: 'r2-', - unexpectedStylesheetPattern: 'r1-', - expectedColorTestId: 'route-r2-card', - expectedColor: ROUTE_TWO_COLOR, - }) -}) - -test('direct SSR entries on different route-css pages stay isolated', async ({ - page, - baseURL, - request, -}) => { - await expectDirectEntry({ - page, - request, - baseURL: baseURL!, - pathname: '/r2', - expectedVisibleTestId: 'route-r2-card', - expectedAbsentTestId: 'route-r1-card', - expectedStylesheetPattern: 'r2-', - unexpectedStylesheetPattern: 'r1-', - expectedColorTestId: 'route-r2-card', - expectedColor: ROUTE_TWO_COLOR, - }) - - await expectDirectEntry({ - page, - request, - baseURL: baseURL!, - pathname: '/r1', - expectedVisibleTestId: 'route-r1-card', - expectedAbsentTestId: 'route-r2-card', - expectedStylesheetPattern: 'r1-', - unexpectedStylesheetPattern: 'r2-', - expectedColorTestId: 'route-r1-card', - expectedColor: ROUTE_ONE_COLOR, - }) -}) - -test('home route only renders the root stylesheet and no route-specific CSS', async ({ - page, - baseURL, - request, -}) => { - const homeUrl = buildUrl(baseURL!, '/') - const response = await request.get(homeUrl) - const ssrHtml = await response.text() - - expect(response.ok()).toBe(true) - expect(ssrHtml).toContain('root-shell-marker') - expect(ssrHtml).toContain('home-copy') - expect(ssrHtml).not.toContain('route-r1-card') - expect(ssrHtml).not.toContain('route-r2-card') - - const stylesheetLinks = getStylesheetHrefsFromHtml(ssrHtml) - - expect(countMatchingStylesheetHrefs(stylesheetLinks, 'r1-')).toBe(0) - expect(countMatchingStylesheetHrefs(stylesheetLinks, 'r2-')).toBe(0) - expect(stylesheetLinks).toHaveLength(1) - - await page.goto(homeUrl) - await expect(page.getByTestId('home-copy')).toBeVisible() - await expect(page.getByTestId('hydration-marker')).toBeVisible() - - await expect - .poll(async () => { - const hrefs = await getHeadStylesheetHrefs(page) - return countMatchingStylesheetHrefs(hrefs, 'r1-') - }) - .toBe(0) - await expect - .poll(async () => { - const hrefs = await getHeadStylesheetHrefs(page) - return countMatchingStylesheetHrefs(hrefs, 'r2-') - }) - .toBe(0) - await expect - .poll(async () => { - const hrefs = await getHeadStylesheetHrefs(page) - return hrefs.length - }) - .toBe(1) - - await expect - .poll(() => getColor('root-shell-marker', page)) - .toBe(ROOT_SHELL_COLOR) -}) - -test('built start manifest preserves shared layout asset identity across sibling routes', async ({ - page, - baseURL, -}) => { - await page.goto(buildUrl(baseURL!, '/shared-a')) - await expect(page.getByTestId('shared-a-card')).toBeVisible() - - const manifest = await loadBuiltStartManifest() - - const sharedAAsset = manifest.routes['/shared-a']?.css?.[0] - const sharedBAsset = manifest.routes['/shared-b']?.css?.[0] - const sharedCAsset = manifest.routes['/shared-c']?.css?.[0] - - expect(sharedAAsset).toBeTruthy() - expect(sharedAAsset).toBe(sharedBAsset) - expect(sharedBAsset).toBe(sharedCAsset) -}) - -test('shared CSS chunk persists across client-side nav', async ({ - page, - baseURL, -}) => { - await page.goto(buildUrl(baseURL!, '/a')) - - await expect(page.getByTestId('page-a')).toBeVisible() - await expect(page.getByTestId('shared-card')).toBeVisible() - await expect - .poll(() => getBackgroundColor('shared-card', page)) - .toBe(SHARED_CARD_BG) - await expect( - page.locator('head link[rel="stylesheet"][href*="SharedCard"]'), - ).toHaveCount(1) - - await page.getByTestId('nav-/b').click() - await page.waitForURL('**/b') - await expect(page.getByTestId('page-b')).toBeVisible() - - await expect( - page.locator('head link[rel="stylesheet"][href*="SharedCard"]'), - ).toHaveCount(1) - await expect - .poll(() => getBackgroundColor('shared-card', page)) - .toBe(SHARED_CARD_BG) -}) - -test('shared widget CSS stays applied when navigating from static to lazy route', async ({ - page, - baseURL, -}) => { - await page.goto(buildUrl(baseURL!, '/lazy-css-static')) - - const widget = page.getByTestId('shared-widget') - await expect(widget).toBeVisible() - await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) - - await expect(page.getByTestId('lazy-css-static-hydrated')).toBeVisible() - - await page.getByTestId('nav-/lazy-css-lazy').click() - await page.waitForURL('**/lazy-css-lazy') - // Both routes render `shared-widget`: wait for the destination route before - // asserting on it, so the assertions cannot match the departing widget. - await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() - - await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) -}) - -test('shared widget CSS stays applied when navigating from lazy to static route', async ({ - page, - baseURL, -}) => { - await page.goto(buildUrl(baseURL!, '/lazy-css-lazy')) - await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() - - const widget = page.getByTestId('shared-widget') - await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) - - await 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() - - await expect(widget).toBeVisible() - 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 ({ - page, - baseURL, -}) => { - await page.goto(buildUrl(baseURL!, '/lazy-css-lazy')) - await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() - - const widget = page.getByTestId('shared-widget') - await expect(widget).toBeVisible() - 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 ({ - page, - baseURL, -}) => { - await page.goto(buildUrl(baseURL!, '/lazy-css-static')) - await expect(page.getByTestId('lazy-css-static-hydrated')).toBeVisible() - - const widget = page.getByTestId('shared-widget') - - await page.getByTestId('nav-/lazy-css-lazy').click() - await page.waitForURL('**/lazy-css-lazy') - await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() - await expect(widget).toBeVisible() - - await page.getByTestId('nav-home').click() - await page.waitForURL((url) => url.pathname === '/') - await expect(page.getByTestId('home-copy')).toBeVisible() - - await page.getByTestId('nav-/lazy-css-lazy').click() - await page.waitForURL('**/lazy-css-lazy') - await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() - - await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) -}) diff --git a/e2e/vue-start/start-manifest/tsconfig.json b/e2e/vue-start/start-manifest/tsconfig.json deleted file mode 100644 index 44a68ebf56..0000000000 --- a/e2e/vue-start/start-manifest/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "include": ["**/*.ts", "**/*.tsx"], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "preserve", - "jsxImportSource": "vue", - "module": "ESNext", - "moduleResolution": "Bundler", - "lib": ["DOM", "DOM.Iterable", "ES2022"], - "isolatedModules": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "target": "ES2024", - "allowJs": true, - "forceConsistentCasingInFileNames": true, - "paths": { - "~/*": ["./src/*"] - }, - "noEmit": true, - "types": ["vite/client"] - } -} diff --git a/e2e/vue-start/start-manifest/vite.config.ts b/e2e/vue-start/start-manifest/vite.config.ts deleted file mode 100644 index f1102cffab..0000000000 --- a/e2e/vue-start/start-manifest/vite.config.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { defineConfig } from 'vite' -import { tanstackStart } from '@tanstack/vue-start/plugin/vite' -import vueJsx from '@vitejs/plugin-vue-jsx' - -export default defineConfig({ - server: { - port: 3000, - }, - resolve: { - tsconfigPaths: true, - }, - plugins: [tanstackStart({ srcDirectory: 'src' }), vueJsx()], -}) diff --git a/e2e/vue-start/streaming-ssr/package.json b/e2e/vue-start/streaming-ssr/package.json deleted file mode 100644 index 382120860a..0000000000 --- a/e2e/vue-start/streaming-ssr/package.json +++ /dev/null @@ -1,59 +0,0 @@ -{ - "name": "tanstack-vue-start-e2e-streaming-ssr", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "vite dev --port 3000", - "dev:e2e": "vite dev", - "build": "vite build && tsc --noEmit", - "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "preview": "vite preview", - "test:e2e": "playwright test --project=chromium", - "test:e2e:preview": "MODE=preview playwright test preview-streaming.spec.ts --project=chromium" - }, - "dependencies": { - "@tanstack/vue-query": "^5.90.0", - "@tanstack/vue-router": "workspace:^", - "@tanstack/vue-router-ssr-query": "workspace:^", - "@tanstack/vue-start": "workspace:^", - "vue": "^3.5.16" - }, - "devDependencies": { - "@playwright/test": "^1.61.0", - "@tanstack/router-e2e-utils": "workspace:^", - "@types/node": "^22.10.2", - "@vitejs/plugin-vue-jsx": "^5.1.5", - "srvx": "^1.0.0", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" - }, - "nx": { - "targets": { - "build": { - "inputs": [ - "buildProduction", - "^buildProduction", - "dependentTaskOutputs", - "streamingSsrTests" - ] - }, - "test:e2e": { - "inputs": [ - "default", - "^production", - "dependentTaskOutputs", - "streamingSsrTests" - ] - }, - "test:e2e:preview": { - "inputs": [ - "default", - "^production", - "streamingSsrTests" - ] - } - } - } -} diff --git a/e2e/vue-start/streaming-ssr/playwright.config.ts b/e2e/vue-start/streaming-ssr/playwright.config.ts deleted file mode 100644 index c2f3b67a0c..0000000000 --- a/e2e/vue-start/streaming-ssr/playwright.config.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' - -const isPreview = process.env.MODE === 'preview' - -const PORT = Number(process.env.E2E_APP_PORT ?? 0) -const baseURL = `http://localhost:${PORT}` - -const ssrCommand = `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start` -const previewCommand = `VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}` - -/** - * See https://playwright.dev/docs/test-configuration. - */ -export default defineConfig({ - testDir: './tests', - workers: 1, - - reporter: [['line']], - - use: { - /* Base URL to use in actions like `await page.goto('/')`. */ - baseURL, - }, - - webServer: { - command: isPreview ? previewCommand : ssrCommand, - wait: appServerReady, - reuseExistingServer: false, - stdout: 'pipe', - }, - - projects: [ - { - name: 'chromium', - use: { ...devices['Desktop Chrome'] }, - }, - ], -}) diff --git a/e2e/vue-start/streaming-ssr/src/routeTree.gen.ts b/e2e/vue-start/streaming-ssr/src/routeTree.gen.ts deleted file mode 100644 index ac4c9ab156..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routeTree.gen.ts +++ /dev/null @@ -1,282 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as ConcurrentRouteImport } from './routes/concurrent' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as DeferredRejectionRouteImport } from './routes/deferred-rejection' -import { Route as FastSerialRouteImport } from './routes/fast-serial' -import { Route as ManyPromisesRouteImport } from './routes/many-promises' -import { Route as NestedDeferredRouteImport } from './routes/nested-deferred' -import { Route as QueryHeavyRouteImport } from './routes/query-heavy' -import { Route as SlowRenderRouteImport } from './routes/slow-render' -import { Route as StreamRouteImport } from './routes/stream' -import { Route as SyncOnlyRouteImport } from './routes/sync-only' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ConcurrentRoute = ConcurrentRouteImport.update({ - id: '/concurrent', - path: '/concurrent', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRejectionRoute = DeferredRejectionRouteImport.update({ - id: '/deferred-rejection', - path: '/deferred-rejection', - getParentRoute: () => rootRouteImport, -} as any) -const FastSerialRoute = FastSerialRouteImport.update({ - id: '/fast-serial', - path: '/fast-serial', - getParentRoute: () => rootRouteImport, -} as any) -const ManyPromisesRoute = ManyPromisesRouteImport.update({ - id: '/many-promises', - path: '/many-promises', - getParentRoute: () => rootRouteImport, -} as any) -const NestedDeferredRoute = NestedDeferredRouteImport.update({ - id: '/nested-deferred', - path: '/nested-deferred', - getParentRoute: () => rootRouteImport, -} as any) -const QueryHeavyRoute = QueryHeavyRouteImport.update({ - id: '/query-heavy', - path: '/query-heavy', - getParentRoute: () => rootRouteImport, -} as any) -const SlowRenderRoute = SlowRenderRouteImport.update({ - id: '/slow-render', - path: '/slow-render', - getParentRoute: () => rootRouteImport, -} as any) -const StreamRoute = StreamRouteImport.update({ - id: '/stream', - path: '/stream', - getParentRoute: () => rootRouteImport, -} as any) -const SyncOnlyRoute = SyncOnlyRouteImport.update({ - id: '/sync-only', - path: '/sync-only', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/concurrent': typeof ConcurrentRoute - '/deferred': typeof DeferredRoute - '/deferred-rejection': typeof DeferredRejectionRoute - '/fast-serial': typeof FastSerialRoute - '/many-promises': typeof ManyPromisesRoute - '/nested-deferred': typeof NestedDeferredRoute - '/query-heavy': typeof QueryHeavyRoute - '/slow-render': typeof SlowRenderRoute - '/stream': typeof StreamRoute - '/sync-only': typeof SyncOnlyRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/concurrent': typeof ConcurrentRoute - '/deferred': typeof DeferredRoute - '/deferred-rejection': typeof DeferredRejectionRoute - '/fast-serial': typeof FastSerialRoute - '/many-promises': typeof ManyPromisesRoute - '/nested-deferred': typeof NestedDeferredRoute - '/query-heavy': typeof QueryHeavyRoute - '/slow-render': typeof SlowRenderRoute - '/stream': typeof StreamRoute - '/sync-only': typeof SyncOnlyRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/concurrent': typeof ConcurrentRoute - '/deferred': typeof DeferredRoute - '/deferred-rejection': typeof DeferredRejectionRoute - '/fast-serial': typeof FastSerialRoute - '/many-promises': typeof ManyPromisesRoute - '/nested-deferred': typeof NestedDeferredRoute - '/query-heavy': typeof QueryHeavyRoute - '/slow-render': typeof SlowRenderRoute - '/stream': typeof StreamRoute - '/sync-only': typeof SyncOnlyRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/concurrent' - | '/deferred' - | '/deferred-rejection' - | '/fast-serial' - | '/many-promises' - | '/nested-deferred' - | '/query-heavy' - | '/slow-render' - | '/stream' - | '/sync-only' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/concurrent' - | '/deferred' - | '/deferred-rejection' - | '/fast-serial' - | '/many-promises' - | '/nested-deferred' - | '/query-heavy' - | '/slow-render' - | '/stream' - | '/sync-only' - id: - | '__root__' - | '/' - | '/concurrent' - | '/deferred' - | '/deferred-rejection' - | '/fast-serial' - | '/many-promises' - | '/nested-deferred' - | '/query-heavy' - | '/slow-render' - | '/stream' - | '/sync-only' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ConcurrentRoute: typeof ConcurrentRoute - DeferredRoute: typeof DeferredRoute - DeferredRejectionRoute: typeof DeferredRejectionRoute - FastSerialRoute: typeof FastSerialRoute - ManyPromisesRoute: typeof ManyPromisesRoute - NestedDeferredRoute: typeof NestedDeferredRoute - QueryHeavyRoute: typeof QueryHeavyRoute - SlowRenderRoute: typeof SlowRenderRoute - StreamRoute: typeof StreamRoute - SyncOnlyRoute: typeof SyncOnlyRoute -} - -declare module '@tanstack/vue-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/concurrent': { - id: '/concurrent' - path: '/concurrent' - fullPath: '/concurrent' - preLoaderRoute: typeof ConcurrentRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred-rejection': { - id: '/deferred-rejection' - path: '/deferred-rejection' - fullPath: '/deferred-rejection' - preLoaderRoute: typeof DeferredRejectionRouteImport - parentRoute: typeof rootRouteImport - } - '/fast-serial': { - id: '/fast-serial' - path: '/fast-serial' - fullPath: '/fast-serial' - preLoaderRoute: typeof FastSerialRouteImport - parentRoute: typeof rootRouteImport - } - '/many-promises': { - id: '/many-promises' - path: '/many-promises' - fullPath: '/many-promises' - preLoaderRoute: typeof ManyPromisesRouteImport - parentRoute: typeof rootRouteImport - } - '/nested-deferred': { - id: '/nested-deferred' - path: '/nested-deferred' - fullPath: '/nested-deferred' - preLoaderRoute: typeof NestedDeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/query-heavy': { - id: '/query-heavy' - path: '/query-heavy' - fullPath: '/query-heavy' - preLoaderRoute: typeof QueryHeavyRouteImport - parentRoute: typeof rootRouteImport - } - '/slow-render': { - id: '/slow-render' - path: '/slow-render' - fullPath: '/slow-render' - preLoaderRoute: typeof SlowRenderRouteImport - parentRoute: typeof rootRouteImport - } - '/stream': { - id: '/stream' - path: '/stream' - fullPath: '/stream' - preLoaderRoute: typeof StreamRouteImport - parentRoute: typeof rootRouteImport - } - '/sync-only': { - id: '/sync-only' - path: '/sync-only' - fullPath: '/sync-only' - preLoaderRoute: typeof SyncOnlyRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ConcurrentRoute: ConcurrentRoute, - DeferredRoute: DeferredRoute, - DeferredRejectionRoute: DeferredRejectionRoute, - FastSerialRoute: FastSerialRoute, - ManyPromisesRoute: ManyPromisesRoute, - NestedDeferredRoute: NestedDeferredRoute, - QueryHeavyRoute: QueryHeavyRoute, - SlowRenderRoute: SlowRenderRoute, - StreamRoute: StreamRoute, - SyncOnlyRoute: SyncOnlyRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/vue-start' -declare module '@tanstack/vue-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/e2e/vue-start/streaming-ssr/src/router.tsx b/e2e/vue-start/streaming-ssr/src/router.tsx deleted file mode 100644 index 257eb8dac9..0000000000 --- a/e2e/vue-start/streaming-ssr/src/router.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { QueryClient } from '@tanstack/vue-query' -import { createRouter } from '@tanstack/vue-router' -import { setupRouterSsrQueryIntegration } from '@tanstack/vue-router-ssr-query' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - const queryClient = new QueryClient() - const router = createRouter({ - routeTree, - context: { queryClient }, - scrollRestoration: true, - }) - setupRouterSsrQueryIntegration({ - router, - queryClient, - }) - return router -} diff --git a/e2e/vue-start/streaming-ssr/src/routes/__root.tsx b/e2e/vue-start/streaming-ssr/src/routes/__root.tsx deleted file mode 100644 index d3b3339720..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routes/__root.tsx +++ /dev/null @@ -1,103 +0,0 @@ -import { - Body, - HeadContent, - Html, - Link, - Outlet, - Scripts, - createRootRouteWithContext, -} from '@tanstack/vue-router' -import { defineComponent, ref } from 'vue' -import type { QueryClient } from '@tanstack/vue-query' - -export const Route = createRootRouteWithContext<{ - queryClient: QueryClient -}>()({ - head: () => ({ - meta: [ - { charSet: 'utf-8' }, - { name: 'viewport', content: 'width=device-width, initial-scale=1' }, - { title: 'Streaming SSR Tests' }, - ], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - - - ) -} - -const HydrationCheck = defineComponent({ - setup() { - const status = ref<'pending' | 'hydrated'>('pending') - - return () => ( -
- - - {status.value} - -
- ) - }, -}) diff --git a/e2e/vue-start/streaming-ssr/src/routes/concurrent.tsx b/e2e/vue-start/streaming-ssr/src/routes/concurrent.tsx deleted file mode 100644 index 5fed8ab517..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routes/concurrent.tsx +++ /dev/null @@ -1,54 +0,0 @@ -import { Await, createFileRoute } from '@tanstack/vue-router' -import { Suspense } from 'vue' -import { createConcurrentLoaderData } from '../../../../streaming-ssr-fixtures' - -export const Route = createFileRoute('/concurrent')({ - loader: async () => createConcurrentLoaderData(), - component: Concurrent, -}) - -function PromiseItem(props: { promise: Promise; testId: string }) { - return ( - - {{ - default: () => ( - ( -
{value}
- )} - /> - ), - fallback: () => ( -
Loading...
- ), - }} -
- ) -} - -function Concurrent() { - const data = Route.useLoaderData() - - return ( -
-

Concurrent Resolution Test (15 promises in 3 batches)

-

Tests multiple promises resolving at the exact same instant.

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

Deferred Rejection Test

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

Deferred Data Test

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

Fast Serialization Test

-

This route tests when serialization completes before render.

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

Streaming SSR Test Scenarios

-

This e2e project tests various SSR streaming scenarios:

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

Many Promises Test (15 deferred)

-

Tests streaming with many concurrent deferred promises.

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

Nested Deferred Test

-

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

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

Query Heavy Test (9 useQuery calls)

-

Tests multiple useQuery with mixed sync/async queryFn.

-

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

- -
-
-

Sync Queries (immediate)

- - - -
- -
-

Fast Async Queries (50-100ms)

- - - -
- -
-

Slow Async Queries (200-400ms)

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

Slow Render Test

-

Tests when render takes longer than serialization.

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

ReadableStream Test

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

Stream chunks:

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

Synchronous Serialization Test

-

{data.value.message}

-

Loaded at: {data.value.timestamp}

-

Source: {data.value.source}

-
    - {data.value.items.map((item: string) => ( -
  • {item}
  • - ))} -
-
- ) -} diff --git a/e2e/vue-start/streaming-ssr/tests/client-navigation.spec.ts b/e2e/vue-start/streaming-ssr/tests/client-navigation.spec.ts deleted file mode 100644 index 8b9b3a8dcc..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/client-navigation.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/client-navigation' diff --git a/e2e/vue-start/streaming-ssr/tests/concurrent.spec.ts b/e2e/vue-start/streaming-ssr/tests/concurrent.spec.ts deleted file mode 100644 index 8625473a58..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/concurrent.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/concurrent' diff --git a/e2e/vue-start/streaming-ssr/tests/deferred-rejection.spec.ts b/e2e/vue-start/streaming-ssr/tests/deferred-rejection.spec.ts deleted file mode 100644 index 355b5019bc..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/deferred-rejection.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/deferred-rejection' diff --git a/e2e/vue-start/streaming-ssr/tests/deferred.spec.ts b/e2e/vue-start/streaming-ssr/tests/deferred.spec.ts deleted file mode 100644 index 3145897d7b..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/deferred.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/deferred' diff --git a/e2e/vue-start/streaming-ssr/tests/fast-serial.spec.ts b/e2e/vue-start/streaming-ssr/tests/fast-serial.spec.ts deleted file mode 100644 index 95df0555e2..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/fast-serial.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/fast-serial' diff --git a/e2e/vue-start/streaming-ssr/tests/home.spec.ts b/e2e/vue-start/streaming-ssr/tests/home.spec.ts deleted file mode 100644 index 5d49d34a56..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/home.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/home' diff --git a/e2e/vue-start/streaming-ssr/tests/many-promises.spec.ts b/e2e/vue-start/streaming-ssr/tests/many-promises.spec.ts deleted file mode 100644 index b747bd7d0a..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/many-promises.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/many-promises' diff --git a/e2e/vue-start/streaming-ssr/tests/nested-deferred.spec.ts b/e2e/vue-start/streaming-ssr/tests/nested-deferred.spec.ts deleted file mode 100644 index 8df20a8a95..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/nested-deferred.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/nested-deferred' diff --git a/e2e/vue-start/streaming-ssr/tests/preview-streaming.spec.ts b/e2e/vue-start/streaming-ssr/tests/preview-streaming.spec.ts deleted file mode 100644 index 34241cfbaa..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/preview-streaming.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/preview-streaming' diff --git a/e2e/vue-start/streaming-ssr/tests/query-heavy.spec.ts b/e2e/vue-start/streaming-ssr/tests/query-heavy.spec.ts deleted file mode 100644 index d15c092f6e..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/query-heavy.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/query-heavy' diff --git a/e2e/vue-start/streaming-ssr/tests/slow-render.spec.ts b/e2e/vue-start/streaming-ssr/tests/slow-render.spec.ts deleted file mode 100644 index 0d5a87363f..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/slow-render.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/slow-render' diff --git a/e2e/vue-start/streaming-ssr/tests/stream.spec.ts b/e2e/vue-start/streaming-ssr/tests/stream.spec.ts deleted file mode 100644 index 9dfc6820ad..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/stream.spec.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { expect, testWithHydration } from '../../../streaming-ssr-assertions' -import '../../../streaming-ssr-specs/stream' - -testWithHydration( - 'reads a replacement stream after an active read', - async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - await page.getByRole('link', { name: 'Stream' }).first().click() - await expect(page.getByTestId('stream-chunk-0')).toHaveText('chunk-0') - await expect(page.getByTestId('stream-complete')).toHaveCount(0) - - await page.getByTestId('refresh-stream').click() - - const streamData = page.getByTestId('stream-data') - await expect(streamData).toHaveAttribute('data-read-count', '2') - await expect(page.getByTestId('stream-complete')).toBeVisible() - await expect( - streamData.locator('[data-testid^="stream-chunk-"]'), - ).toHaveText(['chunk-0', 'chunk-1', 'chunk-2', 'chunk-3', 'chunk-4']) - }, -) diff --git a/e2e/vue-start/streaming-ssr/tests/sync-only.spec.ts b/e2e/vue-start/streaming-ssr/tests/sync-only.spec.ts deleted file mode 100644 index b25572f615..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/sync-only.spec.ts +++ /dev/null @@ -1,7 +0,0 @@ -import '../../../streaming-ssr-specs/sync-only' -import { expect, test } from '../../../streaming-ssr-assertions' - -test('Vue renders an unwrapped document root', async ({ request }) => { - const response = await request.get('/sync-only') - expect(await response.text()).toMatch(/^)/) -}) diff --git a/e2e/vue-start/streaming-ssr/tsconfig.json b/e2e/vue-start/streaming-ssr/tsconfig.json deleted file mode 100644 index 390dad84c0..0000000000 --- a/e2e/vue-start/streaming-ssr/tsconfig.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "include": ["**/*.ts", "**/*.tsx"], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "preserve", - "jsxImportSource": "vue", - "module": "ESNext", - "moduleResolution": "Bundler", - "lib": ["DOM", "DOM.Iterable", "ES2022"], - "isolatedModules": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "target": "ES2022", - "allowJs": true, - "forceConsistentCasingInFileNames": true, - "paths": { - "~/*": ["./src/*"] - }, - "noEmit": true - } -} diff --git a/e2e/vue-start/streaming-ssr/vite.config.ts b/e2e/vue-start/streaming-ssr/vite.config.ts deleted file mode 100644 index 6519ec54c8..0000000000 --- a/e2e/vue-start/streaming-ssr/vite.config.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { defineConfig } from 'vite' -import { tanstackStart } from '@tanstack/vue-start/plugin/vite' -import vueJsx from '@vitejs/plugin-vue-jsx' - -export default defineConfig({ - server: { - port: 3000, - }, - plugins: [tanstackStart(), vueJsx()], -}) diff --git a/e2e/vue-start/virtual-routes/.devcontainer/devcontainer.json b/e2e/vue-start/virtual-routes/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-start/virtual-routes/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-start/virtual-routes/package.json b/e2e/vue-start/virtual-routes/package.json index 90f09ce911..8219236f68 100644 --- a/e2e/vue-start/virtual-routes/package.json +++ b/e2e/vue-start/virtual-routes/package.json @@ -9,30 +9,30 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { - "@tanstack/virtual-file-routes": "workspace:^", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", - "redaxios": "catalog:", - "tailwind-merge": "^3.6.0", + "@tanstack/virtual-file-routes": "workspace:^", + "redaxios": "^0.5.1", + "tailwind-merge": "^2.6.0", + "vite": "^7.3.1", "vue": "^3.5.25", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@playwright/test": "^1.61.0", - "@tailwindcss/vite": "^4.2.2", + "@playwright/test": "^1.50.1", + "@tailwindcss/vite": "^4.1.18", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", - "@vitejs/plugin-vue": "^6.0.5", - "@vitejs/plugin-vue-jsx": "^5.1.5", "combinate": "^1.1.11", - "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" + "srvx": "^0.11.2", + "tailwindcss": "^4.1.18", + "typescript": "^5.7.2", + "@vitejs/plugin-vue": "^6.0.3", + "@vitejs/plugin-vue-jsx": "^5.1.2", + "vite-tsconfig-paths": "^5.1.4" } } diff --git a/e2e/vue-start/virtual-routes/playwright.config.ts b/e2e/vue-start/virtual-routes/playwright.config.ts index 1862174905..b0c365f8bd 100644 --- a/e2e/vue-start/virtual-routes/playwright.config.ts +++ b/e2e/vue-start/virtual-routes/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,19 +18,19 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', - env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, - }, }, projects: [ diff --git a/e2e/vue-start/virtual-routes/src/posts.tsx b/e2e/vue-start/virtual-routes/src/posts.tsx index f7a1941605..1b4c92b41d 100644 --- a/e2e/vue-start/virtual-routes/src/posts.tsx +++ b/e2e/vue-start/virtual-routes/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-start/virtual-routes/src/routeTree.gen.ts b/e2e/vue-start/virtual-routes/src/routeTree.gen.ts index 1a1bc2d27b..addf953a25 100644 --- a/e2e/vue-start/virtual-routes/src/routeTree.gen.ts +++ b/e2e/vue-start/virtual-routes/src/routeTree.gen.ts @@ -9,27 +9,23 @@ // 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 homeRouteImport } from './routes/home' -import { Route as layoutFirstLayoutRouteImport } from './routes/layout/first-layout' -import { Route as postsPostsRouteImport } from './routes/posts/posts' import { Route as pipeRouteImport } from './routes/pipe' -import { Route as layoutSecondLayoutRouteImport } from './routes/layout/second-layout' -import { Route as ClassicHelloRouteRouteImport } from './routes/file-based-subtree/hello/route' -import { Route as postsPostsHomeRouteImport } from './routes/posts/posts-home' +import { Route as postsPostsRouteImport } from './routes/posts/posts' +import { Route as layoutFirstLayoutRouteImport } from './routes/layout/first-layout' +import { Route as homeRouteImport } from './routes/home' import { Route as postsPostsDetailRouteImport } from './routes/posts/posts-detail' +import { Route as layoutSecondLayoutRouteImport } from './routes/layout/second-layout' +import { Route as postsPostsHomeRouteImport } from './routes/posts/posts-home' +import { Route as ClassicHelloRouteRouteImport } from './routes/file-based-subtree/hello/route' import { Route as ClassicHelloIndexRouteImport } from './routes/file-based-subtree/hello/index' -import { Route as ClassicHelloUniverseRouteImport } from './routes/file-based-subtree/hello/universe' import { Route as ClassicHelloWorldRouteImport } from './routes/file-based-subtree/hello/world' -import { Route as aRouteImport } from './routes/a' +import { Route as ClassicHelloUniverseRouteImport } from './routes/file-based-subtree/hello/universe' import { Route as bRouteImport } from './routes/b' +import { Route as aRouteImport } from './routes/a' -const homeRoute = homeRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const layoutFirstLayoutRoute = layoutFirstLayoutRouteImport.update({ - id: '/_first', +const pipeRoute = pipeRouteImport.update({ + id: '/special|pipe', + path: '/special|pipe', getParentRoute: () => rootRouteImport, } as any) const postsPostsRoute = postsPostsRouteImport.update({ @@ -37,55 +33,59 @@ const postsPostsRoute = postsPostsRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const pipeRoute = pipeRouteImport.update({ - id: '/special|pipe', - path: '/special|pipe', +const layoutFirstLayoutRoute = layoutFirstLayoutRouteImport.update({ + id: '/_first', getParentRoute: () => rootRouteImport, } as any) -const layoutSecondLayoutRoute = layoutSecondLayoutRouteImport.update({ - id: '/_second-layout', - getParentRoute: () => layoutFirstLayoutRoute, -} as any) -const ClassicHelloRouteRoute = ClassicHelloRouteRouteImport.update({ - id: '/classic/hello', - path: '/classic/hello', - getParentRoute: () => rootRouteImport, -} as any) -const postsPostsHomeRoute = postsPostsHomeRouteImport.update({ +const homeRoute = homeRouteImport.update({ id: '/', path: '/', - getParentRoute: () => postsPostsRoute, + getParentRoute: () => rootRouteImport, } as any) const postsPostsDetailRoute = postsPostsDetailRouteImport.update({ id: '/$postId', path: '/$postId', getParentRoute: () => postsPostsRoute, } as any) +const layoutSecondLayoutRoute = layoutSecondLayoutRouteImport.update({ + id: '/_second-layout', + getParentRoute: () => layoutFirstLayoutRoute, +} as any) +const postsPostsHomeRoute = postsPostsHomeRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => postsPostsRoute, +} as any) +const ClassicHelloRouteRoute = ClassicHelloRouteRouteImport.update({ + id: '/classic/hello', + path: '/classic/hello', + getParentRoute: () => rootRouteImport, +} as any) const ClassicHelloIndexRoute = ClassicHelloIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => ClassicHelloRouteRoute, } as any) -const ClassicHelloUniverseRoute = ClassicHelloUniverseRouteImport.update({ - id: '/universe', - path: '/universe', - getParentRoute: () => ClassicHelloRouteRoute, -} as any) const ClassicHelloWorldRoute = ClassicHelloWorldRouteImport.update({ id: '/world', path: '/world', getParentRoute: () => ClassicHelloRouteRoute, } as any) -const aRoute = aRouteImport.update({ - id: '/route-without-file/layout-a', - path: '/route-without-file/layout-a', - getParentRoute: () => layoutSecondLayoutRoute, +const ClassicHelloUniverseRoute = ClassicHelloUniverseRouteImport.update({ + id: '/universe', + path: '/universe', + getParentRoute: () => ClassicHelloRouteRoute, } as any) const bRoute = bRouteImport.update({ id: '/route-without-file/layout-b', path: '/route-without-file/layout-b', getParentRoute: () => layoutSecondLayoutRoute, } as any) +const aRoute = aRouteImport.update({ + id: '/route-without-file/layout-a', + path: '/route-without-file/layout-a', + getParentRoute: () => layoutSecondLayoutRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof homeRoute @@ -179,18 +179,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof homeRouteImport - parentRoute: typeof rootRouteImport - } - '/_first': { - id: '/_first' - path: '' - fullPath: '/' - preLoaderRoute: typeof layoutFirstLayoutRouteImport + '/special|pipe': { + id: '/special|pipe' + path: '/special|pipe' + fullPath: '/special|pipe' + preLoaderRoute: typeof pipeRouteImport parentRoute: typeof rootRouteImport } '/posts': { @@ -200,33 +193,19 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof postsPostsRouteImport parentRoute: typeof rootRouteImport } - '/special|pipe': { - id: '/special|pipe' - path: '/special|pipe' - fullPath: '/special|pipe' - preLoaderRoute: typeof pipeRouteImport - parentRoute: typeof rootRouteImport - } - '/_first/_second-layout': { - id: '/_first/_second-layout' + '/_first': { + id: '/_first' path: '' - fullPath: '/' - preLoaderRoute: typeof layoutSecondLayoutRouteImport - parentRoute: typeof layoutFirstLayoutRoute - } - '/classic/hello': { - id: '/classic/hello' - path: '/classic/hello' - fullPath: '/classic/hello' - preLoaderRoute: typeof ClassicHelloRouteRouteImport + fullPath: '' + preLoaderRoute: typeof layoutFirstLayoutRouteImport parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' + '/': { + id: '/' path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof postsPostsHomeRouteImport - parentRoute: typeof postsPostsRoute + fullPath: '/' + preLoaderRoute: typeof homeRouteImport + parentRoute: typeof rootRouteImport } '/posts/$postId': { id: '/posts/$postId' @@ -235,6 +214,27 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof postsPostsDetailRouteImport parentRoute: typeof postsPostsRoute } + '/_first/_second-layout': { + id: '/_first/_second-layout' + path: '' + fullPath: '' + preLoaderRoute: typeof layoutSecondLayoutRouteImport + parentRoute: typeof layoutFirstLayoutRoute + } + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof postsPostsHomeRouteImport + parentRoute: typeof postsPostsRoute + } + '/classic/hello': { + id: '/classic/hello' + path: '/classic/hello' + fullPath: '/classic/hello' + preLoaderRoute: typeof ClassicHelloRouteRouteImport + parentRoute: typeof rootRouteImport + } '/classic/hello/': { id: '/classic/hello/' path: '/' @@ -242,13 +242,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ClassicHelloIndexRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/classic/hello/universe': { - id: '/classic/hello/universe' - path: '/universe' - fullPath: '/classic/hello/universe' - preLoaderRoute: typeof ClassicHelloUniverseRouteImport - parentRoute: typeof ClassicHelloRouteRoute - } '/classic/hello/world': { id: '/classic/hello/world' path: '/world' @@ -256,12 +249,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ClassicHelloWorldRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/_first/_second-layout/route-without-file/layout-a': { - id: '/_first/_second-layout/route-without-file/layout-a' - path: '/route-without-file/layout-a' - fullPath: '/route-without-file/layout-a' - preLoaderRoute: typeof aRouteImport - parentRoute: typeof layoutSecondLayoutRoute + '/classic/hello/universe': { + id: '/classic/hello/universe' + path: '/universe' + fullPath: '/classic/hello/universe' + preLoaderRoute: typeof ClassicHelloUniverseRouteImport + parentRoute: typeof ClassicHelloRouteRoute } '/_first/_second-layout/route-without-file/layout-b': { id: '/_first/_second-layout/route-without-file/layout-b' @@ -270,6 +263,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof bRouteImport parentRoute: typeof layoutSecondLayoutRoute } + '/_first/_second-layout/route-without-file/layout-a': { + id: '/_first/_second-layout/route-without-file/layout-a' + path: '/route-without-file/layout-a' + fullPath: '/route-without-file/layout-a' + preLoaderRoute: typeof aRouteImport + parentRoute: typeof layoutSecondLayoutRoute + } } } diff --git a/e2e/vue-start/virtual-routes/src/routes/posts/posts-detail.tsx b/e2e/vue-start/virtual-routes/src/routes/posts/posts-detail.tsx index 4bc3824f62..5086e3ad88 100644 --- a/e2e/vue-start/virtual-routes/src/routes/posts/posts-detail.tsx +++ b/e2e/vue-start/virtual-routes/src/routes/posts/posts-detail.tsx @@ -1,20 +1,7 @@ -import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' -const PostComponent = defineComponent({ - setup() { - const post = Route.useLoaderData() - return () => ( -
-

{post.value.title}

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

{post.value.title}

+
{post.value.body}
+
+ ) +} diff --git a/e2e/vue-start/virtual-routes/src/routes/posts/posts.tsx b/e2e/vue-start/virtual-routes/src/routes/posts/posts.tsx index dd380aa353..f56d6550a6 100644 --- a/e2e/vue-start/virtual-routes/src/routes/posts/posts.tsx +++ b/e2e/vue-start/virtual-routes/src/routes/posts/posts.tsx @@ -1,39 +1,37 @@ -import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../../posts' -const PostsComponent = defineComponent({ - setup() { - const posts = Route.useLoaderData() - return () => ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ))} -
-
- -
- ) - }, -}) - export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) + +function PostsComponent() { + const posts = Route.useLoaderData() + + return ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ))} +
+
+ +
+ ) +} diff --git a/e2e/vue-start/virtual-routes/src/utils/posts.tsx b/e2e/vue-start/virtual-routes/src/utils/posts.tsx index 11d80d08b5..a193bbc7af 100644 --- a/e2e/vue-start/virtual-routes/src/utils/posts.tsx +++ b/e2e/vue-start/virtual-routes/src/utils/posts.tsx @@ -8,10 +8,14 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export const fetchPost = createServerFn({ method: 'GET' }) - .validator((postId: string) => postId) + .inputValidator((postId: string) => postId) .handler(async ({ data: postId }) => { console.info(`Fetching post with id ${postId}...`) const post = await axios diff --git a/e2e/vue-start/virtual-routes/src/utils/users.tsx b/e2e/vue-start/virtual-routes/src/utils/users.tsx index 7ba645b383..46be4b1580 100644 --- a/e2e/vue-start/virtual-routes/src/utils/users.tsx +++ b/e2e/vue-start/virtual-routes/src/utils/users.tsx @@ -3,3 +3,7 @@ export type User = { name: string email: string } + +const PORT = process.env.VITE_SERVER_PORT || 3000 + +export const DEPLOY_URL = `http://localhost:${PORT}` diff --git a/e2e/vue-start/virtual-routes/tests/app.spec.ts b/e2e/vue-start/virtual-routes/tests/app.spec.ts index e9db98e3f3..3182febfa0 100644 --- a/e2e/vue-start/virtual-routes/tests/app.spec.ts +++ b/e2e/vue-start/virtual-routes/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-start/virtual-routes/tests/setup/global.setup.ts b/e2e/vue-start/virtual-routes/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-start/virtual-routes/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/virtual-routes/tests/setup/global.teardown.ts b/e2e/vue-start/virtual-routes/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-start/virtual-routes/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(packageJson.name) +} diff --git a/e2e/vue-start/virtual-routes/tsconfig.json b/e2e/vue-start/virtual-routes/tsconfig.json index 6f99c0f49a..6d933a5b2c 100644 --- a/e2e/vue-start/virtual-routes/tsconfig.json +++ b/e2e/vue-start/virtual-routes/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/virtual-routes/vite.config.ts b/e2e/vue-start/virtual-routes/vite.config.ts index 20df237264..5c8f24488d 100644 --- a/e2e/vue-start/virtual-routes/vite.config.ts +++ b/e2e/vue-start/virtual-routes/vite.config.ts @@ -1,16 +1,19 @@ import { defineConfig } from 'vite' +import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import tailwindcss from '@tailwindcss/vite' export default defineConfig({ - resolve: { tsconfigPaths: true }, server: { port: 3000, }, plugins: [ tailwindcss(), + tsConfigPaths({ + projects: ['./tsconfig.json'], + }), tanstackStart({ router: { virtualRouteConfig: './routes.ts', diff --git a/e2e/vue-start/website/.devcontainer/devcontainer.json b/e2e/vue-start/website/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/e2e/vue-start/website/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/e2e/vue-start/website/package.json b/e2e/vue-start/website/package.json index 6c30b1500f..da1a3eae12 100644 --- a/e2e/vue-start/website/package.json +++ b/e2e/vue-start/website/package.json @@ -9,28 +9,28 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", - "redaxios": "catalog:", - "tailwind-merge": "^3.6.0", + "redaxios": "^0.5.1", + "tailwind-merge": "^2.6.0", + "vite": "^7.3.1", "vue": "^3.5.25", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@playwright/test": "^1.61.0", - "@tailwindcss/vite": "^4.2.2", + "@playwright/test": "^1.50.1", + "@tailwindcss/vite": "^4.1.18", "@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", - "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "srvx": "^0.11.2", + "tailwindcss": "^4.1.18", + "typescript": "^5.7.2", + "@vitejs/plugin-vue": "^6.0.3", + "@vitejs/plugin-vue-jsx": "^5.1.2", + "vite-tsconfig-paths": "^5.1.4" } } diff --git a/e2e/vue-start/website/playwright.config.ts b/e2e/vue-start/website/playwright.config.ts index e6b92ce385..f6dd61ba6c 100644 --- a/e2e/vue-start/website/playwright.config.ts +++ b/e2e/vue-start/website/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/website/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/website/src/components/DefaultCatchBoundary.tsx index 77c03c5afa..b1f818dd74 100644 --- a/e2e/vue-start/website/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/website/src/components/DefaultCatchBoundary.tsx @@ -1,61 +1,53 @@ -import { defineComponent } from 'vue' -import type { PropType } from 'vue' import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -export const DefaultCatchBoundary = defineComponent({ - props: { - error: { - type: Object as PropType, - required: true, - }, - }, - setup(props) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - return () => { - console.error(props.error) - return ( -
- -
- - {isRoot.value ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) - } - }, -}) +export function DefaultCatchBoundary({ error }: ErrorComponentProps) { + const router = useRouter() + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, + }) + + console.error(error) + + return ( +
+ +
+ + {isRoot.value ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
+
+ ) +} diff --git a/e2e/vue-start/website/src/routeTree.gen.ts b/e2e/vue-start/website/src/routeTree.gen.ts index 0909725a4b..e7b58aae2a 100644 --- a/e2e/vue-start/website/src/routeTree.gen.ts +++ b/e2e/vue-start/website/src/routeTree.gen.ts @@ -10,11 +10,11 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as LibraryRouteImport } from './routes/_library' -import { Route as ProjectIndexRouteImport } from './routes/$project.index' import { Route as LibraryIndexRouteImport } from './routes/_library.index' +import { Route as ProjectIndexRouteImport } from './routes/$project.index' import { Route as LibraryProjectRouteImport } from './routes/_library.$project' -import { Route as ProjectVersionDocsIndexRouteImport } from './routes/$project.$version.docs.index' import { Route as LibraryProjectVersionIndexRouteImport } from './routes/_library.$project.$version.index' +import { Route as ProjectVersionDocsIndexRouteImport } from './routes/$project.$version.docs.index' import { Route as ProjectVersionDocsFrameworkFrameworkRouteImport } from './routes/$project.$version.docs.framework.$framework' import { Route as ProjectVersionDocsFrameworkFrameworkIndexRouteImport } from './routes/$project.$version.docs.framework.$framework.index' import { Route as ProjectVersionDocsFrameworkFrameworkSplatRouteImport } from './routes/$project.$version.docs.framework.$framework.$' @@ -24,32 +24,32 @@ const LibraryRoute = LibraryRouteImport.update({ id: '/_library', getParentRoute: () => rootRouteImport, } as any) -const ProjectIndexRoute = ProjectIndexRouteImport.update({ - id: '/$project/', - path: '/$project/', - getParentRoute: () => rootRouteImport, -} as any) const LibraryIndexRoute = LibraryIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => LibraryRoute, } as any) +const ProjectIndexRoute = ProjectIndexRouteImport.update({ + id: '/$project/', + path: '/$project/', + getParentRoute: () => rootRouteImport, +} as any) const LibraryProjectRoute = LibraryProjectRouteImport.update({ id: '/$project', path: '/$project', getParentRoute: () => LibraryRoute, } as any) -const ProjectVersionDocsIndexRoute = ProjectVersionDocsIndexRouteImport.update({ - id: '/$project/$version/docs/', - path: '/$project/$version/docs/', - getParentRoute: () => rootRouteImport, -} as any) const LibraryProjectVersionIndexRoute = LibraryProjectVersionIndexRouteImport.update({ id: '/$version/', path: '/$version/', getParentRoute: () => LibraryProjectRoute, } as any) +const ProjectVersionDocsIndexRoute = ProjectVersionDocsIndexRouteImport.update({ + id: '/$project/$version/docs/', + path: '/$project/$version/docs/', + getParentRoute: () => rootRouteImport, +} as any) const ProjectVersionDocsFrameworkFrameworkRoute = ProjectVersionDocsFrameworkFrameworkRouteImport.update({ id: '/$project/$version/docs/framework/$framework', @@ -159,13 +159,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LibraryRouteImport parentRoute: typeof rootRouteImport } - '/$project/': { - id: '/$project/' - path: '/$project' - fullPath: '/$project/' - preLoaderRoute: typeof ProjectIndexRouteImport - parentRoute: typeof rootRouteImport - } '/_library/': { id: '/_library/' path: '/' @@ -173,6 +166,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LibraryIndexRouteImport parentRoute: typeof LibraryRoute } + '/$project/': { + id: '/$project/' + path: '/$project' + fullPath: '/$project/' + preLoaderRoute: typeof ProjectIndexRouteImport + parentRoute: typeof rootRouteImport + } '/_library/$project': { id: '/_library/$project' path: '/$project' @@ -180,13 +180,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LibraryProjectRouteImport parentRoute: typeof LibraryRoute } - '/$project/$version/docs/': { - id: '/$project/$version/docs/' - path: '/$project/$version/docs' - fullPath: '/$project/$version/docs/' - preLoaderRoute: typeof ProjectVersionDocsIndexRouteImport - parentRoute: typeof rootRouteImport - } '/_library/$project/$version/': { id: '/_library/$project/$version/' path: '/$version' @@ -194,6 +187,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LibraryProjectVersionIndexRouteImport parentRoute: typeof LibraryProjectRoute } + '/$project/$version/docs/': { + id: '/$project/$version/docs/' + path: '/$project/$version/docs' + fullPath: '/$project/$version/docs/' + preLoaderRoute: typeof ProjectVersionDocsIndexRouteImport + parentRoute: typeof rootRouteImport + } '/$project/$version/docs/framework/$framework': { id: '/$project/$version/docs/framework/$framework' path: '/$project/$version/docs/framework/$framework' diff --git a/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.$.tsx b/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.$.tsx index 1d9173f200..f56c911b88 100644 --- a/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.$.tsx +++ b/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.$.tsx @@ -1,27 +1,9 @@ -import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' import { NotFound } from '~/components/NotFound' import { getDocument } from '~/server/document' import { capitalize, seo } from '~/utils/seo' -const Page = defineComponent({ - setup() { - const post = Route.useLoaderData() - return () => ( -
-

- {post.value.title} -

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

+ {post.value.title} +

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

- {params.value._splat} example -

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

+ {params.value._splat} example +

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

- {pathname.value} -

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

+ {pathname.value} +

+ +
+
+ ) +} diff --git a/e2e/vue-start/website/src/routes/__root.tsx b/e2e/vue-start/website/src/routes/__root.tsx index 744cac4b11..64228c166e 100644 --- a/e2e/vue-start/website/src/routes/__root.tsx +++ b/e2e/vue-start/website/src/routes/__root.tsx @@ -51,11 +51,7 @@ export const Route = createRootRoute({ ], }), errorComponent: (props) => { - return ( -

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

- ) + return

{props.error.stack}

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

- {params.value.project} landing page -

-

- version: {params.value.version} -

-

- - Get started with our documentation. - -

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

+ {params.value.project} landing page +

+

version: {params.value.version}

+

+ + Get started with our documentation. + +

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

- {pathname.value} -

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

+ {pathname.value} +

+ +
+
+ ) +} diff --git a/e2e/vue-start/website/src/server/document.tsx b/e2e/vue-start/website/src/server/document.tsx index 883efbed80..6623a50a5c 100644 --- a/e2e/vue-start/website/src/server/document.tsx +++ b/e2e/vue-start/website/src/server/document.tsx @@ -41,7 +41,7 @@ export const getDocumentHeads = createServerFn({ method: 'GET' }).handler( ) export const getDocument = createServerFn({ method: 'GET' }) - .validator((id: string) => id) + .inputValidator((id: string) => id) .handler(async ({ data: id }) => { await new Promise((resolve) => setTimeout(resolve, 200)) diff --git a/e2e/vue-start/website/src/server/projects.tsx b/e2e/vue-start/website/src/server/projects.tsx index 4ca98c754f..c97604a199 100644 --- a/e2e/vue-start/website/src/server/projects.tsx +++ b/e2e/vue-start/website/src/server/projects.tsx @@ -13,7 +13,7 @@ export const getProjects = createServerFn({ method: 'GET' }).handler( ) export const getProject = createServerFn({ method: 'GET' }) - .validator((project: string) => project) + .inputValidator((project: string) => project) .handler(async (ctx) => { await new Promise((resolve) => setTimeout(resolve, 200)) diff --git a/e2e/vue-start/website/tsconfig.json b/e2e/vue-start/website/tsconfig.json index 390dad84c0..f9f5aab3da 100644 --- a/e2e/vue-start/website/tsconfig.json +++ b/e2e/vue-start/website/tsconfig.json @@ -14,6 +14,7 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/website/vite.config.ts b/e2e/vue-start/website/vite.config.ts index 563e212077..e0b4a0e909 100644 --- a/e2e/vue-start/website/vite.config.ts +++ b/e2e/vue-start/website/vite.config.ts @@ -1,13 +1,21 @@ import { defineConfig } from 'vite' +import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import tailwindcss from '@tailwindcss/vite' export default defineConfig({ - resolve: { tsconfigPaths: true }, server: { port: 3000, }, - plugins: [tailwindcss(), tanstackStart(), vue(), vueJsx()], + plugins: [ + tailwindcss(), + tsConfigPaths({ + projects: ['./tsconfig.json'], + }), + tanstackStart(), + vue(), + vueJsx(), + ], }) diff --git a/eslint.config.js b/eslint.config.js index f58cc3fd10..90e320da68 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -1,10 +1,9 @@ // @ts-check -import { tanstackConfig } from '@tanstack/eslint-config' +import { tanstackConfig } from '@tanstack/config/eslint' import unusedImports from 'eslint-plugin-unused-imports' -/** @type {import('eslint').Linter.Config[]} */ export default [ ...tanstackConfig, { diff --git a/examples/AGENTS.md b/examples/AGENTS.md deleted file mode 100644 index eb47fbd925..0000000000 --- a/examples/AGENTS.md +++ /dev/null @@ -1,4 +0,0 @@ -# Examples - -- Versioned dependencies on this repository's packages resolve locally through `pnpm-workspace.yaml` overrides. Keep published version ranges in example manifests; do not replace them with `workspace:*` as a linking fix. -- Root `pnpm dev` watches package builds. To run an example app, use its own `dev` script after building its workspace dependencies. diff --git a/examples/react/authenticated-routes-firebase/.devcontainer/devcontainer.json b/examples/react/authenticated-routes-firebase/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/authenticated-routes-firebase/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/authenticated-routes-firebase/package.json b/examples/react/authenticated-routes-firebase/package.json index 1efa172047..ac720ecf97 100644 --- a/examples/react/authenticated-routes-firebase/package.json +++ b/examples/react/authenticated-routes-firebase/package.json @@ -9,24 +9,23 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tailwindcss/vite": "^4.1.18", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", + "@tanstack/router-plugin": "^1.161.1", "firebase": "^11.4.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", "simple-icons": "^14.9.0", - "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "tailwindcss": "^4.1.18", + "zod": "^3.24.2" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1" } } diff --git a/examples/react/authenticated-routes-firebase/src/routeTree.gen.ts b/examples/react/authenticated-routes-firebase/src/routeTree.gen.ts index bcc454ab03..f71d146de9 100644 --- a/examples/react/authenticated-routes-firebase/src/routeTree.gen.ts +++ b/examples/react/authenticated-routes-firebase/src/routeTree.gen.ts @@ -9,38 +9,38 @@ // 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 AuthRouteImport } from './routes/_auth' import { Route as LoginRouteImport } from './routes/login' -import { Route as AuthDashboardRouteImport } from './routes/_auth.dashboard' +import { Route as AuthRouteImport } from './routes/_auth' +import { Route as IndexRouteImport } from './routes/index' import { Route as AuthInvoicesRouteImport } from './routes/_auth.invoices' +import { Route as AuthDashboardRouteImport } from './routes/_auth.dashboard' import { Route as AuthInvoicesIndexRouteImport } from './routes/_auth.invoices.index' import { Route as AuthInvoicesInvoiceIdRouteImport } from './routes/_auth.invoices.$invoiceId' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', getParentRoute: () => rootRouteImport, } as any) const AuthRoute = AuthRouteImport.update({ id: '/_auth', getParentRoute: () => rootRouteImport, } as any) -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const AuthDashboardRoute = AuthDashboardRouteImport.update({ - id: '/dashboard', - path: '/dashboard', - getParentRoute: () => AuthRoute, -} as any) const AuthInvoicesRoute = AuthInvoicesRouteImport.update({ id: '/invoices', path: '/invoices', getParentRoute: () => AuthRoute, } as any) +const AuthDashboardRoute = AuthDashboardRouteImport.update({ + id: '/dashboard', + path: '/dashboard', + getParentRoute: () => AuthRoute, +} as any) const AuthInvoicesIndexRoute = AuthInvoicesIndexRouteImport.update({ id: '/', path: '/', @@ -107,20 +107,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_auth': { - id: '/_auth' - path: '' - fullPath: '/' - preLoaderRoute: typeof AuthRouteImport - parentRoute: typeof rootRouteImport - } '/login': { id: '/login' path: '/login' @@ -128,12 +114,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } - '/_auth/dashboard': { - id: '/_auth/dashboard' - path: '/dashboard' - fullPath: '/dashboard' - preLoaderRoute: typeof AuthDashboardRouteImport - parentRoute: typeof AuthRoute + '/_auth': { + id: '/_auth' + path: '' + fullPath: '' + preLoaderRoute: typeof AuthRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/_auth/invoices': { id: '/_auth/invoices' @@ -142,6 +135,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthInvoicesRouteImport parentRoute: typeof AuthRoute } + '/_auth/dashboard': { + id: '/_auth/dashboard' + path: '/dashboard' + fullPath: '/dashboard' + preLoaderRoute: typeof AuthDashboardRouteImport + parentRoute: typeof AuthRoute + } '/_auth/invoices/': { id: '/_auth/invoices/' path: '/' diff --git a/examples/react/authenticated-routes/.devcontainer/devcontainer.json b/examples/react/authenticated-routes/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/authenticated-routes/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/authenticated-routes/package.json b/examples/react/authenticated-routes/package.json index 6af48f1d34..1aaf47e426 100644 --- a/examples/react/authenticated-routes/package.json +++ b/examples/react/authenticated-routes/package.json @@ -9,22 +9,21 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tailwindcss/vite": "^4.1.18", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", + "@tanstack/router-plugin": "^1.161.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "tailwindcss": "^4.1.18", + "zod": "^3.24.2" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1" } } diff --git a/examples/react/authenticated-routes/src/routeTree.gen.ts b/examples/react/authenticated-routes/src/routeTree.gen.ts index bcc454ab03..f71d146de9 100644 --- a/examples/react/authenticated-routes/src/routeTree.gen.ts +++ b/examples/react/authenticated-routes/src/routeTree.gen.ts @@ -9,38 +9,38 @@ // 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 AuthRouteImport } from './routes/_auth' import { Route as LoginRouteImport } from './routes/login' -import { Route as AuthDashboardRouteImport } from './routes/_auth.dashboard' +import { Route as AuthRouteImport } from './routes/_auth' +import { Route as IndexRouteImport } from './routes/index' import { Route as AuthInvoicesRouteImport } from './routes/_auth.invoices' +import { Route as AuthDashboardRouteImport } from './routes/_auth.dashboard' import { Route as AuthInvoicesIndexRouteImport } from './routes/_auth.invoices.index' import { Route as AuthInvoicesInvoiceIdRouteImport } from './routes/_auth.invoices.$invoiceId' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', getParentRoute: () => rootRouteImport, } as any) const AuthRoute = AuthRouteImport.update({ id: '/_auth', getParentRoute: () => rootRouteImport, } as any) -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const AuthDashboardRoute = AuthDashboardRouteImport.update({ - id: '/dashboard', - path: '/dashboard', - getParentRoute: () => AuthRoute, -} as any) const AuthInvoicesRoute = AuthInvoicesRouteImport.update({ id: '/invoices', path: '/invoices', getParentRoute: () => AuthRoute, } as any) +const AuthDashboardRoute = AuthDashboardRouteImport.update({ + id: '/dashboard', + path: '/dashboard', + getParentRoute: () => AuthRoute, +} as any) const AuthInvoicesIndexRoute = AuthInvoicesIndexRouteImport.update({ id: '/', path: '/', @@ -107,20 +107,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_auth': { - id: '/_auth' - path: '' - fullPath: '/' - preLoaderRoute: typeof AuthRouteImport - parentRoute: typeof rootRouteImport - } '/login': { id: '/login' path: '/login' @@ -128,12 +114,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } - '/_auth/dashboard': { - id: '/_auth/dashboard' - path: '/dashboard' - fullPath: '/dashboard' - preLoaderRoute: typeof AuthDashboardRouteImport - parentRoute: typeof AuthRoute + '/_auth': { + id: '/_auth' + path: '' + fullPath: '' + preLoaderRoute: typeof AuthRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/_auth/invoices': { id: '/_auth/invoices' @@ -142,6 +135,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthInvoicesRouteImport parentRoute: typeof AuthRoute } + '/_auth/dashboard': { + id: '/_auth/dashboard' + path: '/dashboard' + fullPath: '/dashboard' + preLoaderRoute: typeof AuthDashboardRouteImport + parentRoute: typeof AuthRoute + } '/_auth/invoices/': { id: '/_auth/invoices/' path: '/' diff --git a/examples/react/authenticated-routes/src/vite-env.d.ts b/examples/react/authenticated-routes/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/authenticated-routes/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/basic-default-search-params/.devcontainer/devcontainer.json b/examples/react/basic-default-search-params/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/basic-default-search-params/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/basic-default-search-params/package.json b/examples/react/basic-default-search-params/package.json index 96c68fecd4..34d9cba5ec 100644 --- a/examples/react/basic-default-search-params/package.json +++ b/examples/react/basic-default-search-params/package.json @@ -9,22 +9,21 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.102.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tailwindcss/vite": "^4.1.18", + "@tanstack/react-query": "^5.90.0", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "tailwindcss": "^4.1.18", + "zod": "^3.24.2" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1" } } diff --git a/examples/react/basic-default-search-params/src/vite-env.d.ts b/examples/react/basic-default-search-params/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/basic-default-search-params/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/basic-devtools-panel/.devcontainer/devcontainer.json b/examples/react/basic-devtools-panel/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/basic-devtools-panel/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/basic-devtools-panel/package.json b/examples/react/basic-devtools-panel/package.json index ccae95d73f..8560358be0 100644 --- a/examples/react/basic-devtools-panel/package.json +++ b/examples/react/basic-devtools-panel/package.json @@ -9,22 +9,20 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.102.0", + "@tailwindcss/vite": "^4.1.18", "@tanstack/react-query-devtools": "^5.67.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.2.2" + "tailwindcss": "^4.1.18" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1" } } diff --git a/examples/react/basic-devtools-panel/src/vite-env.d.ts b/examples/react/basic-devtools-panel/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/basic-devtools-panel/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/basic-file-based/.devcontainer/devcontainer.json b/examples/react/basic-file-based/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/basic-file-based/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/basic-file-based/package.json b/examples/react/basic-file-based/package.json index 9c3cacada1..d6f87855a4 100644 --- a/examples/react/basic-file-based/package.json +++ b/examples/react/basic-file-based/package.json @@ -9,22 +9,21 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tailwindcss/vite": "^4.1.18", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", + "@tanstack/router-plugin": "^1.161.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "tailwindcss": "^4.1.18", + "zod": "^3.24.2" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1" } } diff --git a/examples/react/basic-file-based/src/routeTree.gen.ts b/examples/react/basic-file-based/src/routeTree.gen.ts index f370ad5d03..b8a45d6152 100644 --- a/examples/react/basic-file-based/src/routeTree.gen.ts +++ b/examples/react/basic-file-based/src/routeTree.gen.ts @@ -9,40 +9,35 @@ // 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 PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as AnchorRouteImport } from './routes/anchor' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as PostsRouteRouteImport } from './routes/posts.route' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' +import { Route as IndexRouteImport } from './routes/index' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const AnchorRoute = AnchorRouteImport.update({ + id: '/anchor', + path: '/anchor', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) -const AnchorRoute = AnchorRouteImport.update({ - id: '/anchor', - path: '/anchor', - getParentRoute: () => rootRouteImport, -} as any) const PostsRouteRoute = PostsRouteRouteImport.update({ id: '/posts', path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, - } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -53,11 +48,10 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRouteRoute, } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, } as any) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ @@ -65,6 +59,12 @@ const PathlessLayoutNestedLayoutRouteBRoute = path: '/route-b', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -129,20 +129,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout': { - id: '/_pathlessLayout' - path: '' - fullPath: '/' - preLoaderRoute: typeof PathlessLayoutRouteImport - parentRoute: typeof rootRouteImport - } '/anchor': { id: '/anchor' path: '/anchor' @@ -150,6 +136,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AnchorRouteImport parentRoute: typeof rootRouteImport } + '/_pathlessLayout': { + id: '/_pathlessLayout' + path: '' + fullPath: '' + preLoaderRoute: typeof PathlessLayoutRouteImport + parentRoute: typeof rootRouteImport + } '/posts': { id: '/posts' path: '/posts' @@ -157,12 +150,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' + '/': { + id: '/' + path: '/' fullPath: '/' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/posts/': { id: '/posts/' @@ -178,12 +171,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRouteRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' + path: '' + fullPath: '' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -192,6 +185,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute + } } } diff --git a/examples/react/basic-file-based/src/vite-env.d.ts b/examples/react/basic-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/basic-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/basic-non-nested-devtools/.devcontainer/devcontainer.json b/examples/react/basic-non-nested-devtools/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/basic-non-nested-devtools/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/basic-non-nested-devtools/package.json b/examples/react/basic-non-nested-devtools/package.json index 32e856ebcf..2e545f9006 100644 --- a/examples/react/basic-non-nested-devtools/package.json +++ b/examples/react/basic-non-nested-devtools/package.json @@ -9,20 +9,19 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tailwindcss/vite": "^4.1.18", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.2.2" + "tailwindcss": "^4.1.18" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1" } } diff --git a/examples/react/basic-non-nested-devtools/src/vite-env.d.ts b/examples/react/basic-non-nested-devtools/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/basic-non-nested-devtools/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/basic-react-query-file-based/.devcontainer/devcontainer.json b/examples/react/basic-react-query-file-based/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/basic-react-query-file-based/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/basic-react-query-file-based/package.json b/examples/react/basic-react-query-file-based/package.json index d01a02872e..aca1fb899c 100644 --- a/examples/react/basic-react-query-file-based/package.json +++ b/examples/react/basic-react-query-file-based/package.json @@ -9,24 +9,23 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.102.0", + "@tailwindcss/vite": "^4.1.18", + "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", + "@tanstack/router-plugin": "^1.161.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "tailwindcss": "^4.1.18", + "zod": "^3.24.2" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1" } } diff --git a/examples/react/basic-react-query-file-based/src/routeTree.gen.ts b/examples/react/basic-react-query-file-based/src/routeTree.gen.ts index 9676858c7c..03f3dc23c6 100644 --- a/examples/react/basic-react-query-file-based/src/routeTree.gen.ts +++ b/examples/react/basic-react-query-file-based/src/routeTree.gen.ts @@ -9,20 +9,15 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as PostsRouteRouteImport } from './routes/posts.route' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' +import { Route as IndexRouteImport } from './routes/index' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, @@ -32,11 +27,11 @@ const PostsRouteRoute = PostsRouteRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, - } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -47,11 +42,10 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRouteRoute, } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, } as any) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ @@ -59,6 +53,12 @@ const PathlessLayoutNestedLayoutRouteBRoute = path: '/route-b', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -117,17 +117,10 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/_pathlessLayout': { id: '/_pathlessLayout' path: '' - fullPath: '/' + fullPath: '' preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } @@ -138,12 +131,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' + '/': { + id: '/' + path: '/' fullPath: '/' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/posts/': { id: '/posts/' @@ -159,12 +152,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRouteRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' + path: '' + fullPath: '' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -173,6 +166,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute + } } } diff --git a/examples/react/basic-react-query-file-based/src/vite-env.d.ts b/examples/react/basic-react-query-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/basic-react-query-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/basic-react-query/.devcontainer/devcontainer.json b/examples/react/basic-react-query/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/basic-react-query/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/basic-react-query/package.json b/examples/react/basic-react-query/package.json index edab96afac..2453aaaf14 100644 --- a/examples/react/basic-react-query/package.json +++ b/examples/react/basic-react-query/package.json @@ -9,22 +9,21 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.102.0", + "@tailwindcss/vite": "^4.1.18", + "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.2.2" + "tailwindcss": "^4.1.18" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1" } } diff --git a/examples/react/basic-react-query/src/vite-env.d.ts b/examples/react/basic-react-query/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/basic-react-query/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/basic-ssr-file-based/.devcontainer/devcontainer.json b/examples/react/basic-ssr-file-based/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/basic-ssr-file-based/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/basic-ssr-file-based/package.json b/examples/react/basic-ssr-file-based/package.json index 3222c33e19..d92b140b52 100644 --- a/examples/react/basic-ssr-file-based/package.json +++ b/examples/react/basic-ssr-file-based/package.json @@ -11,23 +11,22 @@ "debug": "node --inspect-brk server" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.161.1", + "@tanstack/router-plugin": "^1.161.1", "compression": "^1.8.0", - "express": "^5.2.1", + "express": "^4.21.2", "get-port": "^7.1.0", "node-fetch": "^3.3.2", "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { - "@tanstack/react-router-devtools": "^1.167.3", - "@types/express": "^5.0.6", + "@tanstack/react-router-devtools": "^1.161.1", + "@types/express": "^4.17.23", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.1", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.5.2", + "typescript": "^5.8.3", + "vite": "^7.3.1" } } diff --git a/examples/react/basic-ssr-file-based/server.js b/examples/react/basic-ssr-file-based/server.js index 6d060a19f0..5686edc048 100644 --- a/examples/react/basic-ssr-file-based/server.js +++ b/examples/react/basic-ssr-file-based/server.js @@ -51,7 +51,7 @@ export async function createServer( if (isProd) app.use(express.static('./dist/client')) - app.use('/{*splat}', async (req, res) => { + app.use('*', async (req, res) => { try { const url = req.originalUrl @@ -97,8 +97,7 @@ export async function createServer( if (!isTest) { createServer().then(async ({ app }) => - app.listen(await getPort({ port: portNumbers(3000, 3100) }), (error) => { - if (error) throw error + app.listen(await getPort({ port: portNumbers(3000, 3100) }), () => { console.info('Client Server: http://localhost:3000') }), ) diff --git a/examples/react/basic-ssr-file-based/src/routeTree.gen.ts b/examples/react/basic-ssr-file-based/src/routeTree.gen.ts index 6f9f3f0f5e..4e61620e43 100644 --- a/examples/react/basic-ssr-file-based/src/routeTree.gen.ts +++ b/examples/react/basic-ssr-file-based/src/routeTree.gen.ts @@ -9,17 +9,12 @@ // 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 ErrorRouteImport } from './routes/error' import { Route as PostsRouteRouteImport } from './routes/posts/route' +import { Route as IndexRouteImport } from './routes/index' import { Route as PostsIndexRouteImport } from './routes/posts/index' import { Route as PostsPostIdRouteImport } from './routes/posts/$postId' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const ErrorRoute = ErrorRouteImport.update({ id: '/error', path: '/error', @@ -30,6 +25,11 @@ const PostsRouteRoute = PostsRouteRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -78,13 +78,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/error': { id: '/error' path: '/error' @@ -99,6 +92,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/posts/': { id: '/posts/' path: '/' diff --git a/examples/react/basic-ssr-file-based/vite.config.ts b/examples/react/basic-ssr-file-based/vite.config.ts index 93ff5dea85..09cc95baa8 100644 --- a/examples/react/basic-ssr-file-based/vite.config.ts +++ b/examples/react/basic-ssr-file-based/vite.config.ts @@ -15,7 +15,7 @@ const ssrBuildConfig: BuildEnvironmentOptions = { ssrEmitAssets: true, copyPublicDir: false, emptyOutDir: true, - rolldownOptions: { + rollupOptions: { input: path.resolve(__dirname, 'src/entry-server.tsx'), output: { entryFileNames: '[name].js', @@ -31,7 +31,7 @@ const clientBuildConfig: BuildEnvironmentOptions = { emitAssets: true, copyPublicDir: true, emptyOutDir: true, - rolldownOptions: { + rollupOptions: { input: path.resolve(__dirname, 'src/entry-client.tsx'), output: { entryFileNames: 'static/[name].js', diff --git a/examples/react/basic-ssr-streaming-file-based/.devcontainer/devcontainer.json b/examples/react/basic-ssr-streaming-file-based/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/basic-ssr-streaming-file-based/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/basic-ssr-streaming-file-based/package.json b/examples/react/basic-ssr-streaming-file-based/package.json index c3c87c8d88..f0a752e779 100644 --- a/examples/react/basic-ssr-streaming-file-based/package.json +++ b/examples/react/basic-ssr-streaming-file-based/package.json @@ -11,23 +11,22 @@ "debug": "node --inspect-brk server" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.161.1", + "@tanstack/router-plugin": "^1.161.1", "compression": "^1.8.0", - "express": "^5.2.1", + "express": "^4.21.2", "get-port": "^7.1.0", "node-fetch": "^3.3.2", "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { - "@tanstack/react-router-devtools": "^1.167.3", - "@types/express": "^5.0.6", + "@tanstack/react-router-devtools": "^1.161.1", + "@types/express": "^4.17.23", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.1", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1" } } diff --git a/examples/react/basic-ssr-streaming-file-based/server.js b/examples/react/basic-ssr-streaming-file-based/server.js index 6d060a19f0..5686edc048 100644 --- a/examples/react/basic-ssr-streaming-file-based/server.js +++ b/examples/react/basic-ssr-streaming-file-based/server.js @@ -51,7 +51,7 @@ export async function createServer( if (isProd) app.use(express.static('./dist/client')) - app.use('/{*splat}', async (req, res) => { + app.use('*', async (req, res) => { try { const url = req.originalUrl @@ -97,8 +97,7 @@ export async function createServer( if (!isTest) { createServer().then(async ({ app }) => - app.listen(await getPort({ port: portNumbers(3000, 3100) }), (error) => { - if (error) throw error + app.listen(await getPort({ port: portNumbers(3000, 3100) }), () => { console.info('Client Server: http://localhost:3000') }), ) diff --git a/examples/react/basic-ssr-streaming-file-based/src/routeTree.gen.ts b/examples/react/basic-ssr-streaming-file-based/src/routeTree.gen.ts index 6f9f3f0f5e..4e61620e43 100644 --- a/examples/react/basic-ssr-streaming-file-based/src/routeTree.gen.ts +++ b/examples/react/basic-ssr-streaming-file-based/src/routeTree.gen.ts @@ -9,17 +9,12 @@ // 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 ErrorRouteImport } from './routes/error' import { Route as PostsRouteRouteImport } from './routes/posts/route' +import { Route as IndexRouteImport } from './routes/index' import { Route as PostsIndexRouteImport } from './routes/posts/index' import { Route as PostsPostIdRouteImport } from './routes/posts/$postId' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const ErrorRoute = ErrorRouteImport.update({ id: '/error', path: '/error', @@ -30,6 +25,11 @@ const PostsRouteRoute = PostsRouteRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -78,13 +78,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/error': { id: '/error' path: '/error' @@ -99,6 +92,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/posts/': { id: '/posts/' path: '/' diff --git a/examples/react/basic-ssr-streaming-file-based/vite.config.ts b/examples/react/basic-ssr-streaming-file-based/vite.config.ts index 50f2ef6300..e6e86d12a0 100644 --- a/examples/react/basic-ssr-streaming-file-based/vite.config.ts +++ b/examples/react/basic-ssr-streaming-file-based/vite.config.ts @@ -15,7 +15,7 @@ const ssrBuildConfig: BuildEnvironmentOptions = { ssrEmitAssets: true, copyPublicDir: false, emptyOutDir: true, - rolldownOptions: { + rollupOptions: { input: path.resolve(__dirname, 'src/entry-server.tsx'), output: { entryFileNames: '[name].js', @@ -31,7 +31,7 @@ const clientBuildConfig: BuildEnvironmentOptions = { emitAssets: true, copyPublicDir: true, emptyOutDir: true, - rolldownOptions: { + rollupOptions: { input: path.resolve(__dirname, 'src/entry-client.tsx'), output: { entryFileNames: 'static/[name].js', diff --git a/examples/react/basic-virtual-file-based/.devcontainer/devcontainer.json b/examples/react/basic-virtual-file-based/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/basic-virtual-file-based/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/basic-virtual-file-based/package.json b/examples/react/basic-virtual-file-based/package.json index 84d326435c..7445f31502 100644 --- a/examples/react/basic-virtual-file-based/package.json +++ b/examples/react/basic-virtual-file-based/package.json @@ -9,23 +9,22 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", - "@tanstack/virtual-file-routes": "^1.162.0", + "@tailwindcss/vite": "^4.1.18", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", + "@tanstack/router-plugin": "^1.161.1", + "@tanstack/virtual-file-routes": "^1.154.7", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "tailwindcss": "^4.1.18", + "zod": "^3.24.2" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1" } } diff --git a/examples/react/basic-virtual-file-based/src/routeTree.gen.ts b/examples/react/basic-virtual-file-based/src/routeTree.gen.ts index 6745e373aa..dc243ae857 100644 --- a/examples/react/basic-virtual-file-based/src/routeTree.gen.ts +++ b/examples/react/basic-virtual-file-based/src/routeTree.gen.ts @@ -8,78 +8,80 @@ // 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 homeRouteImport } from './routes/home' -import { Route as layoutFirstLayoutRouteImport } from './routes/layout/first-layout' -import { Route as postsPostsRouteImport } from './routes/posts/posts' -import { Route as layoutSecondLayoutRouteImport } from './routes/layout/second-layout' -import { Route as ClassicHelloRouteRouteImport } from './routes/file-based-subtree/hello/route' -import { Route as postsPostsHomeRouteImport } from './routes/posts/posts-home' -import { Route as postsPostsDetailRouteImport } from './routes/posts/posts-detail' -import { Route as ClassicHelloIndexRouteImport } from './routes/file-based-subtree/hello/index' -import { Route as ClassicHelloUniverseRouteImport } from './routes/file-based-subtree/hello/universe' -import { Route as ClassicHelloWorldRouteImport } from './routes/file-based-subtree/hello/world' -import { Route as aRouteImport } from './routes/a' -import { Route as bRouteImport } from './routes/b' +import type { CreateFileRoute, FileRoutesByPath } from '@tanstack/react-router' -const homeRoute = homeRouteImport.update({ - id: '/', - path: '/', +import { Route as rootRouteImport } from './routes/root' +import { Route as postsPostsRouteImport } from './routes/posts/posts' +import { Route as layoutFirstLayoutRouteImport } from './routes/layout/first-layout' +import { Route as homeRouteImport } from './routes/home' +import { Route as postsPostsDetailRouteImport } from './routes/posts/posts-detail' +import { Route as layoutSecondLayoutRouteImport } from './routes/layout/second-layout' +import { Route as postsPostsHomeRouteImport } from './routes/posts/posts-home' +import { Route as ClassicHelloRouteRouteImport } from './routes/file-based-subtree/hello/route' +import { Route as ClassicHelloIndexRouteImport } from './routes/file-based-subtree/hello/index' +import { Route as ClassicHelloWorldRouteImport } from './routes/file-based-subtree/hello/world' +import { Route as ClassicHelloUniverseRouteImport } from './routes/file-based-subtree/hello/universe' +import { Route as bRouteImport } from './routes/b' +import { Route as aRouteImport } from './routes/a' + +const postsPostsRoute = postsPostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) const layoutFirstLayoutRoute = layoutFirstLayoutRouteImport.update({ id: '/_first', getParentRoute: () => rootRouteImport, } as any) -const postsPostsRoute = postsPostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const layoutSecondLayoutRoute = layoutSecondLayoutRouteImport.update({ - id: '/_second-layout', - getParentRoute: () => layoutFirstLayoutRoute, -} as any) -const ClassicHelloRouteRoute = ClassicHelloRouteRouteImport.update({ - id: '/classic/hello', - path: '/classic/hello', - getParentRoute: () => rootRouteImport, -} as any) -const postsPostsHomeRoute = postsPostsHomeRouteImport.update({ +const homeRoute = homeRouteImport.update({ id: '/', path: '/', - getParentRoute: () => postsPostsRoute, + getParentRoute: () => rootRouteImport, } as any) const postsPostsDetailRoute = postsPostsDetailRouteImport.update({ id: '/$postId', path: '/$postId', getParentRoute: () => postsPostsRoute, } as any) +const layoutSecondLayoutRoute = layoutSecondLayoutRouteImport.update({ + id: '/_second-layout', + getParentRoute: () => layoutFirstLayoutRoute, +} as any) +const postsPostsHomeRoute = postsPostsHomeRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => postsPostsRoute, +} as any) +const ClassicHelloRouteRoute = ClassicHelloRouteRouteImport.update({ + id: '/classic/hello', + path: '/classic/hello', + getParentRoute: () => rootRouteImport, +} as any) const ClassicHelloIndexRoute = ClassicHelloIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => ClassicHelloRouteRoute, } as any) -const ClassicHelloUniverseRoute = ClassicHelloUniverseRouteImport.update({ - id: '/universe', - path: '/universe', - getParentRoute: () => ClassicHelloRouteRoute, -} as any) const ClassicHelloWorldRoute = ClassicHelloWorldRouteImport.update({ id: '/world', path: '/world', getParentRoute: () => ClassicHelloRouteRoute, } as any) -const aRoute = aRouteImport.update({ - id: '/route-without-file/layout-a', - path: '/route-without-file/layout-a', - getParentRoute: () => layoutSecondLayoutRoute, +const ClassicHelloUniverseRoute = ClassicHelloUniverseRouteImport.update({ + id: '/universe', + path: '/universe', + getParentRoute: () => ClassicHelloRouteRoute, } as any) const bRoute = bRouteImport.update({ id: '/route-without-file/layout-b', path: '/route-without-file/layout-b', getParentRoute: () => layoutSecondLayoutRoute, } as any) +const aRoute = aRouteImport.update({ + id: '/route-without-file/layout-a', + path: '/route-without-file/layout-a', + getParentRoute: () => layoutSecondLayoutRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof homeRoute @@ -166,20 +168,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof homeRouteImport - parentRoute: typeof rootRouteImport - } - '/_first': { - id: '/_first' - path: '' - fullPath: '/' - preLoaderRoute: typeof layoutFirstLayoutRouteImport - parentRoute: typeof rootRouteImport - } '/posts': { id: '/posts' path: '/posts' @@ -187,26 +175,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof postsPostsRouteImport parentRoute: typeof rootRouteImport } - '/_first/_second-layout': { - id: '/_first/_second-layout' + '/_first': { + id: '/_first' path: '' - fullPath: '/' - preLoaderRoute: typeof layoutSecondLayoutRouteImport - parentRoute: typeof layoutFirstLayoutRoute - } - '/classic/hello': { - id: '/classic/hello' - path: '/classic/hello' - fullPath: '/classic/hello' - preLoaderRoute: typeof ClassicHelloRouteRouteImport + fullPath: '' + preLoaderRoute: typeof layoutFirstLayoutRouteImport parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' + '/': { + id: '/' path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof postsPostsHomeRouteImport - parentRoute: typeof postsPostsRoute + fullPath: '/' + preLoaderRoute: typeof homeRouteImport + parentRoute: typeof rootRouteImport } '/posts/$postId': { id: '/posts/$postId' @@ -215,6 +196,27 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof postsPostsDetailRouteImport parentRoute: typeof postsPostsRoute } + '/_first/_second-layout': { + id: '/_first/_second-layout' + path: '' + fullPath: '' + preLoaderRoute: typeof layoutSecondLayoutRouteImport + parentRoute: typeof layoutFirstLayoutRoute + } + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof postsPostsHomeRouteImport + parentRoute: typeof postsPostsRoute + } + '/classic/hello': { + id: '/classic/hello' + path: '/classic/hello' + fullPath: '/classic/hello' + preLoaderRoute: typeof ClassicHelloRouteRouteImport + parentRoute: typeof rootRouteImport + } '/classic/hello/': { id: '/classic/hello/' path: '/' @@ -222,13 +224,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ClassicHelloIndexRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/classic/hello/universe': { - id: '/classic/hello/universe' - path: '/universe' - fullPath: '/classic/hello/universe' - preLoaderRoute: typeof ClassicHelloUniverseRouteImport - parentRoute: typeof ClassicHelloRouteRoute - } '/classic/hello/world': { id: '/classic/hello/world' path: '/world' @@ -236,12 +231,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ClassicHelloWorldRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/_first/_second-layout/route-without-file/layout-a': { - id: '/_first/_second-layout/route-without-file/layout-a' - path: '/route-without-file/layout-a' - fullPath: '/route-without-file/layout-a' - preLoaderRoute: typeof aRouteImport - parentRoute: typeof layoutSecondLayoutRoute + '/classic/hello/universe': { + id: '/classic/hello/universe' + path: '/universe' + fullPath: '/classic/hello/universe' + preLoaderRoute: typeof ClassicHelloUniverseRouteImport + parentRoute: typeof ClassicHelloRouteRoute } '/_first/_second-layout/route-without-file/layout-b': { id: '/_first/_second-layout/route-without-file/layout-b' @@ -250,9 +245,125 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof bRouteImport parentRoute: typeof layoutSecondLayoutRoute } + '/_first/_second-layout/route-without-file/layout-a': { + id: '/_first/_second-layout/route-without-file/layout-a' + path: '/route-without-file/layout-a' + fullPath: '/route-without-file/layout-a' + preLoaderRoute: typeof aRouteImport + parentRoute: typeof layoutSecondLayoutRoute + } } } +declare module './routes/home' { + const createFileRoute: CreateFileRoute< + '/', + FileRoutesByPath['/']['parentRoute'], + FileRoutesByPath['/']['id'], + FileRoutesByPath['/']['path'], + FileRoutesByPath['/']['fullPath'] + > +} +declare module './routes/layout/first-layout' { + const createFileRoute: CreateFileRoute< + '/_first', + FileRoutesByPath['/_first']['parentRoute'], + FileRoutesByPath['/_first']['id'], + FileRoutesByPath['/_first']['path'], + FileRoutesByPath['/_first']['fullPath'] + > +} +declare module './routes/posts/posts' { + const createFileRoute: CreateFileRoute< + '/posts', + FileRoutesByPath['/posts']['parentRoute'], + FileRoutesByPath['/posts']['id'], + FileRoutesByPath['/posts']['path'], + FileRoutesByPath['/posts']['fullPath'] + > +} +declare module './routes/file-based-subtree/hello/route' { + const createFileRoute: CreateFileRoute< + '/classic/hello', + FileRoutesByPath['/classic/hello']['parentRoute'], + FileRoutesByPath['/classic/hello']['id'], + FileRoutesByPath['/classic/hello']['path'], + FileRoutesByPath['/classic/hello']['fullPath'] + > +} +declare module './routes/posts/posts-home' { + const createFileRoute: CreateFileRoute< + '/posts/', + FileRoutesByPath['/posts/']['parentRoute'], + FileRoutesByPath['/posts/']['id'], + FileRoutesByPath['/posts/']['path'], + FileRoutesByPath['/posts/']['fullPath'] + > +} +declare module './routes/layout/second-layout' { + const createFileRoute: CreateFileRoute< + '/_first/_second-layout', + FileRoutesByPath['/_first/_second-layout']['parentRoute'], + FileRoutesByPath['/_first/_second-layout']['id'], + FileRoutesByPath['/_first/_second-layout']['path'], + FileRoutesByPath['/_first/_second-layout']['fullPath'] + > +} +declare module './routes/posts/posts-detail' { + const createFileRoute: CreateFileRoute< + '/posts/$postId', + FileRoutesByPath['/posts/$postId']['parentRoute'], + FileRoutesByPath['/posts/$postId']['id'], + FileRoutesByPath['/posts/$postId']['path'], + FileRoutesByPath['/posts/$postId']['fullPath'] + > +} +declare module './routes/file-based-subtree/hello/universe' { + const createFileRoute: CreateFileRoute< + '/classic/hello/universe', + FileRoutesByPath['/classic/hello/universe']['parentRoute'], + FileRoutesByPath['/classic/hello/universe']['id'], + FileRoutesByPath['/classic/hello/universe']['path'], + FileRoutesByPath['/classic/hello/universe']['fullPath'] + > +} +declare module './routes/file-based-subtree/hello/world' { + const createFileRoute: CreateFileRoute< + '/classic/hello/world', + FileRoutesByPath['/classic/hello/world']['parentRoute'], + FileRoutesByPath['/classic/hello/world']['id'], + FileRoutesByPath['/classic/hello/world']['path'], + FileRoutesByPath['/classic/hello/world']['fullPath'] + > +} +declare module './routes/file-based-subtree/hello/index' { + const createFileRoute: CreateFileRoute< + '/classic/hello/', + FileRoutesByPath['/classic/hello/']['parentRoute'], + FileRoutesByPath['/classic/hello/']['id'], + FileRoutesByPath['/classic/hello/']['path'], + FileRoutesByPath['/classic/hello/']['fullPath'] + > +} +declare module './routes/a' { + const createFileRoute: CreateFileRoute< + '/_first/_second-layout/route-without-file/layout-a', + FileRoutesByPath['/_first/_second-layout/route-without-file/layout-a']['parentRoute'], + FileRoutesByPath['/_first/_second-layout/route-without-file/layout-a']['id'], + FileRoutesByPath['/_first/_second-layout/route-without-file/layout-a']['path'], + FileRoutesByPath['/_first/_second-layout/route-without-file/layout-a']['fullPath'] + > +} +declare module './routes/b' { + const createFileRoute: CreateFileRoute< + '/_first/_second-layout/route-without-file/layout-b', + FileRoutesByPath['/_first/_second-layout/route-without-file/layout-b']['parentRoute'], + FileRoutesByPath['/_first/_second-layout/route-without-file/layout-b']['id'], + FileRoutesByPath['/_first/_second-layout/route-without-file/layout-b']['path'], + FileRoutesByPath['/_first/_second-layout/route-without-file/layout-b']['fullPath'] + > +} + interface layoutSecondLayoutRouteChildren { aRoute: typeof aRoute bRoute: typeof bRoute diff --git a/examples/react/basic-virtual-file-based/src/routes/a.tsx b/examples/react/basic-virtual-file-based/src/routes/a.tsx index 74d17276d9..a190b24202 100644 --- a/examples/react/basic-virtual-file-based/src/routes/a.tsx +++ b/examples/react/basic-virtual-file-based/src/routes/a.tsx @@ -1,7 +1,4 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute( - '/_first/_second-layout/route-without-file/layout-a', -)({ +export const Route = createFileRoute({ component: LayoutAComponent, }) diff --git a/examples/react/basic-virtual-file-based/src/routes/b.tsx b/examples/react/basic-virtual-file-based/src/routes/b.tsx index d9b95f23b4..505f8f6fbf 100644 --- a/examples/react/basic-virtual-file-based/src/routes/b.tsx +++ b/examples/react/basic-virtual-file-based/src/routes/b.tsx @@ -1,7 +1,4 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute( - '/_first/_second-layout/route-without-file/layout-b', -)({ +export const Route = createFileRoute({ component: LayoutBComponent, }) diff --git a/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/index.tsx b/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/index.tsx index 0cc76f4a69..f86335e291 100644 --- a/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/index.tsx +++ b/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/index.tsx @@ -1,4 +1,3 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/classic/hello/')({ +export const Route = createFileRoute({ component: () =>
This is the index
, }) diff --git a/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/route.tsx b/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/route.tsx index 566efc8777..620dd2b76b 100644 --- a/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/route.tsx +++ b/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/route.tsx @@ -1,6 +1,6 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' +import { Link, Outlet } from '@tanstack/react-router' -export const Route = createFileRoute('/classic/hello')({ +export const Route = createFileRoute({ component: () => (
Hello! diff --git a/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/universe.tsx b/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/universe.tsx index 5aaa7d4fa0..20b07c41cc 100644 --- a/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/universe.tsx +++ b/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/universe.tsx @@ -1,4 +1,3 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/classic/hello/universe')({ +export const Route = createFileRoute({ component: () =>
Hello /classic/hello/universe!
, }) diff --git a/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/world.tsx b/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/world.tsx index 790d33a838..4af11357a2 100644 --- a/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/world.tsx +++ b/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/world.tsx @@ -1,4 +1,3 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/classic/hello/world')({ +export const Route = createFileRoute({ component: () =>
Hello /classic/hello/world!
, }) diff --git a/examples/react/basic-virtual-file-based/src/routes/home.tsx b/examples/react/basic-virtual-file-based/src/routes/home.tsx index 0a5b7572ba..b23956ae17 100644 --- a/examples/react/basic-virtual-file-based/src/routes/home.tsx +++ b/examples/react/basic-virtual-file-based/src/routes/home.tsx @@ -1,7 +1,6 @@ -import { createFileRoute } from '@tanstack/react-router' import * as React from 'react' -export const Route = createFileRoute('/')({ +export const Route = createFileRoute({ component: Home, }) diff --git a/examples/react/basic-virtual-file-based/src/routes/layout/first-layout.tsx b/examples/react/basic-virtual-file-based/src/routes/layout/first-layout.tsx index d39e206f2d..5c4a461d8d 100644 --- a/examples/react/basic-virtual-file-based/src/routes/layout/first-layout.tsx +++ b/examples/react/basic-virtual-file-based/src/routes/layout/first-layout.tsx @@ -1,6 +1,6 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' +import { Outlet } from '@tanstack/react-router' -export const Route = createFileRoute('/_first')({ +export const Route = createFileRoute({ component: LayoutComponent, }) diff --git a/examples/react/basic-virtual-file-based/src/routes/layout/second-layout.tsx b/examples/react/basic-virtual-file-based/src/routes/layout/second-layout.tsx index 2f56647492..478d9afbec 100644 --- a/examples/react/basic-virtual-file-based/src/routes/layout/second-layout.tsx +++ b/examples/react/basic-virtual-file-based/src/routes/layout/second-layout.tsx @@ -1,6 +1,6 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' +import { Link, Outlet } from '@tanstack/react-router' -export const Route = createFileRoute('/_first/_second-layout')({ +export const Route = createFileRoute({ component: LayoutComponent, }) diff --git a/examples/react/basic-virtual-file-based/src/routes/posts/posts-detail.tsx b/examples/react/basic-virtual-file-based/src/routes/posts/posts-detail.tsx index 948d52d6d6..654f3cfd18 100644 --- a/examples/react/basic-virtual-file-based/src/routes/posts/posts-detail.tsx +++ b/examples/react/basic-virtual-file-based/src/routes/posts/posts-detail.tsx @@ -1,9 +1,9 @@ import * as React from 'react' -import { ErrorComponent, createFileRoute } from '@tanstack/react-router' +import { ErrorComponent } from '@tanstack/react-router' import { fetchPost } from '../../posts' import type { ErrorComponentProps } from '@tanstack/react-router' -export const Route = createFileRoute('/posts/$postId')({ +export const Route = createFileRoute({ loader: async ({ params: { postId } }) => fetchPost(postId), errorComponent: PostErrorComponent as any, notFoundComponent: () => { diff --git a/examples/react/basic-virtual-file-based/src/routes/posts/posts-home.tsx b/examples/react/basic-virtual-file-based/src/routes/posts/posts-home.tsx index c6b65f1892..fdbe5865e5 100644 --- a/examples/react/basic-virtual-file-based/src/routes/posts/posts-home.tsx +++ b/examples/react/basic-virtual-file-based/src/routes/posts/posts-home.tsx @@ -1,7 +1,6 @@ -import { createFileRoute } from '@tanstack/react-router' import * as React from 'react' -export const Route = createFileRoute('/posts/')({ +export const Route = createFileRoute({ component: PostsIndexComponent, }) diff --git a/examples/react/basic-virtual-file-based/src/routes/posts/posts.tsx b/examples/react/basic-virtual-file-based/src/routes/posts/posts.tsx index a2ab1ee388..f92c37f537 100644 --- a/examples/react/basic-virtual-file-based/src/routes/posts/posts.tsx +++ b/examples/react/basic-virtual-file-based/src/routes/posts/posts.tsx @@ -1,8 +1,8 @@ import * as React from 'react' -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' +import { Link, Outlet } from '@tanstack/react-router' import { fetchPosts } from '../../posts' -export const Route = createFileRoute('/posts')({ +export const Route = createFileRoute({ loader: fetchPosts, component: PostsComponent, }) diff --git a/examples/react/basic-virtual-file-based/src/vite-env.d.ts b/examples/react/basic-virtual-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/basic-virtual-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/basic-virtual-file-based/vite.config.ts b/examples/react/basic-virtual-file-based/vite.config.ts index dd4f00f500..c3c3510479 100644 --- a/examples/react/basic-virtual-file-based/vite.config.ts +++ b/examples/react/basic-virtual-file-based/vite.config.ts @@ -10,6 +10,7 @@ export default defineConfig({ tanstackRouter({ target: 'react', autoCodeSplitting: true, + verboseFileRoutes: false, virtualRouteConfig: './routes.ts', }), react(), diff --git a/examples/react/basic-virtual-inside-file-based/.devcontainer/devcontainer.json b/examples/react/basic-virtual-inside-file-based/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/basic-virtual-inside-file-based/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/basic-virtual-inside-file-based/package.json b/examples/react/basic-virtual-inside-file-based/package.json index c04cb6012e..40103ac64b 100644 --- a/examples/react/basic-virtual-inside-file-based/package.json +++ b/examples/react/basic-virtual-inside-file-based/package.json @@ -9,23 +9,22 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", - "@tanstack/virtual-file-routes": "^1.162.0", + "@tailwindcss/vite": "^4.1.18", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", + "@tanstack/router-plugin": "^1.161.1", + "@tanstack/virtual-file-routes": "^1.154.7", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "tailwindcss": "^4.1.18", + "zod": "^3.24.2" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1" } } diff --git a/examples/react/basic-virtual-inside-file-based/src/routeTree.gen.ts b/examples/react/basic-virtual-inside-file-based/src/routeTree.gen.ts index cda1f85f15..2d3afb4983 100644 --- a/examples/react/basic-virtual-inside-file-based/src/routeTree.gen.ts +++ b/examples/react/basic-virtual-inside-file-based/src/routeTree.gen.ts @@ -8,62 +8,64 @@ // 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 LayoutRouteImport } from './routes/_layout' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' -import { Route as PostsHomeRouteImport } from './routes/posts/home' -import { Route as PostsDetailsRouteImport } from './routes/posts/details' -import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' -import { Route as PostsLetsGoIndexRouteImport } from './routes/posts/lets-go/index' -import { Route as PostsLetsGoDeeperHomeRouteImport } from './routes/posts/lets-go/deeper/home' +import type { CreateFileRoute, FileRoutesByPath } from '@tanstack/react-router' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +import { Route as rootRouteImport } from './routes/__root' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as IndexRouteImport } from './routes/index' +import { Route as postsDetailsRouteImport } from './routes/posts/details' +import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' +import { Route as postsHomeRouteImport } from './routes/posts/home' +import { Route as postsLetsGoIndexRouteImport } from './routes/posts/lets-go/index' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' +import { Route as postsLetsGoDeeperHomeRouteImport } from './routes/posts/lets-go/deeper/home' + +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) const LayoutRoute = LayoutRouteImport.update({ id: '/_layout', getParentRoute: () => rootRouteImport, } as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) +const postsDetailsRoute = postsDetailsRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) const LayoutLayout2Route = LayoutLayout2RouteImport.update({ id: '/_layout-2', getParentRoute: () => LayoutRoute, } as any) -const PostsHomeRoute = PostsHomeRouteImport.update({ +const postsHomeRoute = postsHomeRouteImport.update({ id: '/', path: '/', getParentRoute: () => PostsRoute, } as any) -const PostsDetailsRoute = PostsDetailsRouteImport.update({ - id: '/$postId', - path: '/$postId', +const postsLetsGoIndexRoute = postsLetsGoIndexRouteImport.update({ + id: '/inception/', + path: '/inception/', getParentRoute: () => PostsRoute, } as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, -} as any) const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ id: '/layout-b', path: '/layout-b', getParentRoute: () => LayoutLayout2Route, } as any) -const PostsLetsGoIndexRoute = PostsLetsGoIndexRouteImport.update({ - id: '/inception/', - path: '/inception/', - getParentRoute: () => PostsRoute, +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, } as any) -const PostsLetsGoDeeperHomeRoute = PostsLetsGoDeeperHomeRouteImport.update({ +const postsLetsGoDeeperHomeRoute = postsLetsGoDeeperHomeRouteImport.update({ id: '/inception/deeper/', path: '/inception/deeper/', getParentRoute: () => PostsRoute, @@ -72,34 +74,34 @@ const PostsLetsGoDeeperHomeRoute = PostsLetsGoDeeperHomeRouteImport.update({ export interface FileRoutesByFullPath { '/': typeof IndexRoute '/posts': typeof PostsRouteWithChildren - '/posts/': typeof PostsHomeRoute - '/posts/$postId': typeof PostsDetailsRoute + '/posts/': typeof postsHomeRoute + '/posts/$postId': typeof postsDetailsRoute '/layout-a': typeof LayoutLayout2LayoutARoute '/layout-b': typeof LayoutLayout2LayoutBRoute - '/posts/inception/': typeof PostsLetsGoIndexRoute - '/posts/inception/deeper/': typeof PostsLetsGoDeeperHomeRoute + '/posts/inception': typeof postsLetsGoIndexRoute + '/posts/inception/deeper': typeof postsLetsGoDeeperHomeRoute } export interface FileRoutesByTo { '/': typeof IndexRoute - '/posts': typeof PostsHomeRoute - '/posts/$postId': typeof PostsDetailsRoute + '/posts': typeof postsHomeRoute + '/posts/$postId': typeof postsDetailsRoute '/layout-a': typeof LayoutLayout2LayoutARoute '/layout-b': typeof LayoutLayout2LayoutBRoute - '/posts/inception': typeof PostsLetsGoIndexRoute - '/posts/inception/deeper': typeof PostsLetsGoDeeperHomeRoute + '/posts/inception': typeof postsLetsGoIndexRoute + '/posts/inception/deeper': typeof postsLetsGoDeeperHomeRoute } export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute '/_layout': typeof LayoutRouteWithChildren '/posts': typeof PostsRouteWithChildren - '/posts/': typeof PostsHomeRoute + '/posts/': typeof postsHomeRoute '/_layout/_layout-2': typeof LayoutLayout2RouteWithChildren - '/posts/$postId': typeof PostsDetailsRoute + '/posts/$postId': typeof postsDetailsRoute '/_layout/_layout-2/layout-a': typeof LayoutLayout2LayoutARoute '/_layout/_layout-2/layout-b': typeof LayoutLayout2LayoutBRoute - '/posts/inception/': typeof PostsLetsGoIndexRoute - '/posts/inception/deeper/': typeof PostsLetsGoDeeperHomeRoute + '/posts/inception/': typeof postsLetsGoIndexRoute + '/posts/inception/deeper/': typeof postsLetsGoDeeperHomeRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath @@ -110,8 +112,8 @@ export interface FileRouteTypes { | '/posts/$postId' | '/layout-a' | '/layout-b' - | '/posts/inception/' - | '/posts/inception/deeper/' + | '/posts/inception' + | '/posts/inception/deeper' fileRoutesByTo: FileRoutesByTo to: | '/' @@ -143,20 +145,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout': { - id: '/_layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutRouteImport - parentRoute: typeof rootRouteImport - } '/posts': { id: '/posts' path: '/posts' @@ -164,10 +152,31 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } + '/_layout': { + id: '/_layout' + path: '' + fullPath: '' + preLoaderRoute: typeof LayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof postsDetailsRouteImport + parentRoute: typeof PostsRoute + } '/_layout/_layout-2': { id: '/_layout/_layout-2' path: '' - fullPath: '/' + fullPath: '' preLoaderRoute: typeof LayoutLayout2RouteImport parentRoute: typeof LayoutRoute } @@ -175,23 +184,16 @@ declare module '@tanstack/react-router' { id: '/posts/' path: '/' fullPath: '/posts/' - preLoaderRoute: typeof PostsHomeRouteImport + preLoaderRoute: typeof postsHomeRouteImport parentRoute: typeof PostsRoute } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsDetailsRouteImport + '/posts/inception/': { + id: '/posts/inception/' + path: '/inception' + fullPath: '/posts/inception' + preLoaderRoute: typeof postsLetsGoIndexRouteImport parentRoute: typeof PostsRoute } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route - } '/_layout/_layout-2/layout-b': { id: '/_layout/_layout-2/layout-b' path: '/layout-b' @@ -199,23 +201,114 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport parentRoute: typeof LayoutLayout2Route } - '/posts/inception/': { - id: '/posts/inception/' - path: '/inception' - fullPath: '/posts/inception/' - preLoaderRoute: typeof PostsLetsGoIndexRouteImport - parentRoute: typeof PostsRoute + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route } '/posts/inception/deeper/': { id: '/posts/inception/deeper/' path: '/inception/deeper' - fullPath: '/posts/inception/deeper/' - preLoaderRoute: typeof PostsLetsGoDeeperHomeRouteImport + fullPath: '/posts/inception/deeper' + preLoaderRoute: typeof postsLetsGoDeeperHomeRouteImport parentRoute: typeof PostsRoute } } } +declare module './routes/index' { + const createFileRoute: CreateFileRoute< + '/', + FileRoutesByPath['/']['parentRoute'], + FileRoutesByPath['/']['id'], + FileRoutesByPath['/']['path'], + FileRoutesByPath['/']['fullPath'] + > +} +declare module './routes/_layout' { + const createFileRoute: CreateFileRoute< + '/_layout', + FileRoutesByPath['/_layout']['parentRoute'], + FileRoutesByPath['/_layout']['id'], + FileRoutesByPath['/_layout']['path'], + FileRoutesByPath['/_layout']['fullPath'] + > +} +declare module './routes/posts' { + const createFileRoute: CreateFileRoute< + '/posts', + FileRoutesByPath['/posts']['parentRoute'], + FileRoutesByPath['/posts']['id'], + FileRoutesByPath['/posts']['path'], + FileRoutesByPath['/posts']['fullPath'] + > +} +declare module './routes/posts/home' { + const createFileRoute: CreateFileRoute< + '/posts/', + FileRoutesByPath['/posts/']['parentRoute'], + FileRoutesByPath['/posts/']['id'], + FileRoutesByPath['/posts/']['path'], + FileRoutesByPath['/posts/']['fullPath'] + > +} +declare module './routes/_layout/_layout-2' { + const createFileRoute: CreateFileRoute< + '/_layout/_layout-2', + FileRoutesByPath['/_layout/_layout-2']['parentRoute'], + FileRoutesByPath['/_layout/_layout-2']['id'], + FileRoutesByPath['/_layout/_layout-2']['path'], + FileRoutesByPath['/_layout/_layout-2']['fullPath'] + > +} +declare module './routes/posts/details' { + const createFileRoute: CreateFileRoute< + '/posts/$postId', + FileRoutesByPath['/posts/$postId']['parentRoute'], + FileRoutesByPath['/posts/$postId']['id'], + FileRoutesByPath['/posts/$postId']['path'], + FileRoutesByPath['/posts/$postId']['fullPath'] + > +} +declare module './routes/_layout/_layout-2/layout-a' { + const createFileRoute: CreateFileRoute< + '/_layout/_layout-2/layout-a', + FileRoutesByPath['/_layout/_layout-2/layout-a']['parentRoute'], + FileRoutesByPath['/_layout/_layout-2/layout-a']['id'], + FileRoutesByPath['/_layout/_layout-2/layout-a']['path'], + FileRoutesByPath['/_layout/_layout-2/layout-a']['fullPath'] + > +} +declare module './routes/_layout/_layout-2/layout-b' { + const createFileRoute: CreateFileRoute< + '/_layout/_layout-2/layout-b', + FileRoutesByPath['/_layout/_layout-2/layout-b']['parentRoute'], + FileRoutesByPath['/_layout/_layout-2/layout-b']['id'], + FileRoutesByPath['/_layout/_layout-2/layout-b']['path'], + FileRoutesByPath['/_layout/_layout-2/layout-b']['fullPath'] + > +} +declare module './routes/posts/lets-go/index' { + const createFileRoute: CreateFileRoute< + '/posts/inception/', + FileRoutesByPath['/posts/inception/']['parentRoute'], + FileRoutesByPath['/posts/inception/']['id'], + FileRoutesByPath['/posts/inception/']['path'], + FileRoutesByPath['/posts/inception/']['fullPath'] + > +} +declare module './routes/posts/lets-go/deeper/home' { + const createFileRoute: CreateFileRoute< + '/posts/inception/deeper/', + FileRoutesByPath['/posts/inception/deeper/']['parentRoute'], + FileRoutesByPath['/posts/inception/deeper/']['id'], + FileRoutesByPath['/posts/inception/deeper/']['path'], + FileRoutesByPath['/posts/inception/deeper/']['fullPath'] + > +} + interface LayoutLayout2RouteChildren { LayoutLayout2LayoutARoute: typeof LayoutLayout2LayoutARoute LayoutLayout2LayoutBRoute: typeof LayoutLayout2LayoutBRoute @@ -242,17 +335,17 @@ const LayoutRouteWithChildren = LayoutRoute._addFileChildren(LayoutRouteChildren) interface PostsRouteChildren { - PostsHomeRoute: typeof PostsHomeRoute - PostsDetailsRoute: typeof PostsDetailsRoute - PostsLetsGoIndexRoute: typeof PostsLetsGoIndexRoute - PostsLetsGoDeeperHomeRoute: typeof PostsLetsGoDeeperHomeRoute + postsHomeRoute: typeof postsHomeRoute + postsDetailsRoute: typeof postsDetailsRoute + postsLetsGoIndexRoute: typeof postsLetsGoIndexRoute + postsLetsGoDeeperHomeRoute: typeof postsLetsGoDeeperHomeRoute } const PostsRouteChildren: PostsRouteChildren = { - PostsHomeRoute: PostsHomeRoute, - PostsDetailsRoute: PostsDetailsRoute, - PostsLetsGoIndexRoute: PostsLetsGoIndexRoute, - PostsLetsGoDeeperHomeRoute: PostsLetsGoDeeperHomeRoute, + postsHomeRoute: postsHomeRoute, + postsDetailsRoute: postsDetailsRoute, + postsLetsGoIndexRoute: postsLetsGoIndexRoute, + postsLetsGoDeeperHomeRoute: postsLetsGoDeeperHomeRoute, } const PostsRouteWithChildren = PostsRoute._addFileChildren(PostsRouteChildren) diff --git a/examples/react/basic-virtual-inside-file-based/src/routes/_layout.tsx b/examples/react/basic-virtual-inside-file-based/src/routes/_layout.tsx index 02ddbb1cd9..5c4a461d8d 100644 --- a/examples/react/basic-virtual-inside-file-based/src/routes/_layout.tsx +++ b/examples/react/basic-virtual-inside-file-based/src/routes/_layout.tsx @@ -1,6 +1,6 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' +import { Outlet } from '@tanstack/react-router' -export const Route = createFileRoute('/_layout')({ +export const Route = createFileRoute({ component: LayoutComponent, }) diff --git a/examples/react/basic-virtual-inside-file-based/src/routes/_layout/_layout-2.tsx b/examples/react/basic-virtual-inside-file-based/src/routes/_layout/_layout-2.tsx index 3b7dbf2903..483b910862 100644 --- a/examples/react/basic-virtual-inside-file-based/src/routes/_layout/_layout-2.tsx +++ b/examples/react/basic-virtual-inside-file-based/src/routes/_layout/_layout-2.tsx @@ -1,6 +1,6 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' +import { Link, Outlet } from '@tanstack/react-router' -export const Route = createFileRoute('/_layout/_layout-2')({ +export const Route = createFileRoute({ component: LayoutComponent, }) diff --git a/examples/react/basic-virtual-inside-file-based/src/routes/_layout/_layout-2/layout-a.tsx b/examples/react/basic-virtual-inside-file-based/src/routes/_layout/_layout-2/layout-a.tsx index ed2dea8800..a190b24202 100644 --- a/examples/react/basic-virtual-inside-file-based/src/routes/_layout/_layout-2/layout-a.tsx +++ b/examples/react/basic-virtual-inside-file-based/src/routes/_layout/_layout-2/layout-a.tsx @@ -1,5 +1,4 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/_layout/_layout-2/layout-a')({ +export const Route = createFileRoute({ component: LayoutAComponent, }) diff --git a/examples/react/basic-virtual-inside-file-based/src/routes/_layout/_layout-2/layout-b.tsx b/examples/react/basic-virtual-inside-file-based/src/routes/_layout/_layout-2/layout-b.tsx index 4799d403e9..505f8f6fbf 100644 --- a/examples/react/basic-virtual-inside-file-based/src/routes/_layout/_layout-2/layout-b.tsx +++ b/examples/react/basic-virtual-inside-file-based/src/routes/_layout/_layout-2/layout-b.tsx @@ -1,5 +1,4 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/_layout/_layout-2/layout-b')({ +export const Route = createFileRoute({ component: LayoutBComponent, }) diff --git a/examples/react/basic-virtual-inside-file-based/src/routes/index.tsx b/examples/react/basic-virtual-inside-file-based/src/routes/index.tsx index 0a5b7572ba..b23956ae17 100644 --- a/examples/react/basic-virtual-inside-file-based/src/routes/index.tsx +++ b/examples/react/basic-virtual-inside-file-based/src/routes/index.tsx @@ -1,7 +1,6 @@ -import { createFileRoute } from '@tanstack/react-router' import * as React from 'react' -export const Route = createFileRoute('/')({ +export const Route = createFileRoute({ component: Home, }) diff --git a/examples/react/basic-virtual-inside-file-based/src/routes/posts.tsx b/examples/react/basic-virtual-inside-file-based/src/routes/posts.tsx index c7a09ed7f8..4469b2216a 100644 --- a/examples/react/basic-virtual-inside-file-based/src/routes/posts.tsx +++ b/examples/react/basic-virtual-inside-file-based/src/routes/posts.tsx @@ -1,8 +1,8 @@ import * as React from 'react' -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' +import { Link, Outlet } from '@tanstack/react-router' import { fetchPosts } from '../posts' -export const Route = createFileRoute('/posts')({ +export const Route = createFileRoute({ loader: fetchPosts, component: PostsComponent, }) diff --git a/examples/react/basic-virtual-inside-file-based/src/routes/posts/details.tsx b/examples/react/basic-virtual-inside-file-based/src/routes/posts/details.tsx index 6479bdf803..fc10978507 100644 --- a/examples/react/basic-virtual-inside-file-based/src/routes/posts/details.tsx +++ b/examples/react/basic-virtual-inside-file-based/src/routes/posts/details.tsx @@ -1,9 +1,9 @@ import * as React from 'react' -import { ErrorComponent, createFileRoute } from '@tanstack/react-router' +import { ErrorComponent } from '@tanstack/react-router' import { fetchPost } from '../../posts' import type { ErrorComponentProps } from '@tanstack/react-router' -export const Route = createFileRoute('/posts/$postId')({ +export const Route = createFileRoute({ loader: async ({ params: { postId } }) => fetchPost(postId), errorComponent: PostErrorComponent, notFoundComponent: () => { diff --git a/examples/react/basic-virtual-inside-file-based/src/routes/posts/home.tsx b/examples/react/basic-virtual-inside-file-based/src/routes/posts/home.tsx index c6b65f1892..fdbe5865e5 100644 --- a/examples/react/basic-virtual-inside-file-based/src/routes/posts/home.tsx +++ b/examples/react/basic-virtual-inside-file-based/src/routes/posts/home.tsx @@ -1,7 +1,6 @@ -import { createFileRoute } from '@tanstack/react-router' import * as React from 'react' -export const Route = createFileRoute('/posts/')({ +export const Route = createFileRoute({ component: PostsIndexComponent, }) diff --git a/examples/react/basic-virtual-inside-file-based/src/routes/posts/lets-go/deeper/home.tsx b/examples/react/basic-virtual-inside-file-based/src/routes/posts/lets-go/deeper/home.tsx index d2e95051f6..f8bc76644a 100644 --- a/examples/react/basic-virtual-inside-file-based/src/routes/posts/lets-go/deeper/home.tsx +++ b/examples/react/basic-virtual-inside-file-based/src/routes/posts/lets-go/deeper/home.tsx @@ -1,4 +1,3 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/posts/inception/deeper/')({ +export const Route = createFileRoute({ component: () =>
Hello /posts/inception/deeper/!
, }) diff --git a/examples/react/basic-virtual-inside-file-based/src/routes/posts/lets-go/index.tsx b/examples/react/basic-virtual-inside-file-based/src/routes/posts/lets-go/index.tsx index 1a7358f044..1c7ea68931 100644 --- a/examples/react/basic-virtual-inside-file-based/src/routes/posts/lets-go/index.tsx +++ b/examples/react/basic-virtual-inside-file-based/src/routes/posts/lets-go/index.tsx @@ -1,4 +1,3 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/posts/inception/')({ +export const Route = createFileRoute({ component: () =>
Hello /posts/inception/!
, }) diff --git a/examples/react/basic-virtual-inside-file-based/src/vite-env.d.ts b/examples/react/basic-virtual-inside-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/basic-virtual-inside-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/basic-virtual-inside-file-based/vite.config.ts b/examples/react/basic-virtual-inside-file-based/vite.config.ts index e6a8f48b5f..9630396b91 100644 --- a/examples/react/basic-virtual-inside-file-based/vite.config.ts +++ b/examples/react/basic-virtual-inside-file-based/vite.config.ts @@ -10,6 +10,7 @@ export default defineConfig({ tanstackRouter({ target: 'react', autoCodeSplitting: true, + verboseFileRoutes: false, }), react(), ], diff --git a/examples/react/basic/.devcontainer/devcontainer.json b/examples/react/basic/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/basic/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/basic/package.json b/examples/react/basic/package.json index 2c09a3dfdf..a0745b1922 100644 --- a/examples/react/basic/package.json +++ b/examples/react/basic/package.json @@ -9,20 +9,19 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tailwindcss/vite": "^4.1.18", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.2.2" + "tailwindcss": "^4.1.18" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1" } } diff --git a/examples/react/basic/src/vite-env.d.ts b/examples/react/basic/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/basic/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/deferred-data/.devcontainer/devcontainer.json b/examples/react/deferred-data/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/deferred-data/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/deferred-data/package.json b/examples/react/deferred-data/package.json index 99afb661ee..b768c2fbe3 100644 --- a/examples/react/deferred-data/package.json +++ b/examples/react/deferred-data/package.json @@ -9,21 +9,20 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tailwindcss/vite": "^4.1.18", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "tailwindcss": "^4.1.18", + "zod": "^3.24.2" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1" } } diff --git a/examples/react/deferred-data/src/main.tsx b/examples/react/deferred-data/src/main.tsx index 0a37aa001d..ae5ae0f3fb 100644 --- a/examples/react/deferred-data/src/main.tsx +++ b/examples/react/deferred-data/src/main.tsx @@ -75,7 +75,7 @@ function Spinner({ show, wait }: { show?: boolean; wait?: `delay-${number}` }) {
diff --git a/examples/react/deferred-data/src/vite-env.d.ts b/examples/react/deferred-data/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/deferred-data/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/i18n-paraglide/.devcontainer/devcontainer.json b/examples/react/i18n-paraglide/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/i18n-paraglide/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/i18n-paraglide/README.md b/examples/react/i18n-paraglide/README.md index 98b25f6d0f..0f6b46536d 100644 --- a/examples/react/i18n-paraglide/README.md +++ b/examples/react/i18n-paraglide/README.md @@ -183,7 +183,7 @@ And import into the Paraglide Vite plugin. ## Server-side rendering -For server-side rendering, check out the [TanStack Start guide](https://github.com/TanStack/router/tree/main/examples/react/start-i18n-paraglide). +For server-side rendering with TanStack Start, check out the [Start Middleware guide](https://tanstack.com/router/latest/docs/framework/react/start/guide/middleware). ## Prerender routes diff --git a/examples/react/i18n-paraglide/package.json b/examples/react/i18n-paraglide/package.json index 88140e8911..3c7d4eeaba 100644 --- a/examples/react/i18n-paraglide/package.json +++ b/examples/react/i18n-paraglide/package.json @@ -10,32 +10,20 @@ "test": "vitest run" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/router-plugin": "^1.169.0", + "@tailwindcss/vite": "^4.1.18", + "@tanstack/react-router": "^1.161.1", + "@tanstack/router-plugin": "^1.161.1", "react": "^19.1.1", "react-dom": "^19.1.1", - "tailwindcss": "^4.2.2" + "tailwindcss": "^4.1.18" }, "devDependencies": { "@types/node": "^22.18.6", "@types/react": "^19.1.13", "@types/react-dom": "^19.1.9", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", + "@vitejs/plugin-react": "^5.0.3", + "typescript": "^5.9.2", + "vite": "^7.3.1", "@inlang/paraglide-js": "^2.4.0" - }, - "nx": { - "targets": { - "build": { - "outputs": [ - "...", - "{projectRoot}/src/paraglide", - "{projectRoot}/project.inlang/cache" - ] - } - } } } diff --git a/examples/react/i18n-paraglide/src/routeTree.gen.ts b/examples/react/i18n-paraglide/src/routeTree.gen.ts index 12bc916ae4..59499d9fbf 100644 --- a/examples/react/i18n-paraglide/src/routeTree.gen.ts +++ b/examples/react/i18n-paraglide/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 IndexRouteImport } from './routes/index' import { Route as AboutRouteImport } from './routes/about' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const AboutRoute = AboutRouteImport.update({ id: '/about', path: '/about', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/about': { id: '/about' path: '/about' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/i18n-paraglide/src/vite-env.d.ts b/examples/react/i18n-paraglide/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/i18n-paraglide/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/i18n-paraglide/tsconfig.json b/examples/react/i18n-paraglide/tsconfig.json index c26f8f774e..fded1fca18 100644 --- a/examples/react/i18n-paraglide/tsconfig.json +++ b/examples/react/i18n-paraglide/tsconfig.json @@ -21,6 +21,7 @@ "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "noUncheckedSideEffectImports": true, + "baseUrl": ".", "paths": { "@/*": ["./src/*"] } diff --git a/examples/react/kitchen-sink-file-based/.devcontainer/devcontainer.json b/examples/react/kitchen-sink-file-based/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/kitchen-sink-file-based/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/kitchen-sink-file-based/package.json b/examples/react/kitchen-sink-file-based/package.json index e02defb3ce..e40ac3e566 100644 --- a/examples/react/kitchen-sink-file-based/package.json +++ b/examples/react/kitchen-sink-file-based/package.json @@ -9,23 +9,22 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tailwindcss/vite": "^4.1.18", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", + "@tanstack/router-plugin": "^1.161.1", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "tailwindcss": "^4.1.18", + "zod": "^3.24.2" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1" } } diff --git a/examples/react/kitchen-sink-file-based/src/components/Spinner.tsx b/examples/react/kitchen-sink-file-based/src/components/Spinner.tsx index 6b89facdf0..101c31d35f 100644 --- a/examples/react/kitchen-sink-file-based/src/components/Spinner.tsx +++ b/examples/react/kitchen-sink-file-based/src/components/Spinner.tsx @@ -11,7 +11,7 @@ export function Spinner({
diff --git a/examples/react/kitchen-sink-file-based/src/routeTree.gen.ts b/examples/react/kitchen-sink-file-based/src/routeTree.gen.ts index 03af4e1e58..f3accfa48e 100644 --- a/examples/react/kitchen-sink-file-based/src/routeTree.gen.ts +++ b/examples/react/kitchen-sink-file-based/src/routeTree.gen.ts @@ -8,224 +8,132 @@ // 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 AuthRouteImport } from './routes/_auth' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' -import { Route as DashboardRouteRouteImport } from './routes/dashboard.route' +// Import Routes + +import { Route as rootRoute } from './routes/__root' import { Route as LoginRouteImport } from './routes/login' -import { Route as thisFolderIsNotInTheUrlRouteGroupRouteImport } from './routes/(this-folder-is-not-in-the-url)/route-group' -import { Route as AuthProfileRouteImport } from './routes/_auth.profile' -import { Route as PathlessLayoutRouteARouteImport } from './routes/_pathlessLayout.route-a' -import { Route as PathlessLayoutRouteBRouteImport } from './routes/_pathlessLayout.route-b' -import { Route as DashboardIndexRouteImport } from './routes/dashboard.index' -import { Route as DashboardInvoicesRouteRouteImport } from './routes/dashboard.invoices.route' -import { Route as DashboardUsersRouteRouteImport } from './routes/dashboard.users.route' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as AuthRouteImport } from './routes/_auth' +import { Route as DashboardRouteRouteImport } from './routes/dashboard.route' +import { Route as IndexRouteImport } from './routes/index' import { Route as ExpensiveIndexRouteImport } from './routes/expensive/index' -import { Route as DashboardInvoicesIndexRouteImport } from './routes/dashboard.invoices.index' -import { Route as DashboardInvoicesInvoiceIdRouteImport } from './routes/dashboard.invoices.$invoiceId' +import { Route as DashboardIndexRouteImport } from './routes/dashboard.index' +import { Route as PathlessLayoutRouteBRouteImport } from './routes/_pathlessLayout.route-b' +import { Route as PathlessLayoutRouteARouteImport } from './routes/_pathlessLayout.route-a' +import { Route as AuthProfileRouteImport } from './routes/_auth.profile' +import { Route as thisFolderIsNotInTheUrlRouteGroupRouteImport } from './routes/(this-folder-is-not-in-the-url)/route-group' +import { Route as DashboardUsersRouteRouteImport } from './routes/dashboard.users.route' +import { Route as DashboardInvoicesRouteRouteImport } from './routes/dashboard.invoices.route' import { Route as DashboardUsersIndexRouteImport } from './routes/dashboard.users.index' +import { Route as DashboardInvoicesIndexRouteImport } from './routes/dashboard.invoices.index' import { Route as DashboardUsersUserRouteImport } from './routes/dashboard.users.user' +import { Route as DashboardInvoicesInvoiceIdRouteImport } from './routes/dashboard.invoices.$invoiceId' + +// Create/Update Routes + +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', + getParentRoute: () => rootRoute, +} as any) + +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', + getParentRoute: () => rootRoute, +} as any) + +const AuthRoute = AuthRouteImport.update({ + id: '/_auth', + getParentRoute: () => rootRoute, +} as any) + +const DashboardRouteRoute = DashboardRouteRouteImport.update({ + id: '/dashboard', + path: '/dashboard', + getParentRoute: () => rootRoute, +} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => rootRouteImport, + getParentRoute: () => rootRoute, } as any) -const AuthRoute = AuthRouteImport.update({ - id: '/_auth', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', - getParentRoute: () => rootRouteImport, -} as any) -const DashboardRouteRoute = DashboardRouteRouteImport.update({ - id: '/dashboard', - path: '/dashboard', - getParentRoute: () => rootRouteImport, -} as any) -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', - getParentRoute: () => rootRouteImport, -} as any) -const thisFolderIsNotInTheUrlRouteGroupRoute = - thisFolderIsNotInTheUrlRouteGroupRouteImport.update({ - id: '/(this-folder-is-not-in-the-url)/route-group', - path: '/route-group', - getParentRoute: () => rootRouteImport, - } as any) -const AuthProfileRoute = AuthProfileRouteImport.update({ - id: '/profile', - path: '/profile', - getParentRoute: () => AuthRoute, -} as any) -const PathlessLayoutRouteARoute = PathlessLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutRoute, -} as any) -const PathlessLayoutRouteBRoute = PathlessLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutRoute, + +const ExpensiveIndexRoute = ExpensiveIndexRouteImport.update({ + id: '/expensive/', + path: '/expensive/', + getParentRoute: () => rootRoute, } as any) + const DashboardIndexRoute = DashboardIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => DashboardRouteRoute, } as any) -const DashboardInvoicesRouteRoute = DashboardInvoicesRouteRouteImport.update({ - id: '/invoices', - path: '/invoices', - getParentRoute: () => DashboardRouteRoute, + +const PathlessLayoutRouteBRoute = PathlessLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutRoute, } as any) + +const PathlessLayoutRouteARoute = PathlessLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutRoute, +} as any) + +const AuthProfileRoute = AuthProfileRouteImport.update({ + id: '/profile', + path: '/profile', + getParentRoute: () => AuthRoute, +} as any) + +const thisFolderIsNotInTheUrlRouteGroupRoute = + thisFolderIsNotInTheUrlRouteGroupRouteImport.update({ + id: '/(this-folder-is-not-in-the-url)/route-group', + path: '/route-group', + getParentRoute: () => rootRoute, + } as any) + const DashboardUsersRouteRoute = DashboardUsersRouteRouteImport.update({ id: '/users', path: '/users', getParentRoute: () => DashboardRouteRoute, } as any) -const ExpensiveIndexRoute = ExpensiveIndexRouteImport.update({ - id: '/expensive/', - path: '/expensive/', - getParentRoute: () => rootRouteImport, + +const DashboardInvoicesRouteRoute = DashboardInvoicesRouteRouteImport.update({ + id: '/invoices', + path: '/invoices', + getParentRoute: () => DashboardRouteRoute, } as any) -const DashboardInvoicesIndexRoute = DashboardInvoicesIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => DashboardInvoicesRouteRoute, -} as any) -const DashboardInvoicesInvoiceIdRoute = - DashboardInvoicesInvoiceIdRouteImport.update({ - id: '/$invoiceId', - path: '/$invoiceId', - getParentRoute: () => DashboardInvoicesRouteRoute, - } as any) + const DashboardUsersIndexRoute = DashboardUsersIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => DashboardUsersRouteRoute, } as any) + +const DashboardInvoicesIndexRoute = DashboardInvoicesIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => DashboardInvoicesRouteRoute, +} as any) + const DashboardUsersUserRoute = DashboardUsersUserRouteImport.update({ id: '/user', path: '/user', getParentRoute: () => DashboardUsersRouteRoute, } as any) -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/dashboard': typeof DashboardRouteRouteWithChildren - '/login': typeof LoginRoute - '/dashboard/invoices': typeof DashboardInvoicesRouteRouteWithChildren - '/dashboard/users': typeof DashboardUsersRouteRouteWithChildren - '/route-group': typeof thisFolderIsNotInTheUrlRouteGroupRoute - '/profile': typeof AuthProfileRoute - '/route-a': typeof PathlessLayoutRouteARoute - '/route-b': typeof PathlessLayoutRouteBRoute - '/dashboard/': typeof DashboardIndexRoute - '/expensive/': typeof ExpensiveIndexRoute - '/dashboard/invoices/$invoiceId': typeof DashboardInvoicesInvoiceIdRoute - '/dashboard/users/user': typeof DashboardUsersUserRoute - '/dashboard/invoices/': typeof DashboardInvoicesIndexRoute - '/dashboard/users/': typeof DashboardUsersIndexRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/login': typeof LoginRoute - '/route-group': typeof thisFolderIsNotInTheUrlRouteGroupRoute - '/profile': typeof AuthProfileRoute - '/route-a': typeof PathlessLayoutRouteARoute - '/route-b': typeof PathlessLayoutRouteBRoute - '/dashboard': typeof DashboardIndexRoute - '/expensive': typeof ExpensiveIndexRoute - '/dashboard/invoices/$invoiceId': typeof DashboardInvoicesInvoiceIdRoute - '/dashboard/users/user': typeof DashboardUsersUserRoute - '/dashboard/invoices': typeof DashboardInvoicesIndexRoute - '/dashboard/users': typeof DashboardUsersIndexRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/dashboard': typeof DashboardRouteRouteWithChildren - '/_auth': typeof AuthRouteWithChildren - '/_pathlessLayout': typeof PathlessLayoutRouteWithChildren - '/login': typeof LoginRoute - '/dashboard/invoices': typeof DashboardInvoicesRouteRouteWithChildren - '/dashboard/users': typeof DashboardUsersRouteRouteWithChildren - '/(this-folder-is-not-in-the-url)/route-group': typeof thisFolderIsNotInTheUrlRouteGroupRoute - '/_auth/profile': typeof AuthProfileRoute - '/_pathlessLayout/route-a': typeof PathlessLayoutRouteARoute - '/_pathlessLayout/route-b': typeof PathlessLayoutRouteBRoute - '/dashboard/': typeof DashboardIndexRoute - '/expensive/': typeof ExpensiveIndexRoute - '/dashboard/invoices/$invoiceId': typeof DashboardInvoicesInvoiceIdRoute - '/dashboard/users/user': typeof DashboardUsersUserRoute - '/dashboard/invoices/': typeof DashboardInvoicesIndexRoute - '/dashboard/users/': typeof DashboardUsersIndexRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/dashboard' - | '/login' - | '/dashboard/invoices' - | '/dashboard/users' - | '/route-group' - | '/profile' - | '/route-a' - | '/route-b' - | '/dashboard/' - | '/expensive/' - | '/dashboard/invoices/$invoiceId' - | '/dashboard/users/user' - | '/dashboard/invoices/' - | '/dashboard/users/' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/login' - | '/route-group' - | '/profile' - | '/route-a' - | '/route-b' - | '/dashboard' - | '/expensive' - | '/dashboard/invoices/$invoiceId' - | '/dashboard/users/user' - | '/dashboard/invoices' - | '/dashboard/users' - id: - | '__root__' - | '/' - | '/dashboard' - | '/_auth' - | '/_pathlessLayout' - | '/login' - | '/dashboard/invoices' - | '/dashboard/users' - | '/(this-folder-is-not-in-the-url)/route-group' - | '/_auth/profile' - | '/_pathlessLayout/route-a' - | '/_pathlessLayout/route-b' - | '/dashboard/' - | '/expensive/' - | '/dashboard/invoices/$invoiceId' - | '/dashboard/users/user' - | '/dashboard/invoices/' - | '/dashboard/users/' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - DashboardRouteRoute: typeof DashboardRouteRouteWithChildren - AuthRoute: typeof AuthRouteWithChildren - PathlessLayoutRoute: typeof PathlessLayoutRouteWithChildren - LoginRoute: typeof LoginRoute - thisFolderIsNotInTheUrlRouteGroupRoute: typeof thisFolderIsNotInTheUrlRouteGroupRoute - ExpensiveIndexRoute: typeof ExpensiveIndexRoute -} +const DashboardInvoicesInvoiceIdRoute = + DashboardInvoicesInvoiceIdRouteImport.update({ + id: '/$invoiceId', + path: '/$invoiceId', + getParentRoute: () => DashboardInvoicesRouteRoute, + } as any) + +// Populate the FileRoutesByPath interface declare module '@tanstack/react-router' { interface FileRoutesByPath { @@ -234,123 +142,125 @@ declare module '@tanstack/react-router' { path: '/' fullPath: '/' preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_auth': { - id: '/_auth' - path: '' - fullPath: '/' - preLoaderRoute: typeof AuthRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout': { - id: '/_pathlessLayout' - path: '' - fullPath: '/' - preLoaderRoute: typeof PathlessLayoutRouteImport - parentRoute: typeof rootRouteImport + parentRoute: typeof rootRoute } '/dashboard': { id: '/dashboard' path: '/dashboard' fullPath: '/dashboard' preLoaderRoute: typeof DashboardRouteRouteImport - parentRoute: typeof rootRouteImport + parentRoute: typeof rootRoute + } + '/_auth': { + id: '/_auth' + path: '' + fullPath: '' + preLoaderRoute: typeof AuthRouteImport + parentRoute: typeof rootRoute + } + '/_pathlessLayout': { + id: '/_pathlessLayout' + path: '' + fullPath: '' + preLoaderRoute: typeof PathlessLayoutRouteImport + parentRoute: typeof rootRoute } '/login': { id: '/login' path: '/login' fullPath: '/login' preLoaderRoute: typeof LoginRouteImport - parentRoute: typeof rootRouteImport - } - '/(this-folder-is-not-in-the-url)/route-group': { - id: '/(this-folder-is-not-in-the-url)/route-group' - path: '/route-group' - fullPath: '/route-group' - preLoaderRoute: typeof thisFolderIsNotInTheUrlRouteGroupRouteImport - parentRoute: typeof rootRouteImport - } - '/_auth/profile': { - id: '/_auth/profile' - path: '/profile' - fullPath: '/profile' - preLoaderRoute: typeof AuthProfileRouteImport - parentRoute: typeof AuthRoute - } - '/_pathlessLayout/route-a': { - id: '/_pathlessLayout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutRoute - } - '/_pathlessLayout/route-b': { - id: '/_pathlessLayout/route-b' - path: '/route-b' - fullPath: '/route-b' - preLoaderRoute: typeof PathlessLayoutRouteBRouteImport - parentRoute: typeof PathlessLayoutRoute - } - '/dashboard/': { - id: '/dashboard/' - path: '/' - fullPath: '/dashboard/' - preLoaderRoute: typeof DashboardIndexRouteImport - parentRoute: typeof DashboardRouteRoute + parentRoute: typeof rootRoute } '/dashboard/invoices': { id: '/dashboard/invoices' path: '/invoices' fullPath: '/dashboard/invoices' preLoaderRoute: typeof DashboardInvoicesRouteRouteImport - parentRoute: typeof DashboardRouteRoute + parentRoute: typeof DashboardRouteRouteImport } '/dashboard/users': { id: '/dashboard/users' path: '/users' fullPath: '/dashboard/users' preLoaderRoute: typeof DashboardUsersRouteRouteImport - parentRoute: typeof DashboardRouteRoute + parentRoute: typeof DashboardRouteRouteImport + } + '/(this-folder-is-not-in-the-url)/route-group': { + id: '/(this-folder-is-not-in-the-url)/route-group' + path: '/route-group' + fullPath: '/route-group' + preLoaderRoute: typeof thisFolderIsNotInTheUrlRouteGroupRouteImport + parentRoute: typeof rootRoute + } + '/_auth/profile': { + id: '/_auth/profile' + path: '/profile' + fullPath: '/profile' + preLoaderRoute: typeof AuthProfileRouteImport + parentRoute: typeof AuthRouteImport + } + '/_pathlessLayout/route-a': { + id: '/_pathlessLayout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutRouteImport + } + '/_pathlessLayout/route-b': { + id: '/_pathlessLayout/route-b' + path: '/route-b' + fullPath: '/route-b' + preLoaderRoute: typeof PathlessLayoutRouteBRouteImport + parentRoute: typeof PathlessLayoutRouteImport + } + '/dashboard/': { + id: '/dashboard/' + path: '/' + fullPath: '/dashboard/' + preLoaderRoute: typeof DashboardIndexRouteImport + parentRoute: typeof DashboardRouteRouteImport } '/expensive/': { id: '/expensive/' path: '/expensive' - fullPath: '/expensive/' + fullPath: '/expensive' preLoaderRoute: typeof ExpensiveIndexRouteImport - parentRoute: typeof rootRouteImport - } - '/dashboard/invoices/': { - id: '/dashboard/invoices/' - path: '/' - fullPath: '/dashboard/invoices/' - preLoaderRoute: typeof DashboardInvoicesIndexRouteImport - parentRoute: typeof DashboardInvoicesRouteRoute + parentRoute: typeof rootRoute } '/dashboard/invoices/$invoiceId': { id: '/dashboard/invoices/$invoiceId' path: '/$invoiceId' fullPath: '/dashboard/invoices/$invoiceId' preLoaderRoute: typeof DashboardInvoicesInvoiceIdRouteImport - parentRoute: typeof DashboardInvoicesRouteRoute - } - '/dashboard/users/': { - id: '/dashboard/users/' - path: '/' - fullPath: '/dashboard/users/' - preLoaderRoute: typeof DashboardUsersIndexRouteImport - parentRoute: typeof DashboardUsersRouteRoute + parentRoute: typeof DashboardInvoicesRouteRouteImport } '/dashboard/users/user': { id: '/dashboard/users/user' path: '/user' fullPath: '/dashboard/users/user' preLoaderRoute: typeof DashboardUsersUserRouteImport - parentRoute: typeof DashboardUsersRouteRoute + parentRoute: typeof DashboardUsersRouteRouteImport + } + '/dashboard/invoices/': { + id: '/dashboard/invoices/' + path: '/' + fullPath: '/dashboard/invoices/' + preLoaderRoute: typeof DashboardInvoicesIndexRouteImport + parentRoute: typeof DashboardInvoicesRouteRouteImport + } + '/dashboard/users/': { + id: '/dashboard/users/' + path: '/' + fullPath: '/dashboard/users/' + preLoaderRoute: typeof DashboardUsersIndexRouteImport + parentRoute: typeof DashboardUsersRouteRouteImport } } } +// Create and export the route tree + interface DashboardInvoicesRouteRouteChildren { DashboardInvoicesInvoiceIdRoute: typeof DashboardInvoicesInvoiceIdRoute DashboardInvoicesIndexRoute: typeof DashboardInvoicesIndexRoute @@ -420,6 +330,128 @@ const PathlessLayoutRouteWithChildren = PathlessLayoutRoute._addFileChildren( PathlessLayoutRouteChildren, ) +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/dashboard': typeof DashboardRouteRouteWithChildren + '': typeof PathlessLayoutRouteWithChildren + '/login': typeof LoginRoute + '/dashboard/invoices': typeof DashboardInvoicesRouteRouteWithChildren + '/dashboard/users': typeof DashboardUsersRouteRouteWithChildren + '/route-group': typeof thisFolderIsNotInTheUrlRouteGroupRoute + '/profile': typeof AuthProfileRoute + '/route-a': typeof PathlessLayoutRouteARoute + '/route-b': typeof PathlessLayoutRouteBRoute + '/dashboard/': typeof DashboardIndexRoute + '/expensive': typeof ExpensiveIndexRoute + '/dashboard/invoices/$invoiceId': typeof DashboardInvoicesInvoiceIdRoute + '/dashboard/users/user': typeof DashboardUsersUserRoute + '/dashboard/invoices/': typeof DashboardInvoicesIndexRoute + '/dashboard/users/': typeof DashboardUsersIndexRoute +} + +export interface FileRoutesByTo { + '/': typeof IndexRoute + '': typeof PathlessLayoutRouteWithChildren + '/login': typeof LoginRoute + '/route-group': typeof thisFolderIsNotInTheUrlRouteGroupRoute + '/profile': typeof AuthProfileRoute + '/route-a': typeof PathlessLayoutRouteARoute + '/route-b': typeof PathlessLayoutRouteBRoute + '/dashboard': typeof DashboardIndexRoute + '/expensive': typeof ExpensiveIndexRoute + '/dashboard/invoices/$invoiceId': typeof DashboardInvoicesInvoiceIdRoute + '/dashboard/users/user': typeof DashboardUsersUserRoute + '/dashboard/invoices': typeof DashboardInvoicesIndexRoute + '/dashboard/users': typeof DashboardUsersIndexRoute +} + +export interface FileRoutesById { + __root__: typeof rootRoute + '/': typeof IndexRoute + '/dashboard': typeof DashboardRouteRouteWithChildren + '/_auth': typeof AuthRouteWithChildren + '/_pathlessLayout': typeof PathlessLayoutRouteWithChildren + '/login': typeof LoginRoute + '/dashboard/invoices': typeof DashboardInvoicesRouteRouteWithChildren + '/dashboard/users': typeof DashboardUsersRouteRouteWithChildren + '/(this-folder-is-not-in-the-url)/route-group': typeof thisFolderIsNotInTheUrlRouteGroupRoute + '/_auth/profile': typeof AuthProfileRoute + '/_pathlessLayout/route-a': typeof PathlessLayoutRouteARoute + '/_pathlessLayout/route-b': typeof PathlessLayoutRouteBRoute + '/dashboard/': typeof DashboardIndexRoute + '/expensive/': typeof ExpensiveIndexRoute + '/dashboard/invoices/$invoiceId': typeof DashboardInvoicesInvoiceIdRoute + '/dashboard/users/user': typeof DashboardUsersUserRoute + '/dashboard/invoices/': typeof DashboardInvoicesIndexRoute + '/dashboard/users/': typeof DashboardUsersIndexRoute +} + +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/dashboard' + | '' + | '/login' + | '/dashboard/invoices' + | '/dashboard/users' + | '/route-group' + | '/profile' + | '/route-a' + | '/route-b' + | '/dashboard/' + | '/expensive' + | '/dashboard/invoices/$invoiceId' + | '/dashboard/users/user' + | '/dashboard/invoices/' + | '/dashboard/users/' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '' + | '/login' + | '/route-group' + | '/profile' + | '/route-a' + | '/route-b' + | '/dashboard' + | '/expensive' + | '/dashboard/invoices/$invoiceId' + | '/dashboard/users/user' + | '/dashboard/invoices' + | '/dashboard/users' + id: + | '__root__' + | '/' + | '/dashboard' + | '/_auth' + | '/_pathlessLayout' + | '/login' + | '/dashboard/invoices' + | '/dashboard/users' + | '/(this-folder-is-not-in-the-url)/route-group' + | '/_auth/profile' + | '/_pathlessLayout/route-a' + | '/_pathlessLayout/route-b' + | '/dashboard/' + | '/expensive/' + | '/dashboard/invoices/$invoiceId' + | '/dashboard/users/user' + | '/dashboard/invoices/' + | '/dashboard/users/' + fileRoutesById: FileRoutesById +} + +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + DashboardRouteRoute: typeof DashboardRouteRouteWithChildren + AuthRoute: typeof AuthRouteWithChildren + PathlessLayoutRoute: typeof PathlessLayoutRouteWithChildren + LoginRoute: typeof LoginRoute + thisFolderIsNotInTheUrlRouteGroupRoute: typeof thisFolderIsNotInTheUrlRouteGroupRoute + ExpensiveIndexRoute: typeof ExpensiveIndexRoute +} + const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, DashboardRouteRoute: DashboardRouteRouteWithChildren, @@ -430,6 +462,107 @@ const rootRouteChildren: RootRouteChildren = { thisFolderIsNotInTheUrlRouteGroupRoute, ExpensiveIndexRoute: ExpensiveIndexRoute, } -export const routeTree = rootRouteImport + +export const routeTree = rootRoute ._addFileChildren(rootRouteChildren) ._addFileTypes() + +/* ROUTE_MANIFEST_START +{ + "routes": { + "__root__": { + "filePath": "__root.tsx", + "children": [ + "/", + "/dashboard", + "/_auth", + "/_pathlessLayout", + "/login", + "/(this-folder-is-not-in-the-url)/route-group", + "/expensive/" + ] + }, + "/": { + "filePath": "index.tsx" + }, + "/dashboard": { + "filePath": "dashboard.route.tsx", + "children": [ + "/dashboard/invoices", + "/dashboard/users", + "/dashboard/" + ] + }, + "/_auth": { + "filePath": "_auth.tsx", + "children": [ + "/_auth/profile" + ] + }, + "/_pathlessLayout": { + "filePath": "_pathlessLayout.tsx", + "children": [ + "/_pathlessLayout/route-a", + "/_pathlessLayout/route-b" + ] + }, + "/login": { + "filePath": "login.tsx" + }, + "/dashboard/invoices": { + "filePath": "dashboard.invoices.route.tsx", + "parent": "/dashboard", + "children": [ + "/dashboard/invoices/$invoiceId", + "/dashboard/invoices/" + ] + }, + "/dashboard/users": { + "filePath": "dashboard.users.route.tsx", + "parent": "/dashboard", + "children": [ + "/dashboard/users/user", + "/dashboard/users/" + ] + }, + "/(this-folder-is-not-in-the-url)/route-group": { + "filePath": "(this-folder-is-not-in-the-url)/route-group.tsx" + }, + "/_auth/profile": { + "filePath": "_auth.profile.tsx", + "parent": "/_auth" + }, + "/_pathlessLayout/route-a": { + "filePath": "_pathlessLayout.route-a.tsx", + "parent": "/_pathlessLayout" + }, + "/_pathlessLayout/route-b": { + "filePath": "_pathlessLayout.route-b.tsx", + "parent": "/_pathlessLayout" + }, + "/dashboard/": { + "filePath": "dashboard.index.tsx", + "parent": "/dashboard" + }, + "/expensive/": { + "filePath": "expensive/index.tsx" + }, + "/dashboard/invoices/$invoiceId": { + "filePath": "dashboard.invoices.$invoiceId.tsx", + "parent": "/dashboard/invoices" + }, + "/dashboard/users/user": { + "filePath": "dashboard.users.user.tsx", + "parent": "/dashboard/users" + }, + "/dashboard/invoices/": { + "filePath": "dashboard.invoices.index.tsx", + "parent": "/dashboard/invoices" + }, + "/dashboard/users/": { + "filePath": "dashboard.users.index.tsx", + "parent": "/dashboard/users" + } + } +} +ROUTE_MANIFEST_END */ diff --git a/examples/react/kitchen-sink-file-based/src/vite-env.d.ts b/examples/react/kitchen-sink-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/kitchen-sink-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/kitchen-sink-react-query-file-based/.devcontainer/devcontainer.json b/examples/react/kitchen-sink-react-query-file-based/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/kitchen-sink-react-query-file-based/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/kitchen-sink-react-query-file-based/package.json b/examples/react/kitchen-sink-react-query-file-based/package.json index e3dd032ac2..0984dc3bcb 100644 --- a/examples/react/kitchen-sink-react-query-file-based/package.json +++ b/examples/react/kitchen-sink-react-query-file-based/package.json @@ -9,25 +9,24 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.102.0", + "@tailwindcss/vite": "^4.1.18", + "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", + "@tanstack/router-plugin": "^1.161.1", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "tailwindcss": "^4.1.18", + "zod": "^3.24.2" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1" } } diff --git a/examples/react/kitchen-sink-react-query-file-based/src/components/Spinner.tsx b/examples/react/kitchen-sink-react-query-file-based/src/components/Spinner.tsx index 6b89facdf0..101c31d35f 100644 --- a/examples/react/kitchen-sink-react-query-file-based/src/components/Spinner.tsx +++ b/examples/react/kitchen-sink-react-query-file-based/src/components/Spinner.tsx @@ -11,7 +11,7 @@ export function Spinner({
diff --git a/examples/react/kitchen-sink-react-query-file-based/src/routeTree.gen.ts b/examples/react/kitchen-sink-react-query-file-based/src/routeTree.gen.ts index dbce8cf604..c18ab6eb46 100644 --- a/examples/react/kitchen-sink-react-query-file-based/src/routeTree.gen.ts +++ b/examples/react/kitchen-sink-react-query-file-based/src/routeTree.gen.ts @@ -9,65 +9,80 @@ // 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 AuthRouteImport } from './routes/_auth' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' -import { Route as DashboardRouteRouteImport } from './routes/dashboard.route' import { Route as LoginRouteImport } from './routes/login' -import { Route as AuthProfileRouteImport } from './routes/_auth.profile' -import { Route as PathlessLayoutRouteARouteImport } from './routes/_pathlessLayout.route-a' -import { Route as PathlessLayoutRouteBRouteImport } from './routes/_pathlessLayout.route-b' -import { Route as DashboardIndexRouteImport } from './routes/dashboard.index' -import { Route as DashboardInvoicesRouteRouteImport } from './routes/dashboard.invoices.route' -import { Route as DashboardUsersRouteRouteImport } from './routes/dashboard.users.route' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as AuthRouteImport } from './routes/_auth' +import { Route as DashboardRouteRouteImport } from './routes/dashboard.route' +import { Route as IndexRouteImport } from './routes/index' import { Route as ExpensiveIndexRouteImport } from './routes/expensive/index' +import { Route as DashboardIndexRouteImport } from './routes/dashboard.index' import { Route as FooBarRouteImport } from './routes/foo/bar' -import { Route as DashboardInvoicesIndexRouteImport } from './routes/dashboard.invoices.index' -import { Route as DashboardInvoicesInvoiceIdRouteImport } from './routes/dashboard.invoices.$invoiceId' +import { Route as PathlessLayoutRouteBRouteImport } from './routes/_pathlessLayout.route-b' +import { Route as PathlessLayoutRouteARouteImport } from './routes/_pathlessLayout.route-a' +import { Route as AuthProfileRouteImport } from './routes/_auth.profile' +import { Route as DashboardUsersRouteRouteImport } from './routes/dashboard.users.route' +import { Route as DashboardInvoicesRouteRouteImport } from './routes/dashboard.invoices.route' import { Route as DashboardUsersIndexRouteImport } from './routes/dashboard.users.index' +import { Route as DashboardInvoicesIndexRouteImport } from './routes/dashboard.invoices.index' import { Route as DashboardUsersUserRouteImport } from './routes/dashboard.users.user' +import { Route as DashboardInvoicesInvoiceIdRouteImport } from './routes/dashboard.invoices.$invoiceId' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AuthRoute = AuthRouteImport.update({ - id: '/_auth', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) +const AuthRoute = AuthRouteImport.update({ + id: '/_auth', + getParentRoute: () => rootRouteImport, +} as any) const DashboardRouteRoute = DashboardRouteRouteImport.update({ id: '/dashboard', path: '/dashboard', getParentRoute: () => rootRouteImport, } as any) -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const AuthProfileRoute = AuthProfileRouteImport.update({ - id: '/profile', - path: '/profile', - getParentRoute: () => AuthRoute, +const ExpensiveIndexRoute = ExpensiveIndexRouteImport.update({ + id: '/expensive/', + path: '/expensive/', + getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutRouteARoute = PathlessLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutRoute, +const DashboardIndexRoute = DashboardIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => DashboardRouteRoute, +} as any) +const FooBarRoute = FooBarRouteImport.update({ + id: '/foo/bar', + path: '/foo/bar', + getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutRouteBRoute = PathlessLayoutRouteBRouteImport.update({ id: '/route-b', path: '/route-b', getParentRoute: () => PathlessLayoutRoute, } as any) -const DashboardIndexRoute = DashboardIndexRouteImport.update({ - id: '/', - path: '/', +const PathlessLayoutRouteARoute = PathlessLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutRoute, +} as any) +const AuthProfileRoute = AuthProfileRouteImport.update({ + id: '/profile', + path: '/profile', + getParentRoute: () => AuthRoute, +} as any) +const DashboardUsersRouteRoute = DashboardUsersRouteRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => DashboardRouteRoute, } as any) const DashboardInvoicesRouteRoute = DashboardInvoicesRouteRouteImport.update({ @@ -75,42 +90,27 @@ const DashboardInvoicesRouteRoute = DashboardInvoicesRouteRouteImport.update({ path: '/invoices', getParentRoute: () => DashboardRouteRoute, } as any) -const DashboardUsersRouteRoute = DashboardUsersRouteRouteImport.update({ - id: '/users', - path: '/users', - getParentRoute: () => DashboardRouteRoute, -} as any) -const ExpensiveIndexRoute = ExpensiveIndexRouteImport.update({ - id: '/expensive/', - path: '/expensive/', - getParentRoute: () => rootRouteImport, -} as any) -const FooBarRoute = FooBarRouteImport.update({ - id: '/foo/bar', - path: '/foo/bar', - getParentRoute: () => rootRouteImport, +const DashboardUsersIndexRoute = DashboardUsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => DashboardUsersRouteRoute, } as any) const DashboardInvoicesIndexRoute = DashboardInvoicesIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => DashboardInvoicesRouteRoute, } as any) +const DashboardUsersUserRoute = DashboardUsersUserRouteImport.update({ + id: '/user', + path: '/user', + getParentRoute: () => DashboardUsersRouteRoute, +} as any) const DashboardInvoicesInvoiceIdRoute = DashboardInvoicesInvoiceIdRouteImport.update({ id: '/$invoiceId', path: '/$invoiceId', getParentRoute: () => DashboardInvoicesRouteRoute, } as any) -const DashboardUsersIndexRoute = DashboardUsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => DashboardUsersRouteRoute, -} as any) -const DashboardUsersUserRoute = DashboardUsersUserRouteImport.update({ - id: '/user', - path: '/user', - getParentRoute: () => DashboardUsersRouteRoute, -} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -123,7 +123,7 @@ export interface FileRoutesByFullPath { '/route-b': typeof PathlessLayoutRouteBRoute '/foo/bar': typeof FooBarRoute '/dashboard/': typeof DashboardIndexRoute - '/expensive/': typeof ExpensiveIndexRoute + '/expensive': typeof ExpensiveIndexRoute '/dashboard/invoices/$invoiceId': typeof DashboardInvoicesInvoiceIdRoute '/dashboard/users/user': typeof DashboardUsersUserRoute '/dashboard/invoices/': typeof DashboardInvoicesIndexRoute @@ -176,7 +176,7 @@ export interface FileRouteTypes { | '/route-b' | '/foo/bar' | '/dashboard/' - | '/expensive/' + | '/expensive' | '/dashboard/invoices/$invoiceId' | '/dashboard/users/user' | '/dashboard/invoices/' @@ -228,27 +228,27 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_auth': { - id: '/_auth' - path: '' - fullPath: '/' - preLoaderRoute: typeof AuthRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout': { id: '/_pathlessLayout' path: '' - fullPath: '/' + fullPath: '' preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } + '/_auth': { + id: '/_auth' + path: '' + fullPath: '' + preLoaderRoute: typeof AuthRouteImport + parentRoute: typeof rootRouteImport + } '/dashboard': { id: '/dashboard' path: '/dashboard' @@ -256,26 +256,33 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DashboardRouteRouteImport parentRoute: typeof rootRouteImport } - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/_auth/profile': { - id: '/_auth/profile' - path: '/profile' - fullPath: '/profile' - preLoaderRoute: typeof AuthProfileRouteImport - parentRoute: typeof AuthRoute + '/expensive/': { + id: '/expensive/' + path: '/expensive' + fullPath: '/expensive' + preLoaderRoute: typeof ExpensiveIndexRouteImport + parentRoute: typeof rootRouteImport } - '/_pathlessLayout/route-a': { - id: '/_pathlessLayout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutRoute + '/dashboard/': { + id: '/dashboard/' + path: '/' + fullPath: '/dashboard/' + preLoaderRoute: typeof DashboardIndexRouteImport + parentRoute: typeof DashboardRouteRoute + } + '/foo/bar': { + id: '/foo/bar' + path: '/foo/bar' + fullPath: '/foo/bar' + preLoaderRoute: typeof FooBarRouteImport + parentRoute: typeof rootRouteImport } '/_pathlessLayout/route-b': { id: '/_pathlessLayout/route-b' @@ -284,11 +291,25 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutRoute } - '/dashboard/': { - id: '/dashboard/' - path: '/' - fullPath: '/dashboard/' - preLoaderRoute: typeof DashboardIndexRouteImport + '/_pathlessLayout/route-a': { + id: '/_pathlessLayout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutRoute + } + '/_auth/profile': { + id: '/_auth/profile' + path: '/profile' + fullPath: '/profile' + preLoaderRoute: typeof AuthProfileRouteImport + parentRoute: typeof AuthRoute + } + '/dashboard/users': { + id: '/dashboard/users' + path: '/users' + fullPath: '/dashboard/users' + preLoaderRoute: typeof DashboardUsersRouteRouteImport parentRoute: typeof DashboardRouteRoute } '/dashboard/invoices': { @@ -298,26 +319,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DashboardInvoicesRouteRouteImport parentRoute: typeof DashboardRouteRoute } - '/dashboard/users': { - id: '/dashboard/users' - path: '/users' - fullPath: '/dashboard/users' - preLoaderRoute: typeof DashboardUsersRouteRouteImport - parentRoute: typeof DashboardRouteRoute - } - '/expensive/': { - id: '/expensive/' - path: '/expensive' - fullPath: '/expensive/' - preLoaderRoute: typeof ExpensiveIndexRouteImport - parentRoute: typeof rootRouteImport - } - '/foo/bar': { - id: '/foo/bar' - path: '/foo/bar' - fullPath: '/foo/bar' - preLoaderRoute: typeof FooBarRouteImport - parentRoute: typeof rootRouteImport + '/dashboard/users/': { + id: '/dashboard/users/' + path: '/' + fullPath: '/dashboard/users/' + preLoaderRoute: typeof DashboardUsersIndexRouteImport + parentRoute: typeof DashboardUsersRouteRoute } '/dashboard/invoices/': { id: '/dashboard/invoices/' @@ -326,20 +333,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DashboardInvoicesIndexRouteImport parentRoute: typeof DashboardInvoicesRouteRoute } - '/dashboard/invoices/$invoiceId': { - id: '/dashboard/invoices/$invoiceId' - path: '/$invoiceId' - fullPath: '/dashboard/invoices/$invoiceId' - preLoaderRoute: typeof DashboardInvoicesInvoiceIdRouteImport - parentRoute: typeof DashboardInvoicesRouteRoute - } - '/dashboard/users/': { - id: '/dashboard/users/' - path: '/' - fullPath: '/dashboard/users/' - preLoaderRoute: typeof DashboardUsersIndexRouteImport - parentRoute: typeof DashboardUsersRouteRoute - } '/dashboard/users/user': { id: '/dashboard/users/user' path: '/user' @@ -347,6 +340,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DashboardUsersUserRouteImport parentRoute: typeof DashboardUsersRouteRoute } + '/dashboard/invoices/$invoiceId': { + id: '/dashboard/invoices/$invoiceId' + path: '/$invoiceId' + fullPath: '/dashboard/invoices/$invoiceId' + preLoaderRoute: typeof DashboardInvoicesInvoiceIdRouteImport + parentRoute: typeof DashboardInvoicesRouteRoute + } } } diff --git a/examples/react/kitchen-sink-react-query-file-based/src/vite-env.d.ts b/examples/react/kitchen-sink-react-query-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/kitchen-sink-react-query-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/kitchen-sink-react-query/.devcontainer/devcontainer.json b/examples/react/kitchen-sink-react-query/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/kitchen-sink-react-query/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/kitchen-sink-react-query/package.json b/examples/react/kitchen-sink-react-query/package.json index 14d0dc8e86..34190a0a9b 100644 --- a/examples/react/kitchen-sink-react-query/package.json +++ b/examples/react/kitchen-sink-react-query/package.json @@ -9,24 +9,23 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.102.0", + "@tailwindcss/vite": "^4.1.18", + "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "tailwindcss": "^4.1.18", + "zod": "^3.24.2" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1" } } diff --git a/examples/react/kitchen-sink-react-query/src/main.tsx b/examples/react/kitchen-sink-react-query/src/main.tsx index 93f885aaca..be34b9607a 100644 --- a/examples/react/kitchen-sink-react-query/src/main.tsx +++ b/examples/react/kitchen-sink-react-query/src/main.tsx @@ -1090,7 +1090,7 @@ function Spinner({ show, wait }: { show?: boolean; wait?: `delay-${number}` }) {
diff --git a/examples/react/kitchen-sink-react-query/src/vite-env.d.ts b/examples/react/kitchen-sink-react-query/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/kitchen-sink-react-query/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/kitchen-sink/.devcontainer/devcontainer.json b/examples/react/kitchen-sink/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/kitchen-sink/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/kitchen-sink/package.json b/examples/react/kitchen-sink/package.json index f738efc37e..991a7ec2eb 100644 --- a/examples/react/kitchen-sink/package.json +++ b/examples/react/kitchen-sink/package.json @@ -9,22 +9,21 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tailwindcss/vite": "^4.1.18", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "tailwindcss": "^4.1.18", + "zod": "^3.24.2" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1" } } diff --git a/examples/react/kitchen-sink/src/main.tsx b/examples/react/kitchen-sink/src/main.tsx index 1f6a355302..ce7687c666 100644 --- a/examples/react/kitchen-sink/src/main.tsx +++ b/examples/react/kitchen-sink/src/main.tsx @@ -1048,7 +1048,7 @@ function Spinner({ show, wait }: { show?: boolean; wait?: `delay-${number}` }) {
diff --git a/examples/react/kitchen-sink/src/vite-env.d.ts b/examples/react/kitchen-sink/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/kitchen-sink/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/large-file-based/.devcontainer/devcontainer.json b/examples/react/large-file-based/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/large-file-based/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/large-file-based/package.json b/examples/react/large-file-based/package.json index 23d469d120..5ef16fb179 100644 --- a/examples/react/large-file-based/package.json +++ b/examples/react/large-file-based/package.json @@ -11,23 +11,22 @@ "test:types": "tsc --extendedDiagnostics" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.102.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tailwindcss/vite": "^4.1.18", + "@tanstack/react-query": "^5.90.0", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", + "@tanstack/router-plugin": "^1.161.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "tailwindcss": "^4.1.18", + "zod": "^3.24.2" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1" } } diff --git a/examples/react/large-file-based/src/routeTree.gen.ts b/examples/react/large-file-based/src/routeTree.gen.ts index 8494f51d73..93a5be975c 100644 --- a/examples/react/large-file-based/src/routeTree.gen.ts +++ b/examples/react/large-file-based/src/routeTree.gen.ts @@ -9,23 +9,18 @@ // 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 AbsoluteRouteImport } from './routes/absolute' -import { Route as LinkPropsRouteImport } from './routes/linkProps' -import { Route as ParamsRouteRouteImport } from './routes/params/route' import { Route as RelativeRouteImport } from './routes/relative' +import { Route as LinkPropsRouteImport } from './routes/linkProps' +import { Route as AbsoluteRouteImport } from './routes/absolute' import { Route as SearchRouteRouteImport } from './routes/search/route' -import { Route as ParamsParamsPlaceholderRouteImport } from './routes/params/$paramsPlaceholder' +import { Route as ParamsRouteRouteImport } from './routes/params/route' +import { Route as IndexRouteImport } from './routes/index' import { Route as SearchSearchPlaceholderRouteImport } from './routes/search/searchPlaceholder' +import { Route as ParamsParamsPlaceholderRouteImport } from './routes/params/$paramsPlaceholder' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AbsoluteRoute = AbsoluteRouteImport.update({ - id: '/absolute', - path: '/absolute', +const RelativeRoute = RelativeRouteImport.update({ + id: '/relative', + path: '/relative', getParentRoute: () => rootRouteImport, } as any) const LinkPropsRoute = LinkPropsRouteImport.update({ @@ -33,14 +28,9 @@ const LinkPropsRoute = LinkPropsRouteImport.update({ path: '/linkProps', getParentRoute: () => rootRouteImport, } as any) -const ParamsRouteRoute = ParamsRouteRouteImport.update({ - id: '/params', - path: '/params', - getParentRoute: () => rootRouteImport, -} as any) -const RelativeRoute = RelativeRouteImport.update({ - id: '/relative', - path: '/relative', +const AbsoluteRoute = AbsoluteRouteImport.update({ + id: '/absolute', + path: '/absolute', getParentRoute: () => rootRouteImport, } as any) const SearchRouteRoute = SearchRouteRouteImport.update({ @@ -48,16 +38,26 @@ const SearchRouteRoute = SearchRouteRouteImport.update({ path: '/search', getParentRoute: () => rootRouteImport, } as any) -const ParamsParamsPlaceholderRoute = ParamsParamsPlaceholderRouteImport.update({ - id: '/$paramsPlaceholder', - path: '/$paramsPlaceholder', - getParentRoute: () => ParamsRouteRoute, +const ParamsRouteRoute = ParamsRouteRouteImport.update({ + id: '/params', + path: '/params', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, } as any) const SearchSearchPlaceholderRoute = SearchSearchPlaceholderRouteImport.update({ id: '/searchPlaceholder', path: '/searchPlaceholder', getParentRoute: () => SearchRouteRoute, } as any) +const ParamsParamsPlaceholderRoute = ParamsParamsPlaceholderRouteImport.update({ + id: '/$paramsPlaceholder', + path: '/$paramsPlaceholder', + getParentRoute: () => ParamsRouteRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -134,18 +134,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/absolute': { - id: '/absolute' - path: '/absolute' - fullPath: '/absolute' - preLoaderRoute: typeof AbsoluteRouteImport + '/relative': { + id: '/relative' + path: '/relative' + fullPath: '/relative' + preLoaderRoute: typeof RelativeRouteImport parentRoute: typeof rootRouteImport } '/linkProps': { @@ -155,18 +148,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LinkPropsRouteImport parentRoute: typeof rootRouteImport } - '/params': { - id: '/params' - path: '/params' - fullPath: '/params' - preLoaderRoute: typeof ParamsRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/relative': { - id: '/relative' - path: '/relative' - fullPath: '/relative' - preLoaderRoute: typeof RelativeRouteImport + '/absolute': { + id: '/absolute' + path: '/absolute' + fullPath: '/absolute' + preLoaderRoute: typeof AbsoluteRouteImport parentRoute: typeof rootRouteImport } '/search': { @@ -176,12 +162,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof SearchRouteRouteImport parentRoute: typeof rootRouteImport } - '/params/$paramsPlaceholder': { - id: '/params/$paramsPlaceholder' - path: '/$paramsPlaceholder' - fullPath: '/params/$paramsPlaceholder' - preLoaderRoute: typeof ParamsParamsPlaceholderRouteImport - parentRoute: typeof ParamsRouteRoute + '/params': { + id: '/params' + path: '/params' + fullPath: '/params' + preLoaderRoute: typeof ParamsRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/search/searchPlaceholder': { id: '/search/searchPlaceholder' @@ -190,6 +183,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof SearchSearchPlaceholderRouteImport parentRoute: typeof SearchRouteRoute } + '/params/$paramsPlaceholder': { + id: '/params/$paramsPlaceholder' + path: '/$paramsPlaceholder' + fullPath: '/params/$paramsPlaceholder' + preLoaderRoute: typeof ParamsParamsPlaceholderRouteImport + parentRoute: typeof ParamsRouteRoute + } } } diff --git a/examples/react/large-file-based/src/vite-env.d.ts b/examples/react/large-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/large-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/location-masking/.devcontainer/devcontainer.json b/examples/react/location-masking/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/location-masking/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/location-masking/package.json b/examples/react/location-masking/package.json index fe005c0d2f..54b88147bb 100644 --- a/examples/react/location-masking/package.json +++ b/examples/react/location-masking/package.json @@ -10,21 +10,20 @@ }, "dependencies": { "@radix-ui/react-dialog": "^1.1.6", - "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.102.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tailwindcss/vite": "^4.1.18", + "@tanstack/react-query": "^5.90.0", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.2.2" + "tailwindcss": "^4.1.18" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1" } } diff --git a/examples/react/location-masking/src/vite-env.d.ts b/examples/react/location-masking/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/location-masking/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/navigation-blocking/.devcontainer/devcontainer.json b/examples/react/navigation-blocking/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/navigation-blocking/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/navigation-blocking/package.json b/examples/react/navigation-blocking/package.json index a7677dfd51..ded7ebc58c 100644 --- a/examples/react/navigation-blocking/package.json +++ b/examples/react/navigation-blocking/package.json @@ -9,21 +9,20 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.102.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tailwindcss/vite": "^4.1.18", + "@tanstack/react-query": "^5.90.0", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.2.2" + "tailwindcss": "^4.1.18" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1" } } diff --git a/examples/react/navigation-blocking/src/vite-env.d.ts b/examples/react/navigation-blocking/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/navigation-blocking/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/quickstart-esbuild-file-based/.devcontainer/devcontainer.json b/examples/react/quickstart-esbuild-file-based/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/quickstart-esbuild-file-based/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/quickstart-esbuild-file-based/esbuild.config.js b/examples/react/quickstart-esbuild-file-based/esbuild.config.js index 2f83a79984..fb7950d1fa 100644 --- a/examples/react/quickstart-esbuild-file-based/esbuild.config.js +++ b/examples/react/quickstart-esbuild-file-based/esbuild.config.js @@ -7,5 +7,5 @@ export default { bundle: true, format: 'esm', target: ['esnext'], - plugins: [tanstackRouter({ target: 'react' })], + plugins: [tanstackRouter({ target: 'react', autoCodeSplitting: true })], } diff --git a/examples/react/quickstart-esbuild-file-based/package.json b/examples/react/quickstart-esbuild-file-based/package.json index d855694fec..e0c99b418f 100644 --- a/examples/react/quickstart-esbuild-file-based/package.json +++ b/examples/react/quickstart-esbuild-file-based/package.json @@ -9,17 +9,17 @@ "start": "dev" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", + "@tanstack/router-plugin": "^1.161.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "esbuild": "^0.27.4" + "esbuild": "^0.25.0" } } diff --git a/examples/react/quickstart-file-based/.devcontainer/devcontainer.json b/examples/react/quickstart-file-based/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/quickstart-file-based/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/quickstart-file-based/package.json b/examples/react/quickstart-file-based/package.json index 976ec838d1..dcca6ada99 100644 --- a/examples/react/quickstart-file-based/package.json +++ b/examples/react/quickstart-file-based/package.json @@ -9,22 +9,21 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tailwindcss/vite": "^4.1.18", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", + "@tanstack/router-plugin": "^1.161.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.2.2", - "zod": "^4.4.3" + "tailwindcss": "^4.1.18", + "zod": "^3.24.2" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1" } } diff --git a/examples/react/quickstart-file-based/src/routeTree.gen.ts b/examples/react/quickstart-file-based/src/routeTree.gen.ts index 12bc916ae4..59499d9fbf 100644 --- a/examples/react/quickstart-file-based/src/routeTree.gen.ts +++ b/examples/react/quickstart-file-based/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 IndexRouteImport } from './routes/index' import { Route as AboutRouteImport } from './routes/about' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const AboutRoute = AboutRouteImport.update({ id: '/about', path: '/about', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/about': { id: '/about' path: '/about' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/quickstart-file-based/src/vite-env.d.ts b/examples/react/quickstart-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/quickstart-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/quickstart-rspack-file-based/.devcontainer/devcontainer.json b/examples/react/quickstart-rspack-file-based/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/quickstart-rspack-file-based/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/quickstart-rspack-file-based/package.json b/examples/react/quickstart-rspack-file-based/package.json index 824998f428..7a0b02aa1a 100644 --- a/examples/react/quickstart-rspack-file-based/package.json +++ b/examples/react/quickstart-rspack-file-based/package.json @@ -8,21 +8,20 @@ "preview": "rsbuild preview" }, "dependencies": { - "@tailwindcss/postcss": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tailwindcss/postcss": "^4.1.18", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", "postcss": "^8.5.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "tailwindcss": "^4.2.2" + "tailwindcss": "^4.1.18" }, "devDependencies": { - "@rsbuild/core": "^2.3.1", - "@rsbuild/plugin-react": "^2.0.0", - "@tanstack/router-plugin": "^1.169.0", + "@rsbuild/core": "^1.2.4", + "@rsbuild/plugin-react": "^1.1.0", + "@tanstack/router-plugin": "^1.161.1", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2" + "typescript": "^5.6.2" } } diff --git a/examples/react/quickstart-rspack-file-based/src/routeTree.gen.ts b/examples/react/quickstart-rspack-file-based/src/routeTree.gen.ts index 12bc916ae4..59499d9fbf 100644 --- a/examples/react/quickstart-rspack-file-based/src/routeTree.gen.ts +++ b/examples/react/quickstart-rspack-file-based/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 IndexRouteImport } from './routes/index' import { Route as AboutRouteImport } from './routes/about' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const AboutRoute = AboutRouteImport.update({ id: '/about', path: '/about', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/about': { id: '/about' path: '/about' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/quickstart-rspack-file-based/src/vite-env.d.ts b/examples/react/quickstart-rspack-file-based/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/quickstart-rspack-file-based/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/quickstart-webpack-file-based/.devcontainer/devcontainer.json b/examples/react/quickstart-webpack-file-based/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/quickstart-webpack-file-based/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/quickstart-webpack-file-based/package.json b/examples/react/quickstart-webpack-file-based/package.json index baa14b89dd..1d88d52f0f 100644 --- a/examples/react/quickstart-webpack-file-based/package.json +++ b/examples/react/quickstart-webpack-file-based/package.json @@ -7,23 +7,21 @@ "build": "webpack build && tsc --noEmit" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { - "@swc/core": "^1.15.33", - "@tanstack/router-plugin": "^1.169.0", + "@swc/core": "^1.10.15", + "@tanstack/router-plugin": "^1.161.1", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "html-webpack-plugin": "^5.6.3", - "react-refresh": "^0.18.0", "swc-loader": "^0.2.6", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", + "typescript": "^5.7.2", "webpack": "^5.97.1", "webpack-cli": "^5.1.4", - "webpack-dev-server": "^5.2.4" + "webpack-dev-server": "^5.2.0" } } diff --git a/examples/react/quickstart-webpack-file-based/src/routeTree.gen.ts b/examples/react/quickstart-webpack-file-based/src/routeTree.gen.ts index 12bc916ae4..59499d9fbf 100644 --- a/examples/react/quickstart-webpack-file-based/src/routeTree.gen.ts +++ b/examples/react/quickstart-webpack-file-based/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 IndexRouteImport } from './routes/index' import { Route as AboutRouteImport } from './routes/about' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const AboutRoute = AboutRouteImport.update({ id: '/about', path: '/about', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/about': { id: '/about' path: '/about' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/quickstart-webpack-file-based/webpack.config.js b/examples/react/quickstart-webpack-file-based/webpack.config.js index 878d2a9735..d83e2bea10 100644 --- a/examples/react/quickstart-webpack-file-based/webpack.config.js +++ b/examples/react/quickstart-webpack-file-based/webpack.config.js @@ -23,11 +23,7 @@ export default ({ WEBPACK_SERVE }) => ({ template: path.resolve(__dirname, './public/index.html'), filename: 'index.html', }), - tanstackRouter({ - target: 'react', - autoCodeSplitting: true, - codeSplittingOptions: { addHmr: Boolean(WEBPACK_SERVE) }, - }), + tanstackRouter({ target: 'react', autoCodeSplitting: true }), ], module: { rules: [ diff --git a/examples/react/quickstart/.devcontainer/devcontainer.json b/examples/react/quickstart/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/quickstart/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/quickstart/package.json b/examples/react/quickstart/package.json index b6db476ea8..2c2c5fda77 100644 --- a/examples/react/quickstart/package.json +++ b/examples/react/quickstart/package.json @@ -9,19 +9,18 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tailwindcss/vite": "^4.1.18", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "tailwindcss": "^4.2.2" + "tailwindcss": "^4.1.18" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1" } } diff --git a/examples/react/quickstart/src/vite-env.d.ts b/examples/react/quickstart/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/quickstart/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/router-monorepo-react-query/.devcontainer/devcontainer.json b/examples/react/router-monorepo-react-query/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/router-monorepo-react-query/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/router-monorepo-react-query/package.json b/examples/react/router-monorepo-react-query/package.json index b158eeda56..0a8dcacd35 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.102.0", + "@tanstack/react-query": "^5.90.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", + "@tanstack/router-plugin": "^1.161.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" @@ -23,10 +23,9 @@ "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "@vitejs/plugin-react": "^6.0.1", - "vite": "^8.0.14", + "typescript": "^5.7.2", + "@vitejs/plugin-react": "^4.3.4", + "vite": "^7.3.1", "vite-plugin-dts": "^4.5.4" }, "keywords": [], diff --git a/examples/react/router-monorepo-react-query/packages/app/package.json b/examples/react/router-monorepo-react-query/packages/app/package.json index f0994165c2..8daa45d472 100644 --- a/examples/react/router-monorepo-react-query/packages/app/package.json +++ b/examples/react/router-monorepo-react-query/packages/app/package.json @@ -11,21 +11,20 @@ "dependencies": { "@router-mono-react-query/post-feature": "workspace:*", "@router-mono-react-query/router": "workspace:*", - "@tanstack/react-query": "^5.102.0", + "@tanstack/react-query": "^5.90.0", "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router-devtools": "^1.161.1", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", + "@vitejs/plugin-react": "^4.3.4", + "tailwindcss": "4.1.18", + "typescript": "^5.7.2", + "vite": "^7.3.1", "vite-plugin-dts": "^4.5.4", - "@tailwindcss/vite": "^4.2.2" + "@tailwindcss/vite": "4.1.18" }, "nx": { "targets": { @@ -33,12 +32,6 @@ "dependsOn": [ "^build" ] - }, - "build": { - "inputs": [ - "...", - "{workspaceRoot}/examples/react/router-monorepo-react-query/.gitignore" - ] } } } diff --git a/examples/react/router-monorepo-react-query/packages/app/src/vite-env.d.ts b/examples/react/router-monorepo-react-query/packages/app/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/router-monorepo-react-query/packages/app/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/router-monorepo-react-query/packages/app/tsconfig.json b/examples/react/router-monorepo-react-query/packages/app/tsconfig.json index 196cb055a9..ce3a7d2339 100644 --- a/examples/react/router-monorepo-react-query/packages/app/tsconfig.json +++ b/examples/react/router-monorepo-react-query/packages/app/tsconfig.json @@ -8,6 +8,5 @@ "module": "ESNext", "lib": ["DOM", "DOM.Iterable", "ES2022"], "skipLibCheck": true - }, - "exclude": ["node_modules", "dist"] + } } diff --git a/examples/react/router-monorepo-react-query/packages/post-feature/package.json b/examples/react/router-monorepo-react-query/packages/post-feature/package.json index 7f5e186ab0..616385fff0 100644 --- a/examples/react/router-monorepo-react-query/packages/post-feature/package.json +++ b/examples/react/router-monorepo-react-query/packages/post-feature/package.json @@ -8,7 +8,7 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/react-query": "^5.102.0", + "@tanstack/react-query": "^5.90.0", "@router-mono-react-query/post-query": "workspace:*", "@router-mono-react-query/router": "workspace:*", "react": "^19.0.0", @@ -17,10 +17,9 @@ "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1", "vite-plugin-dts": "^4.5.4" } } diff --git a/examples/react/router-monorepo-react-query/packages/post-feature/vite.config.ts b/examples/react/router-monorepo-react-query/packages/post-feature/vite.config.ts index 02fe64430e..ee998ce7c2 100644 --- a/examples/react/router-monorepo-react-query/packages/post-feature/vite.config.ts +++ b/examples/react/router-monorepo-react-query/packages/post-feature/vite.config.ts @@ -29,7 +29,7 @@ export default defineConfig({ fileName: 'index', formats: ['es'], }, - rolldownOptions: { + rollupOptions: { // External packages that should not be bundled into your library. external: [ 'react', diff --git a/examples/react/router-monorepo-react-query/packages/post-query/package.json b/examples/react/router-monorepo-react-query/packages/post-query/package.json index 98a06051be..0d98ca2762 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,14 +8,13 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/react-query": "^5.102.0", + "@tanstack/react-query": "^5.90.0", "redaxios": "^0.5.1", - "zod": "^4.4.3" + "zod": "^3.24.2" }, "devDependencies": { - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1" } } diff --git a/examples/react/router-monorepo-react-query/packages/post-query/vite.config.ts b/examples/react/router-monorepo-react-query/packages/post-query/vite.config.ts index 0116b9a9fc..cf84936d33 100644 --- a/examples/react/router-monorepo-react-query/packages/post-query/vite.config.ts +++ b/examples/react/router-monorepo-react-query/packages/post-query/vite.config.ts @@ -27,7 +27,7 @@ export default defineConfig({ fileName: 'index', formats: ['es'], }, - rolldownOptions: { + rollupOptions: { // External packages that should not be bundled into your library. external: [ 'react', diff --git a/examples/react/router-monorepo-react-query/packages/router/package.json b/examples/react/router-monorepo-react-query/packages/router/package.json index 1397db14b5..22d596e7ae 100644 --- a/examples/react/router-monorepo-react-query/packages/router/package.json +++ b/examples/react/router-monorepo-react-query/packages/router/package.json @@ -8,23 +8,22 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { + "@tanstack/history": "^1.154.14", + "@tanstack/react-query": "^5.90.0", + "@tanstack/react-router": "^1.161.1", + "@tanstack/router-plugin": "^1.161.1", "@router-mono-react-query/post-query": "workspace:*", - "@tanstack/history": "^1.162.5", - "@tanstack/react-query": "^5.102.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/router-plugin": "^1.169.0", - "react": "^19.0.0", - "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "zod": "^4.4.3" + "zod": "^3.24.2", + "react": "^19.0.0", + "react-dom": "^19.0.0" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1", "vite-plugin-dts": "^4.5.4" } } diff --git a/examples/react/router-monorepo-react-query/packages/router/src/routeTree.gen.ts b/examples/react/router-monorepo-react-query/packages/router/src/routeTree.gen.ts index a4ed448d2f..0820fc5f30 100644 --- a/examples/react/router-monorepo-react-query/packages/router/src/routeTree.gen.ts +++ b/examples/react/router-monorepo-react-query/packages/router/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 IndexRouteImport } from './routes/index' import { Route as PostIdRouteImport } from './routes/$postId' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PostIdRoute = PostIdRouteImport.update({ id: '/$postId', path: '/$postId', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/$postId': { id: '/$postId' path: '/$postId' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostIdRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/router-monorepo-react-query/packages/router/tsconfig.json b/examples/react/router-monorepo-react-query/packages/router/tsconfig.json index aeb605df28..0d04c7789d 100644 --- a/examples/react/router-monorepo-react-query/packages/router/tsconfig.json +++ b/examples/react/router-monorepo-react-query/packages/router/tsconfig.json @@ -7,8 +7,7 @@ "moduleResolution": "Bundler", "module": "ESNext", "lib": ["DOM", "DOM.Iterable", "ES2022"], - "skipLibCheck": true, - "rootDir": "src" + "skipLibCheck": true }, "include": ["src"] } diff --git a/examples/react/router-monorepo-react-query/packages/router/vite.config.ts b/examples/react/router-monorepo-react-query/packages/router/vite.config.ts index b5d58d21b5..b471bd3f58 100644 --- a/examples/react/router-monorepo-react-query/packages/router/vite.config.ts +++ b/examples/react/router-monorepo-react-query/packages/router/vite.config.ts @@ -31,7 +31,7 @@ export default defineConfig({ fileName: 'index', formats: ['es'], }, - rolldownOptions: { + rollupOptions: { // External packages that should not be bundled into your library. external: [ 'react', diff --git a/examples/react/router-monorepo-simple-lazy/.devcontainer/devcontainer.json b/examples/react/router-monorepo-simple-lazy/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/router-monorepo-simple-lazy/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/router-monorepo-simple-lazy/package.json b/examples/react/router-monorepo-simple-lazy/package.json index e044d86681..a0b6d4dd6a 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.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", + "@tanstack/router-plugin": "^1.161.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" @@ -19,10 +19,9 @@ "@types/node": "^22.7.4", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1", "vite-plugin-dts": "^4.5.4" }, "keywords": [], diff --git a/examples/react/router-monorepo-simple-lazy/packages/app/package.json b/examples/react/router-monorepo-simple-lazy/packages/app/package.json index cfc7a94942..78f05e6bcd 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/app/package.json +++ b/examples/react/router-monorepo-simple-lazy/packages/app/package.json @@ -15,16 +15,15 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router-devtools": "^1.161.1", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", + "@vitejs/plugin-react": "^4.3.4", + "tailwindcss": "4.1.18", + "typescript": "^5.7.2", + "vite": "^7.3.1", "vite-plugin-dts": "^4.5.4", - "@tailwindcss/vite": "^4.2.2" + "@tailwindcss/vite": "4.1.18" }, "nx": { "targets": { @@ -32,12 +31,6 @@ "dependsOn": [ "^build" ] - }, - "build": { - "inputs": [ - "...", - "{workspaceRoot}/examples/react/router-monorepo-simple-lazy/.gitignore" - ] } } } diff --git a/examples/react/router-monorepo-simple-lazy/packages/app/src/vite-env.d.ts b/examples/react/router-monorepo-simple-lazy/packages/app/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/router-monorepo-simple-lazy/packages/app/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/router-monorepo-simple-lazy/packages/app/tsconfig.json b/examples/react/router-monorepo-simple-lazy/packages/app/tsconfig.json index 196cb055a9..ce3a7d2339 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/app/tsconfig.json +++ b/examples/react/router-monorepo-simple-lazy/packages/app/tsconfig.json @@ -8,6 +8,5 @@ "module": "ESNext", "lib": ["DOM", "DOM.Iterable", "ES2022"], "skipLibCheck": true - }, - "exclude": ["node_modules", "dist"] + } } diff --git a/examples/react/router-monorepo-simple-lazy/packages/post-feature/package.json b/examples/react/router-monorepo-simple-lazy/packages/post-feature/package.json index 65738d6025..72ef828b4c 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/post-feature/package.json +++ b/examples/react/router-monorepo-simple-lazy/packages/post-feature/package.json @@ -16,7 +16,7 @@ } }, "dependencies": { - "@tanstack/react-query": "^5.102.0", + "@tanstack/react-query": "^5.90.0", "@router-mono-simple-lazy/router": "workspace:*", "react": "^19.0.0", "react-dom": "^19.0.0" @@ -24,10 +24,9 @@ "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1", "vite-plugin-dts": "^4.5.4" } } diff --git a/examples/react/router-monorepo-simple-lazy/packages/post-feature/vite.config.ts b/examples/react/router-monorepo-simple-lazy/packages/post-feature/vite.config.ts index b0f8eab682..79e5b6c46e 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/post-feature/vite.config.ts +++ b/examples/react/router-monorepo-simple-lazy/packages/post-feature/vite.config.ts @@ -28,7 +28,7 @@ export default defineConfig({ name: 'post-feature', formats: ['es'], }, - rolldownOptions: { + rollupOptions: { // External packages that should not be bundled into your library. external: [ 'react', diff --git a/examples/react/router-monorepo-simple-lazy/packages/router/package.json b/examples/react/router-monorepo-simple-lazy/packages/router/package.json index afd4702b5d..586bb34a03 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/router/package.json +++ b/examples/react/router-monorepo-simple-lazy/packages/router/package.json @@ -8,21 +8,20 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/history": "^1.162.5", - "@tanstack/react-router": "^1.170.46", - "@tanstack/router-plugin": "^1.169.0", - "react": "^19.0.0", - "react-dom": "^19.0.0", + "@tanstack/history": "^1.154.14", + "@tanstack/react-router": "^1.161.1", + "@tanstack/router-plugin": "^1.161.1", "redaxios": "^0.5.1", - "zod": "^4.4.3" + "zod": "^3.24.2", + "react": "^19.0.0", + "react-dom": "^19.0.0" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1", "vite-plugin-dts": "^4.5.4" } } diff --git a/examples/react/router-monorepo-simple-lazy/packages/router/src/routeTree.gen.ts b/examples/react/router-monorepo-simple-lazy/packages/router/src/routeTree.gen.ts index a4ed448d2f..0820fc5f30 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/router/src/routeTree.gen.ts +++ b/examples/react/router-monorepo-simple-lazy/packages/router/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 IndexRouteImport } from './routes/index' import { Route as PostIdRouteImport } from './routes/$postId' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PostIdRoute = PostIdRouteImport.update({ id: '/$postId', path: '/$postId', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/$postId': { id: '/$postId' path: '/$postId' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostIdRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/router-monorepo-simple-lazy/packages/router/tsconfig.json b/examples/react/router-monorepo-simple-lazy/packages/router/tsconfig.json index aeb605df28..0d04c7789d 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/router/tsconfig.json +++ b/examples/react/router-monorepo-simple-lazy/packages/router/tsconfig.json @@ -7,8 +7,7 @@ "moduleResolution": "Bundler", "module": "ESNext", "lib": ["DOM", "DOM.Iterable", "ES2022"], - "skipLibCheck": true, - "rootDir": "src" + "skipLibCheck": true }, "include": ["src"] } diff --git a/examples/react/router-monorepo-simple-lazy/packages/router/vite.config.ts b/examples/react/router-monorepo-simple-lazy/packages/router/vite.config.ts index 2a46c98c90..21aa5e70f4 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/router/vite.config.ts +++ b/examples/react/router-monorepo-simple-lazy/packages/router/vite.config.ts @@ -29,7 +29,7 @@ export default defineConfig({ fileName: 'index', formats: ['es'], }, - rolldownOptions: { + rollupOptions: { // External packages that should not be bundled into your library. external: [ 'react', diff --git a/examples/react/router-monorepo-simple/.devcontainer/devcontainer.json b/examples/react/router-monorepo-simple/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/router-monorepo-simple/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/router-monorepo-simple/package.json b/examples/react/router-monorepo-simple/package.json index 800d948c81..f07c106c80 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.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", + "@tanstack/router-plugin": "^1.161.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" @@ -19,10 +19,9 @@ "@types/node": "^22.7.4", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1", "vite-plugin-dts": "^4.5.4" }, "keywords": [], diff --git a/examples/react/router-monorepo-simple/packages/app/package.json b/examples/react/router-monorepo-simple/packages/app/package.json index a06431ef86..97e2c58d3d 100644 --- a/examples/react/router-monorepo-simple/packages/app/package.json +++ b/examples/react/router-monorepo-simple/packages/app/package.json @@ -15,16 +15,15 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router-devtools": "^1.161.1", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", + "@vitejs/plugin-react": "^4.3.4", + "tailwindcss": "4.1.18", + "typescript": "^5.7.2", + "vite": "^7.3.1", "vite-plugin-dts": "^4.5.4", - "@tailwindcss/vite": "^4.2.2" + "@tailwindcss/vite": "4.1.18" }, "nx": { "targets": { @@ -32,12 +31,6 @@ "dependsOn": [ "^build" ] - }, - "build": { - "inputs": [ - "...", - "{workspaceRoot}/examples/react/router-monorepo-simple/.gitignore" - ] } } } diff --git a/examples/react/router-monorepo-simple/packages/app/src/vite-env.d.ts b/examples/react/router-monorepo-simple/packages/app/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/router-monorepo-simple/packages/app/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/router-monorepo-simple/packages/app/tsconfig.json b/examples/react/router-monorepo-simple/packages/app/tsconfig.json index 196cb055a9..ce3a7d2339 100644 --- a/examples/react/router-monorepo-simple/packages/app/tsconfig.json +++ b/examples/react/router-monorepo-simple/packages/app/tsconfig.json @@ -8,6 +8,5 @@ "module": "ESNext", "lib": ["DOM", "DOM.Iterable", "ES2022"], "skipLibCheck": true - }, - "exclude": ["node_modules", "dist"] + } } diff --git a/examples/react/router-monorepo-simple/packages/post-feature/package.json b/examples/react/router-monorepo-simple/packages/post-feature/package.json index 885aa6bbed..0aba775ce5 100644 --- a/examples/react/router-monorepo-simple/packages/post-feature/package.json +++ b/examples/react/router-monorepo-simple/packages/post-feature/package.json @@ -15,10 +15,9 @@ "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1", "vite-plugin-dts": "^4.5.4" } } diff --git a/examples/react/router-monorepo-simple/packages/post-feature/vite.config.ts b/examples/react/router-monorepo-simple/packages/post-feature/vite.config.ts index b9d09b0ced..f07d75fcf3 100644 --- a/examples/react/router-monorepo-simple/packages/post-feature/vite.config.ts +++ b/examples/react/router-monorepo-simple/packages/post-feature/vite.config.ts @@ -29,7 +29,7 @@ export default defineConfig({ fileName: 'index', formats: ['es'], }, - rolldownOptions: { + rollupOptions: { // External packages that should not be bundled into your library. external: [ 'react', diff --git a/examples/react/router-monorepo-simple/packages/router/package.json b/examples/react/router-monorepo-simple/packages/router/package.json index 391b72e610..48239ae6c7 100644 --- a/examples/react/router-monorepo-simple/packages/router/package.json +++ b/examples/react/router-monorepo-simple/packages/router/package.json @@ -8,21 +8,20 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/history": "^1.162.5", - "@tanstack/react-router": "^1.170.46", - "@tanstack/router-plugin": "^1.169.0", - "react": "^19.0.0", - "react-dom": "^19.0.0", + "@tanstack/history": "^1.154.14", + "@tanstack/react-router": "^1.161.1", + "@tanstack/router-plugin": "^1.161.1", "redaxios": "^0.5.1", - "zod": "^4.4.3" + "zod": "^3.24.2", + "react": "^19.0.0", + "react-dom": "^19.0.0" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1", "vite-plugin-dts": "^4.5.4" } } diff --git a/examples/react/router-monorepo-simple/packages/router/src/routeTree.gen.ts b/examples/react/router-monorepo-simple/packages/router/src/routeTree.gen.ts index a4ed448d2f..0820fc5f30 100644 --- a/examples/react/router-monorepo-simple/packages/router/src/routeTree.gen.ts +++ b/examples/react/router-monorepo-simple/packages/router/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 IndexRouteImport } from './routes/index' import { Route as PostIdRouteImport } from './routes/$postId' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PostIdRoute = PostIdRouteImport.update({ id: '/$postId', path: '/$postId', getParentRoute: () => rootRouteImport, } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/$postId': { id: '/$postId' path: '/$postId' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostIdRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/router-monorepo-simple/packages/router/tsconfig.json b/examples/react/router-monorepo-simple/packages/router/tsconfig.json index aeb605df28..0d04c7789d 100644 --- a/examples/react/router-monorepo-simple/packages/router/tsconfig.json +++ b/examples/react/router-monorepo-simple/packages/router/tsconfig.json @@ -7,8 +7,7 @@ "moduleResolution": "Bundler", "module": "ESNext", "lib": ["DOM", "DOM.Iterable", "ES2022"], - "skipLibCheck": true, - "rootDir": "src" + "skipLibCheck": true }, "include": ["src"] } diff --git a/examples/react/router-monorepo-simple/packages/router/vite.config.ts b/examples/react/router-monorepo-simple/packages/router/vite.config.ts index 2a46c98c90..21aa5e70f4 100644 --- a/examples/react/router-monorepo-simple/packages/router/vite.config.ts +++ b/examples/react/router-monorepo-simple/packages/router/vite.config.ts @@ -29,7 +29,7 @@ export default defineConfig({ fileName: 'index', formats: ['es'], }, - rolldownOptions: { + rollupOptions: { // External packages that should not be bundled into your library. external: [ 'react', diff --git a/examples/react/scroll-restoration/.devcontainer/devcontainer.json b/examples/react/scroll-restoration/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/scroll-restoration/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/scroll-restoration/package.json b/examples/react/scroll-restoration/package.json index 704ff13838..45826e5005 100644 --- a/examples/react/scroll-restoration/package.json +++ b/examples/react/scroll-restoration/package.json @@ -9,20 +9,19 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tailwindcss/vite": "^4.1.18", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", "@tanstack/react-virtual": "^3.13.0", "react": "^19.0.0", "react-dom": "^19.0.0", - "tailwindcss": "^4.2.2" + "tailwindcss": "^4.1.18" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1" } } diff --git a/examples/react/scroll-restoration/src/vite-env.d.ts b/examples/react/scroll-restoration/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/scroll-restoration/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/search-validator-adapters/.devcontainer/devcontainer.json b/examples/react/search-validator-adapters/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/search-validator-adapters/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/search-validator-adapters/package.json b/examples/react/search-validator-adapters/package.json index 35e041e825..39c5aec8ad 100644 --- a/examples/react/search-validator-adapters/package.json +++ b/examples/react/search-validator-adapters/package.json @@ -4,37 +4,34 @@ "type": "module", "scripts": { "dev": "vite --port 3000", - "build": "vite build && NODE_OPTIONS=--max-old-space-size=4096 tsc --noEmit", + "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", "test:unit": "vitest" }, "dependencies": { - "@tailwindcss/vite": "^4.2.2", - "@tanstack/arktype-adapter": "^1.167.0", - "@tanstack/react-query": "^5.102.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", - "@tanstack/valibot-adapter": "^1.167.0", - "@tanstack/zod-adapter": "^1.167.0", + "@tailwindcss/vite": "^4.1.18", + "@tanstack/arktype-adapter": "^1.161.1", + "@tanstack/react-query": "^5.90.0", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", + "@tanstack/router-plugin": "^1.161.1", + "@tanstack/valibot-adapter": "^1.161.1", + "@tanstack/zod-adapter": "^1.161.1", "arktype": "^2.1.7", "react": "^19.0.0", "react-dom": "^19.0.0", - "tailwindcss": "^4.2.2", + "tailwindcss": "^4.1.18", "valibot": "1.0.0-beta.15", "zod": "^3.24.2" }, "devDependencies": { - "@testing-library/jest-dom": "^7.0.1", + "@testing-library/jest-dom": "^6.6.3", "@testing-library/react": "^16.2.0", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@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", - "vitest": "^5.0.4" + "@vitejs/plugin-react": "^4.3.4", + "typescript": "^5.7.2", + "vite": "^7.3.1" } } diff --git a/examples/react/search-validator-adapters/src/routeTree.gen.ts b/examples/react/search-validator-adapters/src/routeTree.gen.ts index d58c1ddfa1..c3d792c411 100644 --- a/examples/react/search-validator-adapters/src/routeTree.gen.ts +++ b/examples/react/search-validator-adapters/src/routeTree.gen.ts @@ -8,20 +8,22 @@ // 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 type { CreateFileRoute, FileRoutesByPath } from '@tanstack/react-router' + import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersArktypeIndexRouteImport } from './routes/users/arktype.index' -import { Route as UsersValibotIndexRouteImport } from './routes/users/valibot.index' import { Route as UsersZodIndexRouteImport } from './routes/users/zod.index' +import { Route as UsersValibotIndexRouteImport } from './routes/users/valibot.index' +import { Route as UsersArktypeIndexRouteImport } from './routes/users/arktype.index' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const UsersArktypeIndexRoute = UsersArktypeIndexRouteImport.update({ - id: '/users/arktype/', - path: '/users/arktype/', +const UsersZodIndexRoute = UsersZodIndexRouteImport.update({ + id: '/users/zod/', + path: '/users/zod/', getParentRoute: () => rootRouteImport, } as any) const UsersValibotIndexRoute = UsersValibotIndexRouteImport.update({ @@ -29,9 +31,9 @@ const UsersValibotIndexRoute = UsersValibotIndexRouteImport.update({ path: '/users/valibot/', getParentRoute: () => rootRouteImport, } as any) -const UsersZodIndexRoute = UsersZodIndexRouteImport.update({ - id: '/users/zod/', - path: '/users/zod/', +const UsersArktypeIndexRoute = UsersArktypeIndexRouteImport.update({ + id: '/users/arktype/', + path: '/users/arktype/', getParentRoute: () => rootRouteImport, } as any) @@ -78,11 +80,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/users/arktype/': { - id: '/users/arktype/' - path: '/users/arktype' - fullPath: '/users/arktype/' - preLoaderRoute: typeof UsersArktypeIndexRouteImport + '/users/zod/': { + id: '/users/zod/' + path: '/users/zod' + fullPath: '/users/zod/' + preLoaderRoute: typeof UsersZodIndexRouteImport parentRoute: typeof rootRouteImport } '/users/valibot/': { @@ -92,16 +94,53 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof UsersValibotIndexRouteImport parentRoute: typeof rootRouteImport } - '/users/zod/': { - id: '/users/zod/' - path: '/users/zod' - fullPath: '/users/zod/' - preLoaderRoute: typeof UsersZodIndexRouteImport + '/users/arktype/': { + id: '/users/arktype/' + path: '/users/arktype' + fullPath: '/users/arktype/' + preLoaderRoute: typeof UsersArktypeIndexRouteImport parentRoute: typeof rootRouteImport } } } +declare module './routes/index' { + const createFileRoute: CreateFileRoute< + '/', + FileRoutesByPath['/']['parentRoute'], + FileRoutesByPath['/']['id'], + FileRoutesByPath['/']['path'], + FileRoutesByPath['/']['fullPath'] + > +} +declare module './routes/users/arktype.index' { + const createFileRoute: CreateFileRoute< + '/users/arktype/', + FileRoutesByPath['/users/arktype/']['parentRoute'], + FileRoutesByPath['/users/arktype/']['id'], + FileRoutesByPath['/users/arktype/']['path'], + FileRoutesByPath['/users/arktype/']['fullPath'] + > +} +declare module './routes/users/valibot.index' { + const createFileRoute: CreateFileRoute< + '/users/valibot/', + FileRoutesByPath['/users/valibot/']['parentRoute'], + FileRoutesByPath['/users/valibot/']['id'], + FileRoutesByPath['/users/valibot/']['path'], + FileRoutesByPath['/users/valibot/']['fullPath'] + > +} +declare module './routes/users/zod.index' { + const createFileRoute: CreateFileRoute< + '/users/zod/', + FileRoutesByPath['/users/zod/']['parentRoute'], + FileRoutesByPath['/users/zod/']['id'], + FileRoutesByPath['/users/zod/']['path'], + FileRoutesByPath['/users/zod/']['fullPath'] + > +} + const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, UsersArktypeIndexRoute: UsersArktypeIndexRoute, diff --git a/examples/react/search-validator-adapters/src/routes/index.tsx b/examples/react/search-validator-adapters/src/routes/index.tsx index d0eff7e9f3..e279d9c1e0 100644 --- a/examples/react/search-validator-adapters/src/routes/index.tsx +++ b/examples/react/search-validator-adapters/src/routes/index.tsx @@ -1,4 +1,3 @@ -import { createFileRoute } from '@tanstack/react-router' import * as React from 'react' import { Header } from '../components/Header' @@ -13,6 +12,6 @@ export const Index: React.FunctionComponent = () => { ) } -export const Route = createFileRoute('/')({ +export const Route = createFileRoute({ component: Index, }) diff --git a/examples/react/search-validator-adapters/src/routes/users/arktype.index.tsx b/examples/react/search-validator-adapters/src/routes/users/arktype.index.tsx index 702db7a5d5..38af594c85 100644 --- a/examples/react/search-validator-adapters/src/routes/users/arktype.index.tsx +++ b/examples/react/search-validator-adapters/src/routes/users/arktype.index.tsx @@ -1,5 +1,5 @@ import * as React from 'react' -import { useNavigate, createFileRoute } from '@tanstack/react-router' +import { useNavigate } from '@tanstack/react-router' import { type } from 'arktype' import { Header } from '../../components/Header' import { Users, usersQueryOptions } from '../../components/Users' @@ -32,7 +32,7 @@ const search = type({ search: 'string = ""', }) -export const Route = createFileRoute('/users/arktype/')({ +export const Route = createFileRoute({ validateSearch: search, loaderDeps: (opt) => ({ search: opt.search }), loader: (opt) => { diff --git a/examples/react/search-validator-adapters/src/routes/users/valibot.index.tsx b/examples/react/search-validator-adapters/src/routes/users/valibot.index.tsx index 8ed997e722..1a8bc7dd18 100644 --- a/examples/react/search-validator-adapters/src/routes/users/valibot.index.tsx +++ b/examples/react/search-validator-adapters/src/routes/users/valibot.index.tsx @@ -1,5 +1,5 @@ import * as React from 'react' -import { useNavigate, createFileRoute } from '@tanstack/react-router' +import { useNavigate } from '@tanstack/react-router' import * as v from 'valibot' import { Header } from '../../components/Header' import { Users, usersQueryOptions } from '../../components/Users' @@ -26,7 +26,7 @@ const Valibot = () => { ) } -export const Route = createFileRoute('/users/valibot/')({ +export const Route = createFileRoute({ validateSearch: v.object({ search: v.fallback(v.optional(v.string(), ''), ''), }), diff --git a/examples/react/search-validator-adapters/src/routes/users/zod.index.tsx b/examples/react/search-validator-adapters/src/routes/users/zod.index.tsx index 526509c8d8..8f095d156f 100644 --- a/examples/react/search-validator-adapters/src/routes/users/zod.index.tsx +++ b/examples/react/search-validator-adapters/src/routes/users/zod.index.tsx @@ -1,5 +1,5 @@ import * as React from 'react' -import { useNavigate, createFileRoute } from '@tanstack/react-router' +import { useNavigate } from '@tanstack/react-router' import { fallback, zodValidator } from '@tanstack/zod-adapter' import { z } from 'zod' import { Header } from '../../components/Header' @@ -7,11 +7,6 @@ import { Users, usersQueryOptions } from '../../components/Users' import { Content } from '../../components/Content' import { Search } from '../../components/Search' -const fallbackString = fallback as unknown as ( - schema: z.ZodString, - fallback: string, -) => z.ZodType - const Zod = () => { const search = Route.useSearch({ select: (search) => search.search ?? '', @@ -34,10 +29,10 @@ const Zod = () => { ) } -export const Route = createFileRoute('/users/zod/')({ +export const Route = createFileRoute({ validateSearch: zodValidator( z.object({ - search: fallbackString(z.string(), '').default(''), + search: fallback(z.string().optional(), undefined), }), ), loaderDeps: (opt) => ({ search: opt.search }), diff --git a/examples/react/search-validator-adapters/src/vite-env.d.ts b/examples/react/search-validator-adapters/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/search-validator-adapters/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/search-validator-adapters/tests/arktype.test.tsx b/examples/react/search-validator-adapters/tests/arktype.test.tsx index 776cc8369e..1c3a1baf76 100644 --- a/examples/react/search-validator-adapters/tests/arktype.test.tsx +++ b/examples/react/search-validator-adapters/tests/arktype.test.tsx @@ -8,6 +8,7 @@ import { createRouter, } from '@tanstack/react-router' +import '@testing-library/jest-dom/vitest' import { type } from 'arktype' test('can navigate to the route', async () => { diff --git a/examples/react/search-validator-adapters/tests/jest-dom.setup.ts b/examples/react/search-validator-adapters/tests/jest-dom.setup.ts deleted file mode 100644 index 8f7cbf15be..0000000000 --- a/examples/react/search-validator-adapters/tests/jest-dom.setup.ts +++ /dev/null @@ -1,18 +0,0 @@ -import * as jestDomMatchers from '@testing-library/jest-dom/matchers' -import { expect } from 'vitest' -import type { TestingLibraryMatchers } from '@testing-library/jest-dom/matchers' - -// Workaround for Vitest 5: remove once testing-library/jest-dom#742 is merged -// and released, and go back to `import '@testing-library/jest-dom/vitest'`. -// That entry imports `vitest` from its own install location, which can resolve -// a different Vitest copy than the one running these tests, and its types -// augment Vitest 4's `Assertion` instead of Vitest 5's `Matchers`. -// Keep `jest-dom` in this file name: vite-plugin-solid only skips injecting -// `@testing-library/jest-dom/vitest` when a setup file path contains it. -expect.extend(jestDomMatchers) - -declare module 'vitest' { - // Type parameter names must match Vitest's declaration for the interfaces to merge. - // eslint-disable-next-line @typescript-eslint/naming-convention - interface Matchers extends TestingLibraryMatchers {} -} diff --git a/examples/react/search-validator-adapters/tests/valibot.test.tsx b/examples/react/search-validator-adapters/tests/valibot.test.tsx index d3e18db414..3680d2302c 100644 --- a/examples/react/search-validator-adapters/tests/valibot.test.tsx +++ b/examples/react/search-validator-adapters/tests/valibot.test.tsx @@ -8,6 +8,7 @@ import { createRouter, } from '@tanstack/react-router' import * as v from 'valibot' +import '@testing-library/jest-dom/vitest' test('can navigate to the route', async () => { const rootRoute = createRootRoute() diff --git a/examples/react/search-validator-adapters/vite.config.ts b/examples/react/search-validator-adapters/vite.config.ts index e4b93f5cc3..f4a9fa4f26 100644 --- a/examples/react/search-validator-adapters/vite.config.ts +++ b/examples/react/search-validator-adapters/vite.config.ts @@ -11,13 +11,13 @@ export default defineConfig({ watch: false, environment: 'jsdom', typecheck: { enabled: true }, - setupFiles: ['./tests/jest-dom.setup.ts'], }, plugins: [ tailwindcss(), tanstackRouter({ target: 'react', autoCodeSplitting: true, + verboseFileRoutes: false, }), react(), ], diff --git a/examples/react/start-bare/.devcontainer/devcontainer.json b/examples/react/start-bare/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/start-bare/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/start-bare/README.md b/examples/react/start-bare/README.md index 8f218785c5..9904fb5440 100644 --- a/examples/react/start-bare/README.md +++ b/examples/react/start-bare/README.md @@ -1,32 +1,16 @@ -# TanStack Start - Bare Example +# Deprecated: TanStack Start React Example (`start-bare`) -A minimal TanStack Start example demonstrating the bare essentials. +This example is retained for compatibility and historical reference. -- [TanStack Router Docs](https://tanstack.com/router) +For new projects, use: -## Start a new project based on this example +- [TanStack Builder](https://tanstack.com/builder) +- `npx @tanstack/cli create` -To start a new project based on this example, run: +For topic-specific setup, use the Start guides: -```sh -npx gitpick TanStack/router/tree/main/examples/react/start-bare start-bare -``` +- [Start React Quick Start](https://tanstack.com/router/latest/docs/framework/react/start/quick-start) -## Getting Started +Canonical issue reproduction baseline: -From your terminal: - -```sh -pnpm install -pnpm dev -``` - -This starts your app in development mode, rebuilding assets on file changes. - -## Build - -To build the app for production: - -```sh -pnpm build -``` +- [React `start-basic`](https://github.com/TanStack/router/tree/main/examples/react/start-basic) diff --git a/examples/react/start-bare/package.json b/examples/react/start-bare/package.json deleted file mode 100644 index 4ab9aff272..0000000000 --- a/examples/react/start-bare/package.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "tanstack-start-example-bare", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "vite dev", - "build": "vite build && tsc --noEmit", - "preview": "vite preview", - "start": "pnpx srvx --prod -s ../client dist/server/server.js" - }, - "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "zod": "^4.4.3" - }, - "devDependencies": { - "@types/node": "^22.5.4", - "@types/react": "^19.0.8", - "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" - } -} diff --git a/examples/react/start-bare/src/components/Counter.css b/examples/react/start-bare/src/components/Counter.css deleted file mode 100644 index 308965720f..0000000000 --- a/examples/react/start-bare/src/components/Counter.css +++ /dev/null @@ -1,21 +0,0 @@ -.increment { - font-family: inherit; - font-size: inherit; - padding: 1em 2em; - color: #335d92; - background-color: rgba(68, 107, 158, 0.1); - border-radius: 2em; - border: 2px solid rgba(68, 107, 158, 0); - outline: none; - width: 200px; - font-variant-numeric: tabular-nums; - cursor: pointer; -} - -.increment:focus { - border: 2px solid #335d92; -} - -.increment:active { - background-color: rgba(68, 107, 158, 0.2); -} diff --git a/examples/react/start-bare/src/components/Counter.tsx b/examples/react/start-bare/src/components/Counter.tsx deleted file mode 100644 index 47347c3830..0000000000 --- a/examples/react/start-bare/src/components/Counter.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { useState } from 'react' -import './Counter.css' - -export default function Counter() { - const [count, setCount] = useState(0) - return ( - - ) -} diff --git a/examples/react/start-bare/src/routeTree.gen.ts b/examples/react/start-bare/src/routeTree.gen.ts deleted file mode 100644 index d89758e684..0000000000 --- a/examples/react/start-bare/src/routeTree.gen.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as AboutRouteImport } from './routes/about' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/about': typeof AboutRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/about': typeof AboutRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/about': typeof AboutRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/about' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/about' - id: '__root__' | '/' | '/about' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - AboutRoute: typeof AboutRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - AboutRoute: AboutRoute, -} -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/examples/react/start-bare/src/router.tsx b/examples/react/start-bare/src/router.tsx deleted file mode 100644 index 6f82cbf378..0000000000 --- a/examples/react/start-bare/src/router.tsx +++ /dev/null @@ -1,22 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - const router = createRouter({ - routeTree, - defaultPreload: 'intent', - defaultErrorComponent: (err) => ( -

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

- ), - defaultNotFoundComponent: () =>

not found

, - scrollRestoration: true, - }) - - return router -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/examples/react/start-bare/src/routes/__root.tsx b/examples/react/start-bare/src/routes/__root.tsx deleted file mode 100644 index 4b83d392e9..0000000000 --- a/examples/react/start-bare/src/routes/__root.tsx +++ /dev/null @@ -1,46 +0,0 @@ -/// -import * as React from 'react' -import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' -import { - HeadContent, - Link, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' -import appCss from '~/styles/app.css?url' - -export const Route = createRootRoute({ - head: () => ({ - links: [{ rel: 'stylesheet', href: appCss }], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - ) -} - -function RootDocument({ children }: { children: React.ReactNode }) { - return ( - - - - - -
- Index - About -
- - {children} - - - - - ) -} diff --git a/examples/react/start-bare/src/routes/about.tsx b/examples/react/start-bare/src/routes/about.tsx deleted file mode 100644 index 95a5fe4b86..0000000000 --- a/examples/react/start-bare/src/routes/about.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import Counter from '~/components/Counter' - -export const Route = createFileRoute('/about')({ - component: RouteComponent, -}) - -function RouteComponent() { - return ( -
-

About

- -
- ) -} diff --git a/examples/react/start-bare/src/routes/index.tsx b/examples/react/start-bare/src/routes/index.tsx deleted file mode 100644 index 03832940ce..0000000000 --- a/examples/react/start-bare/src/routes/index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/')({ - component: RouteComponent, -}) - -function RouteComponent() { - return ( -
-

Hello world!

-
- ) -} diff --git a/examples/react/start-bare/src/styles/app.css b/examples/react/start-bare/src/styles/app.css deleted file mode 100644 index a6f35642e4..0000000000 --- a/examples/react/start-bare/src/styles/app.css +++ /dev/null @@ -1,15 +0,0 @@ -body { - font-family: - Gordita, Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', - sans-serif; -} - -a { - margin-right: 1rem; -} - -main { - text-align: center; - padding: 1em; - margin: 0 auto; -} diff --git a/examples/react/start-bare/tsconfig.json b/examples/react/start-bare/tsconfig.json deleted file mode 100644 index af81492efb..0000000000 --- a/examples/react/start-bare/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "include": ["**/*.ts", "**/*.tsx", "public/script*.js"], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "react-jsx", - "module": "ESNext", - "moduleResolution": "Bundler", - "lib": ["DOM", "DOM.Iterable", "ES2022"], - "isolatedModules": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "target": "ES2022", - "allowJs": true, - "forceConsistentCasingInFileNames": true, - "paths": { - "~/*": ["./src/*"] - }, - "noEmit": true - } -} diff --git a/examples/react/start-bare/vite.config.ts b/examples/react/start-bare/vite.config.ts deleted file mode 100644 index d0ee8802cf..0000000000 --- a/examples/react/start-bare/vite.config.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { tanstackStart } from '@tanstack/react-start/plugin/vite' -import { defineConfig } from 'vite' -import viteReact from '@vitejs/plugin-react' - -export default defineConfig({ - server: { - port: 3000, - }, - resolve: { - tsconfigPaths: true, - }, - plugins: [tanstackStart(), viteReact()], -}) diff --git a/examples/react/start-basic-auth/.devcontainer/devcontainer.json b/examples/react/start-basic-auth/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/start-basic-auth/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/start-basic-auth/.env b/examples/react/start-basic-auth/.env deleted file mode 100644 index c498ab59bf..0000000000 --- a/examples/react/start-basic-auth/.env +++ /dev/null @@ -1,7 +0,0 @@ -# Environment variables declared in this file are automatically made available to Prisma. -# See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema - -# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB. -# See the documentation for all the connection string options: https://pris.ly/d/connection-strings - -DATABASE_URL="file:./dev.db" \ No newline at end of file diff --git a/examples/react/start-basic-auth/.gitignore b/examples/react/start-basic-auth/.gitignore deleted file mode 100644 index 2818549158..0000000000 --- a/examples/react/start-basic-auth/.gitignore +++ /dev/null @@ -1,18 +0,0 @@ -node_modules -package-lock.json -yarn.lock - -!.env -.DS_Store -.cache -.vercel -.output -/build/ -/api/ -/server/build -/public/build# Sentry Config File -.env.sentry-build-plugin -/test-results/ -/playwright-report/ -/blob-report/ -/playwright/.cache/ diff --git a/examples/react/start-basic-auth/.vscode/settings.json b/examples/react/start-basic-auth/.vscode/settings.json deleted file mode 100644 index 00b5278e58..0000000000 --- a/examples/react/start-basic-auth/.vscode/settings.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "files.watcherExclude": { - "**/routeTree.gen.ts": true - }, - "search.exclude": { - "**/routeTree.gen.ts": true - }, - "files.readonlyInclude": { - "**/routeTree.gen.ts": true - } -} diff --git a/examples/react/start-basic-auth/README.md b/examples/react/start-basic-auth/README.md index 7f1b093ba5..bf2cea30c0 100644 --- a/examples/react/start-basic-auth/README.md +++ b/examples/react/start-basic-auth/README.md @@ -1,51 +1,17 @@ -# TanStack Start - Basic Auth Example +# Deprecated: TanStack Start React Example (`start-basic-auth`) -A TanStack Start example demonstrating authentication patterns and protected routes. +This example is retained for compatibility and historical reference. -- [TanStack Router Docs](https://tanstack.com/router) +For new projects, use: -## Start a new project based on this example +- [TanStack Builder](https://tanstack.com/builder) +- `npx @tanstack/cli create` -To start a new project based on this example, run: +For topic-specific setup, use the Start guides: -```sh -npx gitpick TanStack/router/tree/main/examples/react/start-basic-auth start-basic-auth -``` +- [Start React Quick Start](https://tanstack.com/router/latest/docs/framework/react/start/quick-start) +- [Start React Guides](https://tanstack.com/router/latest/docs/framework/react/start/guide/routing) -## Getting Started +Canonical issue reproduction baseline: -From your terminal: - -```sh -pnpm install -pnpm dev -``` - -This starts your app in development mode, rebuilding assets on file changes. - -## Build - -To build the app for production: - -```sh -pnpm build -``` - -## Authentication Features - -This example demonstrates: - -- User authentication flow -- 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. +- [React `start-basic`](https://github.com/TanStack/router/tree/main/examples/react/start-basic) diff --git a/examples/react/start-basic-auth/dev.db b/examples/react/start-basic-auth/dev.db deleted file mode 100644 index 5f4ab51a02..0000000000 Binary files a/examples/react/start-basic-auth/dev.db and /dev/null differ diff --git a/examples/react/start-basic-auth/package.json b/examples/react/start-basic-auth/package.json deleted file mode 100644 index 9ab89bdac9..0000000000 --- a/examples/react/start-basic-auth/package.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "tanstack-start-example-basic-auth", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "vite dev", - "build": "vite build", - "preview": "vite preview", - "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "prisma-generate": "prisma generate" - }, - "dependencies": { - "@libsql/client": "^0.15.15", - "@prisma/adapter-libsql": "^7.0.0", - "@prisma/client": "^7.0.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", - "iron-session": "^9.0.1", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "redaxios": "^0.5.1", - "tailwind-merge": "^3.6.0" - }, - "devDependencies": { - "@tailwindcss/vite": "^4.2.2", - "@types/node": "^22.5.4", - "@types/react": "^19.0.8", - "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "dotenv": "^17.2.3", - "prisma": "^7.0.0", - "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" - } -} diff --git a/examples/react/start-basic-auth/prisma.config.ts b/examples/react/start-basic-auth/prisma.config.ts deleted file mode 100644 index 9e548f8b1a..0000000000 --- a/examples/react/start-basic-auth/prisma.config.ts +++ /dev/null @@ -1,12 +0,0 @@ -import 'dotenv/config' -import { defineConfig, env } from 'prisma/config' - -export default defineConfig({ - schema: './prisma/schema.prisma', - migrations: { - path: './prisma/migrations', - }, - datasource: { - url: env('DATABASE_URL'), - }, -}) diff --git a/examples/react/start-basic-auth/prisma/migrations/20240811183753_init/migration.sql b/examples/react/start-basic-auth/prisma/migrations/20240811183753_init/migration.sql deleted file mode 100644 index 4512a8f782..0000000000 --- a/examples/react/start-basic-auth/prisma/migrations/20240811183753_init/migration.sql +++ /dev/null @@ -1,8 +0,0 @@ --- CreateTable -CREATE TABLE "User" ( - "email" TEXT NOT NULL PRIMARY KEY, - "password" TEXT NOT NULL -); - --- CreateIndex -CREATE UNIQUE INDEX "User_email_key" ON "User"("email"); diff --git a/examples/react/start-basic-auth/prisma/migrations/migration_lock.toml b/examples/react/start-basic-auth/prisma/migrations/migration_lock.toml deleted file mode 100644 index e5e5c4705a..0000000000 --- a/examples/react/start-basic-auth/prisma/migrations/migration_lock.toml +++ /dev/null @@ -1,3 +0,0 @@ -# Please do not edit this file manually -# It should be added in your version-control system (i.e. Git) -provider = "sqlite" \ No newline at end of file diff --git a/examples/react/start-basic-auth/prisma/schema.prisma b/examples/react/start-basic-auth/prisma/schema.prisma deleted file mode 100644 index a4ff868891..0000000000 --- a/examples/react/start-basic-auth/prisma/schema.prisma +++ /dev/null @@ -1,16 +0,0 @@ -// This is your Prisma schema file, -// learn more about it in the docs: https://pris.ly/d/prisma-schema - -generator client { - provider = "prisma-client" - output = "../src/prisma-generated" -} - -datasource db { - provider = "sqlite" -} - -model User { - email String @id @unique - password String -} \ No newline at end of file diff --git a/examples/react/start-basic-auth/public/favicon.ico b/examples/react/start-basic-auth/public/favicon.ico deleted file mode 100644 index 1a1751676f..0000000000 Binary files a/examples/react/start-basic-auth/public/favicon.ico and /dev/null differ diff --git a/examples/react/start-basic-auth/src/components/Auth.tsx b/examples/react/start-basic-auth/src/components/Auth.tsx deleted file mode 100644 index 39a4997346..0000000000 --- a/examples/react/start-basic-auth/src/components/Auth.tsx +++ /dev/null @@ -1,57 +0,0 @@ -export function Auth({ - actionText, - onSubmit, - status, - afterSubmit, -}: { - actionText: string - onSubmit: (e: React.FormEvent) => void - status: 'pending' | 'idle' | 'success' | 'error' - afterSubmit?: React.ReactNode -}) { - return ( -
-
-

{actionText}

-
{ - e.preventDefault() - onSubmit(e) - }} - className="space-y-4" - > -
- - -
-
- - -
- - {afterSubmit ? afterSubmit : null} -
-
-
- ) -} diff --git a/examples/react/start-basic-auth/src/components/DefaultCatchBoundary.tsx b/examples/react/start-basic-auth/src/components/DefaultCatchBoundary.tsx deleted file mode 100644 index 405fb5f4a7..0000000000 --- a/examples/react/start-basic-auth/src/components/DefaultCatchBoundary.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { - ErrorComponent, - Link, - useLocation, - useRouter, -} from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' - -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - - console.error(error) - - return ( -
- -
- - {isRoot ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) -} diff --git a/examples/react/start-basic-auth/src/components/Login.tsx b/examples/react/start-basic-auth/src/components/Login.tsx deleted file mode 100644 index b6b6da0c37..0000000000 --- a/examples/react/start-basic-auth/src/components/Login.tsx +++ /dev/null @@ -1,71 +0,0 @@ -import { useRouter } from '@tanstack/react-router' -import { useServerFn } from '@tanstack/react-start' -import { useMutation } from '../hooks/useMutation' -import { loginFn } from '../routes/_authed' -import { Auth } from './Auth' -import { signupFn } from '~/routes/signup' - -export function Login() { - const router = useRouter() - - const loginMutation = useMutation({ - fn: loginFn, - onSuccess: async (ctx) => { - if (!ctx.data?.error) { - await router.invalidate() - router.navigate({ to: '/' }) - return - } - }, - }) - - const signupMutation = useMutation({ - fn: useServerFn(signupFn), - }) - - return ( - { - const formData = new FormData(e.target as HTMLFormElement) - - loginMutation.mutate({ - data: { - email: formData.get('email') as string, - password: formData.get('password') as string, - }, - }) - }} - afterSubmit={ - loginMutation.data ? ( - <> -
{loginMutation.data.message}
- {loginMutation.data.userNotFound ? ( -
- -
- ) : null} - - ) : null - } - /> - ) -} diff --git a/examples/react/start-basic-auth/src/hooks/useMutation.ts b/examples/react/start-basic-auth/src/hooks/useMutation.ts deleted file mode 100644 index 1ff7a4653b..0000000000 --- a/examples/react/start-basic-auth/src/hooks/useMutation.ts +++ /dev/null @@ -1,44 +0,0 @@ -import * as React from 'react' - -export function useMutation(opts: { - fn: (variables: TVariables) => Promise - onSuccess?: (ctx: { data: TData }) => void | Promise -}) { - const [submittedAt, setSubmittedAt] = React.useState() - const [variables, setVariables] = React.useState() - const [error, setError] = React.useState() - const [data, setData] = React.useState() - const [status, setStatus] = React.useState< - 'idle' | 'pending' | 'success' | 'error' - >('idle') - - const mutate = React.useCallback( - async (variables: TVariables): Promise => { - setStatus('pending') - setSubmittedAt(Date.now()) - setVariables(variables) - // - try { - const data = await opts.fn(variables) - await opts.onSuccess?.({ data }) - setStatus('success') - setError(undefined) - setData(data) - return data - } catch (err: any) { - setStatus('error') - setError(err) - } - }, - [opts.fn], - ) - - return { - status, - variables, - submittedAt, - mutate, - error, - data, - } -} diff --git a/examples/react/start-basic-auth/src/prisma-generated/browser.ts b/examples/react/start-basic-auth/src/prisma-generated/browser.ts deleted file mode 100644 index 7ca76c9368..0000000000 --- a/examples/react/start-basic-auth/src/prisma-generated/browser.ts +++ /dev/null @@ -1,23 +0,0 @@ -/* !!! This is code generated by Prisma. Do not edit directly. !!! */ -/* eslint-disable */ -// biome-ignore-all lint: generated file -// @ts-nocheck -/* - * This file should be your main import to use Prisma-related types and utilities in a browser. - * Use it to get access to models, enums, and input types. - * - * This file does not contain a `PrismaClient` class, nor several other helpers that are intended as server-side only. - * See `client.ts` for the standard, server-side entry point. - * - * 🟢 You can import this file directly. - */ - -import * as Prisma from './internal/prismaNamespaceBrowser' -export { Prisma } -export * as $Enums from './enums' -export * from './enums' -/** - * Model User - * - */ -export type User = Prisma.UserModel diff --git a/examples/react/start-basic-auth/src/prisma-generated/client.ts b/examples/react/start-basic-auth/src/prisma-generated/client.ts deleted file mode 100644 index 2be7866ae3..0000000000 --- a/examples/react/start-basic-auth/src/prisma-generated/client.ts +++ /dev/null @@ -1,51 +0,0 @@ -/* !!! This is code generated by Prisma. Do not edit directly. !!! */ -/* eslint-disable */ -// biome-ignore-all lint: generated file -// @ts-nocheck -/* - * This file should be your main import to use Prisma. Through it you get access to all the models, enums, and input types. - * If you're looking for something you can import in the client-side of your application, please refer to the `browser.ts` file instead. - * - * 🟢 You can import this file directly. - */ - -import * as process from 'node:process' -import * as path from 'node:path' -import { fileURLToPath } from 'node:url' -globalThis['__dirname'] = path.dirname(fileURLToPath(import.meta.url)) - -import * as runtime from '@prisma/client/runtime/client' -import * as $Enums from './enums' -import * as $Class from './internal/class' -import * as Prisma from './internal/prismaNamespace' - -export * as $Enums from './enums' -export * from './enums' -/** - * ## Prisma Client - * - * Type-safe database client for TypeScript - * @example - * ``` - * const prisma = new PrismaClient() - * // Fetch zero or more Users - * const users = await prisma.user.findMany() - * ``` - * - * Read more in our [docs](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client). - */ -export const PrismaClient = $Class.getPrismaClientClass() -export type PrismaClient< - LogOpts extends Prisma.LogLevel = never, - OmitOpts extends Prisma.PrismaClientOptions['omit'] = - Prisma.PrismaClientOptions['omit'], - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = $Class.PrismaClient -export { Prisma } - -/** - * Model User - * - */ -export type User = Prisma.UserModel diff --git a/examples/react/start-basic-auth/src/prisma-generated/commonInputTypes.ts b/examples/react/start-basic-auth/src/prisma-generated/commonInputTypes.ts deleted file mode 100644 index 72c68f142e..0000000000 --- a/examples/react/start-basic-auth/src/prisma-generated/commonInputTypes.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* !!! This is code generated by Prisma. Do not edit directly. !!! */ -/* eslint-disable */ -// biome-ignore-all lint: generated file -// @ts-nocheck -/* - * This file exports various common sort, input & filter types that are not directly linked to a particular model. - * - * 🟢 You can import this file directly. - */ - -import type * as runtime from '@prisma/client/runtime/client' -import * as $Enums from './enums' -import type * as Prisma from './internal/prismaNamespace' - -export type StringFilter<$PrismaModel = never> = { - equals?: string | Prisma.StringFieldRefInput<$PrismaModel> - in?: string[] - notIn?: string[] - lt?: string | Prisma.StringFieldRefInput<$PrismaModel> - lte?: string | Prisma.StringFieldRefInput<$PrismaModel> - gt?: string | Prisma.StringFieldRefInput<$PrismaModel> - gte?: string | Prisma.StringFieldRefInput<$PrismaModel> - contains?: string | Prisma.StringFieldRefInput<$PrismaModel> - startsWith?: string | Prisma.StringFieldRefInput<$PrismaModel> - endsWith?: string | Prisma.StringFieldRefInput<$PrismaModel> - not?: Prisma.NestedStringFilter<$PrismaModel> | string -} - -export type StringWithAggregatesFilter<$PrismaModel = never> = { - equals?: string | Prisma.StringFieldRefInput<$PrismaModel> - in?: string[] - notIn?: string[] - lt?: string | Prisma.StringFieldRefInput<$PrismaModel> - lte?: string | Prisma.StringFieldRefInput<$PrismaModel> - gt?: string | Prisma.StringFieldRefInput<$PrismaModel> - gte?: string | Prisma.StringFieldRefInput<$PrismaModel> - contains?: string | Prisma.StringFieldRefInput<$PrismaModel> - startsWith?: string | Prisma.StringFieldRefInput<$PrismaModel> - endsWith?: string | Prisma.StringFieldRefInput<$PrismaModel> - not?: Prisma.NestedStringWithAggregatesFilter<$PrismaModel> | string - _count?: Prisma.NestedIntFilter<$PrismaModel> - _min?: Prisma.NestedStringFilter<$PrismaModel> - _max?: Prisma.NestedStringFilter<$PrismaModel> -} - -export type NestedStringFilter<$PrismaModel = never> = { - equals?: string | Prisma.StringFieldRefInput<$PrismaModel> - in?: string[] - notIn?: string[] - lt?: string | Prisma.StringFieldRefInput<$PrismaModel> - lte?: string | Prisma.StringFieldRefInput<$PrismaModel> - gt?: string | Prisma.StringFieldRefInput<$PrismaModel> - gte?: string | Prisma.StringFieldRefInput<$PrismaModel> - contains?: string | Prisma.StringFieldRefInput<$PrismaModel> - startsWith?: string | Prisma.StringFieldRefInput<$PrismaModel> - endsWith?: string | Prisma.StringFieldRefInput<$PrismaModel> - not?: Prisma.NestedStringFilter<$PrismaModel> | string -} - -export type NestedStringWithAggregatesFilter<$PrismaModel = never> = { - equals?: string | Prisma.StringFieldRefInput<$PrismaModel> - in?: string[] - notIn?: string[] - lt?: string | Prisma.StringFieldRefInput<$PrismaModel> - lte?: string | Prisma.StringFieldRefInput<$PrismaModel> - gt?: string | Prisma.StringFieldRefInput<$PrismaModel> - gte?: string | Prisma.StringFieldRefInput<$PrismaModel> - contains?: string | Prisma.StringFieldRefInput<$PrismaModel> - startsWith?: string | Prisma.StringFieldRefInput<$PrismaModel> - endsWith?: string | Prisma.StringFieldRefInput<$PrismaModel> - not?: Prisma.NestedStringWithAggregatesFilter<$PrismaModel> | string - _count?: Prisma.NestedIntFilter<$PrismaModel> - _min?: Prisma.NestedStringFilter<$PrismaModel> - _max?: Prisma.NestedStringFilter<$PrismaModel> -} - -export type NestedIntFilter<$PrismaModel = never> = { - equals?: number | Prisma.IntFieldRefInput<$PrismaModel> - in?: number[] - notIn?: number[] - lt?: number | Prisma.IntFieldRefInput<$PrismaModel> - lte?: number | Prisma.IntFieldRefInput<$PrismaModel> - gt?: number | Prisma.IntFieldRefInput<$PrismaModel> - gte?: number | Prisma.IntFieldRefInput<$PrismaModel> - not?: Prisma.NestedIntFilter<$PrismaModel> | number -} diff --git a/examples/react/start-basic-auth/src/prisma-generated/enums.ts b/examples/react/start-basic-auth/src/prisma-generated/enums.ts deleted file mode 100644 index 84979fb8d2..0000000000 --- a/examples/react/start-basic-auth/src/prisma-generated/enums.ts +++ /dev/null @@ -1,12 +0,0 @@ -/* !!! This is code generated by Prisma. Do not edit directly. !!! */ -/* eslint-disable */ -// biome-ignore-all lint: generated file -// @ts-nocheck -/* - * This file exports all enum related types from the schema. - * - * 🟢 You can import this file directly. - */ - -// This file is empty because there are no enums in the schema. -export {} diff --git a/examples/react/start-basic-auth/src/prisma-generated/internal/class.ts b/examples/react/start-basic-auth/src/prisma-generated/internal/class.ts deleted file mode 100644 index 594896a020..0000000000 --- a/examples/react/start-basic-auth/src/prisma-generated/internal/class.ts +++ /dev/null @@ -1,241 +0,0 @@ -/* !!! This is code generated by Prisma. Do not edit directly. !!! */ -/* eslint-disable */ -// biome-ignore-all lint: generated file -// @ts-nocheck -/* - * WARNING: This is an internal file that is subject to change! - * - * 🛑 Under no circumstances should you import this file directly! 🛑 - * - * Please import the `PrismaClient` class from the `client.ts` file instead. - */ - -import * as runtime from '@prisma/client/runtime/client' -import type * as Prisma from './prismaNamespace' - -const config: runtime.GetPrismaClientConfig = { - previewFeatures: [], - clientVersion: '7.0.0', - engineVersion: '0c19ccc313cf9911a90d99d2ac2eb0280c76c513', - activeProvider: 'sqlite', - inlineSchema: - '// This is your Prisma schema file,\n// learn more about it in the docs: https://pris.ly/d/prisma-schema\n\ngenerator client {\n provider = "prisma-client"\n output = "../src/prisma-generated"\n}\n\ndatasource db {\n provider = "sqlite"\n}\n\nmodel User {\n email String @id @unique\n password String\n}\n', - runtimeDataModel: { - models: {}, - enums: {}, - types: {}, - }, -} - -config.runtimeDataModel = JSON.parse( - '{"models":{"User":{"fields":[{"name":"email","kind":"scalar","type":"String"},{"name":"password","kind":"scalar","type":"String"}],"dbName":null}},"enums":{},"types":{}}', -) - -async function decodeBase64AsWasm( - wasmBase64: string, -): Promise { - const { Buffer } = await import('node:buffer') - const wasmArray = Buffer.from(wasmBase64, 'base64') - return new WebAssembly.Module(wasmArray) -} - -config.compilerWasm = { - getRuntime: async () => - await import('@prisma/client/runtime/query_compiler_bg.sqlite.mjs'), - - getQueryCompilerWasmModule: async () => { - const { wasm } = - await import('@prisma/client/runtime/query_compiler_bg.sqlite.wasm-base64.mjs') - return await decodeBase64AsWasm(wasm) - }, -} - -export type LogOptions = - 'log' extends keyof ClientOptions - ? ClientOptions['log'] extends Array - ? Prisma.GetEvents - : never - : never - -export interface PrismaClientConstructor { - /** - * ## Prisma Client - * - * Type-safe database client for TypeScript - * @example - * ``` - * const prisma = new PrismaClient() - * // Fetch zero or more Users - * const users = await prisma.user.findMany() - * ``` - * - * Read more in our [docs](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client). - */ - - new < - Options extends Prisma.PrismaClientOptions = Prisma.PrismaClientOptions, - LogOpts extends LogOptions = LogOptions, - OmitOpts extends Prisma.PrismaClientOptions['omit'] = Options extends { - omit: infer U - } - ? U - : Prisma.PrismaClientOptions['omit'], - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, - >( - options: Prisma.Subset, - ): PrismaClient -} - -/** - * ## Prisma Client - * - * Type-safe database client for TypeScript - * @example - * ``` - * const prisma = new PrismaClient() - * // Fetch zero or more Users - * const users = await prisma.user.findMany() - * ``` - * - * Read more in our [docs](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client). - */ - -export interface PrismaClient< - in LogOpts extends Prisma.LogLevel = never, - in out OmitOpts extends Prisma.PrismaClientOptions['omit'] = undefined, - in out ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> { - [K: symbol]: { types: Prisma.TypeMap['other'] } - - $on( - eventType: V, - callback: ( - event: V extends 'query' ? Prisma.QueryEvent : Prisma.LogEvent, - ) => void, - ): PrismaClient - - /** - * Connect with the database - */ - $connect(): runtime.Types.Utils.JsPromise - - /** - * Disconnect from the database - */ - $disconnect(): runtime.Types.Utils.JsPromise - - /** - * Executes a prepared raw query and returns the number of affected rows. - * @example - * ``` - * const result = await prisma.$executeRaw`UPDATE User SET cool = ${true} WHERE email = ${'user@email.com'};` - * ``` - * - * Read more in our [docs](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client/raw-database-access). - */ - $executeRaw( - query: TemplateStringsArray | Prisma.Sql, - ...values: any[] - ): Prisma.PrismaPromise - - /** - * Executes a raw query and returns the number of affected rows. - * Susceptible to SQL injections, see documentation. - * @example - * ``` - * const result = await prisma.$executeRawUnsafe('UPDATE User SET cool = $1 WHERE email = $2 ;', true, 'user@email.com') - * ``` - * - * Read more in our [docs](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client/raw-database-access). - */ - $executeRawUnsafe( - query: string, - ...values: any[] - ): Prisma.PrismaPromise - - /** - * Performs a prepared raw query and returns the `SELECT` data. - * @example - * ``` - * const result = await prisma.$queryRaw`SELECT * FROM User WHERE id = ${1} OR email = ${'user@email.com'};` - * ``` - * - * Read more in our [docs](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client/raw-database-access). - */ - $queryRaw( - query: TemplateStringsArray | Prisma.Sql, - ...values: any[] - ): Prisma.PrismaPromise - - /** - * Performs a raw query and returns the `SELECT` data. - * Susceptible to SQL injections, see documentation. - * @example - * ``` - * const result = await prisma.$queryRawUnsafe('SELECT * FROM User WHERE id = $1 OR email = $2;', 1, 'user@email.com') - * ``` - * - * Read more in our [docs](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client/raw-database-access). - */ - $queryRawUnsafe( - query: string, - ...values: any[] - ): Prisma.PrismaPromise - - /** - * Allows the running of a sequence of read/write operations that are guaranteed to either succeed or fail as a whole. - * @example - * ``` - * const [george, bob, alice] = await prisma.$transaction([ - * prisma.user.create({ data: { name: 'George' } }), - * prisma.user.create({ data: { name: 'Bob' } }), - * prisma.user.create({ data: { name: 'Alice' } }), - * ]) - * ``` - * - * Read more in our [docs](https://www.prisma.io/docs/concepts/components/prisma-client/transactions). - */ - $transaction

[]>( - arg: [...P], - options?: { isolationLevel?: Prisma.TransactionIsolationLevel }, - ): runtime.Types.Utils.JsPromise> - - $transaction( - fn: ( - prisma: Omit, - ) => runtime.Types.Utils.JsPromise, - options?: { - maxWait?: number - timeout?: number - isolationLevel?: Prisma.TransactionIsolationLevel - }, - ): runtime.Types.Utils.JsPromise - - $extends: runtime.Types.Extensions.ExtendsHook< - 'extends', - Prisma.TypeMapCb, - ExtArgs, - runtime.Types.Utils.Call< - Prisma.TypeMapCb, - { - extArgs: ExtArgs - } - > - > - - /** - * `prisma.user`: Exposes CRUD operations for the **User** model. - * Example usage: - * ```ts - * // Fetch zero or more Users - * const users = await prisma.user.findMany() - * ``` - */ - get user(): Prisma.UserDelegate -} - -export function getPrismaClientClass(): PrismaClientConstructor { - return runtime.getPrismaClient(config) as unknown as PrismaClientConstructor -} diff --git a/examples/react/start-basic-auth/src/prisma-generated/internal/prismaNamespace.ts b/examples/react/start-basic-auth/src/prisma-generated/internal/prismaNamespace.ts deleted file mode 100644 index f420c55329..0000000000 --- a/examples/react/start-basic-auth/src/prisma-generated/internal/prismaNamespace.ts +++ /dev/null @@ -1,738 +0,0 @@ -/* !!! This is code generated by Prisma. Do not edit directly. !!! */ -/* eslint-disable */ -// biome-ignore-all lint: generated file -// @ts-nocheck -/* - * WARNING: This is an internal file that is subject to change! - * - * 🛑 Under no circumstances should you import this file directly! 🛑 - * - * All exports from this file are wrapped under a `Prisma` namespace object in the client.ts file. - * While this enables partial backward compatibility, it is not part of the stable public API. - * - * If you are looking for your Models, Enums, and Input Types, please import them from the respective - * model files in the `model` directory! - */ - -import * as runtime from '@prisma/client/runtime/client' -import type * as Prisma from '../models' -import { type PrismaClient } from './class' - -export type * from '../models' - -export type DMMF = typeof runtime.DMMF - -export type PrismaPromise = runtime.Types.Public.PrismaPromise - -/** - * Prisma Errors - */ - -export const PrismaClientKnownRequestError = - runtime.PrismaClientKnownRequestError -export type PrismaClientKnownRequestError = - runtime.PrismaClientKnownRequestError - -export const PrismaClientUnknownRequestError = - runtime.PrismaClientUnknownRequestError -export type PrismaClientUnknownRequestError = - runtime.PrismaClientUnknownRequestError - -export const PrismaClientRustPanicError = runtime.PrismaClientRustPanicError -export type PrismaClientRustPanicError = runtime.PrismaClientRustPanicError - -export const PrismaClientInitializationError = - runtime.PrismaClientInitializationError -export type PrismaClientInitializationError = - runtime.PrismaClientInitializationError - -export const PrismaClientValidationError = runtime.PrismaClientValidationError -export type PrismaClientValidationError = runtime.PrismaClientValidationError - -/** - * Re-export of sql-template-tag - */ -export const sql = runtime.sqltag -export const empty = runtime.empty -export const join = runtime.join -export const raw = runtime.raw -export const Sql = runtime.Sql -export type Sql = runtime.Sql - -/** - * Decimal.js - */ -export const Decimal = runtime.Decimal -export type Decimal = runtime.Decimal - -export type DecimalJsLike = runtime.DecimalJsLike - -/** - * Extensions - */ -export type Extension = runtime.Types.Extensions.UserArgs -export const getExtensionContext = runtime.Extensions.getExtensionContext -export type Args = runtime.Types.Public.Args< - T, - F -> -export type Payload< - T, - F extends runtime.Operation = never, -> = runtime.Types.Public.Payload -export type Result< - T, - A, - F extends runtime.Operation, -> = runtime.Types.Public.Result -export type Exact = runtime.Types.Public.Exact - -export type PrismaVersion = { - client: string - engine: string -} - -/** - * Prisma Client JS version: 7.0.0 - * Query Engine version: 0c19ccc313cf9911a90d99d2ac2eb0280c76c513 - */ -export const prismaVersion: PrismaVersion = { - client: '7.0.0', - engine: '0c19ccc313cf9911a90d99d2ac2eb0280c76c513', -} - -/** - * Utility Types - */ - -export type Bytes = runtime.Bytes -export type JsonObject = runtime.JsonObject -export type JsonArray = runtime.JsonArray -export type JsonValue = runtime.JsonValue -export type InputJsonObject = runtime.InputJsonObject -export type InputJsonArray = runtime.InputJsonArray -export type InputJsonValue = runtime.InputJsonValue - -export const NullTypes = { - DbNull: runtime.NullTypes.DbNull as new ( - secret: never, - ) => typeof runtime.DbNull, - JsonNull: runtime.NullTypes.JsonNull as new ( - secret: never, - ) => typeof runtime.JsonNull, - AnyNull: runtime.NullTypes.AnyNull as new ( - secret: never, - ) => typeof runtime.AnyNull, -} -/** - * Helper for filtering JSON entries that have `null` on the database (empty on the db) - * - * @see https://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields#filtering-on-a-json-field - */ -export const DbNull = runtime.DbNull - -/** - * Helper for filtering JSON entries that have JSON `null` values (not empty on the db) - * - * @see https://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields#filtering-on-a-json-field - */ -export const JsonNull = runtime.JsonNull - -/** - * Helper for filtering JSON entries that are `Prisma.DbNull` or `Prisma.JsonNull` - * - * @see https://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields#filtering-on-a-json-field - */ -export const AnyNull = runtime.AnyNull - -type SelectAndInclude = { - select: any - include: any -} - -type SelectAndOmit = { - select: any - omit: any -} - -/** - * From T, pick a set of properties whose keys are in the union K - */ -type Prisma__Pick = { - [P in K]: T[P] -} - -export type Enumerable = T | Array - -/** - * Subset - * @desc From `T` pick properties that exist in `U`. Simple version of Intersection - */ -export type Subset = { - [key in keyof T]: key extends keyof U ? T[key] : never -} - -/** - * SelectSubset - * @desc From `T` pick properties that exist in `U`. Simple version of Intersection. - * Additionally, it validates, if both select and include are present. If the case, it errors. - */ -export type SelectSubset = { - [key in keyof T]: key extends keyof U ? T[key] : never -} & (T extends SelectAndInclude - ? 'Please either choose `select` or `include`.' - : T extends SelectAndOmit - ? 'Please either choose `select` or `omit`.' - : {}) - -/** - * Subset + Intersection - * @desc From `T` pick properties that exist in `U` and intersect `K` - */ -export type SubsetIntersection = { - [key in keyof T]: key extends keyof U ? T[key] : never -} & K - -type Without = { [P in Exclude]?: never } - -/** - * XOR is needed to have a real mutually exclusive union type - * https://stackoverflow.com/questions/42123407/does-typescript-support-mutually-exclusive-types - */ -export type XOR = T extends object - ? U extends object - ? (Without & U) | (Without & T) - : U - : T - -/** - * Is T a Record? - */ -type IsObject = - T extends Array - ? False - : T extends Date - ? False - : T extends Uint8Array - ? False - : T extends BigInt - ? False - : T extends object - ? True - : False - -/** - * If it's T[], return T - */ -export type UnEnumerate = T extends Array ? U : T - -/** - * From ts-toolbelt - */ - -type __Either = Omit & - { - // Merge all but K - [P in K]: Prisma__Pick // With K possibilities - }[K] - -type EitherStrict = Strict<__Either> - -type EitherLoose = ComputeRaw<__Either> - -type _Either = { - 1: EitherStrict - 0: EitherLoose -}[strict] - -export type Either< - O extends object, - K extends Key, - strict extends Boolean = 1, -> = O extends unknown ? _Either : never - -export type Union = any - -export type PatchUndefined = { - [K in keyof O]: O[K] extends undefined ? At : O[K] -} & {} - -/** Helper Types for "Merge" **/ -export type IntersectOf = ( - U extends unknown ? (k: U) => void : never -) extends (k: infer I) => void - ? I - : never - -export type Overwrite = { - [K in keyof O]: K extends keyof O1 ? O1[K] : O[K] -} & {} - -type _Merge = IntersectOf< - Overwrite< - U, - { - [K in keyof U]-?: At - } - > -> - -type Key = string | number | symbol -type AtStrict = O[K & keyof O] -type AtLoose = O extends unknown - ? AtStrict - : never -export type At = { - 1: AtStrict - 0: AtLoose -}[strict] - -export type ComputeRaw = A extends Function - ? A - : { - [K in keyof A]: A[K] - } & {} - -export type OptionalFlat = { - [K in keyof O]?: O[K] -} & {} - -type _Record = { - [P in K]: T -} - -// cause typescript not to expand types and preserve names -type NoExpand = T extends unknown ? T : never - -// this type assumes the passed object is entirely optional -export type AtLeast = NoExpand< - O extends unknown - ? - | (K extends keyof O ? { [P in K]: O[P] } & O : O) - | ({ [P in keyof O as P extends K ? P : never]-?: O[P] } & O) - : never -> - -type _Strict = U extends unknown - ? U & OptionalFlat<_Record, keyof U>, never>> - : never - -export type Strict = ComputeRaw<_Strict> -/** End Helper Types for "Merge" **/ - -export type Merge = ComputeRaw<_Merge>> - -export type Boolean = True | False - -export type True = 1 - -export type False = 0 - -export type Not = { - 0: 1 - 1: 0 -}[B] - -export type Extends = [A1] extends [never] - ? 0 // anything `never` is false - : A1 extends A2 - ? 1 - : 0 - -export type Has = Not< - Extends, U1> -> - -export type Or = { - 0: { - 0: 0 - 1: 1 - } - 1: { - 0: 1 - 1: 1 - } -}[B1][B2] - -export type Keys = U extends unknown ? keyof U : never - -export type GetScalarType = O extends object - ? { - [P in keyof T]: P extends keyof O ? O[P] : never - } - : never - -type FieldPaths> = - IsObject extends True ? U : T - -export type GetHavingFields = { - [K in keyof T]: Or< - Or, Extends<'AND', K>>, - Extends<'NOT', K> - > extends True - ? // infer is only needed to not hit TS limit - // based on the brilliant idea of Pierre-Antoine Mills - // https://github.com/microsoft/TypeScript/issues/30188#issuecomment-478938437 - T[K] extends infer TK - ? GetHavingFields< - UnEnumerate extends object ? Merge> : never - > - : never - : {} extends FieldPaths - ? never - : K -}[keyof T] - -/** - * Convert tuple to union - */ -type _TupleToUnion = T extends (infer E)[] ? E : never -type TupleToUnion = _TupleToUnion -export type MaybeTupleToUnion = T extends any[] ? TupleToUnion : T - -/** - * Like `Pick`, but additionally can also accept an array of keys - */ -export type PickEnumerable< - T, - K extends Enumerable | keyof T, -> = Prisma__Pick> - -/** - * Exclude all keys with underscores - */ -export type ExcludeUnderscoreKeys = T extends `_${string}` - ? never - : T - -export type FieldRef = runtime.FieldRef - -type FieldRefInputType = Model extends never - ? never - : FieldRef - -export const ModelName = { - User: 'User', -} as const - -export type ModelName = (typeof ModelName)[keyof typeof ModelName] - -export interface TypeMapCb extends runtime.Types.Utils - .Fn< - { extArgs: runtime.Types.Extensions.InternalArgs }, - runtime.Types.Utils.Record -> { - returns: TypeMap -} - -export type TypeMap< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, - GlobalOmitOptions = {}, -> = { - globalOmitOptions: { - omit: GlobalOmitOptions - } - meta: { - modelProps: 'user' - txIsolationLevel: TransactionIsolationLevel - } - model: { - User: { - payload: Prisma.$UserPayload - fields: Prisma.UserFieldRefs - operations: { - findUnique: { - args: Prisma.UserFindUniqueArgs - result: runtime.Types.Utils.PayloadToResult | null - } - findUniqueOrThrow: { - args: Prisma.UserFindUniqueOrThrowArgs - result: runtime.Types.Utils.PayloadToResult - } - findFirst: { - args: Prisma.UserFindFirstArgs - result: runtime.Types.Utils.PayloadToResult | null - } - findFirstOrThrow: { - args: Prisma.UserFindFirstOrThrowArgs - result: runtime.Types.Utils.PayloadToResult - } - findMany: { - args: Prisma.UserFindManyArgs - result: runtime.Types.Utils.PayloadToResult[] - } - create: { - args: Prisma.UserCreateArgs - result: runtime.Types.Utils.PayloadToResult - } - createMany: { - args: Prisma.UserCreateManyArgs - result: BatchPayload - } - createManyAndReturn: { - args: Prisma.UserCreateManyAndReturnArgs - result: runtime.Types.Utils.PayloadToResult[] - } - delete: { - args: Prisma.UserDeleteArgs - result: runtime.Types.Utils.PayloadToResult - } - update: { - args: Prisma.UserUpdateArgs - result: runtime.Types.Utils.PayloadToResult - } - deleteMany: { - args: Prisma.UserDeleteManyArgs - result: BatchPayload - } - updateMany: { - args: Prisma.UserUpdateManyArgs - result: BatchPayload - } - updateManyAndReturn: { - args: Prisma.UserUpdateManyAndReturnArgs - result: runtime.Types.Utils.PayloadToResult[] - } - upsert: { - args: Prisma.UserUpsertArgs - result: runtime.Types.Utils.PayloadToResult - } - aggregate: { - args: Prisma.UserAggregateArgs - result: runtime.Types.Utils.Optional - } - groupBy: { - args: Prisma.UserGroupByArgs - result: runtime.Types.Utils.Optional[] - } - count: { - args: Prisma.UserCountArgs - result: - | runtime.Types.Utils.Optional - | number - } - } - } - } -} & { - other: { - payload: any - operations: { - $executeRaw: { - args: [query: TemplateStringsArray | Sql, ...values: any[]] - result: any - } - $executeRawUnsafe: { - args: [query: string, ...values: any[]] - result: any - } - $queryRaw: { - args: [query: TemplateStringsArray | Sql, ...values: any[]] - result: any - } - $queryRawUnsafe: { - args: [query: string, ...values: any[]] - result: any - } - } - } -} - -/** - * Enums - */ - -export const TransactionIsolationLevel = runtime.makeStrictEnum({ - Serializable: 'Serializable', -} as const) - -export type TransactionIsolationLevel = - (typeof TransactionIsolationLevel)[keyof typeof TransactionIsolationLevel] - -export const UserScalarFieldEnum = { - email: 'email', - password: 'password', -} as const - -export type UserScalarFieldEnum = - (typeof UserScalarFieldEnum)[keyof typeof UserScalarFieldEnum] - -export const SortOrder = { - asc: 'asc', - desc: 'desc', -} as const - -export type SortOrder = (typeof SortOrder)[keyof typeof SortOrder] - -/** - * Field references - */ - -/** - * Reference to a field of type 'String' - */ -export type StringFieldRefInput<$PrismaModel> = FieldRefInputType< - $PrismaModel, - 'String' -> - -/** - * Reference to a field of type 'Int' - */ -export type IntFieldRefInput<$PrismaModel> = FieldRefInputType< - $PrismaModel, - 'Int' -> - -/** - * Batch Payload for updateMany & deleteMany & createMany - */ -export type BatchPayload = { - count: number -} - -export const defineExtension = runtime.Extensions - .defineExtension as unknown as runtime.Types.Extensions.ExtendsHook< - 'define', - TypeMapCb, - runtime.Types.Extensions.DefaultArgs -> -export type DefaultPrismaClient = PrismaClient -export type ErrorFormat = 'pretty' | 'colorless' | 'minimal' -export type PrismaClientOptions = ( - | { - /** - * Instance of a Driver Adapter, e.g., like one provided by `@prisma/adapter-pg`. - */ - adapter: runtime.SqlDriverAdapterFactory - accelerateUrl?: never - } - | { - /** - * Prisma Accelerate URL allowing the client to connect through Accelerate instead of a direct database. - */ - accelerateUrl: string - adapter?: never - } -) & { - /** - * @default "colorless" - */ - errorFormat?: ErrorFormat - /** - * @example - * ``` - * // Shorthand for `emit: 'stdout'` - * log: ['query', 'info', 'warn', 'error'] - * - * // Emit as events only - * log: [ - * { emit: 'event', level: 'query' }, - * { emit: 'event', level: 'info' }, - * { emit: 'event', level: 'warn' } - * { emit: 'event', level: 'error' } - * ] - * - * / Emit as events and log to stdout - * og: [ - * { emit: 'stdout', level: 'query' }, - * { emit: 'stdout', level: 'info' }, - * { emit: 'stdout', level: 'warn' } - * { emit: 'stdout', level: 'error' } - * - * ``` - * Read more in our [docs](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client/logging#the-log-option). - */ - log?: (LogLevel | LogDefinition)[] - /** - * The default values for transactionOptions - * maxWait ?= 2000 - * timeout ?= 5000 - */ - transactionOptions?: { - maxWait?: number - timeout?: number - isolationLevel?: TransactionIsolationLevel - } - /** - * Global configuration for omitting model fields by default. - * - * @example - * ``` - * const prisma = new PrismaClient({ - * omit: { - * user: { - * password: true - * } - * } - * }) - * ``` - */ - omit?: GlobalOmitConfig -} -export type GlobalOmitConfig = { - user?: Prisma.UserOmit -} - -/* Types for Logging */ -export type LogLevel = 'info' | 'query' | 'warn' | 'error' -export type LogDefinition = { - level: LogLevel - emit: 'stdout' | 'event' -} - -export type CheckIsLogLevel = T extends LogLevel ? T : never - -export type GetLogType = CheckIsLogLevel< - T extends LogDefinition ? T['level'] : T -> - -export type GetEvents = - T extends Array ? GetLogType : never - -export type QueryEvent = { - timestamp: Date - query: string - params: string - duration: number - target: string -} - -export type LogEvent = { - timestamp: Date - message: string - target: string -} -/* End Types for Logging */ - -export type PrismaAction = - | 'findUnique' - | 'findUniqueOrThrow' - | 'findMany' - | 'findFirst' - | 'findFirstOrThrow' - | 'create' - | 'createMany' - | 'createManyAndReturn' - | 'update' - | 'updateMany' - | 'updateManyAndReturn' - | 'upsert' - | 'delete' - | 'deleteMany' - | 'executeRaw' - | 'queryRaw' - | 'aggregate' - | 'count' - | 'runCommandRaw' - | 'findRaw' - | 'groupBy' - -/** - * `PrismaClient` proxy available in interactive transactions. - */ -export type TransactionClient = Omit< - DefaultPrismaClient, - runtime.ITXClientDenyList -> diff --git a/examples/react/start-basic-auth/src/prisma-generated/internal/prismaNamespaceBrowser.ts b/examples/react/start-basic-auth/src/prisma-generated/internal/prismaNamespaceBrowser.ts deleted file mode 100644 index d730c0a5bb..0000000000 --- a/examples/react/start-basic-auth/src/prisma-generated/internal/prismaNamespaceBrowser.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* !!! This is code generated by Prisma. Do not edit directly. !!! */ -/* eslint-disable */ -// biome-ignore-all lint: generated file -// @ts-nocheck -/* - * WARNING: This is an internal file that is subject to change! - * - * 🛑 Under no circumstances should you import this file directly! 🛑 - * - * All exports from this file are wrapped under a `Prisma` namespace object in the browser.ts file. - * While this enables partial backward compatibility, it is not part of the stable public API. - * - * If you are looking for your Models, Enums, and Input Types, please import them from the respective - * model files in the `model` directory! - */ - -import * as runtime from '@prisma/client/runtime/index-browser' - -export type * from '../models' -export type * from './prismaNamespace' - -export const Decimal = runtime.Decimal - -export const NullTypes = { - DbNull: runtime.NullTypes.DbNull as new ( - secret: never, - ) => typeof runtime.DbNull, - JsonNull: runtime.NullTypes.JsonNull as new ( - secret: never, - ) => typeof runtime.JsonNull, - AnyNull: runtime.NullTypes.AnyNull as new ( - secret: never, - ) => typeof runtime.AnyNull, -} -/** - * Helper for filtering JSON entries that have `null` on the database (empty on the db) - * - * @see https://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields#filtering-on-a-json-field - */ -export const DbNull = runtime.DbNull - -/** - * Helper for filtering JSON entries that have JSON `null` values (not empty on the db) - * - * @see https://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields#filtering-on-a-json-field - */ -export const JsonNull = runtime.JsonNull - -/** - * Helper for filtering JSON entries that are `Prisma.DbNull` or `Prisma.JsonNull` - * - * @see https://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields#filtering-on-a-json-field - */ -export const AnyNull = runtime.AnyNull - -export const ModelName = { - User: 'User', -} as const - -export type ModelName = (typeof ModelName)[keyof typeof ModelName] - -/* - * Enums - */ - -export const TransactionIsolationLevel = { - Serializable: 'Serializable', -} as const - -export type TransactionIsolationLevel = - (typeof TransactionIsolationLevel)[keyof typeof TransactionIsolationLevel] - -export const UserScalarFieldEnum = { - email: 'email', - password: 'password', -} as const - -export type UserScalarFieldEnum = - (typeof UserScalarFieldEnum)[keyof typeof UserScalarFieldEnum] - -export const SortOrder = { - asc: 'asc', - desc: 'desc', -} as const - -export type SortOrder = (typeof SortOrder)[keyof typeof SortOrder] diff --git a/examples/react/start-basic-auth/src/prisma-generated/models.ts b/examples/react/start-basic-auth/src/prisma-generated/models.ts deleted file mode 100644 index 0222c392e3..0000000000 --- a/examples/react/start-basic-auth/src/prisma-generated/models.ts +++ /dev/null @@ -1,11 +0,0 @@ -/* !!! This is code generated by Prisma. Do not edit directly. !!! */ -/* eslint-disable */ -// biome-ignore-all lint: generated file -// @ts-nocheck -/* - * This is a barrel export file for all models and their related types. - * - * 🟢 You can import this file directly. - */ -export type * from './models/User' -export type * from './commonInputTypes' diff --git a/examples/react/start-basic-auth/src/prisma-generated/models/User.ts b/examples/react/start-basic-auth/src/prisma-generated/models/User.ts deleted file mode 100644 index 4312db9bd9..0000000000 --- a/examples/react/start-basic-auth/src/prisma-generated/models/User.ts +++ /dev/null @@ -1,1323 +0,0 @@ -/* !!! This is code generated by Prisma. Do not edit directly. !!! */ -/* eslint-disable */ -// biome-ignore-all lint: generated file -// @ts-nocheck -/* - * This file exports the `User` model and its related types. - * - * 🟢 You can import this file directly. - */ -import type * as runtime from '@prisma/client/runtime/client' -import type * as $Enums from '../enums' -import type * as Prisma from '../internal/prismaNamespace' - -/** - * Model User - * - */ -export type UserModel = - runtime.Types.Result.DefaultSelection - -export type AggregateUser = { - _count: UserCountAggregateOutputType | null - _min: UserMinAggregateOutputType | null - _max: UserMaxAggregateOutputType | null -} - -export type UserMinAggregateOutputType = { - email: string | null - password: string | null -} - -export type UserMaxAggregateOutputType = { - email: string | null - password: string | null -} - -export type UserCountAggregateOutputType = { - email: number - password: number - _all: number -} - -export type UserMinAggregateInputType = { - email?: true - password?: true -} - -export type UserMaxAggregateInputType = { - email?: true - password?: true -} - -export type UserCountAggregateInputType = { - email?: true - password?: true - _all?: true -} - -export type UserAggregateArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * Filter which User to aggregate. - */ - where?: Prisma.UserWhereInput - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} - * - * Determine the order of Users to fetch. - */ - orderBy?: - | Prisma.UserOrderByWithRelationInput - | Prisma.UserOrderByWithRelationInput[] - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} - * - * Sets the start position - */ - cursor?: Prisma.UserWhereUniqueInput - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} - * - * Take `±n` Users from the position of the cursor. - */ - take?: number - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} - * - * Skip the first `n` Users. - */ - skip?: number - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} - * - * Count returned Users - **/ - _count?: true | UserCountAggregateInputType - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} - * - * Select which fields to find the minimum value - **/ - _min?: UserMinAggregateInputType - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs} - * - * Select which fields to find the maximum value - **/ - _max?: UserMaxAggregateInputType -} - -export type GetUserAggregateType = { - [P in keyof T & keyof AggregateUser]: P extends '_count' | 'count' - ? T[P] extends true - ? number - : Prisma.GetScalarType - : Prisma.GetScalarType -} - -export type UserGroupByArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - where?: Prisma.UserWhereInput - orderBy?: - | Prisma.UserOrderByWithAggregationInput - | Prisma.UserOrderByWithAggregationInput[] - by: Prisma.UserScalarFieldEnum[] | Prisma.UserScalarFieldEnum - having?: Prisma.UserScalarWhereWithAggregatesInput - take?: number - skip?: number - _count?: UserCountAggregateInputType | true - _min?: UserMinAggregateInputType - _max?: UserMaxAggregateInputType -} - -export type UserGroupByOutputType = { - email: string - password: string - _count: UserCountAggregateOutputType | null - _min: UserMinAggregateOutputType | null - _max: UserMaxAggregateOutputType | null -} - -type GetUserGroupByPayload = Prisma.PrismaPromise< - Array< - Prisma.PickEnumerable & { - [P in keyof T & keyof UserGroupByOutputType]: P extends '_count' - ? T[P] extends boolean - ? number - : Prisma.GetScalarType - : Prisma.GetScalarType - } - > -> - -export type UserWhereInput = { - AND?: Prisma.UserWhereInput | Prisma.UserWhereInput[] - OR?: Prisma.UserWhereInput[] - NOT?: Prisma.UserWhereInput | Prisma.UserWhereInput[] - email?: Prisma.StringFilter<'User'> | string - password?: Prisma.StringFilter<'User'> | string -} - -export type UserOrderByWithRelationInput = { - email?: Prisma.SortOrder - password?: Prisma.SortOrder -} - -export type UserWhereUniqueInput = Prisma.AtLeast< - { - email?: string - AND?: Prisma.UserWhereInput | Prisma.UserWhereInput[] - OR?: Prisma.UserWhereInput[] - NOT?: Prisma.UserWhereInput | Prisma.UserWhereInput[] - password?: Prisma.StringFilter<'User'> | string - }, - 'email' | 'email' -> - -export type UserOrderByWithAggregationInput = { - email?: Prisma.SortOrder - password?: Prisma.SortOrder - _count?: Prisma.UserCountOrderByAggregateInput - _max?: Prisma.UserMaxOrderByAggregateInput - _min?: Prisma.UserMinOrderByAggregateInput -} - -export type UserScalarWhereWithAggregatesInput = { - AND?: - | Prisma.UserScalarWhereWithAggregatesInput - | Prisma.UserScalarWhereWithAggregatesInput[] - OR?: Prisma.UserScalarWhereWithAggregatesInput[] - NOT?: - | Prisma.UserScalarWhereWithAggregatesInput - | Prisma.UserScalarWhereWithAggregatesInput[] - email?: Prisma.StringWithAggregatesFilter<'User'> | string - password?: Prisma.StringWithAggregatesFilter<'User'> | string -} - -export type UserCreateInput = { - email: string - password: string -} - -export type UserUncheckedCreateInput = { - email: string - password: string -} - -export type UserUpdateInput = { - email?: Prisma.StringFieldUpdateOperationsInput | string - password?: Prisma.StringFieldUpdateOperationsInput | string -} - -export type UserUncheckedUpdateInput = { - email?: Prisma.StringFieldUpdateOperationsInput | string - password?: Prisma.StringFieldUpdateOperationsInput | string -} - -export type UserCreateManyInput = { - email: string - password: string -} - -export type UserUpdateManyMutationInput = { - email?: Prisma.StringFieldUpdateOperationsInput | string - password?: Prisma.StringFieldUpdateOperationsInput | string -} - -export type UserUncheckedUpdateManyInput = { - email?: Prisma.StringFieldUpdateOperationsInput | string - password?: Prisma.StringFieldUpdateOperationsInput | string -} - -export type UserCountOrderByAggregateInput = { - email?: Prisma.SortOrder - password?: Prisma.SortOrder -} - -export type UserMaxOrderByAggregateInput = { - email?: Prisma.SortOrder - password?: Prisma.SortOrder -} - -export type UserMinOrderByAggregateInput = { - email?: Prisma.SortOrder - password?: Prisma.SortOrder -} - -export type StringFieldUpdateOperationsInput = { - set?: string -} - -export type UserSelect< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = runtime.Types.Extensions.GetSelect< - { - email?: boolean - password?: boolean - }, - ExtArgs['result']['user'] -> - -export type UserSelectCreateManyAndReturn< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = runtime.Types.Extensions.GetSelect< - { - email?: boolean - password?: boolean - }, - ExtArgs['result']['user'] -> - -export type UserSelectUpdateManyAndReturn< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = runtime.Types.Extensions.GetSelect< - { - email?: boolean - password?: boolean - }, - ExtArgs['result']['user'] -> - -export type UserSelectScalar = { - email?: boolean - password?: boolean -} - -export type UserOmit< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = runtime.Types.Extensions.GetOmit< - 'email' | 'password', - ExtArgs['result']['user'] -> - -export type $UserPayload< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - name: 'User' - objects: {} - scalars: runtime.Types.Extensions.GetPayloadResult< - { - email: string - password: string - }, - ExtArgs['result']['user'] - > - composites: {} -} - -export type UserGetPayload< - S extends boolean | null | undefined | UserDefaultArgs, -> = runtime.Types.Result.GetResult - -export type UserCountArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = Omit & { - select?: UserCountAggregateInputType | true -} - -export interface UserDelegate< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, - GlobalOmitOptions = {}, -> { - [K: symbol]: { - types: Prisma.TypeMap['model']['User'] - meta: { name: 'User' } - } - /** - * Find zero or one User that matches the filter. - * @param {UserFindUniqueArgs} args - Arguments to find a User - * @example - * // Get one User - * const user = await prisma.user.findUnique({ - * where: { - * // ... provide filter here - * } - * }) - */ - findUnique( - args: Prisma.SelectSubset>, - ): Prisma.Prisma__UserClient< - runtime.Types.Result.GetResult< - Prisma.$UserPayload, - T, - 'findUnique', - GlobalOmitOptions - > | null, - null, - ExtArgs, - GlobalOmitOptions - > - - /** - * Find one User that matches the filter or throw an error with `error.code='P2025'` - * if no matches were found. - * @param {UserFindUniqueOrThrowArgs} args - Arguments to find a User - * @example - * // Get one User - * const user = await prisma.user.findUniqueOrThrow({ - * where: { - * // ... provide filter here - * } - * }) - */ - findUniqueOrThrow( - args: Prisma.SelectSubset>, - ): Prisma.Prisma__UserClient< - runtime.Types.Result.GetResult< - Prisma.$UserPayload, - T, - 'findUniqueOrThrow', - GlobalOmitOptions - >, - never, - ExtArgs, - GlobalOmitOptions - > - - /** - * Find the first User that matches the filter. - * Note, that providing `undefined` is treated as the value not being there. - * Read more here: https://pris.ly/d/null-undefined - * @param {UserFindFirstArgs} args - Arguments to find a User - * @example - * // Get one User - * const user = await prisma.user.findFirst({ - * where: { - * // ... provide filter here - * } - * }) - */ - findFirst( - args?: Prisma.SelectSubset>, - ): Prisma.Prisma__UserClient< - runtime.Types.Result.GetResult< - Prisma.$UserPayload, - T, - 'findFirst', - GlobalOmitOptions - > | null, - null, - ExtArgs, - GlobalOmitOptions - > - - /** - * Find the first User that matches the filter or - * throw `PrismaKnownClientError` with `P2025` code if no matches were found. - * Note, that providing `undefined` is treated as the value not being there. - * Read more here: https://pris.ly/d/null-undefined - * @param {UserFindFirstOrThrowArgs} args - Arguments to find a User - * @example - * // Get one User - * const user = await prisma.user.findFirstOrThrow({ - * where: { - * // ... provide filter here - * } - * }) - */ - findFirstOrThrow( - args?: Prisma.SelectSubset>, - ): Prisma.Prisma__UserClient< - runtime.Types.Result.GetResult< - Prisma.$UserPayload, - T, - 'findFirstOrThrow', - GlobalOmitOptions - >, - never, - ExtArgs, - GlobalOmitOptions - > - - /** - * Find zero or more Users that matches the filter. - * Note, that providing `undefined` is treated as the value not being there. - * Read more here: https://pris.ly/d/null-undefined - * @param {UserFindManyArgs} args - Arguments to filter and select certain fields only. - * @example - * // Get all Users - * const users = await prisma.user.findMany() - * - * // Get first 10 Users - * const users = await prisma.user.findMany({ take: 10 }) - * - * // Only select the `email` - * const userWithEmailOnly = await prisma.user.findMany({ select: { email: true } }) - * - */ - findMany( - args?: Prisma.SelectSubset>, - ): Prisma.PrismaPromise< - runtime.Types.Result.GetResult< - Prisma.$UserPayload, - T, - 'findMany', - GlobalOmitOptions - > - > - - /** - * Create a User. - * @param {UserCreateArgs} args - Arguments to create a User. - * @example - * // Create one User - * const User = await prisma.user.create({ - * data: { - * // ... data to create a User - * } - * }) - * - */ - create( - args: Prisma.SelectSubset>, - ): Prisma.Prisma__UserClient< - runtime.Types.Result.GetResult< - Prisma.$UserPayload, - T, - 'create', - GlobalOmitOptions - >, - never, - ExtArgs, - GlobalOmitOptions - > - - /** - * Create many Users. - * @param {UserCreateManyArgs} args - Arguments to create many Users. - * @example - * // Create many Users - * const user = await prisma.user.createMany({ - * data: [ - * // ... provide data here - * ] - * }) - * - */ - createMany( - args?: Prisma.SelectSubset>, - ): Prisma.PrismaPromise - - /** - * Create many Users and returns the data saved in the database. - * @param {UserCreateManyAndReturnArgs} args - Arguments to create many Users. - * @example - * // Create many Users - * const user = await prisma.user.createManyAndReturn({ - * data: [ - * // ... provide data here - * ] - * }) - * - * // Create many Users and only return the `email` - * const userWithEmailOnly = await prisma.user.createManyAndReturn({ - * select: { email: true }, - * data: [ - * // ... provide data here - * ] - * }) - * Note, that providing `undefined` is treated as the value not being there. - * Read more here: https://pris.ly/d/null-undefined - * - */ - createManyAndReturn( - args?: Prisma.SelectSubset>, - ): Prisma.PrismaPromise< - runtime.Types.Result.GetResult< - Prisma.$UserPayload, - T, - 'createManyAndReturn', - GlobalOmitOptions - > - > - - /** - * Delete a User. - * @param {UserDeleteArgs} args - Arguments to delete one User. - * @example - * // Delete one User - * const User = await prisma.user.delete({ - * where: { - * // ... filter to delete one User - * } - * }) - * - */ - delete( - args: Prisma.SelectSubset>, - ): Prisma.Prisma__UserClient< - runtime.Types.Result.GetResult< - Prisma.$UserPayload, - T, - 'delete', - GlobalOmitOptions - >, - never, - ExtArgs, - GlobalOmitOptions - > - - /** - * Update one User. - * @param {UserUpdateArgs} args - Arguments to update one User. - * @example - * // Update one User - * const user = await prisma.user.update({ - * where: { - * // ... provide filter here - * }, - * data: { - * // ... provide data here - * } - * }) - * - */ - update( - args: Prisma.SelectSubset>, - ): Prisma.Prisma__UserClient< - runtime.Types.Result.GetResult< - Prisma.$UserPayload, - T, - 'update', - GlobalOmitOptions - >, - never, - ExtArgs, - GlobalOmitOptions - > - - /** - * Delete zero or more Users. - * @param {UserDeleteManyArgs} args - Arguments to filter Users to delete. - * @example - * // Delete a few Users - * const { count } = await prisma.user.deleteMany({ - * where: { - * // ... provide filter here - * } - * }) - * - */ - deleteMany( - args?: Prisma.SelectSubset>, - ): Prisma.PrismaPromise - - /** - * Update zero or more Users. - * Note, that providing `undefined` is treated as the value not being there. - * Read more here: https://pris.ly/d/null-undefined - * @param {UserUpdateManyArgs} args - Arguments to update one or more rows. - * @example - * // Update many Users - * const user = await prisma.user.updateMany({ - * where: { - * // ... provide filter here - * }, - * data: { - * // ... provide data here - * } - * }) - * - */ - updateMany( - args: Prisma.SelectSubset>, - ): Prisma.PrismaPromise - - /** - * Update zero or more Users and returns the data updated in the database. - * @param {UserUpdateManyAndReturnArgs} args - Arguments to update many Users. - * @example - * // Update many Users - * const user = await prisma.user.updateManyAndReturn({ - * where: { - * // ... provide filter here - * }, - * data: [ - * // ... provide data here - * ] - * }) - * - * // Update zero or more Users and only return the `email` - * const userWithEmailOnly = await prisma.user.updateManyAndReturn({ - * select: { email: true }, - * where: { - * // ... provide filter here - * }, - * data: [ - * // ... provide data here - * ] - * }) - * Note, that providing `undefined` is treated as the value not being there. - * Read more here: https://pris.ly/d/null-undefined - * - */ - updateManyAndReturn( - args: Prisma.SelectSubset>, - ): Prisma.PrismaPromise< - runtime.Types.Result.GetResult< - Prisma.$UserPayload, - T, - 'updateManyAndReturn', - GlobalOmitOptions - > - > - - /** - * Create or update one User. - * @param {UserUpsertArgs} args - Arguments to update or create a User. - * @example - * // Update or create a User - * const user = await prisma.user.upsert({ - * create: { - * // ... data to create a User - * }, - * update: { - * // ... in case it already exists, update - * }, - * where: { - * // ... the filter for the User we want to update - * } - * }) - */ - upsert( - args: Prisma.SelectSubset>, - ): Prisma.Prisma__UserClient< - runtime.Types.Result.GetResult< - Prisma.$UserPayload, - T, - 'upsert', - GlobalOmitOptions - >, - never, - ExtArgs, - GlobalOmitOptions - > - - /** - * Count the number of Users. - * Note, that providing `undefined` is treated as the value not being there. - * Read more here: https://pris.ly/d/null-undefined - * @param {UserCountArgs} args - Arguments to filter Users to count. - * @example - * // Count the number of Users - * const count = await prisma.user.count({ - * where: { - * // ... the filter for the Users we want to count - * } - * }) - **/ - count( - args?: Prisma.Subset, - ): Prisma.PrismaPromise< - T extends runtime.Types.Utils.Record<'select', any> - ? T['select'] extends true - ? number - : Prisma.GetScalarType - : number - > - - /** - * Allows you to perform aggregations operations on a User. - * Note, that providing `undefined` is treated as the value not being there. - * Read more here: https://pris.ly/d/null-undefined - * @param {UserAggregateArgs} args - Select which aggregations you would like to apply and on what fields. - * @example - * // Ordered by age ascending - * // Where email contains prisma.io - * // Limited to the 10 users - * const aggregations = await prisma.user.aggregate({ - * _avg: { - * age: true, - * }, - * where: { - * email: { - * contains: "prisma.io", - * }, - * }, - * orderBy: { - * age: "asc", - * }, - * take: 10, - * }) - **/ - aggregate( - args: Prisma.Subset, - ): Prisma.PrismaPromise> - - /** - * Group by User. - * Note, that providing `undefined` is treated as the value not being there. - * Read more here: https://pris.ly/d/null-undefined - * @param {UserGroupByArgs} args - Group by arguments. - * @example - * // Group by city, order by createdAt, get count - * const result = await prisma.user.groupBy({ - * by: ['city', 'createdAt'], - * orderBy: { - * createdAt: true - * }, - * _count: { - * _all: true - * }, - * }) - * - **/ - groupBy< - T extends UserGroupByArgs, - HasSelectOrTake extends Prisma.Or< - Prisma.Extends<'skip', Prisma.Keys>, - Prisma.Extends<'take', Prisma.Keys> - >, - OrderByArg extends Prisma.True extends HasSelectOrTake - ? { orderBy: UserGroupByArgs['orderBy'] } - : { orderBy?: UserGroupByArgs['orderBy'] }, - OrderFields extends Prisma.ExcludeUnderscoreKeys< - Prisma.Keys> - >, - ByFields extends Prisma.MaybeTupleToUnion, - ByValid extends Prisma.Has, - HavingFields extends Prisma.GetHavingFields, - HavingValid extends Prisma.Has, - ByEmpty extends T['by'] extends never[] ? Prisma.True : Prisma.False, - InputErrors extends ByEmpty extends Prisma.True - ? `Error: "by" must not be empty.` - : HavingValid extends Prisma.False - ? { - [P in HavingFields]: P extends ByFields - ? never - : P extends string - ? `Error: Field "${P}" used in "having" needs to be provided in "by".` - : [ - Error, - 'Field ', - P, - ` in "having" needs to be provided in "by"`, - ] - }[HavingFields] - : 'take' extends Prisma.Keys - ? 'orderBy' extends Prisma.Keys - ? ByValid extends Prisma.True - ? {} - : { - [P in OrderFields]: P extends ByFields - ? never - : `Error: Field "${P}" in "orderBy" needs to be provided in "by"` - }[OrderFields] - : 'Error: If you provide "take", you also need to provide "orderBy"' - : 'skip' extends Prisma.Keys - ? 'orderBy' extends Prisma.Keys - ? ByValid extends Prisma.True - ? {} - : { - [P in OrderFields]: P extends ByFields - ? never - : `Error: Field "${P}" in "orderBy" needs to be provided in "by"` - }[OrderFields] - : 'Error: If you provide "skip", you also need to provide "orderBy"' - : ByValid extends Prisma.True - ? {} - : { - [P in OrderFields]: P extends ByFields - ? never - : `Error: Field "${P}" in "orderBy" needs to be provided in "by"` - }[OrderFields], - >( - args: Prisma.SubsetIntersection & - InputErrors, - ): {} extends InputErrors - ? GetUserGroupByPayload - : Prisma.PrismaPromise - /** - * Fields of the User model - */ - readonly fields: UserFieldRefs -} - -/** - * The delegate class that acts as a "Promise-like" for User. - * Why is this prefixed with `Prisma__`? - * Because we want to prevent naming conflicts as mentioned in - * https://github.com/prisma/prisma-client-js/issues/707 - */ -export interface Prisma__UserClient< - T, - Null = never, - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, - GlobalOmitOptions = {}, -> extends Prisma.PrismaPromise { - readonly [Symbol.toStringTag]: 'PrismaPromise' - /** - * Attaches callbacks for the resolution and/or rejection of the Promise. - * @param onfulfilled The callback to execute when the Promise is resolved. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A Promise for the completion of which ever callback is executed. - */ - then( - onfulfilled?: - | ((value: T) => TResult1 | PromiseLike) - | undefined - | null, - onrejected?: - | ((reason: any) => TResult2 | PromiseLike) - | undefined - | null, - ): runtime.Types.Utils.JsPromise - /** - * Attaches a callback for only the rejection of the Promise. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A Promise for the completion of the callback. - */ - catch( - onrejected?: - | ((reason: any) => TResult | PromiseLike) - | undefined - | null, - ): runtime.Types.Utils.JsPromise - /** - * Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The - * resolved value cannot be modified from the callback. - * @param onfinally The callback to execute when the Promise is settled (fulfilled or rejected). - * @returns A Promise for the completion of the callback. - */ - finally( - onfinally?: (() => void) | undefined | null, - ): runtime.Types.Utils.JsPromise -} - -/** - * Fields of the User model - */ -export interface UserFieldRefs { - readonly email: Prisma.FieldRef<'User', 'String'> - readonly password: Prisma.FieldRef<'User', 'String'> -} - -// Custom InputTypes -/** - * User findUnique - */ -export type UserFindUniqueArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * Select specific fields to fetch from the User - */ - select?: Prisma.UserSelect | null - /** - * Omit specific fields from the User - */ - omit?: Prisma.UserOmit | null - /** - * Filter, which User to fetch. - */ - where: Prisma.UserWhereUniqueInput -} - -/** - * User findUniqueOrThrow - */ -export type UserFindUniqueOrThrowArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * Select specific fields to fetch from the User - */ - select?: Prisma.UserSelect | null - /** - * Omit specific fields from the User - */ - omit?: Prisma.UserOmit | null - /** - * Filter, which User to fetch. - */ - where: Prisma.UserWhereUniqueInput -} - -/** - * User findFirst - */ -export type UserFindFirstArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * Select specific fields to fetch from the User - */ - select?: Prisma.UserSelect | null - /** - * Omit specific fields from the User - */ - omit?: Prisma.UserOmit | null - /** - * Filter, which User to fetch. - */ - where?: Prisma.UserWhereInput - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} - * - * Determine the order of Users to fetch. - */ - orderBy?: - | Prisma.UserOrderByWithRelationInput - | Prisma.UserOrderByWithRelationInput[] - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} - * - * Sets the position for searching for Users. - */ - cursor?: Prisma.UserWhereUniqueInput - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} - * - * Take `±n` Users from the position of the cursor. - */ - take?: number - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} - * - * Skip the first `n` Users. - */ - skip?: number - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/distinct Distinct Docs} - * - * Filter by unique combinations of Users. - */ - distinct?: Prisma.UserScalarFieldEnum | Prisma.UserScalarFieldEnum[] -} - -/** - * User findFirstOrThrow - */ -export type UserFindFirstOrThrowArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * Select specific fields to fetch from the User - */ - select?: Prisma.UserSelect | null - /** - * Omit specific fields from the User - */ - omit?: Prisma.UserOmit | null - /** - * Filter, which User to fetch. - */ - where?: Prisma.UserWhereInput - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} - * - * Determine the order of Users to fetch. - */ - orderBy?: - | Prisma.UserOrderByWithRelationInput - | Prisma.UserOrderByWithRelationInput[] - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} - * - * Sets the position for searching for Users. - */ - cursor?: Prisma.UserWhereUniqueInput - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} - * - * Take `±n` Users from the position of the cursor. - */ - take?: number - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} - * - * Skip the first `n` Users. - */ - skip?: number - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/distinct Distinct Docs} - * - * Filter by unique combinations of Users. - */ - distinct?: Prisma.UserScalarFieldEnum | Prisma.UserScalarFieldEnum[] -} - -/** - * User findMany - */ -export type UserFindManyArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * Select specific fields to fetch from the User - */ - select?: Prisma.UserSelect | null - /** - * Omit specific fields from the User - */ - omit?: Prisma.UserOmit | null - /** - * Filter, which Users to fetch. - */ - where?: Prisma.UserWhereInput - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs} - * - * Determine the order of Users to fetch. - */ - orderBy?: - | Prisma.UserOrderByWithRelationInput - | Prisma.UserOrderByWithRelationInput[] - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs} - * - * Sets the position for listing Users. - */ - cursor?: Prisma.UserWhereUniqueInput - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} - * - * Take `±n` Users from the position of the cursor. - */ - take?: number - /** - * {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs} - * - * Skip the first `n` Users. - */ - skip?: number - distinct?: Prisma.UserScalarFieldEnum | Prisma.UserScalarFieldEnum[] -} - -/** - * User create - */ -export type UserCreateArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * Select specific fields to fetch from the User - */ - select?: Prisma.UserSelect | null - /** - * Omit specific fields from the User - */ - omit?: Prisma.UserOmit | null - /** - * The data needed to create a User. - */ - data: Prisma.XOR -} - -/** - * User createMany - */ -export type UserCreateManyArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * The data used to create many Users. - */ - data: Prisma.UserCreateManyInput | Prisma.UserCreateManyInput[] -} - -/** - * User createManyAndReturn - */ -export type UserCreateManyAndReturnArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * Select specific fields to fetch from the User - */ - select?: Prisma.UserSelectCreateManyAndReturn | null - /** - * Omit specific fields from the User - */ - omit?: Prisma.UserOmit | null - /** - * The data used to create many Users. - */ - data: Prisma.UserCreateManyInput | Prisma.UserCreateManyInput[] -} - -/** - * User update - */ -export type UserUpdateArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * Select specific fields to fetch from the User - */ - select?: Prisma.UserSelect | null - /** - * Omit specific fields from the User - */ - omit?: Prisma.UserOmit | null - /** - * The data needed to update a User. - */ - data: Prisma.XOR - /** - * Choose, which User to update. - */ - where: Prisma.UserWhereUniqueInput -} - -/** - * User updateMany - */ -export type UserUpdateManyArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * The data used to update Users. - */ - data: Prisma.XOR< - Prisma.UserUpdateManyMutationInput, - Prisma.UserUncheckedUpdateManyInput - > - /** - * Filter which Users to update - */ - where?: Prisma.UserWhereInput - /** - * Limit how many Users to update. - */ - limit?: number -} - -/** - * User updateManyAndReturn - */ -export type UserUpdateManyAndReturnArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * Select specific fields to fetch from the User - */ - select?: Prisma.UserSelectUpdateManyAndReturn | null - /** - * Omit specific fields from the User - */ - omit?: Prisma.UserOmit | null - /** - * The data used to update Users. - */ - data: Prisma.XOR< - Prisma.UserUpdateManyMutationInput, - Prisma.UserUncheckedUpdateManyInput - > - /** - * Filter which Users to update - */ - where?: Prisma.UserWhereInput - /** - * Limit how many Users to update. - */ - limit?: number -} - -/** - * User upsert - */ -export type UserUpsertArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * Select specific fields to fetch from the User - */ - select?: Prisma.UserSelect | null - /** - * Omit specific fields from the User - */ - omit?: Prisma.UserOmit | null - /** - * The filter to search for the User to update in case it exists. - */ - where: Prisma.UserWhereUniqueInput - /** - * In case the User found by the `where` argument doesn't exist, create a new User with this data. - */ - create: Prisma.XOR - /** - * In case the User was found with the provided `where` argument, update it with this data. - */ - update: Prisma.XOR -} - -/** - * User delete - */ -export type UserDeleteArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * Select specific fields to fetch from the User - */ - select?: Prisma.UserSelect | null - /** - * Omit specific fields from the User - */ - omit?: Prisma.UserOmit | null - /** - * Filter which User to delete. - */ - where: Prisma.UserWhereUniqueInput -} - -/** - * User deleteMany - */ -export type UserDeleteManyArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * Filter which Users to delete - */ - where?: Prisma.UserWhereInput - /** - * Limit how many Users to delete. - */ - limit?: number -} - -/** - * User without action - */ -export type UserDefaultArgs< - ExtArgs extends runtime.Types.Extensions.InternalArgs = - runtime.Types.Extensions.DefaultArgs, -> = { - /** - * Select specific fields to fetch from the User - */ - select?: Prisma.UserSelect | null - /** - * Omit specific fields from the User - */ - omit?: Prisma.UserOmit | null -} diff --git a/examples/react/start-basic-auth/src/routeTree.gen.ts b/examples/react/start-basic-auth/src/routeTree.gen.ts deleted file mode 100644 index a74e753aec..0000000000 --- a/examples/react/start-basic-auth/src/routeTree.gen.ts +++ /dev/null @@ -1,224 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as AuthedRouteImport } from './routes/_authed' -import { Route as LoginRouteImport } from './routes/login' -import { Route as LogoutRouteImport } from './routes/logout' -import { Route as SignupRouteImport } from './routes/signup' -import { Route as AuthedPostsRouteRouteImport } from './routes/_authed/posts.route' -import { Route as AuthedPostsIndexRouteImport } from './routes/_authed/posts.index' -import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AuthedRoute = AuthedRouteImport.update({ - id: '/_authed', - getParentRoute: () => rootRouteImport, -} as any) -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', - getParentRoute: () => rootRouteImport, -} as any) -const LogoutRoute = LogoutRouteImport.update({ - id: '/logout', - path: '/logout', - getParentRoute: () => rootRouteImport, -} as any) -const SignupRoute = SignupRouteImport.update({ - id: '/signup', - path: '/signup', - getParentRoute: () => rootRouteImport, -} as any) -const AuthedPostsRouteRoute = AuthedPostsRouteRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => AuthedRoute, -} as any) -const AuthedPostsIndexRoute = AuthedPostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => AuthedPostsRouteRoute, -} as any) -const AuthedPostsPostIdRoute = AuthedPostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => AuthedPostsRouteRoute, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/login': typeof LoginRoute - '/logout': typeof LogoutRoute - '/signup': typeof SignupRoute - '/posts': typeof AuthedPostsRouteRouteWithChildren - '/posts/$postId': typeof AuthedPostsPostIdRoute - '/posts/': typeof AuthedPostsIndexRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/login': typeof LoginRoute - '/logout': typeof LogoutRoute - '/signup': typeof SignupRoute - '/posts/$postId': typeof AuthedPostsPostIdRoute - '/posts': typeof AuthedPostsIndexRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/_authed': typeof AuthedRouteWithChildren - '/login': typeof LoginRoute - '/logout': typeof LogoutRoute - '/signup': typeof SignupRoute - '/_authed/posts': typeof AuthedPostsRouteRouteWithChildren - '/_authed/posts/$postId': typeof AuthedPostsPostIdRoute - '/_authed/posts/': typeof AuthedPostsIndexRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/login' - | '/logout' - | '/signup' - | '/posts' - | '/posts/$postId' - | '/posts/' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/login' | '/logout' | '/signup' | '/posts/$postId' | '/posts' - id: - | '__root__' - | '/' - | '/_authed' - | '/login' - | '/logout' - | '/signup' - | '/_authed/posts' - | '/_authed/posts/$postId' - | '/_authed/posts/' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - AuthedRoute: typeof AuthedRouteWithChildren - LoginRoute: typeof LoginRoute - LogoutRoute: typeof LogoutRoute - SignupRoute: typeof SignupRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_authed': { - id: '/_authed' - path: '' - fullPath: '/' - preLoaderRoute: typeof AuthedRouteImport - parentRoute: typeof rootRouteImport - } - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport - parentRoute: typeof rootRouteImport - } - '/logout': { - id: '/logout' - path: '/logout' - fullPath: '/logout' - preLoaderRoute: typeof LogoutRouteImport - parentRoute: typeof rootRouteImport - } - '/signup': { - id: '/signup' - path: '/signup' - fullPath: '/signup' - preLoaderRoute: typeof SignupRouteImport - parentRoute: typeof rootRouteImport - } - '/_authed/posts': { - id: '/_authed/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof AuthedPostsRouteRouteImport - parentRoute: typeof AuthedRoute - } - '/_authed/posts/': { - id: '/_authed/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof AuthedPostsIndexRouteImport - parentRoute: typeof AuthedPostsRouteRoute - } - '/_authed/posts/$postId': { - id: '/_authed/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof AuthedPostsPostIdRouteImport - parentRoute: typeof AuthedPostsRouteRoute - } - } -} - -interface AuthedPostsRouteRouteChildren { - AuthedPostsPostIdRoute: typeof AuthedPostsPostIdRoute - AuthedPostsIndexRoute: typeof AuthedPostsIndexRoute -} - -const AuthedPostsRouteRouteChildren: AuthedPostsRouteRouteChildren = { - AuthedPostsPostIdRoute: AuthedPostsPostIdRoute, - AuthedPostsIndexRoute: AuthedPostsIndexRoute, -} - -const AuthedPostsRouteRouteWithChildren = - AuthedPostsRouteRoute._addFileChildren(AuthedPostsRouteRouteChildren) - -interface AuthedRouteChildren { - AuthedPostsRouteRoute: typeof AuthedPostsRouteRouteWithChildren -} - -const AuthedRouteChildren: AuthedRouteChildren = { - AuthedPostsRouteRoute: AuthedPostsRouteRouteWithChildren, -} - -const AuthedRouteWithChildren = - AuthedRoute._addFileChildren(AuthedRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - AuthedRoute: AuthedRouteWithChildren, - LoginRoute: LoginRoute, - LogoutRoute: LogoutRoute, - SignupRoute: SignupRoute, -} -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/examples/react/start-basic-auth/src/router.tsx b/examples/react/start-basic-auth/src/router.tsx deleted file mode 100644 index f648dfcf8c..0000000000 --- a/examples/react/start-basic-auth/src/router.tsx +++ /dev/null @@ -1,22 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' -import { DefaultCatchBoundary } from './components/DefaultCatchBoundary' -import { NotFound } from './components/NotFound' - -export function getRouter() { - const router = createRouter({ - routeTree, - defaultPreload: 'intent', - defaultErrorComponent: DefaultCatchBoundary, - defaultNotFoundComponent: () => , - scrollRestoration: true, - }) - - return router -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/examples/react/start-basic-auth/src/routes/__root.tsx b/examples/react/start-basic-auth/src/routes/__root.tsx deleted file mode 100644 index 3367c62f27..0000000000 --- a/examples/react/start-basic-auth/src/routes/__root.tsx +++ /dev/null @@ -1,141 +0,0 @@ -/// -import { - HeadContent, - Link, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' -import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' -import { createServerFn } from '@tanstack/react-start' -import * as React from 'react' -import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary.js' -import { NotFound } from '~/components/NotFound.js' -import appCss from '~/styles/app.css?url' -import { seo } from '~/utils/seo.js' -import { getAppSession } from '~/utils/session.js' - -const fetchUser = createServerFn({ method: 'GET' }).handler(async () => { - // We need to auth on the server so we have access to secure cookies - const session = await getAppSession() - - if (!session.userEmail) { - return null - } - - return { - email: session.userEmail, - } -}) - -export const Route = createRootRoute({ - beforeLoad: async () => { - const user = await fetchUser() - - return { - user, - } - }, - head: () => ({ - meta: [ - { - charSet: 'utf-8', - }, - { - name: 'viewport', - content: 'width=device-width, initial-scale=1', - }, - ...seo({ - title: - 'TanStack Start | Type-Safe, Client-First, Full-Stack React Framework', - description: `TanStack Start is a type-safe, client-first, full-stack React framework. `, - }), - ], - links: [ - { rel: 'stylesheet', href: appCss }, - { - rel: 'apple-touch-icon', - sizes: '180x180', - href: '/apple-touch-icon.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '32x32', - href: '/favicon-32x32.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '16x16', - href: '/favicon-16x16.png', - }, - { rel: 'manifest', href: '/site.webmanifest', color: '#fffff' }, - { rel: 'icon', href: '/favicon.ico' }, - ], - }), - errorComponent: (props) => { - return ( - - - - ) - }, - notFoundComponent: () => , - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - ) -} - -function RootDocument({ children }: { children: React.ReactNode }) { - const { user } = Route.useRouteContext() - - return ( - - - - - -

-
- {children} - - - - - ) -} diff --git a/examples/react/start-basic-auth/src/routes/_authed.tsx b/examples/react/start-basic-auth/src/routes/_authed.tsx deleted file mode 100644 index 0b5c6f9047..0000000000 --- a/examples/react/start-basic-auth/src/routes/_authed.tsx +++ /dev/null @@ -1,55 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { createServerFn } from '@tanstack/react-start' -import { hashPassword, prismaClient } from '~/utils/prisma' -import { Login } from '~/components/Login' -import { getAppSession } from '~/utils/session' - -export const loginFn = createServerFn({ method: 'POST' }) - .validator((d: { email: string; password: string }) => d) - .handler(async ({ data }) => { - // Find the user - const user = await prismaClient.user.findUnique({ - where: { - email: data.email, - }, - }) - - // Check if the user exists - if (!user) { - return { - error: true, - userNotFound: true, - message: 'User not found', - } - } - - // Check if the password is correct - const hashedPassword = await hashPassword(data.password) - - if (user.password !== hashedPassword) { - return { - error: true, - message: 'Incorrect password', - } - } - - // Store the user's email in the session - const session = await getAppSession() - session.userEmail = user.email - await session.save() - }) - -export const Route = createFileRoute('/_authed')({ - beforeLoad: ({ context }) => { - if (!context.user) { - throw new Error('Not authenticated') - } - }, - errorComponent: ({ error }) => { - if (error instanceof Error && error.message === 'Not authenticated') { - return - } - - throw error - }, -}) diff --git a/examples/react/start-basic-auth/src/routes/_authed/posts.$postId.tsx b/examples/react/start-basic-auth/src/routes/_authed/posts.$postId.tsx deleted file mode 100644 index 039271bb89..0000000000 --- a/examples/react/start-basic-auth/src/routes/_authed/posts.$postId.tsx +++ /dev/null @@ -1,28 +0,0 @@ -import { ErrorComponent, createFileRoute } from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' -import { NotFound } from '~/components/NotFound.js' -import { fetchPost } from '~/utils/posts.js' - -export const Route = createFileRoute('/_authed/posts/$postId')({ - loader: ({ params: { postId } }) => fetchPost({ data: postId }), - errorComponent: PostErrorComponent, - component: PostComponent, - notFoundComponent: () => { - return Post not found - }, -}) - -export function PostErrorComponent({ error }: ErrorComponentProps) { - return -} - -function PostComponent() { - const post = Route.useLoaderData() - - return ( -
-

{post.title}

-
{post.body}
-
- ) -} diff --git a/examples/react/start-basic-auth/src/routes/_authed/posts.index.tsx b/examples/react/start-basic-auth/src/routes/_authed/posts.index.tsx deleted file mode 100644 index de01fe5dde..0000000000 --- a/examples/react/start-basic-auth/src/routes/_authed/posts.index.tsx +++ /dev/null @@ -1,8 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/_authed/posts/')({ - component: PostsIndexComponent, -}) - -function PostsIndexComponent() { - return
Select a post.
-} diff --git a/examples/react/start-basic-auth/src/routes/_authed/posts.route.tsx b/examples/react/start-basic-auth/src/routes/_authed/posts.route.tsx deleted file mode 100644 index 86c8ef4138..0000000000 --- a/examples/react/start-basic-auth/src/routes/_authed/posts.route.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' -import { fetchPosts } from '~/utils/posts.js' - -export const Route = createFileRoute('/_authed/posts')({ - loader: () => fetchPosts(), - component: PostsComponent, -}) - -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[...posts, { id: 'i-do-not-exist', title: 'Non-existent Post' }].map( - (post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - }, - )} -
-
- -
- ) -} diff --git a/examples/react/start-basic-auth/src/routes/index.tsx b/examples/react/start-basic-auth/src/routes/index.tsx deleted file mode 100644 index 37c8d237bd..0000000000 --- a/examples/react/start-basic-auth/src/routes/index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/')({ - component: Home, -}) - -function Home() { - return ( -
-

Welcome Home!!!

-
- ) -} diff --git a/examples/react/start-basic-auth/src/routes/login.tsx b/examples/react/start-basic-auth/src/routes/login.tsx deleted file mode 100644 index 03ced20832..0000000000 --- a/examples/react/start-basic-auth/src/routes/login.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { Login } from '~/components/Login' - -export const Route = createFileRoute('/login')({ - component: LoginComp, -}) - -function LoginComp() { - return -} diff --git a/examples/react/start-basic-auth/src/routes/logout.tsx b/examples/react/start-basic-auth/src/routes/logout.tsx deleted file mode 100644 index 73cdaf1600..0000000000 --- a/examples/react/start-basic-auth/src/routes/logout.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { redirect, createFileRoute } from '@tanstack/react-router' -import { createServerFn } from '@tanstack/react-start' -import { getAppSession } from '~/utils/session' - -const logoutFn = createServerFn().handler(async () => { - const session = await getAppSession() - session.destroy() - - throw redirect({ - href: '/', - }) -}) - -export const Route = createFileRoute('/logout')({ - preload: false, - loader: () => logoutFn(), -}) diff --git a/examples/react/start-basic-auth/src/routes/signup.tsx b/examples/react/start-basic-auth/src/routes/signup.tsx deleted file mode 100644 index 4dc8e350ac..0000000000 --- a/examples/react/start-basic-auth/src/routes/signup.tsx +++ /dev/null @@ -1,94 +0,0 @@ -import { redirect, createFileRoute } from '@tanstack/react-router' -import { createServerFn, useServerFn } from '@tanstack/react-start' -import { hashPassword, prismaClient } from '~/utils/prisma' -import { useMutation } from '~/hooks/useMutation' -import { Auth } from '~/components/Auth' -import { getAppSession } from '~/utils/session' - -export const signupFn = createServerFn({ method: 'POST' }) - .validator( - (d: { email: string; password: string; redirectUrl?: string }) => d, - ) - .handler(async ({ data }) => { - // Check if the user already exists - const found = await prismaClient.user.findUnique({ - where: { - email: data.email, - }, - }) - - // Encrypt the password using Sha256 into plaintext - const password = await hashPassword(data.password) - - if (found) { - if (found.password !== password) { - return { - error: true, - userExists: true, - message: 'User already exists', - } - } - - // Store the user's email in the session - const session = await getAppSession() - session.userEmail = found.email - await session.save() - - // Redirect to the prev page stored in the "redirect" search param - throw redirect({ - href: data.redirectUrl || '/', - }) - } - - // Create the user - const user = await prismaClient.user.create({ - data: { - email: data.email, - password, - }, - }) - - // Store the user's email in the session - const session = await getAppSession() - session.userEmail = user.email - await session.save() - - // Redirect to the prev page stored in the "redirect" search param - throw redirect({ - href: data.redirectUrl || '/', - }) - }) - -export const Route = createFileRoute('/signup')({ - component: SignupComp, -}) - -function SignupComp() { - const signupMutation = useMutation({ - fn: useServerFn(signupFn), - }) - - return ( - { - const formData = new FormData(e.target as HTMLFormElement) - - signupMutation.mutate({ - data: { - email: formData.get('email') as string, - password: formData.get('password') as string, - }, - }) - }} - afterSubmit={ - signupMutation.data?.error ? ( - <> -
{signupMutation.data.message}
- - ) : null - } - /> - ) -} diff --git a/examples/react/start-basic-auth/src/styles/app.css b/examples/react/start-basic-auth/src/styles/app.css deleted file mode 100644 index 37c1f5a6e2..0000000000 --- a/examples/react/start-basic-auth/src/styles/app.css +++ /dev/null @@ -1,30 +0,0 @@ -@import 'tailwindcss' source('../'); - -@layer base { - *, - ::after, - ::before, - ::backdrop, - ::file-selector-button { - border-color: var(--color-gray-200, currentcolor); - } -} - -@layer base { - html { - color-scheme: light dark; - } - - * { - @apply border-gray-200 dark:border-gray-800; - } - - html, - body { - @apply text-gray-900 bg-gray-50 dark:bg-gray-950 dark:text-gray-200; - } - - .using-mouse * { - outline: none !important; - } -} diff --git a/examples/react/start-basic-auth/src/utils/posts.ts b/examples/react/start-basic-auth/src/utils/posts.ts deleted file mode 100644 index a7e0e99cfa..0000000000 --- a/examples/react/start-basic-auth/src/utils/posts.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { notFound } from '@tanstack/react-router' -import { createServerFn } from '@tanstack/react-start' -import axios from 'redaxios' - -export type PostType = { - id: string - title: string - body: string -} - -export const fetchPost = createServerFn({ method: 'GET' }) - .validator((postId: string) => postId) - .handler(async ({ data }) => { - console.info(`Fetching post with id ${data}...`) - const post = await axios - .get(`https://jsonplaceholder.typicode.com/posts/${data}`) - .then((r) => r.data) - .catch((err) => { - console.error(err) - if (err.status === 404) { - throw notFound() - } - throw err - }) - - return post - }) - -export const fetchPosts = createServerFn({ method: 'GET' }).handler( - async () => { - console.info('Fetching posts...') - await new Promise((r) => setTimeout(r, 1000)) - return axios - .get>('https://jsonplaceholder.typicode.com/posts') - .then((r) => r.data.slice(0, 10)) - }, -) diff --git a/examples/react/start-basic-auth/src/utils/prisma.ts b/examples/react/start-basic-auth/src/utils/prisma.ts deleted file mode 100644 index d08622b30b..0000000000 --- a/examples/react/start-basic-auth/src/utils/prisma.ts +++ /dev/null @@ -1,20 +0,0 @@ -import crypto from 'node:crypto' -import { PrismaLibSql } from '@prisma/adapter-libsql' -import { PrismaClient } from '../prisma-generated/client' - -const adapter = new PrismaLibSql({ - url: process.env.DATABASE_URL || 'file:./prisma/dev.db', -}) -export const prismaClient = new PrismaClient({ adapter }) - -export function hashPassword(password: string) { - return new Promise((resolve, reject) => { - crypto.pbkdf2(password, 'salt', 100000, 64, 'sha256', (err, derivedKey) => { - if (err) { - reject(err) - } else { - resolve(derivedKey.toString('hex')) - } - }) - }) -} diff --git a/examples/react/start-basic-auth/src/utils/session.ts b/examples/react/start-basic-auth/src/utils/session.ts deleted file mode 100644 index 7df7bc4da2..0000000000 --- a/examples/react/start-basic-auth/src/utils/session.ts +++ /dev/null @@ -1,29 +0,0 @@ -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 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-auth/tsconfig.json b/examples/react/start-basic-auth/tsconfig.json deleted file mode 100644 index cef9369516..0000000000 --- a/examples/react/start-basic-auth/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "include": ["**/*.ts", "**/*.tsx"], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "react-jsx", - "module": "ESNext", - "moduleResolution": "Bundler", - "lib": ["DOM", "DOM.Iterable", "ES2022"], - "isolatedModules": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "target": "ES2022", - "allowJs": true, - "forceConsistentCasingInFileNames": true, - "paths": { - "~/*": ["./src/*"] - }, - "noEmit": true - } -} diff --git a/examples/react/start-basic-auth/vite.config.ts b/examples/react/start-basic-auth/vite.config.ts deleted file mode 100644 index ed6799764a..0000000000 --- a/examples/react/start-basic-auth/vite.config.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { tanstackStart } from '@tanstack/react-start/plugin/vite' -import { defineConfig } from 'vite' -import viteReact from '@vitejs/plugin-react' -import tailwindcss from '@tailwindcss/vite' - -export default defineConfig({ - server: { - port: 3000, - }, - resolve: { - tsconfigPaths: true, - }, - plugins: [tailwindcss(), tanstackStart(), viteReact()], -}) diff --git a/examples/react/start-basic-authjs/.devcontainer/devcontainer.json b/examples/react/start-basic-authjs/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/start-basic-authjs/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/start-basic-authjs/.env.example b/examples/react/start-basic-authjs/.env.example deleted file mode 100644 index 062e707907..0000000000 --- a/examples/react/start-basic-authjs/.env.example +++ /dev/null @@ -1,11 +0,0 @@ -# Auth.js Configuration -AUTH_SECRET=your-secret-key-here-min-32-chars-long - -# Auth.js URL (must include the auth path) -AUTH_URL=http://localhost:10000/api/auth - -# Auth0 Configuration (https://manage.auth0.com) -# Auth.js auto-reads these env vars for the Auth0 provider -AUTH_AUTH0_ID=your-auth0-client-id -AUTH_AUTH0_SECRET=your-auth0-client-secret -AUTH_AUTH0_ISSUER=https://your-tenant.auth0.com diff --git a/examples/react/start-basic-authjs/.gitignore b/examples/react/start-basic-authjs/.gitignore deleted file mode 100644 index dc87421f7d..0000000000 --- a/examples/react/start-basic-authjs/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -node_modules -dist -.env -*.local -.DS_Store -.tanstack \ No newline at end of file diff --git a/examples/react/start-basic-authjs/README.md b/examples/react/start-basic-authjs/README.md index 4a908d8069..4560cf8bd5 100644 --- a/examples/react/start-basic-authjs/README.md +++ b/examples/react/start-basic-authjs/README.md @@ -1,51 +1,17 @@ -# TanStack Start - Auth.js Example +# Deprecated: TanStack Start React Example (`start-basic-authjs`) -A TanStack Start example demonstrating authentication with Auth.js (NextAuth.js). +This example is retained for compatibility and historical reference. -- [TanStack Router Docs](https://tanstack.com/router) -- [Auth.js Documentation](https://authjs.dev/) +For new projects, use: -## Start a new project based on this example +- [TanStack Builder](https://tanstack.com/builder) +- `npx @tanstack/cli create` -To start a new project based on this example, run: +For topic-specific setup, use the Start guides: -```sh -npx gitpick TanStack/router/tree/main/examples/react/start-basic-authjs start-basic-authjs -``` +- [Start React Quick Start](https://tanstack.com/router/latest/docs/framework/react/start/quick-start) +- [Start React Guides](https://tanstack.com/router/latest/docs/framework/react/start/guide/routing) -## Setup +Canonical issue reproduction baseline: -This example requires environment variables for Auth.js configuration. Copy the `.env.example` file to `.env` and fill in your authentication provider credentials: - -```sh -cp .env.example .env -``` - -Edit `.env` and add your authentication provider credentials. - -## Getting Started - -From your terminal: - -```sh -pnpm install -pnpm dev -``` - -This starts your app in development mode, rebuilding assets on file changes. - -## Build - -To build the app for production: - -```sh -pnpm build -``` - -## Authentication Configuration - -This example demonstrates how to integrate Auth.js with TanStack Start. Check the source code for examples of: - -- Configuring authentication providers -- Protecting routes with authentication -- Accessing session data in server functions +- [React `start-basic`](https://github.com/TanStack/router/tree/main/examples/react/start-basic) diff --git a/examples/react/start-basic-authjs/package.json b/examples/react/start-basic-authjs/package.json deleted file mode 100644 index e9fa789ea6..0000000000 --- a/examples/react/start-basic-authjs/package.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "name": "tanstack-router-react-example-basic-authjs", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "vite dev", - "build": "vite build", - "preview": "vite preview", - "start": "pnpx srvx --prod -s ../client dist/server/server.js" - }, - "dependencies": { - "@auth/core": "^0.41.1", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "start-authjs": "^1.0.0", - "tailwind-merge": "^3.6.0" - }, - "devDependencies": { - "@tailwindcss/vite": "^4.2.2", - "@types/node": "^22.5.4", - "@types/react": "^19.0.8", - "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" - } -} diff --git a/examples/react/start-basic-authjs/src/components/DefaultCatchBoundary.tsx b/examples/react/start-basic-authjs/src/components/DefaultCatchBoundary.tsx deleted file mode 100644 index 4a22649ed4..0000000000 --- a/examples/react/start-basic-authjs/src/components/DefaultCatchBoundary.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { - ErrorComponent, - Link, - useLocation, - useRouter, -} from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' - -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - - console.error('DefaultCatchBoundary Error:', error) - - return ( -
- -
- - {isRoot ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) -} diff --git a/examples/react/start-basic-authjs/src/components/NotFound.tsx b/examples/react/start-basic-authjs/src/components/NotFound.tsx deleted file mode 100644 index fd4e75befe..0000000000 --- a/examples/react/start-basic-authjs/src/components/NotFound.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { Link } from '@tanstack/react-router' - -export function NotFound({ children }: { children?: any }) { - return ( -
-
- {children ||

The page you are looking for does not exist.

} -
-

- - - Start Over - -

-
- ) -} diff --git a/examples/react/start-basic-authjs/src/routeTree.gen.ts b/examples/react/start-basic-authjs/src/routeTree.gen.ts deleted file mode 100644 index 4abcbc8048..0000000000 --- a/examples/react/start-basic-authjs/src/routeTree.gen.ts +++ /dev/null @@ -1,122 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as LoginRouteImport } from './routes/login' -import { Route as ProtectedRouteImport } from './routes/protected' -import { Route as ApiAuthSplatRouteImport } from './routes/api/auth/$' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', - getParentRoute: () => rootRouteImport, -} as any) -const ProtectedRoute = ProtectedRouteImport.update({ - id: '/protected', - path: '/protected', - getParentRoute: () => rootRouteImport, -} as any) -const ApiAuthSplatRoute = ApiAuthSplatRouteImport.update({ - id: '/api/auth/$', - path: '/api/auth/$', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/login': typeof LoginRoute - '/protected': typeof ProtectedRoute - '/api/auth/$': typeof ApiAuthSplatRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/login': typeof LoginRoute - '/protected': typeof ProtectedRoute - '/api/auth/$': typeof ApiAuthSplatRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/login': typeof LoginRoute - '/protected': typeof ProtectedRoute - '/api/auth/$': typeof ApiAuthSplatRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/login' | '/protected' | '/api/auth/$' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/login' | '/protected' | '/api/auth/$' - id: '__root__' | '/' | '/login' | '/protected' | '/api/auth/$' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - LoginRoute: typeof LoginRoute - ProtectedRoute: typeof ProtectedRoute - ApiAuthSplatRoute: typeof ApiAuthSplatRoute -} - -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 - } - '/protected': { - id: '/protected' - path: '/protected' - fullPath: '/protected' - preLoaderRoute: typeof ProtectedRouteImport - parentRoute: typeof rootRouteImport - } - '/api/auth/$': { - id: '/api/auth/$' - path: '/api/auth/$' - fullPath: '/api/auth/$' - preLoaderRoute: typeof ApiAuthSplatRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - LoginRoute: LoginRoute, - ProtectedRoute: ProtectedRoute, - ApiAuthSplatRoute: ApiAuthSplatRoute, -} -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/examples/react/start-basic-authjs/src/router.tsx b/examples/react/start-basic-authjs/src/router.tsx deleted file mode 100644 index f380f73be7..0000000000 --- a/examples/react/start-basic-authjs/src/router.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' -import { DefaultCatchBoundary } from './components/DefaultCatchBoundary' -import { NotFound } from './components/NotFound' - -export function getRouter() { - const router = createRouter({ - routeTree, - defaultPreload: 'intent', - defaultErrorComponent: DefaultCatchBoundary, - defaultNotFoundComponent: () => , - scrollRestoration: true, - }) - return router -} diff --git a/examples/react/start-basic-authjs/src/routes/__root.tsx b/examples/react/start-basic-authjs/src/routes/__root.tsx deleted file mode 100644 index af2c24ab57..0000000000 --- a/examples/react/start-basic-authjs/src/routes/__root.tsx +++ /dev/null @@ -1,117 +0,0 @@ -/// -import type { ReactNode } from 'react' -import type { AuthSession } from 'start-authjs' -import { - HeadContent, - Link, - Outlet, - Scripts, - createRootRouteWithContext, -} from '@tanstack/react-router' -import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' -import { createServerFn } from '@tanstack/react-start' -import { getRequest } from '@tanstack/react-start/server' -import { getSession } from 'start-authjs' -import { authConfig } from '~/utils/auth' -import appCss from '~/styles/app.css?url' - -interface RouterContext { - session: AuthSession | null -} - -const fetchSession = createServerFn({ method: 'GET' }).handler(async () => { - const request = getRequest() - const session = await getSession(request, authConfig) - return session -}) - -export const Route = createRootRouteWithContext()({ - beforeLoad: async () => { - const session = await fetchSession() - return { - session, - } - }, - head: () => ({ - meta: [ - { - charSet: 'utf-8', - }, - { - name: 'viewport', - content: 'width=device-width, initial-scale=1', - }, - { - title: 'TanStack Start Auth Example', - }, - ], - links: [{ rel: 'stylesheet', href: appCss }], - }), - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - ) -} - -function RootDocument({ children }: { children: ReactNode }) { - return ( - - - - - - -
{children}
- - - - - ) -} - -function NavBar() { - const routeContext = Route.useRouteContext() - - return ( -
- ) -} diff --git a/examples/react/start-basic-authjs/src/routes/api/auth/$.ts b/examples/react/start-basic-authjs/src/routes/api/auth/$.ts deleted file mode 100644 index 3e59239db5..0000000000 --- a/examples/react/start-basic-authjs/src/routes/api/auth/$.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { StartAuthJS } from 'start-authjs' -import { authConfig } from '~/utils/auth' - -/** - * Auth.js API route handler - * Handles all auth routes: /api/auth/* - */ -const { GET, POST } = StartAuthJS(authConfig) - -export const Route = createFileRoute('/api/auth/$')({ - server: { - handlers: { - GET: ({ request }) => GET({ request, response: new Response() }), - POST: ({ request }) => POST({ request, response: new Response() }), - }, - }, -}) diff --git a/examples/react/start-basic-authjs/src/routes/index.tsx b/examples/react/start-basic-authjs/src/routes/index.tsx deleted file mode 100644 index 5723b0f030..0000000000 --- a/examples/react/start-basic-authjs/src/routes/index.tsx +++ /dev/null @@ -1,50 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: Home, -}) - -function Home() { - const { session } = Route.useRouteContext() - const user = session?.user - - return ( -
-

- TanStack Start Auth.js Example -

-

- This example demonstrates auth.js integration with TanStack Start using - Auth0 OAuth. -

- -
-

Auth Status

- - {session ? ( -
-

Authenticated

- {user?.image && ( - Avatar - )} -

- Name: {user?.name ?? 'N/A'} -

-

- Email: {user?.email ?? 'N/A'} -

-
- ) : ( -

- You are not signed in. Click "Sign In" in the navigation bar to - authenticate with Auth0. -

- )} -
-
- ) -} diff --git a/examples/react/start-basic-authjs/src/routes/login.tsx b/examples/react/start-basic-authjs/src/routes/login.tsx deleted file mode 100644 index 008f62d511..0000000000 --- a/examples/react/start-basic-authjs/src/routes/login.tsx +++ /dev/null @@ -1,48 +0,0 @@ -import { useState, useEffect, Suspense } from 'react' -import { createFileRoute, redirect } from '@tanstack/react-router' - -export const Route = createFileRoute('/login')({ - beforeLoad: ({ context }) => { - // Redirect if already authenticated - if (context.session) { - throw redirect({ to: '/' }) - } - }, - component: Login, -}) - -function Login() { - const [csrfToken, setCsrfToken] = useState('') - - useEffect(() => { - fetch('/api/auth/csrf') - .then((res) => res.json()) - .then((data) => setCsrfToken(data.csrfToken)) - }, []) - - return ( -
-

Sign In

- -
-
- - - -
- -

- You'll be redirected to Auth0 to complete the sign-in process. -

-
-
- ) -} diff --git a/examples/react/start-basic-authjs/src/routes/protected.tsx b/examples/react/start-basic-authjs/src/routes/protected.tsx deleted file mode 100644 index a5b960582a..0000000000 --- a/examples/react/start-basic-authjs/src/routes/protected.tsx +++ /dev/null @@ -1,55 +0,0 @@ -import { createFileRoute, redirect } from '@tanstack/react-router' - -export const Route = createFileRoute('/protected')({ - beforeLoad: ({ context }) => { - if (!context.session) { - throw redirect({ to: '/login' }) - } - }, - component: Protected, -}) - -function Protected() { - const { session } = Route.useRouteContext() - const user = session?.user - - return ( -
-

Protected Page

-

- This page is only accessible to authenticated users. -

- -
-

- Welcome, {user?.name ?? 'User'}! -

- - {user && ( -
-

- Email: {user?.email ?? 'N/A'} -

- {user?.image && ( -
- Avatar: - User avatar -
- )} -
- )} -
- -
-

Session Data (Debug)

-
-          {JSON.stringify(session, null, 2)}
-        
-
-
- ) -} diff --git a/examples/react/start-basic-authjs/src/styles/app.css b/examples/react/start-basic-authjs/src/styles/app.css deleted file mode 100644 index 23fa2415ca..0000000000 --- a/examples/react/start-basic-authjs/src/styles/app.css +++ /dev/null @@ -1 +0,0 @@ -@import 'tailwindcss' source('../'); diff --git a/examples/react/start-basic-authjs/src/utils/auth.ts b/examples/react/start-basic-authjs/src/utils/auth.ts deleted file mode 100644 index 8d5c0b1baf..0000000000 --- a/examples/react/start-basic-authjs/src/utils/auth.ts +++ /dev/null @@ -1,50 +0,0 @@ -import Auth0 from '@auth/core/providers/auth0' -import { setCookie } from '@tanstack/react-start/server' -import type { Profile } from '@auth/core/types' -import type { StartAuthJSConfig } from 'start-authjs' - -declare module '@auth/core/types' { - export interface Session { - user: { - name: string - email: string - sub: string - email_verified: boolean - } & Profile - account: { - access_token: string - } - expires: Date - } -} - -/** - * Auth.js configuration for TanStack Start with Auth0 - */ -export const authConfig: StartAuthJSConfig = { - // basePath is derived from AUTH_URL env var - secret: process.env.AUTH_SECRET, - providers: [ - Auth0({ - // Auth.js auto-reads AUTH_AUTH0_ID, AUTH_AUTH0_SECRET, AUTH_AUTH0_ISSUER from env - authorization: { - params: { - scope: 'email email_verified openid profile', - prompt: 'login', - }, - }, - async profile(profile, tokens) { - await setCookie( - 'auth0Token', - encodeURIComponent(tokens.access_token ?? ''), - ) - await setCookie( - 'auth0User', - encodeURIComponent(JSON.stringify(profile)), - ) - - return profile - }, - }), - ], -} diff --git a/examples/react/start-basic-authjs/tsconfig.json b/examples/react/start-basic-authjs/tsconfig.json deleted file mode 100644 index ff21ac7cfa..0000000000 --- a/examples/react/start-basic-authjs/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2022", - "lib": ["ES2022", "DOM", "DOM.Iterable"], - "module": "ESNext", - "skipLibCheck": true, - "moduleResolution": "bundler", - "allowImportingTsExtensions": true, - "resolveJsonModule": true, - "isolatedModules": true, - "noEmit": true, - "jsx": "react-jsx", - "strict": true, - "noUnusedLocals": true, - "noUnusedParameters": true, - "noFallthroughCasesInSwitch": true, - "allowSyntheticDefaultImports": true, - "paths": { - "~/*": ["./src/*"] - } - }, - "include": ["src", "env.d.ts", "vite.config.ts"] -} diff --git a/examples/react/start-basic-authjs/vite.config.ts b/examples/react/start-basic-authjs/vite.config.ts deleted file mode 100644 index 90f81aedf7..0000000000 --- a/examples/react/start-basic-authjs/vite.config.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { tanstackStart } from '@tanstack/react-start/plugin/vite' -import { defineConfig } from 'vite' -import viteReact from '@vitejs/plugin-react' -import tailwindcss from '@tailwindcss/vite' - -export default defineConfig({ - server: { - port: 10000, - strictPort: true, - }, - resolve: { - tsconfigPaths: true, - }, - plugins: [tailwindcss(), tanstackStart(), viteReact()], -}) diff --git a/examples/react/start-basic-cloudflare/.devcontainer/devcontainer.json b/examples/react/start-basic-cloudflare/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/start-basic-cloudflare/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/start-basic-cloudflare/.gitignore b/examples/react/start-basic-cloudflare/.gitignore deleted file mode 100644 index 32f79ff6cd..0000000000 --- a/examples/react/start-basic-cloudflare/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -node_modules -.DS_Store -.cache -.env -dist -.wrangler diff --git a/examples/react/start-basic-cloudflare/.prettierignore b/examples/react/start-basic-cloudflare/.prettierignore deleted file mode 100644 index f36f42b7c8..0000000000 --- a/examples/react/start-basic-cloudflare/.prettierignore +++ /dev/null @@ -1,4 +0,0 @@ -**/public -pnpm-lock.yaml -routeTree.gen.ts -worker-configuration.d.ts diff --git a/examples/react/start-basic-cloudflare/.vscode/settings.json b/examples/react/start-basic-cloudflare/.vscode/settings.json deleted file mode 100644 index 00b5278e58..0000000000 --- a/examples/react/start-basic-cloudflare/.vscode/settings.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "files.watcherExclude": { - "**/routeTree.gen.ts": true - }, - "search.exclude": { - "**/routeTree.gen.ts": true - }, - "files.readonlyInclude": { - "**/routeTree.gen.ts": true - } -} diff --git a/examples/react/start-basic-cloudflare/README.md b/examples/react/start-basic-cloudflare/README.md index 711b60f2d4..ad91c8de50 100644 --- a/examples/react/start-basic-cloudflare/README.md +++ b/examples/react/start-basic-cloudflare/README.md @@ -1,68 +1,17 @@ -# TanStack Start - Cloudflare Example +# Deprecated: TanStack Start React Example (`start-basic-cloudflare`) -A TanStack Start example demonstrating deployment to Cloudflare Workers. +This example is retained for compatibility and historical reference. -- [TanStack Router Docs](https://tanstack.com/router) -- [Cloudflare Workers Documentation](https://developers.cloudflare.com/workers/) +For new projects, use: -## Start a new project based on this example +- [TanStack Builder](https://tanstack.com/builder) +- `npx @tanstack/cli create` -To start a new project based on this example, run: +For topic-specific setup, use the Start guides: -```sh -npx gitpick TanStack/router/tree/main/examples/react/start-basic-cloudflare start-basic-cloudflare -``` +- [Start React Quick Start](https://tanstack.com/router/latest/docs/framework/react/start/quick-start) +- [Start React Hosting Guide](https://tanstack.com/router/latest/docs/framework/react/start/guide/hosting) -## Getting Started +Canonical issue reproduction baseline: -From your terminal: - -```sh -pnpm install -pnpm dev -``` - -This starts your app in development mode, rebuilding assets on file changes. - -## Build - -To build the app for production: - -```sh -pnpm build -``` - -## Preview - -To preview the production build locally: - -```sh -pnpm preview -``` - -## Deploy to Cloudflare - -To deploy your app to Cloudflare Workers: - -```sh -pnpm run deploy -``` - -## Accessing Cloudflare Bindings - -You can access Cloudflare bindings in server functions by using importable `env`: - -```ts -import { env } from 'cloudflare:workers' -``` - -See `src/routes/index.tsx` for an example. - -## Cloudflare Configuration - -This example includes: - -- Wrangler configuration for Cloudflare Workers -- Type generation for Cloudflare bindings -- Server-side rendering on the edge -- Access to Cloudflare platform features (KV, D1, R2, etc.) +- [React `start-basic`](https://github.com/TanStack/router/tree/main/examples/react/start-basic) diff --git a/examples/react/start-basic-cloudflare/package.json b/examples/react/start-basic-cloudflare/package.json deleted file mode 100644 index 2108922446..0000000000 --- a/examples/react/start-basic-cloudflare/package.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "tanstack-start-example-basic-cloudflare", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "vite dev", - "build": "vite build && tsc --noEmit", - "preview": "vite preview", - "deploy": "npm run build && wrangler deploy", - "cf-typegen": "wrangler types", - "postinstall": "WRANGLER_LOG=warn npm run --silent cf-typegen" - }, - "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", - "react": "^19.0.0", - "react-dom": "^19.0.0" - }, - "devDependencies": { - "@cloudflare/vite-plugin": "^1.29.0", - "@tailwindcss/vite": "^4.2.2", - "@types/node": "^22.5.4", - "@types/react": "^19.0.8", - "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "wrangler": "^4.74.0" - } -} diff --git a/examples/react/start-basic-cloudflare/public/android-chrome-192x192.png b/examples/react/start-basic-cloudflare/public/android-chrome-192x192.png deleted file mode 100644 index 09c8324f8c..0000000000 Binary files a/examples/react/start-basic-cloudflare/public/android-chrome-192x192.png and /dev/null differ diff --git a/examples/react/start-basic-cloudflare/public/android-chrome-512x512.png b/examples/react/start-basic-cloudflare/public/android-chrome-512x512.png deleted file mode 100644 index 11d626ea3d..0000000000 Binary files a/examples/react/start-basic-cloudflare/public/android-chrome-512x512.png and /dev/null differ diff --git a/examples/react/start-basic-cloudflare/public/apple-touch-icon.png b/examples/react/start-basic-cloudflare/public/apple-touch-icon.png deleted file mode 100644 index 5a9423cc02..0000000000 Binary files a/examples/react/start-basic-cloudflare/public/apple-touch-icon.png and /dev/null differ diff --git a/examples/react/start-basic-cloudflare/public/favicon-16x16.png b/examples/react/start-basic-cloudflare/public/favicon-16x16.png deleted file mode 100644 index e3389b0044..0000000000 Binary files a/examples/react/start-basic-cloudflare/public/favicon-16x16.png and /dev/null differ diff --git a/examples/react/start-basic-cloudflare/public/favicon-32x32.png b/examples/react/start-basic-cloudflare/public/favicon-32x32.png deleted file mode 100644 index 900c77d444..0000000000 Binary files a/examples/react/start-basic-cloudflare/public/favicon-32x32.png and /dev/null differ diff --git a/examples/react/start-basic-cloudflare/public/favicon.ico b/examples/react/start-basic-cloudflare/public/favicon.ico deleted file mode 100644 index 1a1751676f..0000000000 Binary files a/examples/react/start-basic-cloudflare/public/favicon.ico and /dev/null differ diff --git a/examples/react/start-basic-cloudflare/public/favicon.png b/examples/react/start-basic-cloudflare/public/favicon.png deleted file mode 100644 index 1e77bc0609..0000000000 Binary files a/examples/react/start-basic-cloudflare/public/favicon.png and /dev/null differ diff --git a/examples/react/start-basic-cloudflare/public/site.webmanifest b/examples/react/start-basic-cloudflare/public/site.webmanifest deleted file mode 100644 index fa99de77db..0000000000 --- a/examples/react/start-basic-cloudflare/public/site.webmanifest +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "", - "short_name": "", - "icons": [ - { - "src": "/android-chrome-192x192.png", - "sizes": "192x192", - "type": "image/png" - }, - { - "src": "/android-chrome-512x512.png", - "sizes": "512x512", - "type": "image/png" - } - ], - "theme_color": "#ffffff", - "background_color": "#ffffff", - "display": "standalone" -} diff --git a/examples/react/start-basic-cloudflare/src/components/DefaultCatchBoundary.tsx b/examples/react/start-basic-cloudflare/src/components/DefaultCatchBoundary.tsx deleted file mode 100644 index 4a22649ed4..0000000000 --- a/examples/react/start-basic-cloudflare/src/components/DefaultCatchBoundary.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { - ErrorComponent, - Link, - useLocation, - useRouter, -} from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' - -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - - console.error('DefaultCatchBoundary Error:', error) - - return ( -
- -
- - {isRoot ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) -} diff --git a/examples/react/start-basic-cloudflare/src/components/NotFound.tsx b/examples/react/start-basic-cloudflare/src/components/NotFound.tsx deleted file mode 100644 index fd4e75befe..0000000000 --- a/examples/react/start-basic-cloudflare/src/components/NotFound.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { Link } from '@tanstack/react-router' - -export function NotFound({ children }: { children?: any }) { - return ( -
-
- {children ||

The page you are looking for does not exist.

} -
-

- - - Start Over - -

-
- ) -} diff --git a/examples/react/start-basic-cloudflare/src/components/PostError.tsx b/examples/react/start-basic-cloudflare/src/components/PostError.tsx deleted file mode 100644 index 271f2d1de1..0000000000 --- a/examples/react/start-basic-cloudflare/src/components/PostError.tsx +++ /dev/null @@ -1,6 +0,0 @@ -import { ErrorComponent } from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' - -export function PostErrorComponent({ error }: ErrorComponentProps) { - return -} diff --git a/examples/react/start-basic-cloudflare/src/components/UserError.tsx b/examples/react/start-basic-cloudflare/src/components/UserError.tsx deleted file mode 100644 index af5d0c6f16..0000000000 --- a/examples/react/start-basic-cloudflare/src/components/UserError.tsx +++ /dev/null @@ -1,6 +0,0 @@ -import { ErrorComponent } from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' - -export function UserErrorComponent({ error }: ErrorComponentProps) { - return -} diff --git a/examples/react/start-basic-cloudflare/src/routeTree.gen.ts b/examples/react/start-basic-cloudflare/src/routeTree.gen.ts deleted file mode 100644 index 57b849492d..0000000000 --- a/examples/react/start-basic-cloudflare/src/routeTree.gen.ts +++ /dev/null @@ -1,447 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' -import { Route as CustomScriptDotjsRouteImport } from './routes/customScript[.]js' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as RedirectRouteImport } from './routes/redirect' -import { Route as UsersRouteImport } from './routes/users' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as ApiUsersRouteImport } from './routes/api/users' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' -import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', - getParentRoute: () => rootRouteImport, -} as any) -const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ - id: '/customScript.js', - path: '/customScript.js', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', - getParentRoute: () => rootRouteImport, -} as any) -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, - } as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', - getParentRoute: () => rootRouteImport, -} as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, -} as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, -} as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) -const PathlessLayoutNestedLayoutRouteBRoute = - PathlessLayoutNestedLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) -const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => ApiUsersRoute, -} as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/customScript.js': typeof CustomScriptDotjsRoute - '/deferred': typeof DeferredRoute - '/posts': typeof PostsRouteWithChildren - '/redirect': typeof RedirectRoute - '/users': typeof UsersRouteWithChildren - '/api/users': typeof ApiUsersRouteWithChildren - '/posts/$postId': typeof PostsPostIdRoute - '/users/$userId': typeof UsersUserIdRoute - '/posts/': typeof PostsIndexRoute - '/users/': typeof UsersIndexRoute - '/route-a': typeof PathlessLayoutNestedLayoutRouteARoute - '/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute - '/api/users/$userId': typeof ApiUsersUserIdRoute - '/posts/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/customScript.js': typeof CustomScriptDotjsRoute - '/deferred': typeof DeferredRoute - '/redirect': typeof RedirectRoute - '/api/users': typeof ApiUsersRouteWithChildren - '/posts/$postId': typeof PostsPostIdRoute - '/users/$userId': typeof UsersUserIdRoute - '/posts': typeof PostsIndexRoute - '/users': typeof UsersIndexRoute - '/route-a': typeof PathlessLayoutNestedLayoutRouteARoute - '/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute - '/api/users/$userId': typeof ApiUsersUserIdRoute - '/posts/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/_pathlessLayout': typeof PathlessLayoutRouteWithChildren - '/customScript.js': typeof CustomScriptDotjsRoute - '/deferred': typeof DeferredRoute - '/posts': typeof PostsRouteWithChildren - '/redirect': typeof RedirectRoute - '/users': typeof UsersRouteWithChildren - '/_pathlessLayout/_nested-layout': typeof PathlessLayoutNestedLayoutRouteWithChildren - '/api/users': typeof ApiUsersRouteWithChildren - '/posts/$postId': typeof PostsPostIdRoute - '/users/$userId': typeof UsersUserIdRoute - '/posts/': typeof PostsIndexRoute - '/users/': typeof UsersIndexRoute - '/_pathlessLayout/_nested-layout/route-a': typeof PathlessLayoutNestedLayoutRouteARoute - '/_pathlessLayout/_nested-layout/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute - '/api/users/$userId': typeof ApiUsersUserIdRoute - '/posts_/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/customScript.js' - | '/deferred' - | '/posts' - | '/redirect' - | '/users' - | '/api/users' - | '/posts/$postId' - | '/users/$userId' - | '/posts/' - | '/users/' - | '/route-a' - | '/route-b' - | '/api/users/$userId' - | '/posts/$postId/deep' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/customScript.js' - | '/deferred' - | '/redirect' - | '/api/users' - | '/posts/$postId' - | '/users/$userId' - | '/posts' - | '/users' - | '/route-a' - | '/route-b' - | '/api/users/$userId' - | '/posts/$postId/deep' - id: - | '__root__' - | '/' - | '/_pathlessLayout' - | '/customScript.js' - | '/deferred' - | '/posts' - | '/redirect' - | '/users' - | '/_pathlessLayout/_nested-layout' - | '/api/users' - | '/posts/$postId' - | '/users/$userId' - | '/posts/' - | '/users/' - | '/_pathlessLayout/_nested-layout/route-a' - | '/_pathlessLayout/_nested-layout/route-b' - | '/api/users/$userId' - | '/posts_/$postId/deep' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - PathlessLayoutRoute: typeof PathlessLayoutRouteWithChildren - CustomScriptDotjsRoute: typeof CustomScriptDotjsRoute - DeferredRoute: typeof DeferredRoute - PostsRoute: typeof PostsRouteWithChildren - RedirectRoute: typeof RedirectRoute - UsersRoute: typeof UsersRouteWithChildren - ApiUsersRoute: typeof ApiUsersRouteWithChildren - PostsPostIdDeepRoute: typeof PostsPostIdDeepRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout': { - id: '/_pathlessLayout' - path: '' - fullPath: '/' - preLoaderRoute: typeof PathlessLayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/customScript.js': { - id: '/customScript.js' - path: '/customScript.js' - fullPath: '/customScript.js' - preLoaderRoute: typeof CustomScriptDotjsRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport - parentRoute: typeof rootRouteImport - } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute - } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport - parentRoute: typeof rootRouteImport - } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute - } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute - } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } - '/_pathlessLayout/_nested-layout/route-b': { - id: '/_pathlessLayout/_nested-layout/route-b' - path: '/route-b' - fullPath: '/route-b' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } - '/api/users/$userId': { - id: '/api/users/$userId' - path: '/$userId' - fullPath: '/api/users/$userId' - preLoaderRoute: typeof ApiUsersUserIdRouteImport - parentRoute: typeof ApiUsersRoute - } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -interface PathlessLayoutNestedLayoutRouteChildren { - PathlessLayoutNestedLayoutRouteARoute: typeof PathlessLayoutNestedLayoutRouteARoute - PathlessLayoutNestedLayoutRouteBRoute: typeof PathlessLayoutNestedLayoutRouteBRoute -} - -const PathlessLayoutNestedLayoutRouteChildren: PathlessLayoutNestedLayoutRouteChildren = - { - PathlessLayoutNestedLayoutRouteARoute: - PathlessLayoutNestedLayoutRouteARoute, - PathlessLayoutNestedLayoutRouteBRoute: - PathlessLayoutNestedLayoutRouteBRoute, - } - -const PathlessLayoutNestedLayoutRouteWithChildren = - PathlessLayoutNestedLayoutRoute._addFileChildren( - PathlessLayoutNestedLayoutRouteChildren, - ) - -interface PathlessLayoutRouteChildren { - PathlessLayoutNestedLayoutRoute: typeof PathlessLayoutNestedLayoutRouteWithChildren -} - -const PathlessLayoutRouteChildren: PathlessLayoutRouteChildren = { - PathlessLayoutNestedLayoutRoute: PathlessLayoutNestedLayoutRouteWithChildren, -} - -const PathlessLayoutRouteWithChildren = PathlessLayoutRoute._addFileChildren( - PathlessLayoutRouteChildren, -) - -interface PostsRouteChildren { - PostsPostIdRoute: typeof PostsPostIdRoute - PostsIndexRoute: typeof PostsIndexRoute -} - -const PostsRouteChildren: PostsRouteChildren = { - PostsPostIdRoute: PostsPostIdRoute, - PostsIndexRoute: PostsIndexRoute, -} - -const PostsRouteWithChildren = PostsRoute._addFileChildren(PostsRouteChildren) - -interface UsersRouteChildren { - UsersUserIdRoute: typeof UsersUserIdRoute - UsersIndexRoute: typeof UsersIndexRoute -} - -const UsersRouteChildren: UsersRouteChildren = { - UsersUserIdRoute: UsersUserIdRoute, - UsersIndexRoute: UsersIndexRoute, -} - -const UsersRouteWithChildren = UsersRoute._addFileChildren(UsersRouteChildren) - -interface ApiUsersRouteChildren { - ApiUsersUserIdRoute: typeof ApiUsersUserIdRoute -} - -const ApiUsersRouteChildren: ApiUsersRouteChildren = { - ApiUsersUserIdRoute: ApiUsersUserIdRoute, -} - -const ApiUsersRouteWithChildren = ApiUsersRoute._addFileChildren( - ApiUsersRouteChildren, -) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - PathlessLayoutRoute: PathlessLayoutRouteWithChildren, - CustomScriptDotjsRoute: CustomScriptDotjsRoute, - DeferredRoute: DeferredRoute, - PostsRoute: PostsRouteWithChildren, - RedirectRoute: RedirectRoute, - UsersRoute: UsersRouteWithChildren, - ApiUsersRoute: ApiUsersRouteWithChildren, - PostsPostIdDeepRoute: PostsPostIdDeepRoute, -} -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/examples/react/start-basic-cloudflare/src/router.tsx b/examples/react/start-basic-cloudflare/src/router.tsx deleted file mode 100644 index 1a1d8822d2..0000000000 --- a/examples/react/start-basic-cloudflare/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' -import { DefaultCatchBoundary } from './components/DefaultCatchBoundary' -import { NotFound } from './components/NotFound' - -export function getRouter() { - const router = createRouter({ - routeTree, - defaultPreload: 'intent', - defaultErrorComponent: DefaultCatchBoundary, - defaultNotFoundComponent: () => , - scrollRestoration: true, - }) - - return router -} diff --git a/examples/react/start-basic-cloudflare/src/routes/__root.tsx b/examples/react/start-basic-cloudflare/src/routes/__root.tsx deleted file mode 100644 index 346409e9d9..0000000000 --- a/examples/react/start-basic-cloudflare/src/routes/__root.tsx +++ /dev/null @@ -1,131 +0,0 @@ -/// -import { - HeadContent, - Link, - Scripts, - createRootRoute, -} from '@tanstack/react-router' -import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' -import * as React from 'react' -import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary' -import { NotFound } from '~/components/NotFound' -import appCss from '~/styles/app.css?url' -import { seo } from '~/utils/seo' - -export const Route = createRootRoute({ - head: () => ({ - meta: [ - { - charSet: 'utf-8', - }, - { - name: 'viewport', - content: 'width=device-width, initial-scale=1', - }, - ...seo({ - title: - 'TanStack Start | Type-Safe, Client-First, Full-Stack React Framework', - description: `TanStack Start is a type-safe, client-first, full-stack React framework. `, - }), - ], - links: [ - { rel: 'stylesheet', href: appCss }, - { - rel: 'apple-touch-icon', - sizes: '180x180', - href: '/apple-touch-icon.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '32x32', - href: '/favicon-32x32.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '16x16', - href: '/favicon-16x16.png', - }, - { rel: 'manifest', href: '/site.webmanifest', color: '#fffff' }, - { rel: 'icon', href: '/favicon.ico' }, - ], - scripts: [ - { - src: '/customScript.js', - type: 'text/javascript', - }, - ], - }), - errorComponent: DefaultCatchBoundary, - notFoundComponent: () => , - shellComponent: RootDocument, -}) - -function RootDocument({ children }: { children: React.ReactNode }) { - return ( - - - - - -
- - Home - {' '} - - Posts - {' '} - - Users - {' '} - - Pathless Layout - {' '} - - Deferred - {' '} - - This Route Does Not Exist - -
-
- {children} - - - - - ) -} diff --git a/examples/react/start-basic-cloudflare/src/routes/_pathlessLayout.tsx b/examples/react/start-basic-cloudflare/src/routes/_pathlessLayout.tsx deleted file mode 100644 index c3b12442b8..0000000000 --- a/examples/react/start-basic-cloudflare/src/routes/_pathlessLayout.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_pathlessLayout')({ - component: LayoutComponent, -}) - -function LayoutComponent() { - return ( -
-
I'm a layout
-
- -
-
- ) -} diff --git a/examples/react/start-basic-cloudflare/src/routes/_pathlessLayout/_nested-layout.tsx b/examples/react/start-basic-cloudflare/src/routes/_pathlessLayout/_nested-layout.tsx deleted file mode 100644 index 9a48b73a46..0000000000 --- a/examples/react/start-basic-cloudflare/src/routes/_pathlessLayout/_nested-layout.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_pathlessLayout/_nested-layout')({ - component: LayoutComponent, -}) - -function LayoutComponent() { - return ( -
-
I'm a nested layout
-
- - Go to route A - - - Go to route B - -
-
- -
-
- ) -} diff --git a/examples/react/start-basic-cloudflare/src/routes/_pathlessLayout/_nested-layout/route-a.tsx b/examples/react/start-basic-cloudflare/src/routes/_pathlessLayout/_nested-layout/route-a.tsx deleted file mode 100644 index 426a8fe486..0000000000 --- a/examples/react/start-basic-cloudflare/src/routes/_pathlessLayout/_nested-layout/route-a.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_pathlessLayout/_nested-layout/route-a')( - { - component: LayoutAComponent, - }, -) - -function LayoutAComponent() { - return
I'm A!
-} diff --git a/examples/react/start-basic-cloudflare/src/routes/_pathlessLayout/_nested-layout/route-b.tsx b/examples/react/start-basic-cloudflare/src/routes/_pathlessLayout/_nested-layout/route-b.tsx deleted file mode 100644 index 20facf2daf..0000000000 --- a/examples/react/start-basic-cloudflare/src/routes/_pathlessLayout/_nested-layout/route-b.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_pathlessLayout/_nested-layout/route-b')( - { - component: LayoutBComponent, - }, -) - -function LayoutBComponent() { - return
I'm B!
-} diff --git a/examples/react/start-basic-cloudflare/src/routes/api/users.$userId.ts b/examples/react/start-basic-cloudflare/src/routes/api/users.$userId.ts deleted file mode 100644 index ee34d7a189..0000000000 --- a/examples/react/start-basic-cloudflare/src/routes/api/users.$userId.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import type { User } from '~/utils/users' - -export const Route = createFileRoute('/api/users/$userId')({ - server: { - handlers: { - GET: async ({ params, request }) => { - console.info(`Fetching users by id=${params.userId}... @`, request.url) - try { - const res = await fetch( - 'https://jsonplaceholder.typicode.com/users/' + params.userId, - ) - if (!res.ok) { - throw new Error('Failed to fetch user') - } - - const user = (await res.json()) as User - - return Response.json({ - id: user.id, - name: user.name, - email: user.email, - }) - } catch (e) { - console.error(e) - return Response.json({ error: 'User not found' }, { status: 404 }) - } - }, - }, - }, -}) diff --git a/examples/react/start-basic-cloudflare/src/routes/api/users.ts b/examples/react/start-basic-cloudflare/src/routes/api/users.ts deleted file mode 100644 index 4cecd01852..0000000000 --- a/examples/react/start-basic-cloudflare/src/routes/api/users.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { getRequestHeaders } from '@tanstack/react-start/server' -import { createMiddleware } from '@tanstack/react-start' -import type { User } from '~/utils/users' - -const userLoggerMiddleware = createMiddleware().server(async ({ next }) => { - console.info('In: /users') - console.info('Request Headers:', getRequestHeaders()) - const result = await next() - result.response.headers.set('x-users', 'true') - console.info('Out: /users') - return result -}) - -const testParentMiddleware = createMiddleware().server(async ({ next }) => { - console.info('In: testParentMiddleware') - const result = await next() - result.response.headers.set('x-test-parent', 'true') - console.info('Out: testParentMiddleware') - return result -}) - -const testMiddleware = createMiddleware() - .middleware([testParentMiddleware]) - .server(async ({ next }) => { - console.info('In: testMiddleware') - const result = await next() - result.response.headers.set('x-test', 'true') - - // if (Math.random() > 0.5) { - // throw new Response(null, { - // status: 302, - // headers: { Location: 'https://www.google.com' }, - // }) - // } - - console.info('Out: testMiddleware') - return result - }) - -export const Route = createFileRoute('/api/users')({ - server: { - middleware: [testMiddleware, userLoggerMiddleware], - handlers: { - GET: async ({ request }) => { - console.info('GET /api/users @', request.url) - console.info('Fetching users... @', request.url) - const res = await fetch('https://jsonplaceholder.typicode.com/users') - if (!res.ok) { - throw new Error('Failed to fetch users') - } - - const data = (await res.json()) as Array - - const list = data.slice(0, 10) - - return Response.json( - list.map((u) => ({ id: u.id, name: u.name, email: u.email })), - ) - }, - }, - }, -}) diff --git a/examples/react/start-basic-cloudflare/src/routes/customScript[.]js.ts b/examples/react/start-basic-cloudflare/src/routes/customScript[.]js.ts deleted file mode 100644 index 811471ac15..0000000000 --- a/examples/react/start-basic-cloudflare/src/routes/customScript[.]js.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/customScript.js')({ - server: { - handlers: { - GET: () => { - return new Response('console.log("Hello from customScript.js!")', { - headers: { - 'Content-Type': 'application/javascript', - }, - }) - }, - }, - }, -}) diff --git a/examples/react/start-basic-cloudflare/src/routes/deferred.tsx b/examples/react/start-basic-cloudflare/src/routes/deferred.tsx deleted file mode 100644 index f3e09d1d4e..0000000000 --- a/examples/react/start-basic-cloudflare/src/routes/deferred.tsx +++ /dev/null @@ -1,62 +0,0 @@ -import { Await, createFileRoute } from '@tanstack/react-router' -import { createServerFn } from '@tanstack/react-start' -import { Suspense, useState } from 'react' - -const personServerFn = createServerFn({ method: 'GET' }) - .validator((d: string) => d) - .handler(({ data: name }) => { - return { name, randomNumber: Math.floor(Math.random() * 100) } - }) - -const slowServerFn = createServerFn({ method: 'GET' }) - .validator((d: string) => d) - .handler(async ({ data: name }) => { - await new Promise((r) => setTimeout(r, 1000)) - return { name, randomNumber: Math.floor(Math.random() * 100) } - }) - -export const Route = createFileRoute('/deferred')({ - loader: async () => { - return { - deferredStuff: new Promise((r) => - setTimeout(() => r('Hello deferred!'), 2000), - ), - deferredPerson: slowServerFn({ data: 'Tanner Linsley' }), - person: await personServerFn({ data: 'John Doe' }), - } - }, - component: Deferred, -}) - -function Deferred() { - const [count, setCount] = useState(0) - const { deferredStuff, deferredPerson, person } = Route.useLoaderData() - - return ( -
-
- {person.name} - {person.randomNumber} -
- Loading person...
}> - ( -
- {data.name} - {data.randomNumber} -
- )} - /> - - Loading stuff...
}> -

{data}

} - /> - -
Count: {count}
-
- -
-
- ) -} diff --git a/examples/react/start-basic-cloudflare/src/routes/index.tsx b/examples/react/start-basic-cloudflare/src/routes/index.tsx deleted file mode 100644 index 44c66fe668..0000000000 --- a/examples/react/start-basic-cloudflare/src/routes/index.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { createServerFn } from '@tanstack/react-start' -import { env } from 'cloudflare:workers' - -export const Route = createFileRoute('/')({ - loader: () => getData(), - component: Home, -}) - -const getData = createServerFn().handler(() => { - return { - message: `Running in ${navigator.userAgent}`, - myVar: env.MY_VAR, - } -}) - -function Home() { - const data = Route.useLoaderData() - - return ( -
-

Welcome Home!!!

-

{data.message}

-

{data.myVar}

-
- ) -} diff --git a/examples/react/start-basic-cloudflare/src/routes/posts.$postId.tsx b/examples/react/start-basic-cloudflare/src/routes/posts.$postId.tsx deleted file mode 100644 index 7e111fa20d..0000000000 --- a/examples/react/start-basic-cloudflare/src/routes/posts.$postId.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import { Link, createFileRoute } from '@tanstack/react-router' -import { fetchPost } from '~/utils/posts' -import { NotFound } from '~/components/NotFound' -import { PostErrorComponent } from '~/components/PostError' - -export const Route = createFileRoute('/posts/$postId')({ - loader: ({ params: { postId } }) => fetchPost({ data: postId }), - errorComponent: PostErrorComponent, - component: PostComponent, - notFoundComponent: () => { - return Post not found - }, -}) - -function PostComponent() { - const post = Route.useLoaderData() - - return ( -
-

{post.title}

-
{post.body}
- - Deep View - -
- ) -} diff --git a/examples/react/start-basic-cloudflare/src/routes/posts.index.tsx b/examples/react/start-basic-cloudflare/src/routes/posts.index.tsx deleted file mode 100644 index 5b5f08f95b..0000000000 --- a/examples/react/start-basic-cloudflare/src/routes/posts.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/posts/')({ - component: PostsIndexComponent, -}) - -function PostsIndexComponent() { - return
Select a post.
-} diff --git a/examples/react/start-basic-cloudflare/src/routes/posts.tsx b/examples/react/start-basic-cloudflare/src/routes/posts.tsx deleted file mode 100644 index 095b2e248f..0000000000 --- a/examples/react/start-basic-cloudflare/src/routes/posts.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' -import { fetchPosts } from '~/utils/posts' - -export const Route = createFileRoute('/posts')({ - loader: async () => fetchPosts(), - component: PostsComponent, -}) - -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[...posts, { id: 'i-do-not-exist', title: 'Non-existent Post' }].map( - (post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - }, - )} -
-
- -
- ) -} diff --git a/examples/react/start-basic-cloudflare/src/routes/posts_.$postId.deep.tsx b/examples/react/start-basic-cloudflare/src/routes/posts_.$postId.deep.tsx deleted file mode 100644 index 48d317ec30..0000000000 --- a/examples/react/start-basic-cloudflare/src/routes/posts_.$postId.deep.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { Link, createFileRoute } from '@tanstack/react-router' -import { fetchPost } from '~/utils/posts' -import { PostErrorComponent } from '~/components/PostError' - -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.title}

-
{post.body}
-
- ) -} diff --git a/examples/react/start-basic-cloudflare/src/routes/redirect.tsx b/examples/react/start-basic-cloudflare/src/routes/redirect.tsx deleted file mode 100644 index ea34b6e420..0000000000 --- a/examples/react/start-basic-cloudflare/src/routes/redirect.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute, redirect } from '@tanstack/react-router' - -export const Route = createFileRoute('/redirect')({ - beforeLoad: () => { - throw redirect({ - to: '/posts', - }) - }, -}) diff --git a/examples/react/start-basic-cloudflare/src/routes/users.$userId.tsx b/examples/react/start-basic-cloudflare/src/routes/users.$userId.tsx deleted file mode 100644 index fe22eb86c3..0000000000 --- a/examples/react/start-basic-cloudflare/src/routes/users.$userId.tsx +++ /dev/null @@ -1,45 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { NotFound } from '../components/NotFound' -import { UserErrorComponent } from '../components/UserError' -import type { User } from '~/utils/users' - -export const Route = createFileRoute('/users/$userId')({ - loader: async ({ params: { userId } }) => { - try { - const res = await fetch('/api/users/' + userId) - if (!res.ok) { - throw new Error('Unexpected status code') - } - - const data = await res.json() - - return data as User - } catch { - throw new Error('Failed to fetch user') - } - }, - errorComponent: UserErrorComponent, - component: UserComponent, - notFoundComponent: () => { - return User not found - }, -}) - -function UserComponent() { - const user = Route.useLoaderData() - - return ( -
- ) -} diff --git a/examples/react/start-basic-cloudflare/src/routes/users.index.tsx b/examples/react/start-basic-cloudflare/src/routes/users.index.tsx deleted file mode 100644 index 27d136987e..0000000000 --- a/examples/react/start-basic-cloudflare/src/routes/users.index.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/users/')({ - component: UsersIndexComponent, -}) - -function UsersIndexComponent() { - return ( -
- Select a user or{' '} - - view as JSON - -
- ) -} diff --git a/examples/react/start-basic-cloudflare/src/routes/users.tsx b/examples/react/start-basic-cloudflare/src/routes/users.tsx deleted file mode 100644 index 55b22b6e40..0000000000 --- a/examples/react/start-basic-cloudflare/src/routes/users.tsx +++ /dev/null @@ -1,49 +0,0 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' -import type { User } from '~/utils/users' - -export const Route = createFileRoute('/users')({ - loader: async () => { - const res = await fetch('/api/users') - - if (!res.ok) { - throw new Error('Unexpected status code') - } - - const data = await res.json() - - return data as Array - }, - component: UsersComponent, -}) - -function UsersComponent() { - const users = Route.useLoaderData() - - return ( -
-
    - {[ - ...users, - { id: 'i-do-not-exist', name: 'Non-existent User', email: '' }, - ].map((user) => { - return ( -
  • - -
    {user.name}
    - -
  • - ) - })} -
-
- -
- ) -} diff --git a/examples/react/start-basic-cloudflare/src/styles/app.css b/examples/react/start-basic-cloudflare/src/styles/app.css deleted file mode 100644 index 37c1f5a6e2..0000000000 --- a/examples/react/start-basic-cloudflare/src/styles/app.css +++ /dev/null @@ -1,30 +0,0 @@ -@import 'tailwindcss' source('../'); - -@layer base { - *, - ::after, - ::before, - ::backdrop, - ::file-selector-button { - border-color: var(--color-gray-200, currentcolor); - } -} - -@layer base { - html { - color-scheme: light dark; - } - - * { - @apply border-gray-200 dark:border-gray-800; - } - - html, - body { - @apply text-gray-900 bg-gray-50 dark:bg-gray-950 dark:text-gray-200; - } - - .using-mouse * { - outline: none !important; - } -} diff --git a/examples/react/start-basic-cloudflare/src/utils/loggingMiddleware.tsx b/examples/react/start-basic-cloudflare/src/utils/loggingMiddleware.tsx deleted file mode 100644 index 3ea9a06439..0000000000 --- a/examples/react/start-basic-cloudflare/src/utils/loggingMiddleware.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import { createMiddleware } from '@tanstack/react-start' - -const preLogMiddleware = createMiddleware({ type: 'function' }) - .client(async (ctx) => { - const clientTime = new Date() - - return ctx.next({ - context: { - clientTime, - }, - sendContext: { - clientTime, - }, - }) - }) - .server(async (ctx) => { - const serverTime = new Date() - - return ctx.next({ - sendContext: { - serverTime, - durationToServer: - serverTime.getTime() - ctx.context.clientTime.getTime(), - }, - }) - }) - -export const logMiddleware = createMiddleware({ type: 'function' }) - .middleware([preLogMiddleware]) - .client(async (ctx) => { - const res = await ctx.next() - - const now = new Date() - console.log('Client Req/Res:', { - duration: now.getTime() - res.context.clientTime.getTime(), - durationToServer: res.context.durationToServer, - durationFromServer: now.getTime() - res.context.serverTime.getTime(), - }) - - return res - }) diff --git a/examples/react/start-basic-cloudflare/src/utils/posts.tsx b/examples/react/start-basic-cloudflare/src/utils/posts.tsx deleted file mode 100644 index ea7dd0a721..0000000000 --- a/examples/react/start-basic-cloudflare/src/utils/posts.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import { notFound } from '@tanstack/react-router' -import { createServerFn } from '@tanstack/react-start' - -export type PostType = { - id: number - title: string - body: string -} - -export const fetchPost = createServerFn({ method: 'POST' }) - .validator((d: string) => d) - .handler(async ({ data }) => { - console.info(`Fetching post with id ${data}...`) - const res = await fetch( - `https://jsonplaceholder.typicode.com/posts/${data}`, - ) - if (!res.ok) { - if (res.status === 404) { - throw notFound() - } - - throw new Error('Failed to fetch post') - } - - const post = await res.json() - - return post as PostType - }) - -export const fetchPosts = createServerFn().handler(async () => { - console.info('Fetching posts...') - const res = await fetch('https://jsonplaceholder.typicode.com/posts') - if (!res.ok) { - throw new Error('Failed to fetch posts') - } - - const posts = await res.json() - - return (posts as Array).slice(0, 10) -}) diff --git a/examples/react/start-basic-cloudflare/src/utils/seo.ts b/examples/react/start-basic-cloudflare/src/utils/seo.ts deleted file mode 100644 index d18ad84b74..0000000000 --- a/examples/react/start-basic-cloudflare/src/utils/seo.ts +++ /dev/null @@ -1,33 +0,0 @@ -export const seo = ({ - title, - description, - keywords, - image, -}: { - title: string - description?: string - image?: string - keywords?: string -}) => { - const tags = [ - { title }, - { name: 'description', content: description }, - { name: 'keywords', content: keywords }, - { name: 'twitter:title', content: title }, - { name: 'twitter:description', content: description }, - { name: 'twitter:creator', content: '@tannerlinsley' }, - { name: 'twitter:site', content: '@tannerlinsley' }, - { name: 'og:type', content: 'website' }, - { name: 'og:title', content: title }, - { name: 'og:description', content: description }, - ...(image - ? [ - { name: 'twitter:image', content: image }, - { name: 'twitter:card', content: 'summary_large_image' }, - { name: 'og:image', content: image }, - ] - : []), - ] - - return tags -} diff --git a/examples/react/start-basic-cloudflare/src/utils/users.tsx b/examples/react/start-basic-cloudflare/src/utils/users.tsx deleted file mode 100644 index 7ba645b383..0000000000 --- a/examples/react/start-basic-cloudflare/src/utils/users.tsx +++ /dev/null @@ -1,5 +0,0 @@ -export type User = { - id: number - name: string - email: string -} diff --git a/examples/react/start-basic-cloudflare/tsconfig.json b/examples/react/start-basic-cloudflare/tsconfig.json deleted file mode 100644 index cef9369516..0000000000 --- a/examples/react/start-basic-cloudflare/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "include": ["**/*.ts", "**/*.tsx"], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "react-jsx", - "module": "ESNext", - "moduleResolution": "Bundler", - "lib": ["DOM", "DOM.Iterable", "ES2022"], - "isolatedModules": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "target": "ES2022", - "allowJs": true, - "forceConsistentCasingInFileNames": true, - "paths": { - "~/*": ["./src/*"] - }, - "noEmit": true - } -} diff --git a/examples/react/start-basic-cloudflare/vite.config.ts b/examples/react/start-basic-cloudflare/vite.config.ts deleted file mode 100644 index ad9418ef35..0000000000 --- a/examples/react/start-basic-cloudflare/vite.config.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { defineConfig } from 'vite' -import { cloudflare } from '@cloudflare/vite-plugin' -import { tanstackStart } from '@tanstack/react-start/plugin/vite' -import viteReact from '@vitejs/plugin-react' -import tailwindcss from '@tailwindcss/vite' - -export default defineConfig({ - server: { - port: 3000, - }, - resolve: { - tsconfigPaths: true, - }, - plugins: [ - tailwindcss(), - cloudflare({ viteEnvironment: { name: 'ssr' } }), - tanstackStart(), - viteReact(), - ], -}) diff --git a/examples/react/start-basic-cloudflare/worker-configuration.d.ts b/examples/react/start-basic-cloudflare/worker-configuration.d.ts deleted file mode 100644 index f7a8f16397..0000000000 --- a/examples/react/start-basic-cloudflare/worker-configuration.d.ts +++ /dev/null @@ -1,12071 +0,0 @@ -/* eslint-disable */ -// Generated by Wrangler by running `wrangler types` (hash: b11df627d8b3c51b1bf3230a546b0f20) -// Runtime types generated with workerd@1.20260317.1 2025-09-24 nodejs_compat -declare namespace Cloudflare { - interface Env { - MY_VAR: "Hello from Cloudflare"; - } -} -interface Env extends Cloudflare.Env {} -type StringifyValues> = { - [Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string; -}; -declare namespace NodeJS { - interface ProcessEnv extends StringifyValues> {} -} - -// Begin runtime types -/*! ***************************************************************************** -Copyright (c) Cloudflare. All rights reserved. -Copyright (c) Microsoft Corporation. All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ -/* eslint-disable */ -// noinspection JSUnusedGlobalSymbols -declare var onmessage: never; -/** - * The **`DOMException`** interface represents an abnormal event (called an **exception**) that occurs as a result of calling a method or accessing a property of a web API. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException) - */ -declare class DOMException extends Error { - constructor(message?: string, name?: string); - /** - * The **`message`** read-only property of the a message or description associated with the given error name. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) - */ - readonly message: string; - /** - * The **`name`** read-only property of the one of the strings associated with an error name. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) - */ - readonly name: string; - /** - * The **`code`** read-only property of the DOMException interface returns one of the legacy error code constants, or `0` if none match. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) - */ - readonly code: number; - static readonly INDEX_SIZE_ERR: number; - static readonly DOMSTRING_SIZE_ERR: number; - static readonly HIERARCHY_REQUEST_ERR: number; - static readonly WRONG_DOCUMENT_ERR: number; - static readonly INVALID_CHARACTER_ERR: number; - static readonly NO_DATA_ALLOWED_ERR: number; - static readonly NO_MODIFICATION_ALLOWED_ERR: number; - static readonly NOT_FOUND_ERR: number; - static readonly NOT_SUPPORTED_ERR: number; - static readonly INUSE_ATTRIBUTE_ERR: number; - static readonly INVALID_STATE_ERR: number; - static readonly SYNTAX_ERR: number; - static readonly INVALID_MODIFICATION_ERR: number; - static readonly NAMESPACE_ERR: number; - static readonly INVALID_ACCESS_ERR: number; - static readonly VALIDATION_ERR: number; - static readonly TYPE_MISMATCH_ERR: number; - static readonly SECURITY_ERR: number; - static readonly NETWORK_ERR: number; - static readonly ABORT_ERR: number; - static readonly URL_MISMATCH_ERR: number; - static readonly QUOTA_EXCEEDED_ERR: number; - static readonly TIMEOUT_ERR: number; - static readonly INVALID_NODE_TYPE_ERR: number; - static readonly DATA_CLONE_ERR: number; - get stack(): any; - set stack(value: any); -} -type WorkerGlobalScopeEventMap = { - fetch: FetchEvent; - scheduled: ScheduledEvent; - queue: QueueEvent; - unhandledrejection: PromiseRejectionEvent; - rejectionhandled: PromiseRejectionEvent; -}; -declare abstract class WorkerGlobalScope extends EventTarget { - EventTarget: typeof EventTarget; -} -/* The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). * - * The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) - */ -interface Console { - "assert"(condition?: boolean, ...data: any[]): void; - /** - * The **`console.clear()`** static method clears the console if possible. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) - */ - clear(): void; - /** - * The **`console.count()`** static method logs the number of times that this particular call to `count()` has been called. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) - */ - count(label?: string): void; - /** - * The **`console.countReset()`** static method resets counter used with console/count_static. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) - */ - countReset(label?: string): void; - /** - * The **`console.debug()`** static method outputs a message to the console at the 'debug' log level. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) - */ - debug(...data: any[]): void; - /** - * The **`console.dir()`** static method displays a list of the properties of the specified JavaScript object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) - */ - dir(item?: any, options?: any): void; - /** - * The **`console.dirxml()`** static method displays an interactive tree of the descendant elements of the specified XML/HTML element. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) - */ - dirxml(...data: any[]): void; - /** - * The **`console.error()`** static method outputs a message to the console at the 'error' log level. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) - */ - error(...data: any[]): void; - /** - * The **`console.group()`** static method creates a new inline group in the Web console log, causing any subsequent console messages to be indented by an additional level, until console/groupEnd_static is called. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) - */ - group(...data: any[]): void; - /** - * The **`console.groupCollapsed()`** static method creates a new inline group in the console. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) - */ - groupCollapsed(...data: any[]): void; - /** - * The **`console.groupEnd()`** static method exits the current inline group in the console. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) - */ - groupEnd(): void; - /** - * The **`console.info()`** static method outputs a message to the console at the 'info' log level. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) - */ - info(...data: any[]): void; - /** - * The **`console.log()`** static method outputs a message to the console. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) - */ - log(...data: any[]): void; - /** - * The **`console.table()`** static method displays tabular data as a table. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) - */ - table(tabularData?: any, properties?: string[]): void; - /** - * The **`console.time()`** static method starts a timer you can use to track how long an operation takes. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) - */ - time(label?: string): void; - /** - * The **`console.timeEnd()`** static method stops a timer that was previously started by calling console/time_static. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) - */ - timeEnd(label?: string): void; - /** - * The **`console.timeLog()`** static method logs the current value of a timer that was previously started by calling console/time_static. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) - */ - timeLog(label?: string, ...data: any[]): void; - timeStamp(label?: string): void; - /** - * The **`console.trace()`** static method outputs a stack trace to the console. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) - */ - trace(...data: any[]): void; - /** - * The **`console.warn()`** static method outputs a warning message to the console at the 'warning' log level. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) - */ - warn(...data: any[]): void; -} -declare const console: Console; -type BufferSource = ArrayBufferView | ArrayBuffer; -type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array; -declare namespace WebAssembly { - class CompileError extends Error { - constructor(message?: string); - } - class RuntimeError extends Error { - constructor(message?: string); - } - type ValueType = "anyfunc" | "externref" | "f32" | "f64" | "i32" | "i64" | "v128"; - interface GlobalDescriptor { - value: ValueType; - mutable?: boolean; - } - class Global { - constructor(descriptor: GlobalDescriptor, value?: any); - value: any; - valueOf(): any; - } - type ImportValue = ExportValue | number; - type ModuleImports = Record; - type Imports = Record; - type ExportValue = Function | Global | Memory | Table; - type Exports = Record; - class Instance { - constructor(module: Module, imports?: Imports); - readonly exports: Exports; - } - interface MemoryDescriptor { - initial: number; - maximum?: number; - shared?: boolean; - } - class Memory { - constructor(descriptor: MemoryDescriptor); - readonly buffer: ArrayBuffer; - grow(delta: number): number; - } - type ImportExportKind = "function" | "global" | "memory" | "table"; - interface ModuleExportDescriptor { - kind: ImportExportKind; - name: string; - } - interface ModuleImportDescriptor { - kind: ImportExportKind; - module: string; - name: string; - } - abstract class Module { - static customSections(module: Module, sectionName: string): ArrayBuffer[]; - static exports(module: Module): ModuleExportDescriptor[]; - static imports(module: Module): ModuleImportDescriptor[]; - } - type TableKind = "anyfunc" | "externref"; - interface TableDescriptor { - element: TableKind; - initial: number; - maximum?: number; - } - class Table { - constructor(descriptor: TableDescriptor, value?: any); - readonly length: number; - get(index: number): any; - grow(delta: number, value?: any): number; - set(index: number, value?: any): void; - } - function instantiate(module: Module, imports?: Imports): Promise; - function validate(bytes: BufferSource): boolean; -} -/** - * The **`ServiceWorkerGlobalScope`** interface of the Service Worker API represents the global execution context of a service worker. - * Available only in secure contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) - */ -interface ServiceWorkerGlobalScope extends WorkerGlobalScope { - DOMException: typeof DOMException; - WorkerGlobalScope: typeof WorkerGlobalScope; - btoa(data: string): string; - atob(data: string): string; - setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; - setTimeout(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; - clearTimeout(timeoutId: number | null): void; - setInterval(callback: (...args: any[]) => void, msDelay?: number): number; - setInterval(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; - clearInterval(timeoutId: number | null): void; - queueMicrotask(task: Function): void; - structuredClone(value: T, options?: StructuredSerializeOptions): T; - reportError(error: any): void; - fetch(input: RequestInfo | URL, init?: RequestInit): Promise; - self: ServiceWorkerGlobalScope; - crypto: Crypto; - caches: CacheStorage; - scheduler: Scheduler; - performance: Performance; - Cloudflare: Cloudflare; - readonly origin: string; - Event: typeof Event; - ExtendableEvent: typeof ExtendableEvent; - CustomEvent: typeof CustomEvent; - PromiseRejectionEvent: typeof PromiseRejectionEvent; - FetchEvent: typeof FetchEvent; - TailEvent: typeof TailEvent; - TraceEvent: typeof TailEvent; - ScheduledEvent: typeof ScheduledEvent; - MessageEvent: typeof MessageEvent; - CloseEvent: typeof CloseEvent; - ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; - ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; - ReadableStream: typeof ReadableStream; - WritableStream: typeof WritableStream; - WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; - TransformStream: typeof TransformStream; - ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; - CountQueuingStrategy: typeof CountQueuingStrategy; - ErrorEvent: typeof ErrorEvent; - MessageChannel: typeof MessageChannel; - MessagePort: typeof MessagePort; - EventSource: typeof EventSource; - ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; - ReadableStreamDefaultController: typeof ReadableStreamDefaultController; - ReadableByteStreamController: typeof ReadableByteStreamController; - WritableStreamDefaultController: typeof WritableStreamDefaultController; - TransformStreamDefaultController: typeof TransformStreamDefaultController; - CompressionStream: typeof CompressionStream; - DecompressionStream: typeof DecompressionStream; - TextEncoderStream: typeof TextEncoderStream; - TextDecoderStream: typeof TextDecoderStream; - Headers: typeof Headers; - Body: typeof Body; - Request: typeof Request; - Response: typeof Response; - WebSocket: typeof WebSocket; - WebSocketPair: typeof WebSocketPair; - WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; - AbortController: typeof AbortController; - AbortSignal: typeof AbortSignal; - TextDecoder: typeof TextDecoder; - TextEncoder: typeof TextEncoder; - navigator: Navigator; - Navigator: typeof Navigator; - URL: typeof URL; - URLSearchParams: typeof URLSearchParams; - URLPattern: typeof URLPattern; - Blob: typeof Blob; - File: typeof File; - FormData: typeof FormData; - Crypto: typeof Crypto; - SubtleCrypto: typeof SubtleCrypto; - CryptoKey: typeof CryptoKey; - CacheStorage: typeof CacheStorage; - Cache: typeof Cache; - FixedLengthStream: typeof FixedLengthStream; - IdentityTransformStream: typeof IdentityTransformStream; - HTMLRewriter: typeof HTMLRewriter; -} -declare function addEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void; -declare function removeEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetEventListenerOptions | boolean): void; -/** - * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) - */ -declare function dispatchEvent(event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap]): boolean; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/btoa) */ -declare function btoa(data: string): string; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/atob) */ -declare function atob(data: string): string; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */ -declare function setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */ -declare function setTimeout(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearTimeout) */ -declare function clearTimeout(timeoutId: number | null): void; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */ -declare function setInterval(callback: (...args: any[]) => void, msDelay?: number): number; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */ -declare function setInterval(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearInterval) */ -declare function clearInterval(timeoutId: number | null): void; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/queueMicrotask) */ -declare function queueMicrotask(task: Function): void; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/structuredClone) */ -declare function structuredClone(value: T, options?: StructuredSerializeOptions): T; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/reportError) */ -declare function reportError(error: any): void; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) */ -declare function fetch(input: RequestInfo | URL, init?: RequestInit): Promise; -declare const self: ServiceWorkerGlobalScope; -/** -* The Web Crypto API provides a set of low-level functions for common cryptographic tasks. -* The Workers runtime implements the full surface of this API, but with some differences in -* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) -* compared to those implemented in most browsers. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) -*/ -declare const crypto: Crypto; -/** -* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) -*/ -declare const caches: CacheStorage; -declare const scheduler: Scheduler; -/** -* The Workers runtime supports a subset of the Performance API, used to measure timing and performance, -* as well as timing of subrequests and other operations. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) -*/ -declare const performance: Performance; -declare const Cloudflare: Cloudflare; -declare const origin: string; -declare const navigator: Navigator; -interface TestController { -} -interface ExecutionContext { - waitUntil(promise: Promise): void; - passThroughOnException(): void; - readonly props: Props; -} -type ExportedHandlerFetchHandler = (request: Request>, env: Env, ctx: ExecutionContext) => Response | Promise; -type ExportedHandlerTailHandler = (events: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTraceHandler = (traces: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTailStreamHandler = (event: TailStream.TailEvent, env: Env, ctx: ExecutionContext) => TailStream.TailEventHandlerType | Promise; -type ExportedHandlerScheduledHandler = (controller: ScheduledController, env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerQueueHandler = (batch: MessageBatch, env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTestHandler = (controller: TestController, env: Env, ctx: ExecutionContext) => void | Promise; -interface ExportedHandler { - fetch?: ExportedHandlerFetchHandler; - tail?: ExportedHandlerTailHandler; - trace?: ExportedHandlerTraceHandler; - tailStream?: ExportedHandlerTailStreamHandler; - scheduled?: ExportedHandlerScheduledHandler; - test?: ExportedHandlerTestHandler; - email?: EmailExportedHandler; - queue?: ExportedHandlerQueueHandler; -} -interface StructuredSerializeOptions { - transfer?: any[]; -} -declare abstract class Navigator { - sendBeacon(url: string, body?: BodyInit): boolean; - readonly userAgent: string; - readonly hardwareConcurrency: number; - readonly language: string; - readonly languages: string[]; -} -interface AlarmInvocationInfo { - readonly isRetry: boolean; - readonly retryCount: number; -} -interface Cloudflare { - readonly compatibilityFlags: Record; -} -interface DurableObject { - fetch(request: Request): Response | Promise; - alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; - webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; - webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise; - webSocketError?(ws: WebSocket, error: unknown): void | Promise; -} -type DurableObjectStub = Fetcher & { - readonly id: DurableObjectId; - readonly name?: string; -}; -interface DurableObjectId { - toString(): string; - equals(other: DurableObjectId): boolean; - readonly name?: string; -} -declare abstract class DurableObjectNamespace { - newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId; - idFromName(name: string): DurableObjectId; - idFromString(id: string): DurableObjectId; - get(id: DurableObjectId, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; - getByName(name: string, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; - jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; -} -type DurableObjectJurisdiction = "eu" | "fedramp" | "fedramp-high"; -interface DurableObjectNamespaceNewUniqueIdOptions { - jurisdiction?: DurableObjectJurisdiction; -} -type DurableObjectLocationHint = "wnam" | "enam" | "sam" | "weur" | "eeur" | "apac" | "oc" | "afr" | "me"; -type DurableObjectRoutingMode = "primary-only"; -interface DurableObjectNamespaceGetDurableObjectOptions { - locationHint?: DurableObjectLocationHint; - routingMode?: DurableObjectRoutingMode; -} -interface DurableObjectClass<_T extends Rpc.DurableObjectBranded | undefined = undefined> { -} -interface DurableObjectState { - waitUntil(promise: Promise): void; - readonly props: Props; - readonly id: DurableObjectId; - readonly storage: DurableObjectStorage; - container?: Container; - blockConcurrencyWhile(callback: () => Promise): Promise; - acceptWebSocket(ws: WebSocket, tags?: string[]): void; - getWebSockets(tag?: string): WebSocket[]; - setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; - getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; - getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; - setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; - getHibernatableWebSocketEventTimeout(): number | null; - getTags(ws: WebSocket): string[]; - abort(reason?: string): void; -} -interface DurableObjectTransaction { - get(key: string, options?: DurableObjectGetOptions): Promise; - get(keys: string[], options?: DurableObjectGetOptions): Promise>; - list(options?: DurableObjectListOptions): Promise>; - put(key: string, value: T, options?: DurableObjectPutOptions): Promise; - put(entries: Record, options?: DurableObjectPutOptions): Promise; - delete(key: string, options?: DurableObjectPutOptions): Promise; - delete(keys: string[], options?: DurableObjectPutOptions): Promise; - rollback(): void; - getAlarm(options?: DurableObjectGetAlarmOptions): Promise; - setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; - deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; -} -interface DurableObjectStorage { - get(key: string, options?: DurableObjectGetOptions): Promise; - get(keys: string[], options?: DurableObjectGetOptions): Promise>; - list(options?: DurableObjectListOptions): Promise>; - put(key: string, value: T, options?: DurableObjectPutOptions): Promise; - put(entries: Record, options?: DurableObjectPutOptions): Promise; - delete(key: string, options?: DurableObjectPutOptions): Promise; - delete(keys: string[], options?: DurableObjectPutOptions): Promise; - deleteAll(options?: DurableObjectPutOptions): Promise; - transaction(closure: (txn: DurableObjectTransaction) => Promise): Promise; - getAlarm(options?: DurableObjectGetAlarmOptions): Promise; - setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; - deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; - sync(): Promise; - sql: SqlStorage; - kv: SyncKvStorage; - transactionSync(closure: () => T): T; - getCurrentBookmark(): Promise; - getBookmarkForTime(timestamp: number | Date): Promise; - onNextSessionRestoreBookmark(bookmark: string): Promise; -} -interface DurableObjectListOptions { - start?: string; - startAfter?: string; - end?: string; - prefix?: string; - reverse?: boolean; - limit?: number; - allowConcurrency?: boolean; - noCache?: boolean; -} -interface DurableObjectGetOptions { - allowConcurrency?: boolean; - noCache?: boolean; -} -interface DurableObjectGetAlarmOptions { - allowConcurrency?: boolean; -} -interface DurableObjectPutOptions { - allowConcurrency?: boolean; - allowUnconfirmed?: boolean; - noCache?: boolean; -} -interface DurableObjectSetAlarmOptions { - allowConcurrency?: boolean; - allowUnconfirmed?: boolean; -} -declare class WebSocketRequestResponsePair { - constructor(request: string, response: string); - get request(): string; - get response(): string; -} -interface AnalyticsEngineDataset { - writeDataPoint(event?: AnalyticsEngineDataPoint): void; -} -interface AnalyticsEngineDataPoint { - indexes?: ((ArrayBuffer | string) | null)[]; - doubles?: number[]; - blobs?: ((ArrayBuffer | string) | null)[]; -} -/** - * The **`Event`** interface represents an event which takes place on an `EventTarget`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event) - */ -declare class Event { - constructor(type: string, init?: EventInit); - /** - * The **`type`** read-only property of the Event interface returns a string containing the event's type. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) - */ - get type(): string; - /** - * The **`eventPhase`** read-only property of the being evaluated. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) - */ - get eventPhase(): number; - /** - * The read-only **`composed`** property of the or not the event will propagate across the shadow DOM boundary into the standard DOM. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) - */ - get composed(): boolean; - /** - * The **`bubbles`** read-only property of the Event interface indicates whether the event bubbles up through the DOM tree or not. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) - */ - get bubbles(): boolean; - /** - * The **`cancelable`** read-only property of the Event interface indicates whether the event can be canceled, and therefore prevented as if the event never happened. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) - */ - get cancelable(): boolean; - /** - * The **`defaultPrevented`** read-only property of the Event interface returns a boolean value indicating whether or not the call to Event.preventDefault() canceled the event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) - */ - get defaultPrevented(): boolean; - /** - * The Event property **`returnValue`** indicates whether the default action for this event has been prevented or not. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) - */ - get returnValue(): boolean; - /** - * The **`currentTarget`** read-only property of the Event interface identifies the element to which the event handler has been attached. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) - */ - get currentTarget(): EventTarget | undefined; - /** - * The read-only **`target`** property of the dispatched. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target) - */ - get target(): EventTarget | undefined; - /** - * The deprecated **`Event.srcElement`** is an alias for the Event.target property. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) - */ - get srcElement(): EventTarget | undefined; - /** - * The **`timeStamp`** read-only property of the Event interface returns the time (in milliseconds) at which the event was created. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) - */ - get timeStamp(): number; - /** - * The **`isTrusted`** read-only property of the when the event was generated by the user agent (including via user actions and programmatic methods such as HTMLElement.focus()), and `false` when the event was dispatched via The only exception is the `click` event, which initializes the `isTrusted` property to `false` in user agents. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) - */ - get isTrusted(): boolean; - /** - * The **`cancelBubble`** property of the Event interface is deprecated. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) - */ - get cancelBubble(): boolean; - /** - * The **`cancelBubble`** property of the Event interface is deprecated. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) - */ - set cancelBubble(value: boolean); - /** - * The **`stopImmediatePropagation()`** method of the If several listeners are attached to the same element for the same event type, they are called in the order in which they were added. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) - */ - stopImmediatePropagation(): void; - /** - * The **`preventDefault()`** method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) - */ - preventDefault(): void; - /** - * The **`stopPropagation()`** method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) - */ - stopPropagation(): void; - /** - * The **`composedPath()`** method of the Event interface returns the event's path which is an array of the objects on which listeners will be invoked. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) - */ - composedPath(): EventTarget[]; - static readonly NONE: number; - static readonly CAPTURING_PHASE: number; - static readonly AT_TARGET: number; - static readonly BUBBLING_PHASE: number; -} -interface EventInit { - bubbles?: boolean; - cancelable?: boolean; - composed?: boolean; -} -type EventListener = (event: EventType) => void; -interface EventListenerObject { - handleEvent(event: EventType): void; -} -type EventListenerOrEventListenerObject = EventListener | EventListenerObject; -/** - * The **`EventTarget`** interface is implemented by objects that can receive events and may have listeners for them. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget) - */ -declare class EventTarget = Record> { - constructor(); - /** - * The **`addEventListener()`** method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) - */ - addEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void; - /** - * The **`removeEventListener()`** method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) - */ - removeEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetEventListenerOptions | boolean): void; - /** - * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) - */ - dispatchEvent(event: EventMap[keyof EventMap]): boolean; -} -interface EventTargetEventListenerOptions { - capture?: boolean; -} -interface EventTargetAddEventListenerOptions { - capture?: boolean; - passive?: boolean; - once?: boolean; - signal?: AbortSignal; -} -interface EventTargetHandlerObject { - handleEvent: (event: Event) => any | undefined; -} -/** - * The **`AbortController`** interface represents a controller object that allows you to abort one or more Web requests as and when desired. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController) - */ -declare class AbortController { - constructor(); - /** - * The **`signal`** read-only property of the AbortController interface returns an AbortSignal object instance, which can be used to communicate with/abort an asynchronous operation as desired. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) - */ - get signal(): AbortSignal; - /** - * The **`abort()`** method of the AbortController interface aborts an asynchronous operation before it has completed. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) - */ - abort(reason?: any): void; -} -/** - * The **`AbortSignal`** interface represents a signal object that allows you to communicate with an asynchronous operation (such as a fetch request) and abort it if required via an AbortController object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal) - */ -declare abstract class AbortSignal extends EventTarget { - /** - * The **`AbortSignal.abort()`** static method returns an AbortSignal that is already set as aborted (and which does not trigger an AbortSignal/abort_event event). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) - */ - static abort(reason?: any): AbortSignal; - /** - * The **`AbortSignal.timeout()`** static method returns an AbortSignal that will automatically abort after a specified time. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) - */ - static timeout(delay: number): AbortSignal; - /** - * The **`AbortSignal.any()`** static method takes an iterable of abort signals and returns an AbortSignal. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static) - */ - static any(signals: AbortSignal[]): AbortSignal; - /** - * The **`aborted`** read-only property returns a value that indicates whether the asynchronous operations the signal is communicating with are aborted (`true`) or not (`false`). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) - */ - get aborted(): boolean; - /** - * The **`reason`** read-only property returns a JavaScript value that indicates the abort reason. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) - */ - get reason(): any; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ - get onabort(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ - set onabort(value: any | null); - /** - * The **`throwIfAborted()`** method throws the signal's abort AbortSignal.reason if the signal has been aborted; otherwise it does nothing. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) - */ - throwIfAborted(): void; -} -interface Scheduler { - wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; -} -interface SchedulerWaitOptions { - signal?: AbortSignal; -} -/** - * The **`ExtendableEvent`** interface extends the lifetime of the `install` and `activate` events dispatched on the global scope as part of the service worker lifecycle. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent) - */ -declare abstract class ExtendableEvent extends Event { - /** - * The **`ExtendableEvent.waitUntil()`** method tells the event dispatcher that work is ongoing. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) - */ - waitUntil(promise: Promise): void; -} -/** - * The **`CustomEvent`** interface represents events initialized by an application for any purpose. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent) - */ -declare class CustomEvent extends Event { - constructor(type: string, init?: CustomEventCustomEventInit); - /** - * The read-only **`detail`** property of the CustomEvent interface returns any data passed when initializing the event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) - */ - get detail(): T; -} -interface CustomEventCustomEventInit { - bubbles?: boolean; - cancelable?: boolean; - composed?: boolean; - detail?: any; -} -/** - * The **`Blob`** interface represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a ReadableStream so its methods can be used for processing the data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob) - */ -declare class Blob { - constructor(type?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], options?: BlobOptions); - /** - * The **`size`** read-only property of the Blob interface returns the size of the Blob or File in bytes. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) - */ - get size(): number; - /** - * The **`type`** read-only property of the Blob interface returns the MIME type of the file. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) - */ - get type(): string; - /** - * The **`slice()`** method of the Blob interface creates and returns a new `Blob` object which contains data from a subset of the blob on which it's called. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) - */ - slice(start?: number, end?: number, type?: string): Blob; - /** - * The **`arrayBuffer()`** method of the Blob interface returns a Promise that resolves with the contents of the blob as binary data contained in an ArrayBuffer. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) - */ - arrayBuffer(): Promise; - /** - * The **`bytes()`** method of the Blob interface returns a Promise that resolves with a Uint8Array containing the contents of the blob as an array of bytes. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/bytes) - */ - bytes(): Promise; - /** - * The **`text()`** method of the string containing the contents of the blob, interpreted as UTF-8. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) - */ - text(): Promise; - /** - * The **`stream()`** method of the Blob interface returns a ReadableStream which upon reading returns the data contained within the `Blob`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) - */ - stream(): ReadableStream; -} -interface BlobOptions { - type?: string; -} -/** - * The **`File`** interface provides information about files and allows JavaScript in a web page to access their content. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File) - */ -declare class File extends Blob { - constructor(bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, name: string, options?: FileOptions); - /** - * The **`name`** read-only property of the File interface returns the name of the file represented by a File object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) - */ - get name(): string; - /** - * The **`lastModified`** read-only property of the File interface provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) - */ - get lastModified(): number; -} -interface FileOptions { - type?: string; - lastModified?: number; -} -/** -* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) -*/ -declare abstract class CacheStorage { - /** - * The **`open()`** method of the the Cache object matching the `cacheName`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) - */ - open(cacheName: string): Promise; - readonly default: Cache; -} -/** -* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) -*/ -declare abstract class Cache { - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#delete) */ - delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#match) */ - match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#put) */ - put(request: RequestInfo | URL, response: Response): Promise; -} -interface CacheQueryOptions { - ignoreMethod?: boolean; -} -/** -* The Web Crypto API provides a set of low-level functions for common cryptographic tasks. -* The Workers runtime implements the full surface of this API, but with some differences in -* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) -* compared to those implemented in most browsers. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) -*/ -declare abstract class Crypto { - /** - * The **`Crypto.subtle`** read-only property returns a cryptographic operations. - * Available only in secure contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) - */ - get subtle(): SubtleCrypto; - /** - * The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) - */ - getRandomValues(buffer: T): T; - /** - * The **`randomUUID()`** method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator. - * Available only in secure contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) - */ - randomUUID(): string; - DigestStream: typeof DigestStream; -} -/** - * The **`SubtleCrypto`** interface of the Web Crypto API provides a number of low-level cryptographic functions. - * Available only in secure contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto) - */ -declare abstract class SubtleCrypto { - /** - * The **`encrypt()`** method of the SubtleCrypto interface encrypts data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/encrypt) - */ - encrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, plainText: ArrayBuffer | ArrayBufferView): Promise; - /** - * The **`decrypt()`** method of the SubtleCrypto interface decrypts some encrypted data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt) - */ - decrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, cipherText: ArrayBuffer | ArrayBufferView): Promise; - /** - * The **`sign()`** method of the SubtleCrypto interface generates a digital signature. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/sign) - */ - sign(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, data: ArrayBuffer | ArrayBufferView): Promise; - /** - * The **`verify()`** method of the SubtleCrypto interface verifies a digital signature. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/verify) - */ - verify(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, signature: ArrayBuffer | ArrayBufferView, data: ArrayBuffer | ArrayBufferView): Promise; - /** - * The **`digest()`** method of the SubtleCrypto interface generates a _digest_ of the given data, using the specified hash function. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest) - */ - digest(algorithm: string | SubtleCryptoHashAlgorithm, data: ArrayBuffer | ArrayBufferView): Promise; - /** - * The **`generateKey()`** method of the SubtleCrypto interface is used to generate a new key (for symmetric algorithms) or key pair (for public-key algorithms). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) - */ - generateKey(algorithm: string | SubtleCryptoGenerateKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; - /** - * The **`deriveKey()`** method of the SubtleCrypto interface can be used to derive a secret key from a master key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) - */ - deriveKey(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; - /** - * The **`deriveBits()`** method of the key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits) - */ - deriveBits(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, length?: number | null): Promise; - /** - * The **`importKey()`** method of the SubtleCrypto interface imports a key: that is, it takes as input a key in an external, portable format and gives you a CryptoKey object that you can use in the Web Crypto API. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) - */ - importKey(format: string, keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, algorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; - /** - * The **`exportKey()`** method of the SubtleCrypto interface exports a key: that is, it takes as input a CryptoKey object and gives you the key in an external, portable format. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey) - */ - exportKey(format: string, key: CryptoKey): Promise; - /** - * The **`wrapKey()`** method of the SubtleCrypto interface 'wraps' a key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey) - */ - wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm): Promise; - /** - * The **`unwrapKey()`** method of the SubtleCrypto interface 'unwraps' a key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) - */ - unwrapKey(format: string, wrappedKey: ArrayBuffer | ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; - timingSafeEqual(a: ArrayBuffer | ArrayBufferView, b: ArrayBuffer | ArrayBufferView): boolean; -} -/** - * The **`CryptoKey`** interface of the Web Crypto API represents a cryptographic key obtained from one of the SubtleCrypto methods SubtleCrypto.generateKey, SubtleCrypto.deriveKey, SubtleCrypto.importKey, or SubtleCrypto.unwrapKey. - * Available only in secure contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey) - */ -declare abstract class CryptoKey { - /** - * The read-only **`type`** property of the CryptoKey interface indicates which kind of key is represented by the object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) - */ - readonly type: string; - /** - * The read-only **`extractable`** property of the CryptoKey interface indicates whether or not the key may be extracted using `SubtleCrypto.exportKey()` or `SubtleCrypto.wrapKey()`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) - */ - readonly extractable: boolean; - /** - * The read-only **`algorithm`** property of the CryptoKey interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) - */ - readonly algorithm: CryptoKeyKeyAlgorithm | CryptoKeyAesKeyAlgorithm | CryptoKeyHmacKeyAlgorithm | CryptoKeyRsaKeyAlgorithm | CryptoKeyEllipticKeyAlgorithm | CryptoKeyArbitraryKeyAlgorithm; - /** - * The read-only **`usages`** property of the CryptoKey interface indicates what can be done with the key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) - */ - readonly usages: string[]; -} -interface CryptoKeyPair { - publicKey: CryptoKey; - privateKey: CryptoKey; -} -interface JsonWebKey { - kty: string; - use?: string; - key_ops?: string[]; - alg?: string; - ext?: boolean; - crv?: string; - x?: string; - y?: string; - d?: string; - n?: string; - e?: string; - p?: string; - q?: string; - dp?: string; - dq?: string; - qi?: string; - oth?: RsaOtherPrimesInfo[]; - k?: string; -} -interface RsaOtherPrimesInfo { - r?: string; - d?: string; - t?: string; -} -interface SubtleCryptoDeriveKeyAlgorithm { - name: string; - salt?: (ArrayBuffer | ArrayBufferView); - iterations?: number; - hash?: (string | SubtleCryptoHashAlgorithm); - $public?: CryptoKey; - info?: (ArrayBuffer | ArrayBufferView); -} -interface SubtleCryptoEncryptAlgorithm { - name: string; - iv?: (ArrayBuffer | ArrayBufferView); - additionalData?: (ArrayBuffer | ArrayBufferView); - tagLength?: number; - counter?: (ArrayBuffer | ArrayBufferView); - length?: number; - label?: (ArrayBuffer | ArrayBufferView); -} -interface SubtleCryptoGenerateKeyAlgorithm { - name: string; - hash?: (string | SubtleCryptoHashAlgorithm); - modulusLength?: number; - publicExponent?: (ArrayBuffer | ArrayBufferView); - length?: number; - namedCurve?: string; -} -interface SubtleCryptoHashAlgorithm { - name: string; -} -interface SubtleCryptoImportKeyAlgorithm { - name: string; - hash?: (string | SubtleCryptoHashAlgorithm); - length?: number; - namedCurve?: string; - compressed?: boolean; -} -interface SubtleCryptoSignAlgorithm { - name: string; - hash?: (string | SubtleCryptoHashAlgorithm); - dataLength?: number; - saltLength?: number; -} -interface CryptoKeyKeyAlgorithm { - name: string; -} -interface CryptoKeyAesKeyAlgorithm { - name: string; - length: number; -} -interface CryptoKeyHmacKeyAlgorithm { - name: string; - hash: CryptoKeyKeyAlgorithm; - length: number; -} -interface CryptoKeyRsaKeyAlgorithm { - name: string; - modulusLength: number; - publicExponent: ArrayBuffer | ArrayBufferView; - hash?: CryptoKeyKeyAlgorithm; -} -interface CryptoKeyEllipticKeyAlgorithm { - name: string; - namedCurve: string; -} -interface CryptoKeyArbitraryKeyAlgorithm { - name: string; - hash?: CryptoKeyKeyAlgorithm; - namedCurve?: string; - length?: number; -} -declare class DigestStream extends WritableStream { - constructor(algorithm: string | SubtleCryptoHashAlgorithm); - readonly digest: Promise; - get bytesWritten(): number | bigint; -} -/** - * The **`TextDecoder`** interface represents a decoder for a specific text encoding, such as `UTF-8`, `ISO-8859-2`, `KOI8-R`, `GBK`, etc. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder) - */ -declare class TextDecoder { - constructor(label?: string, options?: TextDecoderConstructorOptions); - /** - * The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) - */ - decode(input?: (ArrayBuffer | ArrayBufferView), options?: TextDecoderDecodeOptions): string; - get encoding(): string; - get fatal(): boolean; - get ignoreBOM(): boolean; -} -/** - * The **`TextEncoder`** interface takes a stream of code points as input and emits a stream of UTF-8 bytes. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder) - */ -declare class TextEncoder { - constructor(); - /** - * The **`TextEncoder.encode()`** method takes a string as input, and returns a Global_Objects/Uint8Array containing the text given in parameters encoded with the specific method for that TextEncoder object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) - */ - encode(input?: string): Uint8Array; - /** - * The **`TextEncoder.encodeInto()`** method takes a string to encode and a destination Uint8Array to put resulting UTF-8 encoded text into, and returns a dictionary object indicating the progress of the encoding. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) - */ - encodeInto(input: string, buffer: Uint8Array): TextEncoderEncodeIntoResult; - get encoding(): string; -} -interface TextDecoderConstructorOptions { - fatal: boolean; - ignoreBOM: boolean; -} -interface TextDecoderDecodeOptions { - stream: boolean; -} -interface TextEncoderEncodeIntoResult { - read: number; - written: number; -} -/** - * The **`ErrorEvent`** interface represents events providing information related to errors in scripts or in files. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent) - */ -declare class ErrorEvent extends Event { - constructor(type: string, init?: ErrorEventErrorEventInit); - /** - * The **`filename`** read-only property of the ErrorEvent interface returns a string containing the name of the script file in which the error occurred. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) - */ - get filename(): string; - /** - * The **`message`** read-only property of the ErrorEvent interface returns a string containing a human-readable error message describing the problem. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) - */ - get message(): string; - /** - * The **`lineno`** read-only property of the ErrorEvent interface returns an integer containing the line number of the script file on which the error occurred. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) - */ - get lineno(): number; - /** - * The **`colno`** read-only property of the ErrorEvent interface returns an integer containing the column number of the script file on which the error occurred. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) - */ - get colno(): number; - /** - * The **`error`** read-only property of the ErrorEvent interface returns a JavaScript value, such as an Error or DOMException, representing the error associated with this event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) - */ - get error(): any; -} -interface ErrorEventErrorEventInit { - message?: string; - filename?: string; - lineno?: number; - colno?: number; - error?: any; -} -/** - * The **`MessageEvent`** interface represents a message received by a target object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent) - */ -declare class MessageEvent extends Event { - constructor(type: string, initializer: MessageEventInit); - /** - * The **`data`** read-only property of the The data sent by the message emitter; this can be any data type, depending on what originated this event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data) - */ - readonly data: any; - /** - * The **`origin`** read-only property of the origin of the message emitter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/origin) - */ - readonly origin: string | null; - /** - * The **`lastEventId`** read-only property of the unique ID for the event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/lastEventId) - */ - readonly lastEventId: string; - /** - * The **`source`** read-only property of the a WindowProxy, MessagePort, or a `MessageEventSource` (which can be a WindowProxy, message emitter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source) - */ - readonly source: MessagePort | null; - /** - * The **`ports`** read-only property of the containing all MessagePort objects sent with the message, in order. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/ports) - */ - readonly ports: MessagePort[]; -} -interface MessageEventInit { - data: ArrayBuffer | string; -} -/** - * The **`PromiseRejectionEvent`** interface represents events which are sent to the global script context when JavaScript Promises are rejected. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent) - */ -declare abstract class PromiseRejectionEvent extends Event { - /** - * The PromiseRejectionEvent interface's **`promise`** read-only property indicates the JavaScript rejected. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) - */ - readonly promise: Promise; - /** - * The PromiseRejectionEvent **`reason`** read-only property is any JavaScript value or Object which provides the reason passed into Promise.reject(). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) - */ - readonly reason: any; -} -/** - * The **`FormData`** interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using the Window/fetch, XMLHttpRequest.send() or navigator.sendBeacon() methods. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData) - */ -declare class FormData { - constructor(); - /** - * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) - */ - append(name: string, value: string | Blob): void; - /** - * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) - */ - append(name: string, value: string): void; - /** - * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) - */ - append(name: string, value: Blob, filename?: string): void; - /** - * The **`delete()`** method of the FormData interface deletes a key and its value(s) from a `FormData` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete) - */ - delete(name: string): void; - /** - * The **`get()`** method of the FormData interface returns the first value associated with a given key from within a `FormData` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get) - */ - get(name: string): (File | string) | null; - /** - * The **`getAll()`** method of the FormData interface returns all the values associated with a given key from within a `FormData` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/getAll) - */ - getAll(name: string): (File | string)[]; - /** - * The **`has()`** method of the FormData interface returns whether a `FormData` object contains a certain key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has) - */ - has(name: string): boolean; - /** - * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) - */ - set(name: string, value: string | Blob): void; - /** - * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) - */ - set(name: string, value: string): void; - /** - * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) - */ - set(name: string, value: Blob, filename?: string): void; - /* Returns an array of key, value pairs for every entry in the list. */ - entries(): IterableIterator<[ - key: string, - value: File | string - ]>; - /* Returns a list of keys in the list. */ - keys(): IterableIterator; - /* Returns a list of values in the list. */ - values(): IterableIterator<(File | string)>; - forEach(callback: (this: This, value: File | string, key: string, parent: FormData) => void, thisArg?: This): void; - [Symbol.iterator](): IterableIterator<[ - key: string, - value: File | string - ]>; -} -interface ContentOptions { - html?: boolean; -} -declare class HTMLRewriter { - constructor(); - on(selector: string, handlers: HTMLRewriterElementContentHandlers): HTMLRewriter; - onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; - transform(response: Response): Response; -} -interface HTMLRewriterElementContentHandlers { - element?(element: Element): void | Promise; - comments?(comment: Comment): void | Promise; - text?(element: Text): void | Promise; -} -interface HTMLRewriterDocumentContentHandlers { - doctype?(doctype: Doctype): void | Promise; - comments?(comment: Comment): void | Promise; - text?(text: Text): void | Promise; - end?(end: DocumentEnd): void | Promise; -} -interface Doctype { - readonly name: string | null; - readonly publicId: string | null; - readonly systemId: string | null; -} -interface Element { - tagName: string; - readonly attributes: IterableIterator; - readonly removed: boolean; - readonly namespaceURI: string; - getAttribute(name: string): string | null; - hasAttribute(name: string): boolean; - setAttribute(name: string, value: string): Element; - removeAttribute(name: string): Element; - before(content: string | ReadableStream | Response, options?: ContentOptions): Element; - after(content: string | ReadableStream | Response, options?: ContentOptions): Element; - prepend(content: string | ReadableStream | Response, options?: ContentOptions): Element; - append(content: string | ReadableStream | Response, options?: ContentOptions): Element; - replace(content: string | ReadableStream | Response, options?: ContentOptions): Element; - remove(): Element; - removeAndKeepContent(): Element; - setInnerContent(content: string | ReadableStream | Response, options?: ContentOptions): Element; - onEndTag(handler: (tag: EndTag) => void | Promise): void; -} -interface EndTag { - name: string; - before(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; - after(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; - remove(): EndTag; -} -interface Comment { - text: string; - readonly removed: boolean; - before(content: string, options?: ContentOptions): Comment; - after(content: string, options?: ContentOptions): Comment; - replace(content: string, options?: ContentOptions): Comment; - remove(): Comment; -} -interface Text { - readonly text: string; - readonly lastInTextNode: boolean; - readonly removed: boolean; - before(content: string | ReadableStream | Response, options?: ContentOptions): Text; - after(content: string | ReadableStream | Response, options?: ContentOptions): Text; - replace(content: string | ReadableStream | Response, options?: ContentOptions): Text; - remove(): Text; -} -interface DocumentEnd { - append(content: string, options?: ContentOptions): DocumentEnd; -} -/** - * This is the event type for `fetch` events dispatched on the ServiceWorkerGlobalScope. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent) - */ -declare abstract class FetchEvent extends ExtendableEvent { - /** - * The **`request`** read-only property of the the event handler. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) - */ - readonly request: Request; - /** - * The **`respondWith()`** method of allows you to provide a promise for a Response yourself. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) - */ - respondWith(promise: Response | Promise): void; - passThroughOnException(): void; -} -type HeadersInit = Headers | Iterable> | Record; -/** - * The **`Headers`** interface of the Fetch API allows you to perform various actions on HTTP request and response headers. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers) - */ -declare class Headers { - constructor(init?: HeadersInit); - /** - * The **`get()`** method of the Headers interface returns a byte string of all the values of a header within a `Headers` object with a given name. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get) - */ - get(name: string): string | null; - getAll(name: string): string[]; - /** - * The **`getSetCookie()`** method of the Headers interface returns an array containing the values of all Set-Cookie headers associated with a response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie) - */ - getSetCookie(): string[]; - /** - * The **`has()`** method of the Headers interface returns a boolean stating whether a `Headers` object contains a certain header. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has) - */ - has(name: string): boolean; - /** - * The **`set()`** method of the Headers interface sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set) - */ - set(name: string, value: string): void; - /** - * The **`append()`** method of the Headers interface appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append) - */ - append(name: string, value: string): void; - /** - * The **`delete()`** method of the Headers interface deletes a header from the current `Headers` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete) - */ - delete(name: string): void; - forEach(callback: (this: This, value: string, key: string, parent: Headers) => void, thisArg?: This): void; - /* Returns an iterator allowing to go through all key/value pairs contained in this object. */ - entries(): IterableIterator<[ - key: string, - value: string - ]>; - /* Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ - keys(): IterableIterator; - /* Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ - values(): IterableIterator; - [Symbol.iterator](): IterableIterator<[ - key: string, - value: string - ]>; -} -type BodyInit = ReadableStream | string | ArrayBuffer | ArrayBufferView | Blob | URLSearchParams | FormData; -declare abstract class Body { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) */ - get body(): ReadableStream | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */ - get bodyUsed(): boolean; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */ - arrayBuffer(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) */ - bytes(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/text) */ - text(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */ - json(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData) */ - formData(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */ - blob(): Promise; -} -/** - * The **`Response`** interface of the Fetch API represents the response to a request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) - */ -declare var Response: { - prototype: Response; - new (body?: BodyInit | null, init?: ResponseInit): Response; - error(): Response; - redirect(url: string, status?: number): Response; - json(any: any, maybeInit?: (ResponseInit | Response)): Response; -}; -/** - * The **`Response`** interface of the Fetch API represents the response to a request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) - */ -interface Response extends Body { - /** - * The **`clone()`** method of the Response interface creates a clone of a response object, identical in every way, but stored in a different variable. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) - */ - clone(): Response; - /** - * The **`status`** read-only property of the Response interface contains the HTTP status codes of the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) - */ - status: number; - /** - * The **`statusText`** read-only property of the Response interface contains the status message corresponding to the HTTP status code in Response.status. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) - */ - statusText: string; - /** - * The **`headers`** read-only property of the with the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) - */ - headers: Headers; - /** - * The **`ok`** read-only property of the Response interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) - */ - ok: boolean; - /** - * The **`redirected`** read-only property of the Response interface indicates whether or not the response is the result of a request you made which was redirected. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) - */ - redirected: boolean; - /** - * The **`url`** read-only property of the Response interface contains the URL of the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) - */ - url: string; - webSocket: WebSocket | null; - cf: any | undefined; - /** - * The **`type`** read-only property of the Response interface contains the type of the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/type) - */ - type: "default" | "error"; -} -interface ResponseInit { - status?: number; - statusText?: string; - headers?: HeadersInit; - cf?: any; - webSocket?: (WebSocket | null); - encodeBody?: "automatic" | "manual"; -} -type RequestInfo> = Request | string; -/** - * The **`Request`** interface of the Fetch API represents a resource request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) - */ -declare var Request: { - prototype: Request; - new >(input: RequestInfo | URL, init?: RequestInit): Request; -}; -/** - * The **`Request`** interface of the Fetch API represents a resource request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) - */ -interface Request> extends Body { - /** - * The **`clone()`** method of the Request interface creates a copy of the current `Request` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) - */ - clone(): Request; - /** - * The **`method`** read-only property of the `POST`, etc.) A String indicating the method of the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) - */ - method: string; - /** - * The **`url`** read-only property of the Request interface contains the URL of the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) - */ - url: string; - /** - * The **`headers`** read-only property of the with the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) - */ - headers: Headers; - /** - * The **`redirect`** read-only property of the Request interface contains the mode for how redirects are handled. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) - */ - redirect: string; - fetcher: Fetcher | null; - /** - * The read-only **`signal`** property of the Request interface returns the AbortSignal associated with the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) - */ - signal: AbortSignal; - cf?: Cf; - /** - * The **`integrity`** read-only property of the Request interface contains the subresource integrity value of the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) - */ - integrity: string; - /** - * The **`keepalive`** read-only property of the Request interface contains the request's `keepalive` setting (`true` or `false`), which indicates whether the browser will keep the associated request alive if the page that initiated it is unloaded before the request is complete. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) - */ - keepalive: boolean; - /** - * The **`cache`** read-only property of the Request interface contains the cache mode of the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/cache) - */ - cache?: "no-store" | "no-cache"; -} -interface RequestInit { - /* A string to set request's method. */ - method?: string; - /* A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ - headers?: HeadersInit; - /* A BodyInit object or null to set request's body. */ - body?: BodyInit | null; - /* A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ - redirect?: string; - fetcher?: (Fetcher | null); - cf?: Cf; - /* A string indicating how the request will interact with the browser's cache to set request's cache. */ - cache?: "no-store" | "no-cache"; - /* A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ - integrity?: string; - /* An AbortSignal to set request's signal. */ - signal?: (AbortSignal | null); - encodeResponseBody?: "automatic" | "manual"; -} -type Service Rpc.WorkerEntrypointBranded) | Rpc.WorkerEntrypointBranded | ExportedHandler | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? Fetcher> : T extends Rpc.WorkerEntrypointBranded ? Fetcher : T extends Exclude ? never : Fetcher; -type Fetcher = (T extends Rpc.EntrypointBranded ? Rpc.Provider : unknown) & { - fetch(input: RequestInfo | URL, init?: RequestInit): Promise; - connect(address: SocketAddress | string, options?: SocketOptions): Socket; -}; -interface KVNamespaceListKey { - name: Key; - expiration?: number; - metadata?: Metadata; -} -type KVNamespaceListResult = { - list_complete: false; - keys: KVNamespaceListKey[]; - cursor: string; - cacheStatus: string | null; -} | { - list_complete: true; - keys: KVNamespaceListKey[]; - cacheStatus: string | null; -}; -interface KVNamespace { - get(key: Key, options?: Partial>): Promise; - get(key: Key, type: "text"): Promise; - get(key: Key, type: "json"): Promise; - get(key: Key, type: "arrayBuffer"): Promise; - get(key: Key, type: "stream"): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"text">): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"json">): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"arrayBuffer">): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"stream">): Promise; - get(key: Array, type: "text"): Promise>; - get(key: Array, type: "json"): Promise>; - get(key: Array, options?: Partial>): Promise>; - get(key: Array, options?: KVNamespaceGetOptions<"text">): Promise>; - get(key: Array, options?: KVNamespaceGetOptions<"json">): Promise>; - list(options?: KVNamespaceListOptions): Promise>; - put(key: Key, value: string | ArrayBuffer | ArrayBufferView | ReadableStream, options?: KVNamespacePutOptions): Promise; - getWithMetadata(key: Key, options?: Partial>): Promise>; - getWithMetadata(key: Key, type: "text"): Promise>; - getWithMetadata(key: Key, type: "json"): Promise>; - getWithMetadata(key: Key, type: "arrayBuffer"): Promise>; - getWithMetadata(key: Key, type: "stream"): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"text">): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"json">): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"arrayBuffer">): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"stream">): Promise>; - getWithMetadata(key: Array, type: "text"): Promise>>; - getWithMetadata(key: Array, type: "json"): Promise>>; - getWithMetadata(key: Array, options?: Partial>): Promise>>; - getWithMetadata(key: Array, options?: KVNamespaceGetOptions<"text">): Promise>>; - getWithMetadata(key: Array, options?: KVNamespaceGetOptions<"json">): Promise>>; - delete(key: Key): Promise; -} -interface KVNamespaceListOptions { - limit?: number; - prefix?: (string | null); - cursor?: (string | null); -} -interface KVNamespaceGetOptions { - type: Type; - cacheTtl?: number; -} -interface KVNamespacePutOptions { - expiration?: number; - expirationTtl?: number; - metadata?: (any | null); -} -interface KVNamespaceGetWithMetadataResult { - value: Value | null; - metadata: Metadata | null; - cacheStatus: string | null; -} -type QueueContentType = "text" | "bytes" | "json" | "v8"; -interface Queue { - send(message: Body, options?: QueueSendOptions): Promise; - sendBatch(messages: Iterable>, options?: QueueSendBatchOptions): Promise; -} -interface QueueSendOptions { - contentType?: QueueContentType; - delaySeconds?: number; -} -interface QueueSendBatchOptions { - delaySeconds?: number; -} -interface MessageSendRequest { - body: Body; - contentType?: QueueContentType; - delaySeconds?: number; -} -interface QueueRetryOptions { - delaySeconds?: number; -} -interface Message { - readonly id: string; - readonly timestamp: Date; - readonly body: Body; - readonly attempts: number; - retry(options?: QueueRetryOptions): void; - ack(): void; -} -interface QueueEvent extends ExtendableEvent { - readonly messages: readonly Message[]; - readonly queue: string; - retryAll(options?: QueueRetryOptions): void; - ackAll(): void; -} -interface MessageBatch { - readonly messages: readonly Message[]; - readonly queue: string; - retryAll(options?: QueueRetryOptions): void; - ackAll(): void; -} -interface R2Error extends Error { - readonly name: string; - readonly code: number; - readonly message: string; - readonly action: string; - readonly stack: any; -} -interface R2ListOptions { - limit?: number; - prefix?: string; - cursor?: string; - delimiter?: string; - startAfter?: string; - include?: ("httpMetadata" | "customMetadata")[]; -} -declare abstract class R2Bucket { - head(key: string): Promise; - get(key: string, options: R2GetOptions & { - onlyIf: R2Conditional | Headers; - }): Promise; - get(key: string, options?: R2GetOptions): Promise; - put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions & { - onlyIf: R2Conditional | Headers; - }): Promise; - put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions): Promise; - createMultipartUpload(key: string, options?: R2MultipartOptions): Promise; - resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; - delete(keys: string | string[]): Promise; - list(options?: R2ListOptions): Promise; -} -interface R2MultipartUpload { - readonly key: string; - readonly uploadId: string; - uploadPart(partNumber: number, value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, options?: R2UploadPartOptions): Promise; - abort(): Promise; - complete(uploadedParts: R2UploadedPart[]): Promise; -} -interface R2UploadedPart { - partNumber: number; - etag: string; -} -declare abstract class R2Object { - readonly key: string; - readonly version: string; - readonly size: number; - readonly etag: string; - readonly httpEtag: string; - readonly checksums: R2Checksums; - readonly uploaded: Date; - readonly httpMetadata?: R2HTTPMetadata; - readonly customMetadata?: Record; - readonly range?: R2Range; - readonly storageClass: string; - readonly ssecKeyMd5?: string; - writeHttpMetadata(headers: Headers): void; -} -interface R2ObjectBody extends R2Object { - get body(): ReadableStream; - get bodyUsed(): boolean; - arrayBuffer(): Promise; - bytes(): Promise; - text(): Promise; - json(): Promise; - blob(): Promise; -} -type R2Range = { - offset: number; - length?: number; -} | { - offset?: number; - length: number; -} | { - suffix: number; -}; -interface R2Conditional { - etagMatches?: string; - etagDoesNotMatch?: string; - uploadedBefore?: Date; - uploadedAfter?: Date; - secondsGranularity?: boolean; -} -interface R2GetOptions { - onlyIf?: (R2Conditional | Headers); - range?: (R2Range | Headers); - ssecKey?: (ArrayBuffer | string); -} -interface R2PutOptions { - onlyIf?: (R2Conditional | Headers); - httpMetadata?: (R2HTTPMetadata | Headers); - customMetadata?: Record; - md5?: ((ArrayBuffer | ArrayBufferView) | string); - sha1?: ((ArrayBuffer | ArrayBufferView) | string); - sha256?: ((ArrayBuffer | ArrayBufferView) | string); - sha384?: ((ArrayBuffer | ArrayBufferView) | string); - sha512?: ((ArrayBuffer | ArrayBufferView) | string); - storageClass?: string; - ssecKey?: (ArrayBuffer | string); -} -interface R2MultipartOptions { - httpMetadata?: (R2HTTPMetadata | Headers); - customMetadata?: Record; - storageClass?: string; - ssecKey?: (ArrayBuffer | string); -} -interface R2Checksums { - readonly md5?: ArrayBuffer; - readonly sha1?: ArrayBuffer; - readonly sha256?: ArrayBuffer; - readonly sha384?: ArrayBuffer; - readonly sha512?: ArrayBuffer; - toJSON(): R2StringChecksums; -} -interface R2StringChecksums { - md5?: string; - sha1?: string; - sha256?: string; - sha384?: string; - sha512?: string; -} -interface R2HTTPMetadata { - contentType?: string; - contentLanguage?: string; - contentDisposition?: string; - contentEncoding?: string; - cacheControl?: string; - cacheExpiry?: Date; -} -type R2Objects = { - objects: R2Object[]; - delimitedPrefixes: string[]; -} & ({ - truncated: true; - cursor: string; -} | { - truncated: false; -}); -interface R2UploadPartOptions { - ssecKey?: (ArrayBuffer | string); -} -declare abstract class ScheduledEvent extends ExtendableEvent { - readonly scheduledTime: number; - readonly cron: string; - noRetry(): void; -} -interface ScheduledController { - readonly scheduledTime: number; - readonly cron: string; - noRetry(): void; -} -interface QueuingStrategy { - highWaterMark?: (number | bigint); - size?: (chunk: T) => number | bigint; -} -interface UnderlyingSink { - type?: string; - start?: (controller: WritableStreamDefaultController) => void | Promise; - write?: (chunk: W, controller: WritableStreamDefaultController) => void | Promise; - abort?: (reason: any) => void | Promise; - close?: () => void | Promise; -} -interface UnderlyingByteSource { - type: "bytes"; - autoAllocateChunkSize?: number; - start?: (controller: ReadableByteStreamController) => void | Promise; - pull?: (controller: ReadableByteStreamController) => void | Promise; - cancel?: (reason: any) => void | Promise; -} -interface UnderlyingSource { - type?: "" | undefined; - start?: (controller: ReadableStreamDefaultController) => void | Promise; - pull?: (controller: ReadableStreamDefaultController) => void | Promise; - cancel?: (reason: any) => void | Promise; - expectedLength?: (number | bigint); -} -interface Transformer { - readableType?: string; - writableType?: string; - start?: (controller: TransformStreamDefaultController) => void | Promise; - transform?: (chunk: I, controller: TransformStreamDefaultController) => void | Promise; - flush?: (controller: TransformStreamDefaultController) => void | Promise; - cancel?: (reason: any) => void | Promise; - expectedLength?: number; -} -interface StreamPipeOptions { - preventAbort?: boolean; - preventCancel?: boolean; - /** - * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. - * - * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. - * - * Errors and closures of the source and destination streams propagate as follows: - * - * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination. - * - * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source. - * - * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. - * - * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. - * - * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. - */ - preventClose?: boolean; - signal?: AbortSignal; -} -type ReadableStreamReadResult = { - done: false; - value: R; -} | { - done: true; - value?: undefined; -}; -/** - * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) - */ -interface ReadableStream { - /** - * The **`locked`** read-only property of the ReadableStream interface returns whether or not the readable stream is locked to a reader. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) - */ - get locked(): boolean; - /** - * The **`cancel()`** method of the ReadableStream interface returns a Promise that resolves when the stream is canceled. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) - */ - cancel(reason?: any): Promise; - /** - * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) - */ - getReader(): ReadableStreamDefaultReader; - /** - * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) - */ - getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; - /** - * The **`pipeThrough()`** method of the ReadableStream interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) - */ - pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; - /** - * The **`pipeTo()`** method of the ReadableStream interface pipes the current `ReadableStream` to a given WritableStream and returns a Promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) - */ - pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; - /** - * The **`tee()`** method of the two-element array containing the two resulting branches as new ReadableStream instances. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) - */ - tee(): [ - ReadableStream, - ReadableStream - ]; - values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; - [Symbol.asyncIterator](options?: ReadableStreamValuesOptions): AsyncIterableIterator; -} -/** - * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) - */ -declare const ReadableStream: { - prototype: ReadableStream; - new (underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; - new (underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; -}; -/** - * The **`ReadableStreamDefaultReader`** interface of the Streams API represents a default reader that can be used to read stream data supplied from a network (such as a fetch request). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader) - */ -declare class ReadableStreamDefaultReader { - constructor(stream: ReadableStream); - get closed(): Promise; - cancel(reason?: any): Promise; - /** - * The **`read()`** method of the ReadableStreamDefaultReader interface returns a Promise providing access to the next chunk in the stream's internal queue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) - */ - read(): Promise>; - /** - * The **`releaseLock()`** method of the ReadableStreamDefaultReader interface releases the reader's lock on the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) - */ - releaseLock(): void; -} -/** - * The `ReadableStreamBYOBReader` interface of the Streams API defines a reader for a ReadableStream that supports zero-copy reading from an underlying byte source. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) - */ -declare class ReadableStreamBYOBReader { - constructor(stream: ReadableStream); - get closed(): Promise; - cancel(reason?: any): Promise; - /** - * The **`read()`** method of the ReadableStreamBYOBReader interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) - */ - read(view: T): Promise>; - /** - * The **`releaseLock()`** method of the ReadableStreamBYOBReader interface releases the reader's lock on the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) - */ - releaseLock(): void; - readAtLeast(minElements: number, view: T): Promise>; -} -interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { - min?: number; -} -interface ReadableStreamGetReaderOptions { - /** - * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. - * - * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. - */ - mode: "byob"; -} -/** - * The **`ReadableStreamBYOBRequest`** interface of the Streams API represents a 'pull request' for data from an underlying source that will made as a zero-copy transfer to a consumer (bypassing the stream's internal queues). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) - */ -declare abstract class ReadableStreamBYOBRequest { - /** - * The **`view`** getter property of the ReadableStreamBYOBRequest interface returns the current view. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) - */ - get view(): Uint8Array | null; - /** - * The **`respond()`** method of the ReadableStreamBYOBRequest interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the ReadableStreamBYOBRequest.view. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) - */ - respond(bytesWritten: number): void; - /** - * The **`respondWithNewView()`** method of the ReadableStreamBYOBRequest interface specifies a new view that the consumer of the associated readable byte stream should write to instead of ReadableStreamBYOBRequest.view. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) - */ - respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; - get atLeast(): number | null; -} -/** - * The **`ReadableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a ReadableStream's state and internal queue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) - */ -declare abstract class ReadableStreamDefaultController { - /** - * The **`desiredSize`** read-only property of the required to fill the stream's internal queue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) - */ - get desiredSize(): number | null; - /** - * The **`close()`** method of the ReadableStreamDefaultController interface closes the associated stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) - */ - close(): void; - /** - * The **`enqueue()`** method of the ```js-nolint enqueue(chunk) ``` - `chunk` - : The chunk to enqueue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) - */ - enqueue(chunk?: R): void; - /** - * The **`error()`** method of the with the associated stream to error. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) - */ - error(reason: any): void; -} -/** - * The **`ReadableByteStreamController`** interface of the Streams API represents a controller for a readable byte stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) - */ -declare abstract class ReadableByteStreamController { - /** - * The **`byobRequest`** read-only property of the ReadableByteStreamController interface returns the current BYOB request, or `null` if there are no pending requests. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) - */ - get byobRequest(): ReadableStreamBYOBRequest | null; - /** - * The **`desiredSize`** read-only property of the ReadableByteStreamController interface returns the number of bytes required to fill the stream's internal queue to its 'desired size'. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) - */ - get desiredSize(): number | null; - /** - * The **`close()`** method of the ReadableByteStreamController interface closes the associated stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) - */ - close(): void; - /** - * The **`enqueue()`** method of the ReadableByteStreamController interface enqueues a given chunk on the associated readable byte stream (the chunk is copied into the stream's internal queues). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) - */ - enqueue(chunk: ArrayBuffer | ArrayBufferView): void; - /** - * The **`error()`** method of the ReadableByteStreamController interface causes any future interactions with the associated stream to error with the specified reason. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) - */ - error(reason: any): void; -} -/** - * The **`WritableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a WritableStream's state. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) - */ -declare abstract class WritableStreamDefaultController { - /** - * The read-only **`signal`** property of the WritableStreamDefaultController interface returns the AbortSignal associated with the controller. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) - */ - get signal(): AbortSignal; - /** - * The **`error()`** method of the with the associated stream to error. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) - */ - error(reason?: any): void; -} -/** - * The **`TransformStreamDefaultController`** interface of the Streams API provides methods to manipulate the associated ReadableStream and WritableStream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) - */ -declare abstract class TransformStreamDefaultController { - /** - * The **`desiredSize`** read-only property of the TransformStreamDefaultController interface returns the desired size to fill the queue of the associated ReadableStream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) - */ - get desiredSize(): number | null; - /** - * The **`enqueue()`** method of the TransformStreamDefaultController interface enqueues the given chunk in the readable side of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) - */ - enqueue(chunk?: O): void; - /** - * The **`error()`** method of the TransformStreamDefaultController interface errors both sides of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) - */ - error(reason: any): void; - /** - * The **`terminate()`** method of the TransformStreamDefaultController interface closes the readable side and errors the writable side of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) - */ - terminate(): void; -} -interface ReadableWritablePair { - readable: ReadableStream; - /** - * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use. - * - * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. - */ - writable: WritableStream; -} -/** - * The **`WritableStream`** interface of the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream) - */ -declare class WritableStream { - constructor(underlyingSink?: UnderlyingSink, queuingStrategy?: QueuingStrategy); - /** - * The **`locked`** read-only property of the WritableStream interface returns a boolean indicating whether the `WritableStream` is locked to a writer. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) - */ - get locked(): boolean; - /** - * The **`abort()`** method of the WritableStream interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) - */ - abort(reason?: any): Promise; - /** - * The **`close()`** method of the WritableStream interface closes the associated stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) - */ - close(): Promise; - /** - * The **`getWriter()`** method of the WritableStream interface returns a new instance of WritableStreamDefaultWriter and locks the stream to that instance. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) - */ - getWriter(): WritableStreamDefaultWriter; -} -/** - * The **`WritableStreamDefaultWriter`** interface of the Streams API is the object returned by WritableStream.getWriter() and once created locks the writer to the `WritableStream` ensuring that no other streams can write to the underlying sink. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter) - */ -declare class WritableStreamDefaultWriter { - constructor(stream: WritableStream); - /** - * The **`closed`** read-only property of the the stream errors or the writer's lock is released. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) - */ - get closed(): Promise; - /** - * The **`ready`** read-only property of the that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) - */ - get ready(): Promise; - /** - * The **`desiredSize`** read-only property of the to fill the stream's internal queue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) - */ - get desiredSize(): number | null; - /** - * The **`abort()`** method of the the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) - */ - abort(reason?: any): Promise; - /** - * The **`close()`** method of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) - */ - close(): Promise; - /** - * The **`write()`** method of the operation. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) - */ - write(chunk?: W): Promise; - /** - * The **`releaseLock()`** method of the corresponding stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) - */ - releaseLock(): void; -} -/** - * The **`TransformStream`** interface of the Streams API represents a concrete implementation of the pipe chain _transform stream_ concept. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream) - */ -declare class TransformStream { - constructor(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy); - /** - * The **`readable`** read-only property of the TransformStream interface returns the ReadableStream instance controlled by this `TransformStream`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) - */ - get readable(): ReadableStream; - /** - * The **`writable`** read-only property of the TransformStream interface returns the WritableStream instance controlled by this `TransformStream`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) - */ - get writable(): WritableStream; -} -declare class FixedLengthStream extends IdentityTransformStream { - constructor(expectedLength: number | bigint, queuingStrategy?: IdentityTransformStreamQueuingStrategy); -} -declare class IdentityTransformStream extends TransformStream { - constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); -} -interface IdentityTransformStreamQueuingStrategy { - highWaterMark?: (number | bigint); -} -interface ReadableStreamValuesOptions { - preventCancel?: boolean; -} -/** - * The **`CompressionStream`** interface of the Compression Streams API is an API for compressing a stream of data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream) - */ -declare class CompressionStream extends TransformStream { - constructor(format: "gzip" | "deflate" | "deflate-raw"); -} -/** - * The **`DecompressionStream`** interface of the Compression Streams API is an API for decompressing a stream of data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream) - */ -declare class DecompressionStream extends TransformStream { - constructor(format: "gzip" | "deflate" | "deflate-raw"); -} -/** - * The **`TextEncoderStream`** interface of the Encoding API converts a stream of strings into bytes in the UTF-8 encoding. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoderStream) - */ -declare class TextEncoderStream extends TransformStream { - constructor(); - get encoding(): string; -} -/** - * The **`TextDecoderStream`** interface of the Encoding API converts a stream of text in a binary encoding, such as UTF-8 etc., to a stream of strings. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoderStream) - */ -declare class TextDecoderStream extends TransformStream { - constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); - get encoding(): string; - get fatal(): boolean; - get ignoreBOM(): boolean; -} -interface TextDecoderStreamTextDecoderStreamInit { - fatal?: boolean; - ignoreBOM?: boolean; -} -/** - * The **`ByteLengthQueuingStrategy`** interface of the Streams API provides a built-in byte length queuing strategy that can be used when constructing streams. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy) - */ -declare class ByteLengthQueuingStrategy implements QueuingStrategy { - constructor(init: QueuingStrategyInit); - /** - * The read-only **`ByteLengthQueuingStrategy.highWaterMark`** property returns the total number of bytes that can be contained in the internal queue before backpressure is applied. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) - */ - get highWaterMark(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ - get size(): (chunk?: any) => number; -} -/** - * The **`CountQueuingStrategy`** interface of the Streams API provides a built-in chunk counting queuing strategy that can be used when constructing streams. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy) - */ -declare class CountQueuingStrategy implements QueuingStrategy { - constructor(init: QueuingStrategyInit); - /** - * The read-only **`CountQueuingStrategy.highWaterMark`** property returns the total number of chunks that can be contained in the internal queue before backpressure is applied. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) - */ - get highWaterMark(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ - get size(): (chunk?: any) => number; -} -interface QueuingStrategyInit { - /** - * Creates a new ByteLengthQueuingStrategy with the provided high water mark. - * - * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw. - */ - highWaterMark: number; -} -interface ScriptVersion { - id?: string; - tag?: string; - message?: string; -} -declare abstract class TailEvent extends ExtendableEvent { - readonly events: TraceItem[]; - readonly traces: TraceItem[]; -} -interface TraceItem { - readonly event: (TraceItemFetchEventInfo | TraceItemJsRpcEventInfo | TraceItemScheduledEventInfo | TraceItemAlarmEventInfo | TraceItemQueueEventInfo | TraceItemEmailEventInfo | TraceItemTailEventInfo | TraceItemCustomEventInfo | TraceItemHibernatableWebSocketEventInfo) | null; - readonly eventTimestamp: number | null; - readonly logs: TraceLog[]; - readonly exceptions: TraceException[]; - readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; - readonly scriptName: string | null; - readonly entrypoint?: string; - readonly scriptVersion?: ScriptVersion; - readonly dispatchNamespace?: string; - readonly scriptTags?: string[]; - readonly durableObjectId?: string; - readonly outcome: string; - readonly executionModel: string; - readonly truncated: boolean; - readonly cpuTime: number; - readonly wallTime: number; -} -interface TraceItemAlarmEventInfo { - readonly scheduledTime: Date; -} -interface TraceItemCustomEventInfo { -} -interface TraceItemScheduledEventInfo { - readonly scheduledTime: number; - readonly cron: string; -} -interface TraceItemQueueEventInfo { - readonly queue: string; - readonly batchSize: number; -} -interface TraceItemEmailEventInfo { - readonly mailFrom: string; - readonly rcptTo: string; - readonly rawSize: number; -} -interface TraceItemTailEventInfo { - readonly consumedEvents: TraceItemTailEventInfoTailItem[]; -} -interface TraceItemTailEventInfoTailItem { - readonly scriptName: string | null; -} -interface TraceItemFetchEventInfo { - readonly response?: TraceItemFetchEventInfoResponse; - readonly request: TraceItemFetchEventInfoRequest; -} -interface TraceItemFetchEventInfoRequest { - readonly cf?: any; - readonly headers: Record; - readonly method: string; - readonly url: string; - getUnredacted(): TraceItemFetchEventInfoRequest; -} -interface TraceItemFetchEventInfoResponse { - readonly status: number; -} -interface TraceItemJsRpcEventInfo { - readonly rpcMethod: string; -} -interface TraceItemHibernatableWebSocketEventInfo { - readonly getWebSocketEvent: TraceItemHibernatableWebSocketEventInfoMessage | TraceItemHibernatableWebSocketEventInfoClose | TraceItemHibernatableWebSocketEventInfoError; -} -interface TraceItemHibernatableWebSocketEventInfoMessage { - readonly webSocketEventType: string; -} -interface TraceItemHibernatableWebSocketEventInfoClose { - readonly webSocketEventType: string; - readonly code: number; - readonly wasClean: boolean; -} -interface TraceItemHibernatableWebSocketEventInfoError { - readonly webSocketEventType: string; -} -interface TraceLog { - readonly timestamp: number; - readonly level: string; - readonly message: any; -} -interface TraceException { - readonly timestamp: number; - readonly message: string; - readonly name: string; - readonly stack?: string; -} -interface TraceDiagnosticChannelEvent { - readonly timestamp: number; - readonly channel: string; - readonly message: any; -} -interface TraceMetrics { - readonly cpuTime: number; - readonly wallTime: number; -} -interface UnsafeTraceMetrics { - fromTrace(item: TraceItem): TraceMetrics; -} -/** - * The **`URL`** interface is used to parse, construct, normalize, and encode URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL) - */ -declare class URL { - constructor(url: string | URL, base?: string | URL); - /** - * The **`origin`** read-only property of the URL interface returns a string containing the Unicode serialization of the origin of the represented URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) - */ - get origin(): string; - /** - * The **`href`** property of the URL interface is a string containing the whole URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) - */ - get href(): string; - /** - * The **`href`** property of the URL interface is a string containing the whole URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) - */ - set href(value: string); - /** - * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) - */ - get protocol(): string; - /** - * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) - */ - set protocol(value: string); - /** - * The **`username`** property of the URL interface is a string containing the username component of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) - */ - get username(): string; - /** - * The **`username`** property of the URL interface is a string containing the username component of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) - */ - set username(value: string); - /** - * The **`password`** property of the URL interface is a string containing the password component of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) - */ - get password(): string; - /** - * The **`password`** property of the URL interface is a string containing the password component of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) - */ - set password(value: string); - /** - * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) - */ - get host(): string; - /** - * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) - */ - set host(value: string); - /** - * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) - */ - get hostname(): string; - /** - * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) - */ - set hostname(value: string); - /** - * The **`port`** property of the URL interface is a string containing the port number of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) - */ - get port(): string; - /** - * The **`port`** property of the URL interface is a string containing the port number of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) - */ - set port(value: string); - /** - * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) - */ - get pathname(): string; - /** - * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) - */ - set pathname(value: string); - /** - * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) - */ - get search(): string; - /** - * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) - */ - set search(value: string); - /** - * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) - */ - get hash(): string; - /** - * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) - */ - set hash(value: string); - /** - * The **`searchParams`** read-only property of the access to the [MISSING: httpmethod('GET')] decoded query arguments contained in the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) - */ - get searchParams(): URLSearchParams; - /** - * The **`toJSON()`** method of the URL interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as ```js-nolint toJSON() ``` None. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) - */ - toJSON(): string; - /*function toString() { [native code] }*/ - toString(): string; - /** - * The **`URL.canParse()`** static method of the URL interface returns a boolean indicating whether or not an absolute URL, or a relative URL combined with a base URL, are parsable and valid. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) - */ - static canParse(url: string, base?: string): boolean; - /** - * The **`URL.parse()`** static method of the URL interface returns a newly created URL object representing the URL defined by the parameters. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/parse_static) - */ - static parse(url: string, base?: string): URL | null; - /** - * The **`createObjectURL()`** static method of the URL interface creates a string containing a URL representing the object given in the parameter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static) - */ - static createObjectURL(object: File | Blob): string; - /** - * The **`revokeObjectURL()`** static method of the URL interface releases an existing object URL which was previously created by calling Call this method when you've finished using an object URL to let the browser know not to keep the reference to the file any longer. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static) - */ - static revokeObjectURL(object_url: string): void; -} -/** - * The **`URLSearchParams`** interface defines utility methods to work with the query string of a URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams) - */ -declare class URLSearchParams { - constructor(init?: (Iterable> | Record | string)); - /** - * The **`size`** read-only property of the URLSearchParams interface indicates the total number of search parameter entries. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/size) - */ - get size(): number; - /** - * The **`append()`** method of the URLSearchParams interface appends a specified key/value pair as a new search parameter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/append) - */ - append(name: string, value: string): void; - /** - * The **`delete()`** method of the URLSearchParams interface deletes specified parameters and their associated value(s) from the list of all search parameters. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/delete) - */ - delete(name: string, value?: string): void; - /** - * The **`get()`** method of the URLSearchParams interface returns the first value associated to the given search parameter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/get) - */ - get(name: string): string | null; - /** - * The **`getAll()`** method of the URLSearchParams interface returns all the values associated with a given search parameter as an array. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/getAll) - */ - getAll(name: string): string[]; - /** - * The **`has()`** method of the URLSearchParams interface returns a boolean value that indicates whether the specified parameter is in the search parameters. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/has) - */ - has(name: string, value?: string): boolean; - /** - * The **`set()`** method of the URLSearchParams interface sets the value associated with a given search parameter to the given value. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/set) - */ - set(name: string, value: string): void; - /** - * The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns `undefined`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort) - */ - sort(): void; - /* Returns an array of key, value pairs for every entry in the search params. */ - entries(): IterableIterator<[ - key: string, - value: string - ]>; - /* Returns a list of keys in the search params. */ - keys(): IterableIterator; - /* Returns a list of values in the search params. */ - values(): IterableIterator; - forEach(callback: (this: This, value: string, key: string, parent: URLSearchParams) => void, thisArg?: This): void; - /*function toString() { [native code] }*/ - toString(): string; - [Symbol.iterator](): IterableIterator<[ - key: string, - value: string - ]>; -} -declare class URLPattern { - constructor(input?: (string | URLPatternInit), baseURL?: (string | URLPatternOptions), patternOptions?: URLPatternOptions); - get protocol(): string; - get username(): string; - get password(): string; - get hostname(): string; - get port(): string; - get pathname(): string; - get search(): string; - get hash(): string; - get hasRegExpGroups(): boolean; - test(input?: (string | URLPatternInit), baseURL?: string): boolean; - exec(input?: (string | URLPatternInit), baseURL?: string): URLPatternResult | null; -} -interface URLPatternInit { - protocol?: string; - username?: string; - password?: string; - hostname?: string; - port?: string; - pathname?: string; - search?: string; - hash?: string; - baseURL?: string; -} -interface URLPatternComponentResult { - input: string; - groups: Record; -} -interface URLPatternResult { - inputs: (string | URLPatternInit)[]; - protocol: URLPatternComponentResult; - username: URLPatternComponentResult; - password: URLPatternComponentResult; - hostname: URLPatternComponentResult; - port: URLPatternComponentResult; - pathname: URLPatternComponentResult; - search: URLPatternComponentResult; - hash: URLPatternComponentResult; -} -interface URLPatternOptions { - ignoreCase?: boolean; -} -/** - * A `CloseEvent` is sent to clients using WebSockets when the connection is closed. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent) - */ -declare class CloseEvent extends Event { - constructor(type: string, initializer?: CloseEventInit); - /** - * The **`code`** read-only property of the CloseEvent interface returns a WebSocket connection close code indicating the reason the connection was closed. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) - */ - readonly code: number; - /** - * The **`reason`** read-only property of the CloseEvent interface returns the WebSocket connection close reason the server gave for closing the connection; that is, a concise human-readable prose explanation for the closure. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) - */ - readonly reason: string; - /** - * The **`wasClean`** read-only property of the CloseEvent interface returns `true` if the connection closed cleanly. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) - */ - readonly wasClean: boolean; -} -interface CloseEventInit { - code?: number; - reason?: string; - wasClean?: boolean; -} -type WebSocketEventMap = { - close: CloseEvent; - message: MessageEvent; - open: Event; - error: ErrorEvent; -}; -/** - * The `WebSocket` object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) - */ -declare var WebSocket: { - prototype: WebSocket; - new (url: string, protocols?: (string[] | string)): WebSocket; - readonly READY_STATE_CONNECTING: number; - readonly CONNECTING: number; - readonly READY_STATE_OPEN: number; - readonly OPEN: number; - readonly READY_STATE_CLOSING: number; - readonly CLOSING: number; - readonly READY_STATE_CLOSED: number; - readonly CLOSED: number; -}; -/** - * The `WebSocket` object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) - */ -interface WebSocket extends EventTarget { - accept(options?: WebSocketAcceptOptions): void; - /** - * The **`WebSocket.send()`** method enqueues the specified data to be transmitted to the server over the WebSocket connection, increasing the value of `bufferedAmount` by the number of bytes needed to contain the data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) - */ - send(message: (ArrayBuffer | ArrayBufferView) | string): void; - /** - * The **`WebSocket.close()`** method closes the already `CLOSED`, this method does nothing. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) - */ - close(code?: number, reason?: string): void; - serializeAttachment(attachment: any): void; - deserializeAttachment(): any | null; - /** - * The **`WebSocket.readyState`** read-only property returns the current state of the WebSocket connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) - */ - readyState: number; - /** - * The **`WebSocket.url`** read-only property returns the absolute URL of the WebSocket as resolved by the constructor. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) - */ - url: string | null; - /** - * The **`WebSocket.protocol`** read-only property returns the name of the sub-protocol the server selected; this will be one of the strings specified in the `protocols` parameter when creating the WebSocket object, or the empty string if no connection is established. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) - */ - protocol: string | null; - /** - * The **`WebSocket.extensions`** read-only property returns the extensions selected by the server. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) - */ - extensions: string | null; - /** - * The **`WebSocket.binaryType`** property controls the type of binary data being received over the WebSocket connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/binaryType) - */ - binaryType: "blob" | "arraybuffer"; -} -interface WebSocketAcceptOptions { - /** - * When set to `true`, receiving a server-initiated WebSocket Close frame will not - * automatically send a reciprocal Close frame, leaving the connection in a half-open - * state. This is useful for proxying scenarios where you need to coordinate closing - * both sides independently. Defaults to `false` when the - * `no_web_socket_half_open_by_default` compatibility flag is enabled. - */ - allowHalfOpen?: boolean; -} -declare const WebSocketPair: { - new (): { - 0: WebSocket; - 1: WebSocket; - }; -}; -interface SqlStorage { - exec>(query: string, ...bindings: any[]): SqlStorageCursor; - get databaseSize(): number; - Cursor: typeof SqlStorageCursor; - Statement: typeof SqlStorageStatement; -} -declare abstract class SqlStorageStatement { -} -type SqlStorageValue = ArrayBuffer | string | number | null; -declare abstract class SqlStorageCursor> { - next(): { - done?: false; - value: T; - } | { - done: true; - value?: never; - }; - toArray(): T[]; - one(): T; - raw(): IterableIterator; - columnNames: string[]; - get rowsRead(): number; - get rowsWritten(): number; - [Symbol.iterator](): IterableIterator; -} -interface Socket { - get readable(): ReadableStream; - get writable(): WritableStream; - get closed(): Promise; - get opened(): Promise; - get upgraded(): boolean; - get secureTransport(): "on" | "off" | "starttls"; - close(): Promise; - startTls(options?: TlsOptions): Socket; -} -interface SocketOptions { - secureTransport?: string; - allowHalfOpen: boolean; - highWaterMark?: (number | bigint); -} -interface SocketAddress { - hostname: string; - port: number; -} -interface TlsOptions { - expectedServerHostname?: string; -} -interface SocketInfo { - remoteAddress?: string; - localAddress?: string; -} -/** - * The **`EventSource`** interface is web content's interface to server-sent events. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource) - */ -declare class EventSource extends EventTarget { - constructor(url: string, init?: EventSourceEventSourceInit); - /** - * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the ```js-nolint close() ``` None. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) - */ - close(): void; - /** - * The **`url`** read-only property of the URL of the source. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) - */ - get url(): string; - /** - * The **`withCredentials`** read-only property of the the `EventSource` object was instantiated with CORS credentials set. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) - */ - get withCredentials(): boolean; - /** - * The **`readyState`** read-only property of the connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) - */ - get readyState(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ - get onopen(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ - set onopen(value: any | null); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ - get onmessage(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ - set onmessage(value: any | null); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ - get onerror(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ - set onerror(value: any | null); - static readonly CONNECTING: number; - static readonly OPEN: number; - static readonly CLOSED: number; - static from(stream: ReadableStream): EventSource; -} -interface EventSourceEventSourceInit { - withCredentials?: boolean; - fetcher?: Fetcher; -} -interface Container { - get running(): boolean; - start(options?: ContainerStartupOptions): void; - monitor(): Promise; - destroy(error?: any): Promise; - signal(signo: number): void; - getTcpPort(port: number): Fetcher; - setInactivityTimeout(durationMs: number | bigint): Promise; - interceptOutboundHttp(addr: string, binding: Fetcher): Promise; - interceptAllOutboundHttp(binding: Fetcher): Promise; -} -interface ContainerStartupOptions { - entrypoint?: string[]; - enableInternet: boolean; - env?: Record; - hardTimeout?: (number | bigint); -} -/** - * The **`MessagePort`** interface of the Channel Messaging API represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort) - */ -declare abstract class MessagePort extends EventTarget { - /** - * The **`postMessage()`** method of the transfers ownership of objects to other browsing contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/postMessage) - */ - postMessage(data?: any, options?: (any[] | MessagePortPostMessageOptions)): void; - /** - * The **`close()`** method of the MessagePort interface disconnects the port, so it is no longer active. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/close) - */ - close(): void; - /** - * The **`start()`** method of the MessagePort interface starts the sending of messages queued on the port. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/start) - */ - start(): void; - get onmessage(): any | null; - set onmessage(value: any | null); -} -/** - * The **`MessageChannel`** interface of the Channel Messaging API allows us to create a new message channel and send data through it via its two MessagePort properties. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel) - */ -declare class MessageChannel { - constructor(); - /** - * The **`port1`** read-only property of the the port attached to the context that originated the channel. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port1) - */ - readonly port1: MessagePort; - /** - * The **`port2`** read-only property of the the port attached to the context at the other end of the channel, which the message is initially sent to. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port2) - */ - readonly port2: MessagePort; -} -interface MessagePortPostMessageOptions { - transfer?: any[]; -} -type LoopbackForExport Rpc.EntrypointBranded) | ExportedHandler | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? LoopbackServiceStub> : T extends new (...args: any[]) => Rpc.DurableObjectBranded ? LoopbackDurableObjectClass> : T extends ExportedHandler ? LoopbackServiceStub : undefined; -type LoopbackServiceStub = Fetcher & (T extends CloudflareWorkersModule.WorkerEntrypoint ? (opts: { - props?: Props; -}) => Fetcher : (opts: { - props?: any; -}) => Fetcher); -type LoopbackDurableObjectClass = DurableObjectClass & (T extends CloudflareWorkersModule.DurableObject ? (opts: { - props?: Props; -}) => DurableObjectClass : (opts: { - props?: any; -}) => DurableObjectClass); -interface SyncKvStorage { - get(key: string): T | undefined; - list(options?: SyncKvListOptions): Iterable<[ - string, - T - ]>; - put(key: string, value: T): void; - delete(key: string): boolean; -} -interface SyncKvListOptions { - start?: string; - startAfter?: string; - end?: string; - prefix?: string; - reverse?: boolean; - limit?: number; -} -interface WorkerStub { - getEntrypoint(name?: string, options?: WorkerStubEntrypointOptions): Fetcher; -} -interface WorkerStubEntrypointOptions { - props?: any; -} -interface WorkerLoader { - get(name: string | null, getCode: () => WorkerLoaderWorkerCode | Promise): WorkerStub; - load(code: WorkerLoaderWorkerCode): WorkerStub; -} -interface WorkerLoaderModule { - js?: string; - cjs?: string; - text?: string; - data?: ArrayBuffer; - json?: any; - py?: string; - wasm?: ArrayBuffer; -} -interface WorkerLoaderWorkerCode { - compatibilityDate: string; - compatibilityFlags?: string[]; - allowExperimental?: boolean; - mainModule: string; - modules: Record; - env?: any; - globalOutbound?: (Fetcher | null); - tails?: Fetcher[]; - streamingTails?: Fetcher[]; -} -/** -* The Workers runtime supports a subset of the Performance API, used to measure timing and performance, -* as well as timing of subrequests and other operations. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) -*/ -declare abstract class Performance { - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancetimeorigin) */ - get timeOrigin(): number; - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */ - now(): number; - /** - * The **`toJSON()`** method of the Performance interface is a Serialization; it returns a JSON representation of the Performance object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/toJSON) - */ - toJSON(): object; -} -// AI Search V2 API Error Interfaces -interface AiSearchInternalError extends Error { -} -interface AiSearchNotFoundError extends Error { -} -interface AiSearchNameNotSetError extends Error { -} -// AI Search V2 Request Types -type AiSearchSearchRequest = { - messages: Array<{ - role: 'system' | 'developer' | 'user' | 'assistant' | 'tool'; - content: string | null; - }>; - ai_search_options?: { - retrieval?: { - retrieval_type?: 'vector' | 'keyword' | 'hybrid'; - /** Match threshold (0-1, default 0.4) */ - match_threshold?: number; - /** Maximum number of results (1-50, default 10) */ - max_num_results?: number; - filters?: VectorizeVectorMetadataFilter; - /** Context expansion (0-3, default 0) */ - context_expansion?: number; - [key: string]: unknown; - }; - query_rewrite?: { - enabled?: boolean; - model?: string; - rewrite_prompt?: string; - [key: string]: unknown; - }; - reranking?: { - /** Enable reranking (default false) */ - enabled?: boolean; - model?: '@cf/baai/bge-reranker-base' | ''; - /** Match threshold (0-1, default 0.4) */ - match_threshold?: number; - [key: string]: unknown; - }; - [key: string]: unknown; - }; -}; -type AiSearchChatCompletionsRequest = { - messages: Array<{ - role: 'system' | 'developer' | 'user' | 'assistant' | 'tool'; - content: string | null; - }>; - model?: string; - stream?: boolean; - ai_search_options?: { - retrieval?: { - retrieval_type?: 'vector' | 'keyword' | 'hybrid'; - match_threshold?: number; - max_num_results?: number; - filters?: VectorizeVectorMetadataFilter; - context_expansion?: number; - [key: string]: unknown; - }; - query_rewrite?: { - enabled?: boolean; - model?: string; - rewrite_prompt?: string; - [key: string]: unknown; - }; - reranking?: { - enabled?: boolean; - model?: '@cf/baai/bge-reranker-base' | ''; - match_threshold?: number; - [key: string]: unknown; - }; - [key: string]: unknown; - }; - [key: string]: unknown; -}; -// AI Search V2 Response Types -type AiSearchSearchResponse = { - search_query: string; - chunks: Array<{ - id: string; - type: string; - /** Match score (0-1) */ - score: number; - text: string; - item: { - timestamp?: number; - key: string; - metadata?: Record; - }; - scoring_details?: { - /** Keyword match score (0-1) */ - keyword_score?: number; - /** Vector similarity score (0-1) */ - vector_score?: number; - }; - }>; -}; -type AiSearchListResponse = Array<{ - id: string; - internal_id?: string; - account_id?: string; - account_tag?: string; - /** Whether the instance is enabled (default true) */ - enable?: boolean; - type?: 'r2' | 'web-crawler'; - source?: string; - [key: string]: unknown; -}>; -type AiSearchConfig = { - /** Instance ID (1-32 chars, pattern: ^[a-z0-9_]+(?:-[a-z0-9_]+)*$) */ - id: string; - type: 'r2' | 'web-crawler'; - source: string; - source_params?: object; - /** Token ID (UUID format) */ - token_id?: string; - ai_gateway_id?: string; - /** Enable query rewriting (default false) */ - rewrite_query?: boolean; - /** Enable reranking (default false) */ - reranking?: boolean; - embedding_model?: string; - ai_search_model?: string; -}; -type AiSearchInstance = { - id: string; - enable?: boolean; - type?: 'r2' | 'web-crawler'; - source?: string; - [key: string]: unknown; -}; -// AI Search Instance Service - Instance-level operations -declare abstract class AiSearchInstanceService { - /** - * Search the AI Search instance for relevant chunks. - * @param params Search request with messages and AI search options - * @returns Search response with matching chunks - */ - search(params: AiSearchSearchRequest): Promise; - /** - * Generate chat completions with AI Search context. - * @param params Chat completions request with optional streaming - * @returns Response object (if streaming) or chat completion result - */ - chatCompletions(params: AiSearchChatCompletionsRequest): Promise; - /** - * Delete this AI Search instance. - */ - delete(): Promise; -} -// AI Search Account Service - Account-level operations -declare abstract class AiSearchAccountService { - /** - * List all AI Search instances in the account. - * @returns Array of AI Search instances - */ - list(): Promise; - /** - * Get an AI Search instance by ID. - * @param name Instance ID - * @returns Instance service for performing operations - */ - get(name: string): AiSearchInstanceService; - /** - * Create a new AI Search instance. - * @param config Instance configuration - * @returns Instance service for performing operations - */ - create(config: AiSearchConfig): Promise; -} -type AiImageClassificationInput = { - image: number[]; -}; -type AiImageClassificationOutput = { - score?: number; - label?: string; -}[]; -declare abstract class BaseAiImageClassification { - inputs: AiImageClassificationInput; - postProcessedOutputs: AiImageClassificationOutput; -} -type AiImageToTextInput = { - image: number[]; - prompt?: string; - max_tokens?: number; - temperature?: number; - top_p?: number; - top_k?: number; - seed?: number; - repetition_penalty?: number; - frequency_penalty?: number; - presence_penalty?: number; - raw?: boolean; - messages?: RoleScopedChatInput[]; -}; -type AiImageToTextOutput = { - description: string; -}; -declare abstract class BaseAiImageToText { - inputs: AiImageToTextInput; - postProcessedOutputs: AiImageToTextOutput; -} -type AiImageTextToTextInput = { - image: string; - prompt?: string; - max_tokens?: number; - temperature?: number; - ignore_eos?: boolean; - top_p?: number; - top_k?: number; - seed?: number; - repetition_penalty?: number; - frequency_penalty?: number; - presence_penalty?: number; - raw?: boolean; - messages?: RoleScopedChatInput[]; -}; -type AiImageTextToTextOutput = { - description: string; -}; -declare abstract class BaseAiImageTextToText { - inputs: AiImageTextToTextInput; - postProcessedOutputs: AiImageTextToTextOutput; -} -type AiMultimodalEmbeddingsInput = { - image: string; - text: string[]; -}; -type AiIMultimodalEmbeddingsOutput = { - data: number[][]; - shape: number[]; -}; -declare abstract class BaseAiMultimodalEmbeddings { - inputs: AiImageTextToTextInput; - postProcessedOutputs: AiImageTextToTextOutput; -} -type AiObjectDetectionInput = { - image: number[]; -}; -type AiObjectDetectionOutput = { - score?: number; - label?: string; -}[]; -declare abstract class BaseAiObjectDetection { - inputs: AiObjectDetectionInput; - postProcessedOutputs: AiObjectDetectionOutput; -} -type AiSentenceSimilarityInput = { - source: string; - sentences: string[]; -}; -type AiSentenceSimilarityOutput = number[]; -declare abstract class BaseAiSentenceSimilarity { - inputs: AiSentenceSimilarityInput; - postProcessedOutputs: AiSentenceSimilarityOutput; -} -type AiAutomaticSpeechRecognitionInput = { - audio: number[]; -}; -type AiAutomaticSpeechRecognitionOutput = { - text?: string; - words?: { - word: string; - start: number; - end: number; - }[]; - vtt?: string; -}; -declare abstract class BaseAiAutomaticSpeechRecognition { - inputs: AiAutomaticSpeechRecognitionInput; - postProcessedOutputs: AiAutomaticSpeechRecognitionOutput; -} -type AiSummarizationInput = { - input_text: string; - max_length?: number; -}; -type AiSummarizationOutput = { - summary: string; -}; -declare abstract class BaseAiSummarization { - inputs: AiSummarizationInput; - postProcessedOutputs: AiSummarizationOutput; -} -type AiTextClassificationInput = { - text: string; -}; -type AiTextClassificationOutput = { - score?: number; - label?: string; -}[]; -declare abstract class BaseAiTextClassification { - inputs: AiTextClassificationInput; - postProcessedOutputs: AiTextClassificationOutput; -} -type AiTextEmbeddingsInput = { - text: string | string[]; -}; -type AiTextEmbeddingsOutput = { - shape: number[]; - data: number[][]; -}; -declare abstract class BaseAiTextEmbeddings { - inputs: AiTextEmbeddingsInput; - postProcessedOutputs: AiTextEmbeddingsOutput; -} -type RoleScopedChatInput = { - role: "user" | "assistant" | "system" | "tool" | (string & NonNullable); - content: string; - name?: string; -}; -type AiTextGenerationToolLegacyInput = { - name: string; - description: string; - parameters?: { - type: "object" | (string & NonNullable); - properties: { - [key: string]: { - type: string; - description?: string; - }; - }; - required: string[]; - }; -}; -type AiTextGenerationToolInput = { - type: "function" | (string & NonNullable); - function: { - name: string; - description: string; - parameters?: { - type: "object" | (string & NonNullable); - properties: { - [key: string]: { - type: string; - description?: string; - }; - }; - required: string[]; - }; - }; -}; -type AiTextGenerationFunctionsInput = { - name: string; - code: string; -}; -type AiTextGenerationResponseFormat = { - type: string; - json_schema?: any; -}; -type AiTextGenerationInput = { - prompt?: string; - raw?: boolean; - stream?: boolean; - max_tokens?: number; - temperature?: number; - top_p?: number; - top_k?: number; - seed?: number; - repetition_penalty?: number; - frequency_penalty?: number; - presence_penalty?: number; - messages?: RoleScopedChatInput[]; - response_format?: AiTextGenerationResponseFormat; - tools?: AiTextGenerationToolInput[] | AiTextGenerationToolLegacyInput[] | (object & NonNullable); - functions?: AiTextGenerationFunctionsInput[]; -}; -type AiTextGenerationToolLegacyOutput = { - name: string; - arguments: unknown; -}; -type AiTextGenerationToolOutput = { - id: string; - type: "function"; - function: { - name: string; - arguments: string; - }; -}; -type UsageTags = { - prompt_tokens: number; - completion_tokens: number; - total_tokens: number; -}; -type AiTextGenerationOutput = { - response?: string; - tool_calls?: AiTextGenerationToolLegacyOutput[] & AiTextGenerationToolOutput[]; - usage?: UsageTags; -}; -declare abstract class BaseAiTextGeneration { - inputs: AiTextGenerationInput; - postProcessedOutputs: AiTextGenerationOutput; -} -type AiTextToSpeechInput = { - prompt: string; - lang?: string; -}; -type AiTextToSpeechOutput = Uint8Array | { - audio: string; -}; -declare abstract class BaseAiTextToSpeech { - inputs: AiTextToSpeechInput; - postProcessedOutputs: AiTextToSpeechOutput; -} -type AiTextToImageInput = { - prompt: string; - negative_prompt?: string; - height?: number; - width?: number; - image?: number[]; - image_b64?: string; - mask?: number[]; - num_steps?: number; - strength?: number; - guidance?: number; - seed?: number; -}; -type AiTextToImageOutput = ReadableStream; -declare abstract class BaseAiTextToImage { - inputs: AiTextToImageInput; - postProcessedOutputs: AiTextToImageOutput; -} -type AiTranslationInput = { - text: string; - target_lang: string; - source_lang?: string; -}; -type AiTranslationOutput = { - translated_text?: string; -}; -declare abstract class BaseAiTranslation { - inputs: AiTranslationInput; - postProcessedOutputs: AiTranslationOutput; -} -/** - * Workers AI support for OpenAI's Responses API - * Reference: https://github.com/openai/openai-node/blob/master/src/resources/responses/responses.ts - * - * It's a stripped down version from its source. - * It currently supports basic function calling, json mode and accepts images as input. - * - * It does not include types for WebSearch, CodeInterpreter, FileInputs, MCP, CustomTools. - * We plan to add those incrementally as model + platform capabilities evolve. - */ -type ResponsesInput = { - background?: boolean | null; - conversation?: string | ResponseConversationParam | null; - include?: Array | null; - input?: string | ResponseInput; - instructions?: string | null; - max_output_tokens?: number | null; - parallel_tool_calls?: boolean | null; - previous_response_id?: string | null; - prompt_cache_key?: string; - reasoning?: Reasoning | null; - safety_identifier?: string; - service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; - stream?: boolean | null; - stream_options?: StreamOptions | null; - temperature?: number | null; - text?: ResponseTextConfig; - tool_choice?: ToolChoiceOptions | ToolChoiceFunction; - tools?: Array; - top_p?: number | null; - truncation?: "auto" | "disabled" | null; -}; -type ResponsesOutput = { - id?: string; - created_at?: number; - output_text?: string; - error?: ResponseError | null; - incomplete_details?: ResponseIncompleteDetails | null; - instructions?: string | Array | null; - object?: "response"; - output?: Array; - parallel_tool_calls?: boolean; - temperature?: number | null; - tool_choice?: ToolChoiceOptions | ToolChoiceFunction; - tools?: Array; - top_p?: number | null; - max_output_tokens?: number | null; - previous_response_id?: string | null; - prompt?: ResponsePrompt | null; - reasoning?: Reasoning | null; - safety_identifier?: string; - service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; - status?: ResponseStatus; - text?: ResponseTextConfig; - truncation?: "auto" | "disabled" | null; - usage?: ResponseUsage; -}; -type EasyInputMessage = { - content: string | ResponseInputMessageContentList; - role: "user" | "assistant" | "system" | "developer"; - type?: "message"; -}; -type ResponsesFunctionTool = { - name: string; - parameters: { - [key: string]: unknown; - } | null; - strict: boolean | null; - type: "function"; - description?: string | null; -}; -type ResponseIncompleteDetails = { - reason?: "max_output_tokens" | "content_filter"; -}; -type ResponsePrompt = { - id: string; - variables?: { - [key: string]: string | ResponseInputText | ResponseInputImage; - } | null; - version?: string | null; -}; -type Reasoning = { - effort?: ReasoningEffort | null; - generate_summary?: "auto" | "concise" | "detailed" | null; - summary?: "auto" | "concise" | "detailed" | null; -}; -type ResponseContent = ResponseInputText | ResponseInputImage | ResponseOutputText | ResponseOutputRefusal | ResponseContentReasoningText; -type ResponseContentReasoningText = { - text: string; - type: "reasoning_text"; -}; -type ResponseConversationParam = { - id: string; -}; -type ResponseCreatedEvent = { - response: Response; - sequence_number: number; - type: "response.created"; -}; -type ResponseCustomToolCallOutput = { - call_id: string; - output: string | Array; - type: "custom_tool_call_output"; - id?: string; -}; -type ResponseError = { - code: "server_error" | "rate_limit_exceeded" | "invalid_prompt" | "vector_store_timeout" | "invalid_image" | "invalid_image_format" | "invalid_base64_image" | "invalid_image_url" | "image_too_large" | "image_too_small" | "image_parse_error" | "image_content_policy_violation" | "invalid_image_mode" | "image_file_too_large" | "unsupported_image_media_type" | "empty_image_file" | "failed_to_download_image" | "image_file_not_found"; - message: string; -}; -type ResponseErrorEvent = { - code: string | null; - message: string; - param: string | null; - sequence_number: number; - type: "error"; -}; -type ResponseFailedEvent = { - response: Response; - sequence_number: number; - type: "response.failed"; -}; -type ResponseFormatText = { - type: "text"; -}; -type ResponseFormatJSONObject = { - type: "json_object"; -}; -type ResponseFormatTextConfig = ResponseFormatText | ResponseFormatTextJSONSchemaConfig | ResponseFormatJSONObject; -type ResponseFormatTextJSONSchemaConfig = { - name: string; - schema: { - [key: string]: unknown; - }; - type: "json_schema"; - description?: string; - strict?: boolean | null; -}; -type ResponseFunctionCallArgumentsDeltaEvent = { - delta: string; - item_id: string; - output_index: number; - sequence_number: number; - type: "response.function_call_arguments.delta"; -}; -type ResponseFunctionCallArgumentsDoneEvent = { - arguments: string; - item_id: string; - name: string; - output_index: number; - sequence_number: number; - type: "response.function_call_arguments.done"; -}; -type ResponseFunctionCallOutputItem = ResponseInputTextContent | ResponseInputImageContent; -type ResponseFunctionCallOutputItemList = Array; -type ResponseFunctionToolCall = { - arguments: string; - call_id: string; - name: string; - type: "function_call"; - id?: string; - status?: "in_progress" | "completed" | "incomplete"; -}; -interface ResponseFunctionToolCallItem extends ResponseFunctionToolCall { - id: string; -} -type ResponseFunctionToolCallOutputItem = { - id: string; - call_id: string; - output: string | Array; - type: "function_call_output"; - status?: "in_progress" | "completed" | "incomplete"; -}; -type ResponseIncludable = "message.input_image.image_url" | "message.output_text.logprobs"; -type ResponseIncompleteEvent = { - response: Response; - sequence_number: number; - type: "response.incomplete"; -}; -type ResponseInput = Array; -type ResponseInputContent = ResponseInputText | ResponseInputImage; -type ResponseInputImage = { - detail: "low" | "high" | "auto"; - type: "input_image"; - /** - * Base64 encoded image - */ - image_url?: string | null; -}; -type ResponseInputImageContent = { - type: "input_image"; - detail?: "low" | "high" | "auto" | null; - /** - * Base64 encoded image - */ - image_url?: string | null; -}; -type ResponseInputItem = EasyInputMessage | ResponseInputItemMessage | ResponseOutputMessage | ResponseFunctionToolCall | ResponseInputItemFunctionCallOutput | ResponseReasoningItem; -type ResponseInputItemFunctionCallOutput = { - call_id: string; - output: string | ResponseFunctionCallOutputItemList; - type: "function_call_output"; - id?: string | null; - status?: "in_progress" | "completed" | "incomplete" | null; -}; -type ResponseInputItemMessage = { - content: ResponseInputMessageContentList; - role: "user" | "system" | "developer"; - status?: "in_progress" | "completed" | "incomplete"; - type?: "message"; -}; -type ResponseInputMessageContentList = Array; -type ResponseInputMessageItem = { - id: string; - content: ResponseInputMessageContentList; - role: "user" | "system" | "developer"; - status?: "in_progress" | "completed" | "incomplete"; - type?: "message"; -}; -type ResponseInputText = { - text: string; - type: "input_text"; -}; -type ResponseInputTextContent = { - text: string; - type: "input_text"; -}; -type ResponseItem = ResponseInputMessageItem | ResponseOutputMessage | ResponseFunctionToolCallItem | ResponseFunctionToolCallOutputItem; -type ResponseOutputItem = ResponseOutputMessage | ResponseFunctionToolCall | ResponseReasoningItem; -type ResponseOutputItemAddedEvent = { - item: ResponseOutputItem; - output_index: number; - sequence_number: number; - type: "response.output_item.added"; -}; -type ResponseOutputItemDoneEvent = { - item: ResponseOutputItem; - output_index: number; - sequence_number: number; - type: "response.output_item.done"; -}; -type ResponseOutputMessage = { - id: string; - content: Array; - role: "assistant"; - status: "in_progress" | "completed" | "incomplete"; - type: "message"; -}; -type ResponseOutputRefusal = { - refusal: string; - type: "refusal"; -}; -type ResponseOutputText = { - text: string; - type: "output_text"; - logprobs?: Array; -}; -type ResponseReasoningItem = { - id: string; - summary: Array; - type: "reasoning"; - content?: Array; - encrypted_content?: string | null; - status?: "in_progress" | "completed" | "incomplete"; -}; -type ResponseReasoningSummaryItem = { - text: string; - type: "summary_text"; -}; -type ResponseReasoningContentItem = { - text: string; - type: "reasoning_text"; -}; -type ResponseReasoningTextDeltaEvent = { - content_index: number; - delta: string; - item_id: string; - output_index: number; - sequence_number: number; - type: "response.reasoning_text.delta"; -}; -type ResponseReasoningTextDoneEvent = { - content_index: number; - item_id: string; - output_index: number; - sequence_number: number; - text: string; - type: "response.reasoning_text.done"; -}; -type ResponseRefusalDeltaEvent = { - content_index: number; - delta: string; - item_id: string; - output_index: number; - sequence_number: number; - type: "response.refusal.delta"; -}; -type ResponseRefusalDoneEvent = { - content_index: number; - item_id: string; - output_index: number; - refusal: string; - sequence_number: number; - type: "response.refusal.done"; -}; -type ResponseStatus = "completed" | "failed" | "in_progress" | "cancelled" | "queued" | "incomplete"; -type ResponseStreamEvent = ResponseCompletedEvent | ResponseCreatedEvent | ResponseErrorEvent | ResponseFunctionCallArgumentsDeltaEvent | ResponseFunctionCallArgumentsDoneEvent | ResponseFailedEvent | ResponseIncompleteEvent | ResponseOutputItemAddedEvent | ResponseOutputItemDoneEvent | ResponseReasoningTextDeltaEvent | ResponseReasoningTextDoneEvent | ResponseRefusalDeltaEvent | ResponseRefusalDoneEvent | ResponseTextDeltaEvent | ResponseTextDoneEvent; -type ResponseCompletedEvent = { - response: Response; - sequence_number: number; - type: "response.completed"; -}; -type ResponseTextConfig = { - format?: ResponseFormatTextConfig; - verbosity?: "low" | "medium" | "high" | null; -}; -type ResponseTextDeltaEvent = { - content_index: number; - delta: string; - item_id: string; - logprobs: Array; - output_index: number; - sequence_number: number; - type: "response.output_text.delta"; -}; -type ResponseTextDoneEvent = { - content_index: number; - item_id: string; - logprobs: Array; - output_index: number; - sequence_number: number; - text: string; - type: "response.output_text.done"; -}; -type Logprob = { - token: string; - logprob: number; - top_logprobs?: Array; -}; -type TopLogprob = { - token?: string; - logprob?: number; -}; -type ResponseUsage = { - input_tokens: number; - output_tokens: number; - total_tokens: number; -}; -type Tool = ResponsesFunctionTool; -type ToolChoiceFunction = { - name: string; - type: "function"; -}; -type ToolChoiceOptions = "none"; -type ReasoningEffort = "minimal" | "low" | "medium" | "high" | null; -type StreamOptions = { - include_obfuscation?: boolean; -}; -type Ai_Cf_Baai_Bge_Base_En_V1_5_Input = { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: "mean" | "cls"; -} | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: "mean" | "cls"; - }[]; -}; -type Ai_Cf_Baai_Bge_Base_En_V1_5_Output = { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: "mean" | "cls"; -} | Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse; -interface Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Baai_Bge_Base_En_V1_5 { - inputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Output; -} -type Ai_Cf_Openai_Whisper_Input = string | { - /** - * An array of integers that represent the audio data constrained to 8-bit unsigned integer values - */ - audio: number[]; -}; -interface Ai_Cf_Openai_Whisper_Output { - /** - * The transcription - */ - text: string; - word_count?: number; - words?: { - word?: string; - /** - * The second this word begins in the recording - */ - start?: number; - /** - * The ending second when the word completes - */ - end?: number; - }[]; - vtt?: string; -} -declare abstract class Base_Ai_Cf_Openai_Whisper { - inputs: Ai_Cf_Openai_Whisper_Input; - postProcessedOutputs: Ai_Cf_Openai_Whisper_Output; -} -type Ai_Cf_Meta_M2M100_1_2B_Input = { - /** - * The text to be translated - */ - text: string; - /** - * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified - */ - source_lang?: string; - /** - * The language code to translate the text into (e.g., 'es' for Spanish) - */ - target_lang: string; -} | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { - /** - * The text to be translated - */ - text: string; - /** - * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified - */ - source_lang?: string; - /** - * The language code to translate the text into (e.g., 'es' for Spanish) - */ - target_lang: string; - }[]; -}; -type Ai_Cf_Meta_M2M100_1_2B_Output = { - /** - * The translated text in the target language - */ - translated_text?: string; -} | Ai_Cf_Meta_M2M100_1_2B_AsyncResponse; -interface Ai_Cf_Meta_M2M100_1_2B_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Meta_M2M100_1_2B { - inputs: Ai_Cf_Meta_M2M100_1_2B_Input; - postProcessedOutputs: Ai_Cf_Meta_M2M100_1_2B_Output; -} -type Ai_Cf_Baai_Bge_Small_En_V1_5_Input = { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: "mean" | "cls"; -} | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: "mean" | "cls"; - }[]; -}; -type Ai_Cf_Baai_Bge_Small_En_V1_5_Output = { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: "mean" | "cls"; -} | Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse; -interface Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Baai_Bge_Small_En_V1_5 { - inputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Output; -} -type Ai_Cf_Baai_Bge_Large_En_V1_5_Input = { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: "mean" | "cls"; -} | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: "mean" | "cls"; - }[]; -}; -type Ai_Cf_Baai_Bge_Large_En_V1_5_Output = { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: "mean" | "cls"; -} | Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse; -interface Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Baai_Bge_Large_En_V1_5 { - inputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Output; -} -type Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input = string | { - /** - * The input text prompt for the model to generate a response. - */ - prompt?: string; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; - image: number[] | (string & NonNullable); - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; -}; -interface Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output { - description?: string; -} -declare abstract class Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M { - inputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input; - postProcessedOutputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output; -} -type Ai_Cf_Openai_Whisper_Tiny_En_Input = string | { - /** - * An array of integers that represent the audio data constrained to 8-bit unsigned integer values - */ - audio: number[]; -}; -interface Ai_Cf_Openai_Whisper_Tiny_En_Output { - /** - * The transcription - */ - text: string; - word_count?: number; - words?: { - word?: string; - /** - * The second this word begins in the recording - */ - start?: number; - /** - * The ending second when the word completes - */ - end?: number; - }[]; - vtt?: string; -} -declare abstract class Base_Ai_Cf_Openai_Whisper_Tiny_En { - inputs: Ai_Cf_Openai_Whisper_Tiny_En_Input; - postProcessedOutputs: Ai_Cf_Openai_Whisper_Tiny_En_Output; -} -interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input { - /** - * Base64 encoded value of the audio data. - */ - audio: string; - /** - * Supported tasks are 'translate' or 'transcribe'. - */ - task?: string; - /** - * The language of the audio being transcribed or translated. - */ - language?: string; - /** - * Preprocess the audio with a voice activity detection model. - */ - vad_filter?: boolean; - /** - * A text prompt to help provide context to the model on the contents of the audio. - */ - initial_prompt?: string; - /** - * The prefix it appended the the beginning of the output of the transcription and can guide the transcription result. - */ - prefix?: string; -} -interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output { - transcription_info?: { - /** - * The language of the audio being transcribed or translated. - */ - language?: string; - /** - * The confidence level or probability of the detected language being accurate, represented as a decimal between 0 and 1. - */ - language_probability?: number; - /** - * The total duration of the original audio file, in seconds. - */ - duration?: number; - /** - * The duration of the audio after applying Voice Activity Detection (VAD) to remove silent or irrelevant sections, in seconds. - */ - duration_after_vad?: number; - }; - /** - * The complete transcription of the audio. - */ - text: string; - /** - * The total number of words in the transcription. - */ - word_count?: number; - segments?: { - /** - * The starting time of the segment within the audio, in seconds. - */ - start?: number; - /** - * The ending time of the segment within the audio, in seconds. - */ - end?: number; - /** - * The transcription of the segment. - */ - text?: string; - /** - * The temperature used in the decoding process, controlling randomness in predictions. Lower values result in more deterministic outputs. - */ - temperature?: number; - /** - * The average log probability of the predictions for the words in this segment, indicating overall confidence. - */ - avg_logprob?: number; - /** - * The compression ratio of the input to the output, measuring how much the text was compressed during the transcription process. - */ - compression_ratio?: number; - /** - * The probability that the segment contains no speech, represented as a decimal between 0 and 1. - */ - no_speech_prob?: number; - words?: { - /** - * The individual word transcribed from the audio. - */ - word?: string; - /** - * The starting time of the word within the audio, in seconds. - */ - start?: number; - /** - * The ending time of the word within the audio, in seconds. - */ - end?: number; - }[]; - }[]; - /** - * The transcription in WebVTT format, which includes timing and text information for use in subtitles. - */ - vtt?: string; -} -declare abstract class Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo { - inputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input; - postProcessedOutputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output; -} -type Ai_Cf_Baai_Bge_M3_Input = Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts | Ai_Cf_Baai_Bge_M3_Input_Embedding | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: (Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 | Ai_Cf_Baai_Bge_M3_Input_Embedding_1)[]; -}; -interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts { - /** - * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts - */ - query?: string; - /** - * List of provided contexts. Note that the index in this array is important, as the response will refer to it. - */ - contexts: { - /** - * One of the provided context content - */ - text?: string; - }[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; -} -interface Ai_Cf_Baai_Bge_M3_Input_Embedding { - text: string | string[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; -} -interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 { - /** - * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts - */ - query?: string; - /** - * List of provided contexts. Note that the index in this array is important, as the response will refer to it. - */ - contexts: { - /** - * One of the provided context content - */ - text?: string; - }[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; -} -interface Ai_Cf_Baai_Bge_M3_Input_Embedding_1 { - text: string | string[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; -} -type Ai_Cf_Baai_Bge_M3_Output = Ai_Cf_Baai_Bge_M3_Ouput_Query | Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts | Ai_Cf_Baai_Bge_M3_Ouput_Embedding | Ai_Cf_Baai_Bge_M3_AsyncResponse; -interface Ai_Cf_Baai_Bge_M3_Ouput_Query { - response?: { - /** - * Index of the context in the request - */ - id?: number; - /** - * Score of the context under the index. - */ - score?: number; - }[]; -} -interface Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts { - response?: number[][]; - shape?: number[]; - /** - * The pooling method used in the embedding process. - */ - pooling?: "mean" | "cls"; -} -interface Ai_Cf_Baai_Bge_M3_Ouput_Embedding { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: "mean" | "cls"; -} -interface Ai_Cf_Baai_Bge_M3_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Baai_Bge_M3 { - inputs: Ai_Cf_Baai_Bge_M3_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output; -} -interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input { - /** - * A text description of the image you want to generate. - */ - prompt: string; - /** - * The number of diffusion steps; higher values can improve quality but take longer. - */ - steps?: number; -} -interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output { - /** - * The generated image in Base64 format. - */ - image?: string; -} -declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell { - inputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input; - postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output; -} -type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt | Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages; -interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - image?: number[] | (string & NonNullable); - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; -} -interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: string | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - image?: number[] | (string & NonNullable); - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - /** - * If true, the response will be streamed back incrementally. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output = { - /** - * The generated text response from the model - */ - response?: string; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -}; -declare abstract class Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct { - inputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output; -} -type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch; -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - /** - * The content of the message as a string. - */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch { - requests?: { - /** - * User-supplied reference. This field will be present in the response as well it can be used to reference the request and response. It's NOT validated to be unique. - */ - external_reference?: string; - /** - * Prompt for the text generation model - */ - prompt?: string; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; - response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2; - }[]; -} -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -} | string | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse; -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast { - inputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output; -} -interface Ai_Cf_Meta_Llama_Guard_3_8B_Input { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender must alternate between 'user' and 'assistant'. - */ - role: "user" | "assistant"; - /** - * The content of the message as a string. - */ - content: string; - }[]; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Dictate the output format of the generated response. - */ - response_format?: { - /** - * Set to json_object to process and output generated text as JSON. - */ - type?: string; - }; -} -interface Ai_Cf_Meta_Llama_Guard_3_8B_Output { - response?: string | { - /** - * Whether the conversation is safe or not. - */ - safe?: boolean; - /** - * A list of what hazard categories predicted for the conversation, if the conversation is deemed unsafe. - */ - categories?: string[]; - }; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; -} -declare abstract class Base_Ai_Cf_Meta_Llama_Guard_3_8B { - inputs: Ai_Cf_Meta_Llama_Guard_3_8B_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_Guard_3_8B_Output; -} -interface Ai_Cf_Baai_Bge_Reranker_Base_Input { - /** - * A query you wish to perform against the provided contexts. - */ - /** - * Number of returned results starting with the best score. - */ - top_k?: number; - /** - * List of provided contexts. Note that the index in this array is important, as the response will refer to it. - */ - contexts: { - /** - * One of the provided context content - */ - text?: string; - }[]; -} -interface Ai_Cf_Baai_Bge_Reranker_Base_Output { - response?: { - /** - * Index of the context in the request - */ - id?: number; - /** - * Score of the context under the index. - */ - score?: number; - }[]; -} -declare abstract class Base_Ai_Cf_Baai_Bge_Reranker_Base { - inputs: Ai_Cf_Baai_Bge_Reranker_Base_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Reranker_Base_Output; -} -type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt | Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages; -interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - /** - * The content of the message as a string. - */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -}; -declare abstract class Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct { - inputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input; - postProcessedOutputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output; -} -type Ai_Cf_Qwen_Qwq_32B_Input = Ai_Cf_Qwen_Qwq_32B_Prompt | Ai_Cf_Qwen_Qwq_32B_Messages; -interface Ai_Cf_Qwen_Qwq_32B_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwq_32B_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: string | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -type Ai_Cf_Qwen_Qwq_32B_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -}; -declare abstract class Base_Ai_Cf_Qwen_Qwq_32B { - inputs: Ai_Cf_Qwen_Qwq_32B_Input; - postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output; -} -type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt | Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages; -interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: string | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -}; -declare abstract class Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct { - inputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input; - postProcessedOutputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output; -} -type Ai_Cf_Google_Gemma_3_12B_It_Input = Ai_Cf_Google_Gemma_3_12B_It_Prompt | Ai_Cf_Google_Gemma_3_12B_It_Messages; -interface Ai_Cf_Google_Gemma_3_12B_It_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Google_Gemma_3_12B_It_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - content?: string | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[]; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -type Ai_Cf_Google_Gemma_3_12B_It_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -}; -declare abstract class Base_Ai_Cf_Google_Gemma_3_12B_It { - inputs: Ai_Cf_Google_Gemma_3_12B_It_Input; - postProcessedOutputs: Ai_Cf_Google_Gemma_3_12B_It_Output; -} -type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch; -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: string | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch { - requests: (Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner)[]; -} -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: string | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The tool call id. - */ - id?: string; - /** - * Specifies the type of tool (e.g., 'function'). - */ - type?: string; - /** - * Details of the function tool. - */ - function?: { - /** - * The name of the tool to be called - */ - name?: string; - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - }; - }[]; -}; -declare abstract class Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct { - inputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output; -} -type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input = Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch; -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - /** - * The content of the message as a string. - */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch { - requests: (Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1)[]; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1 { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - /** - * The content of the message as a string. - */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output = Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response | string | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse; -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response { - /** - * Unique identifier for the completion - */ - id?: string; - /** - * Object type identifier - */ - object?: "chat.completion"; - /** - * Unix timestamp of when the completion was created - */ - created?: number; - /** - * Model used for the completion - */ - model?: string; - /** - * List of completion choices - */ - choices?: { - /** - * Index of the choice in the list - */ - index?: number; - /** - * The message generated by the model - */ - message?: { - /** - * Role of the message author - */ - role: string; - /** - * The content of the message - */ - content: string; - /** - * Internal reasoning content (if available) - */ - reasoning_content?: string; - /** - * Tool calls made by the assistant - */ - tool_calls?: { - /** - * Unique identifier for the tool call - */ - id: string; - /** - * Type of tool call - */ - type: "function"; - function: { - /** - * Name of the function to call - */ - name: string; - /** - * JSON string of arguments for the function - */ - arguments: string; - }; - }[]; - }; - /** - * Reason why the model stopped generating - */ - finish_reason?: string; - /** - * Stop reason (may be null) - */ - stop_reason?: string | null; - /** - * Log probabilities (if requested) - */ - logprobs?: {} | null; - }[]; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * Log probabilities for the prompt (if requested) - */ - prompt_logprobs?: {} | null; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response { - /** - * Unique identifier for the completion - */ - id?: string; - /** - * Object type identifier - */ - object?: "text_completion"; - /** - * Unix timestamp of when the completion was created - */ - created?: number; - /** - * Model used for the completion - */ - model?: string; - /** - * List of completion choices - */ - choices?: { - /** - * Index of the choice in the list - */ - index: number; - /** - * The generated text completion - */ - text: string; - /** - * Reason why the model stopped generating - */ - finish_reason: string; - /** - * Stop reason (may be null) - */ - stop_reason?: string | null; - /** - * Log probabilities (if requested) - */ - logprobs?: {} | null; - /** - * Log probabilities for the prompt (if requested) - */ - prompt_logprobs?: {} | null; - }[]; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8 { - inputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input; - postProcessedOutputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output; -} -interface Ai_Cf_Deepgram_Nova_3_Input { - audio: { - body: object; - contentType: string; - }; - /** - * Sets how the model will interpret strings submitted to the custom_topic param. When strict, the model will only return topics submitted using the custom_topic param. When extended, the model will return its own detected topics in addition to those submitted using the custom_topic param. - */ - custom_topic_mode?: "extended" | "strict"; - /** - * Custom topics you want the model to detect within your input audio or text if present Submit up to 100 - */ - custom_topic?: string; - /** - * Sets how the model will interpret intents submitted to the custom_intent param. When strict, the model will only return intents submitted using the custom_intent param. When extended, the model will return its own detected intents in addition those submitted using the custom_intents param - */ - custom_intent_mode?: "extended" | "strict"; - /** - * Custom intents you want the model to detect within your input audio if present - */ - custom_intent?: string; - /** - * Identifies and extracts key entities from content in submitted audio - */ - detect_entities?: boolean; - /** - * Identifies the dominant language spoken in submitted audio - */ - detect_language?: boolean; - /** - * Recognize speaker changes. Each word in the transcript will be assigned a speaker number starting at 0 - */ - diarize?: boolean; - /** - * Identify and extract key entities from content in submitted audio - */ - dictation?: boolean; - /** - * Specify the expected encoding of your submitted audio - */ - encoding?: "linear16" | "flac" | "mulaw" | "amr-nb" | "amr-wb" | "opus" | "speex" | "g729"; - /** - * Arbitrary key-value pairs that are attached to the API response for usage in downstream processing - */ - extra?: string; - /** - * Filler Words can help transcribe interruptions in your audio, like 'uh' and 'um' - */ - filler_words?: boolean; - /** - * Key term prompting can boost or suppress specialized terminology and brands. - */ - keyterm?: string; - /** - * Keywords can boost or suppress specialized terminology and brands. - */ - keywords?: string; - /** - * The BCP-47 language tag that hints at the primary spoken language. Depending on the Model and API endpoint you choose only certain languages are available. - */ - language?: string; - /** - * Spoken measurements will be converted to their corresponding abbreviations. - */ - measurements?: boolean; - /** - * Opts out requests from the Deepgram Model Improvement Program. Refer to our Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip. - */ - mip_opt_out?: boolean; - /** - * Mode of operation for the model representing broad area of topic that will be talked about in the supplied audio - */ - mode?: "general" | "medical" | "finance"; - /** - * Transcribe each audio channel independently. - */ - multichannel?: boolean; - /** - * Numerals converts numbers from written format to numerical format. - */ - numerals?: boolean; - /** - * Splits audio into paragraphs to improve transcript readability. - */ - paragraphs?: boolean; - /** - * Profanity Filter looks for recognized profanity and converts it to the nearest recognized non-profane word or removes it from the transcript completely. - */ - profanity_filter?: boolean; - /** - * Add punctuation and capitalization to the transcript. - */ - punctuate?: boolean; - /** - * Redaction removes sensitive information from your transcripts. - */ - redact?: string; - /** - * Search for terms or phrases in submitted audio and replaces them. - */ - replace?: string; - /** - * Search for terms or phrases in submitted audio. - */ - search?: string; - /** - * Recognizes the sentiment throughout a transcript or text. - */ - sentiment?: boolean; - /** - * Apply formatting to transcript output. When set to true, additional formatting will be applied to transcripts to improve readability. - */ - smart_format?: boolean; - /** - * Detect topics throughout a transcript or text. - */ - topics?: boolean; - /** - * Segments speech into meaningful semantic units. - */ - utterances?: boolean; - /** - * Seconds to wait before detecting a pause between words in submitted audio. - */ - utt_split?: number; - /** - * The number of channels in the submitted audio - */ - channels?: number; - /** - * Specifies whether the streaming endpoint should provide ongoing transcription updates as more audio is received. When set to true, the endpoint sends continuous updates, meaning transcription results may evolve over time. Note: Supported only for webosockets. - */ - interim_results?: boolean; - /** - * Indicates how long model will wait to detect whether a speaker has finished speaking or pauses for a significant period of time. When set to a value, the streaming endpoint immediately finalizes the transcription for the processed time range and returns the transcript with a speech_final parameter set to true. Can also be set to false to disable endpointing - */ - endpointing?: string; - /** - * Indicates that speech has started. You'll begin receiving Speech Started messages upon speech starting. Note: Supported only for webosockets. - */ - vad_events?: boolean; - /** - * Indicates how long model will wait to send an UtteranceEnd message after a word has been transcribed. Use with interim_results. Note: Supported only for webosockets. - */ - utterance_end_ms?: boolean; -} -interface Ai_Cf_Deepgram_Nova_3_Output { - results?: { - channels?: { - alternatives?: { - confidence?: number; - transcript?: string; - words?: { - confidence?: number; - end?: number; - start?: number; - word?: string; - }[]; - }[]; - }[]; - summary?: { - result?: string; - short?: string; - }; - sentiments?: { - segments?: { - text?: string; - start_word?: number; - end_word?: number; - sentiment?: string; - sentiment_score?: number; - }[]; - average?: { - sentiment?: string; - sentiment_score?: number; - }; - }; - }; -} -declare abstract class Base_Ai_Cf_Deepgram_Nova_3 { - inputs: Ai_Cf_Deepgram_Nova_3_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Nova_3_Output; -} -interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input { - queries?: string | string[]; - /** - * Optional instruction for the task - */ - instruction?: string; - documents?: string | string[]; - text?: string | string[]; -} -interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output { - data?: number[][]; - shape?: number[]; -} -declare abstract class Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B { - inputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input; - postProcessedOutputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output; -} -type Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input = { - /** - * readable stream with audio data and content-type specified for that data - */ - audio: { - body: object; - contentType: string; - }; - /** - * type of data PCM data that's sent to the inference server as raw array - */ - dtype?: "uint8" | "float32" | "float64"; -} | { - /** - * base64 encoded audio data - */ - audio: string; - /** - * type of data PCM data that's sent to the inference server as raw array - */ - dtype?: "uint8" | "float32" | "float64"; -}; -interface Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output { - /** - * if true, end-of-turn was detected - */ - is_complete?: boolean; - /** - * probability of the end-of-turn detection - */ - probability?: number; -} -declare abstract class Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2 { - inputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input; - postProcessedOutputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output; -} -declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_120B { - inputs: ResponsesInput; - postProcessedOutputs: ResponsesOutput; -} -declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_20B { - inputs: ResponsesInput; - postProcessedOutputs: ResponsesOutput; -} -interface Ai_Cf_Leonardo_Phoenix_1_0_Input { - /** - * A text description of the image you want to generate. - */ - prompt: string; - /** - * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt - */ - guidance?: number; - /** - * Random seed for reproducibility of the image generation - */ - seed?: number; - /** - * The height of the generated image in pixels - */ - height?: number; - /** - * The width of the generated image in pixels - */ - width?: number; - /** - * The number of diffusion steps; higher values can improve quality but take longer - */ - num_steps?: number; - /** - * Specify what to exclude from the generated images - */ - negative_prompt?: string; -} -/** - * The generated image in JPEG format - */ -type Ai_Cf_Leonardo_Phoenix_1_0_Output = string; -declare abstract class Base_Ai_Cf_Leonardo_Phoenix_1_0 { - inputs: Ai_Cf_Leonardo_Phoenix_1_0_Input; - postProcessedOutputs: Ai_Cf_Leonardo_Phoenix_1_0_Output; -} -interface Ai_Cf_Leonardo_Lucid_Origin_Input { - /** - * A text description of the image you want to generate. - */ - prompt: string; - /** - * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt - */ - guidance?: number; - /** - * Random seed for reproducibility of the image generation - */ - seed?: number; - /** - * The height of the generated image in pixels - */ - height?: number; - /** - * The width of the generated image in pixels - */ - width?: number; - /** - * The number of diffusion steps; higher values can improve quality but take longer - */ - num_steps?: number; - /** - * The number of diffusion steps; higher values can improve quality but take longer - */ - steps?: number; -} -interface Ai_Cf_Leonardo_Lucid_Origin_Output { - /** - * The generated image in Base64 format. - */ - image?: string; -} -declare abstract class Base_Ai_Cf_Leonardo_Lucid_Origin { - inputs: Ai_Cf_Leonardo_Lucid_Origin_Input; - postProcessedOutputs: Ai_Cf_Leonardo_Lucid_Origin_Output; -} -interface Ai_Cf_Deepgram_Aura_1_Input { - /** - * Speaker used to produce the audio. - */ - speaker?: "angus" | "asteria" | "arcas" | "orion" | "orpheus" | "athena" | "luna" | "zeus" | "perseus" | "helios" | "hera" | "stella"; - /** - * Encoding of the output audio. - */ - encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; - /** - * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. - */ - container?: "none" | "wav" | "ogg"; - /** - * The text content to be converted to speech - */ - text: string; - /** - * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable - */ - sample_rate?: number; - /** - * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. - */ - bit_rate?: number; -} -/** - * The generated audio in MP3 format - */ -type Ai_Cf_Deepgram_Aura_1_Output = string; -declare abstract class Base_Ai_Cf_Deepgram_Aura_1 { - inputs: Ai_Cf_Deepgram_Aura_1_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Aura_1_Output; -} -interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input { - /** - * Input text to translate. Can be a single string or a list of strings. - */ - text: string | string[]; - /** - * Target language to translate to - */ - target_language: "asm_Beng" | "awa_Deva" | "ben_Beng" | "bho_Deva" | "brx_Deva" | "doi_Deva" | "eng_Latn" | "gom_Deva" | "gon_Deva" | "guj_Gujr" | "hin_Deva" | "hne_Deva" | "kan_Knda" | "kas_Arab" | "kas_Deva" | "kha_Latn" | "lus_Latn" | "mag_Deva" | "mai_Deva" | "mal_Mlym" | "mar_Deva" | "mni_Beng" | "mni_Mtei" | "npi_Deva" | "ory_Orya" | "pan_Guru" | "san_Deva" | "sat_Olck" | "snd_Arab" | "snd_Deva" | "tam_Taml" | "tel_Telu" | "urd_Arab" | "unr_Deva"; -} -interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output { - /** - * Translated texts - */ - translations: string[]; -} -declare abstract class Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B { - inputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input; - postProcessedOutputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output; -} -type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input = Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch; -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - /** - * The content of the message as a string. - */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch { - requests: (Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1)[]; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1 { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - /** - * The content of the message as a string. - */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output = Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response | string | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse; -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response { - /** - * Unique identifier for the completion - */ - id?: string; - /** - * Object type identifier - */ - object?: "chat.completion"; - /** - * Unix timestamp of when the completion was created - */ - created?: number; - /** - * Model used for the completion - */ - model?: string; - /** - * List of completion choices - */ - choices?: { - /** - * Index of the choice in the list - */ - index?: number; - /** - * The message generated by the model - */ - message?: { - /** - * Role of the message author - */ - role: string; - /** - * The content of the message - */ - content: string; - /** - * Internal reasoning content (if available) - */ - reasoning_content?: string; - /** - * Tool calls made by the assistant - */ - tool_calls?: { - /** - * Unique identifier for the tool call - */ - id: string; - /** - * Type of tool call - */ - type: "function"; - function: { - /** - * Name of the function to call - */ - name: string; - /** - * JSON string of arguments for the function - */ - arguments: string; - }; - }[]; - }; - /** - * Reason why the model stopped generating - */ - finish_reason?: string; - /** - * Stop reason (may be null) - */ - stop_reason?: string | null; - /** - * Log probabilities (if requested) - */ - logprobs?: {} | null; - }[]; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * Log probabilities for the prompt (if requested) - */ - prompt_logprobs?: {} | null; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response { - /** - * Unique identifier for the completion - */ - id?: string; - /** - * Object type identifier - */ - object?: "text_completion"; - /** - * Unix timestamp of when the completion was created - */ - created?: number; - /** - * Model used for the completion - */ - model?: string; - /** - * List of completion choices - */ - choices?: { - /** - * Index of the choice in the list - */ - index: number; - /** - * The generated text completion - */ - text: string; - /** - * Reason why the model stopped generating - */ - finish_reason: string; - /** - * Stop reason (may be null) - */ - stop_reason?: string | null; - /** - * Log probabilities (if requested) - */ - logprobs?: {} | null; - /** - * Log probabilities for the prompt (if requested) - */ - prompt_logprobs?: {} | null; - }[]; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It { - inputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input; - postProcessedOutputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output; -} -interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Input { - /** - * Input text to embed. Can be a single string or a list of strings. - */ - text: string | string[]; -} -interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Output { - /** - * Embedding vectors, where each vector is a list of floats. - */ - data: number[][]; - /** - * Shape of the embedding data as [number_of_embeddings, embedding_dimension]. - * - * @minItems 2 - * @maxItems 2 - */ - shape: [ - number, - number - ]; -} -declare abstract class Base_Ai_Cf_Pfnet_Plamo_Embedding_1B { - inputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Input; - postProcessedOutputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Output; -} -interface Ai_Cf_Deepgram_Flux_Input { - /** - * Encoding of the audio stream. Currently only supports raw signed little-endian 16-bit PCM. - */ - encoding: "linear16"; - /** - * Sample rate of the audio stream in Hz. - */ - sample_rate: string; - /** - * End-of-turn confidence required to fire an eager end-of-turn event. When set, enables EagerEndOfTurn and TurnResumed events. Valid Values 0.3 - 0.9. - */ - eager_eot_threshold?: string; - /** - * End-of-turn confidence required to finish a turn. Valid Values 0.5 - 0.9. - */ - eot_threshold?: string; - /** - * A turn will be finished when this much time has passed after speech, regardless of EOT confidence. - */ - eot_timeout_ms?: string; - /** - * Keyterm prompting can improve recognition of specialized terminology. Pass multiple keyterm query parameters to boost multiple keyterms. - */ - keyterm?: string; - /** - * Opts out requests from the Deepgram Model Improvement Program. Refer to Deepgram Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip - */ - mip_opt_out?: "true" | "false"; - /** - * Label your requests for the purpose of identification during usage reporting - */ - tag?: string; -} -/** - * Output will be returned as websocket messages. - */ -interface Ai_Cf_Deepgram_Flux_Output { - /** - * The unique identifier of the request (uuid) - */ - request_id?: string; - /** - * Starts at 0 and increments for each message the server sends to the client. - */ - sequence_id?: number; - /** - * The type of event being reported. - */ - event?: "Update" | "StartOfTurn" | "EagerEndOfTurn" | "TurnResumed" | "EndOfTurn"; - /** - * The index of the current turn - */ - turn_index?: number; - /** - * Start time in seconds of the audio range that was transcribed - */ - audio_window_start?: number; - /** - * End time in seconds of the audio range that was transcribed - */ - audio_window_end?: number; - /** - * Text that was said over the course of the current turn - */ - transcript?: string; - /** - * The words in the transcript - */ - words?: { - /** - * The individual punctuated, properly-cased word from the transcript - */ - word: string; - /** - * Confidence that this word was transcribed correctly - */ - confidence: number; - }[]; - /** - * Confidence that no more speech is coming in this turn - */ - end_of_turn_confidence?: number; -} -declare abstract class Base_Ai_Cf_Deepgram_Flux { - inputs: Ai_Cf_Deepgram_Flux_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Flux_Output; -} -interface Ai_Cf_Deepgram_Aura_2_En_Input { - /** - * Speaker used to produce the audio. - */ - speaker?: "amalthea" | "andromeda" | "apollo" | "arcas" | "aries" | "asteria" | "athena" | "atlas" | "aurora" | "callista" | "cora" | "cordelia" | "delia" | "draco" | "electra" | "harmonia" | "helena" | "hera" | "hermes" | "hyperion" | "iris" | "janus" | "juno" | "jupiter" | "luna" | "mars" | "minerva" | "neptune" | "odysseus" | "ophelia" | "orion" | "orpheus" | "pandora" | "phoebe" | "pluto" | "saturn" | "thalia" | "theia" | "vesta" | "zeus"; - /** - * Encoding of the output audio. - */ - encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; - /** - * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. - */ - container?: "none" | "wav" | "ogg"; - /** - * The text content to be converted to speech - */ - text: string; - /** - * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable - */ - sample_rate?: number; - /** - * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. - */ - bit_rate?: number; -} -/** - * The generated audio in MP3 format - */ -type Ai_Cf_Deepgram_Aura_2_En_Output = string; -declare abstract class Base_Ai_Cf_Deepgram_Aura_2_En { - inputs: Ai_Cf_Deepgram_Aura_2_En_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_En_Output; -} -interface Ai_Cf_Deepgram_Aura_2_Es_Input { - /** - * Speaker used to produce the audio. - */ - speaker?: "sirio" | "nestor" | "carina" | "celeste" | "alvaro" | "diana" | "aquila" | "selena" | "estrella" | "javier"; - /** - * Encoding of the output audio. - */ - encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; - /** - * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. - */ - container?: "none" | "wav" | "ogg"; - /** - * The text content to be converted to speech - */ - text: string; - /** - * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable - */ - sample_rate?: number; - /** - * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. - */ - bit_rate?: number; -} -/** - * The generated audio in MP3 format - */ -type Ai_Cf_Deepgram_Aura_2_Es_Output = string; -declare abstract class Base_Ai_Cf_Deepgram_Aura_2_Es { - inputs: Ai_Cf_Deepgram_Aura_2_Es_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_Es_Output; -} -interface AiModels { - "@cf/huggingface/distilbert-sst-2-int8": BaseAiTextClassification; - "@cf/stabilityai/stable-diffusion-xl-base-1.0": BaseAiTextToImage; - "@cf/runwayml/stable-diffusion-v1-5-inpainting": BaseAiTextToImage; - "@cf/runwayml/stable-diffusion-v1-5-img2img": BaseAiTextToImage; - "@cf/lykon/dreamshaper-8-lcm": BaseAiTextToImage; - "@cf/bytedance/stable-diffusion-xl-lightning": BaseAiTextToImage; - "@cf/myshell-ai/melotts": BaseAiTextToSpeech; - "@cf/google/embeddinggemma-300m": BaseAiTextEmbeddings; - "@cf/microsoft/resnet-50": BaseAiImageClassification; - "@cf/meta/llama-2-7b-chat-int8": BaseAiTextGeneration; - "@cf/mistral/mistral-7b-instruct-v0.1": BaseAiTextGeneration; - "@cf/meta/llama-2-7b-chat-fp16": BaseAiTextGeneration; - "@hf/thebloke/llama-2-13b-chat-awq": BaseAiTextGeneration; - "@hf/thebloke/mistral-7b-instruct-v0.1-awq": BaseAiTextGeneration; - "@hf/thebloke/zephyr-7b-beta-awq": BaseAiTextGeneration; - "@hf/thebloke/openhermes-2.5-mistral-7b-awq": BaseAiTextGeneration; - "@hf/thebloke/neural-chat-7b-v3-1-awq": BaseAiTextGeneration; - "@hf/thebloke/llamaguard-7b-awq": BaseAiTextGeneration; - "@hf/thebloke/deepseek-coder-6.7b-base-awq": BaseAiTextGeneration; - "@hf/thebloke/deepseek-coder-6.7b-instruct-awq": BaseAiTextGeneration; - "@cf/deepseek-ai/deepseek-math-7b-instruct": BaseAiTextGeneration; - "@cf/defog/sqlcoder-7b-2": BaseAiTextGeneration; - "@cf/openchat/openchat-3.5-0106": BaseAiTextGeneration; - "@cf/tiiuae/falcon-7b-instruct": BaseAiTextGeneration; - "@cf/thebloke/discolm-german-7b-v1-awq": BaseAiTextGeneration; - "@cf/qwen/qwen1.5-0.5b-chat": BaseAiTextGeneration; - "@cf/qwen/qwen1.5-7b-chat-awq": BaseAiTextGeneration; - "@cf/qwen/qwen1.5-14b-chat-awq": BaseAiTextGeneration; - "@cf/tinyllama/tinyllama-1.1b-chat-v1.0": BaseAiTextGeneration; - "@cf/microsoft/phi-2": BaseAiTextGeneration; - "@cf/qwen/qwen1.5-1.8b-chat": BaseAiTextGeneration; - "@cf/mistral/mistral-7b-instruct-v0.2-lora": BaseAiTextGeneration; - "@hf/nousresearch/hermes-2-pro-mistral-7b": BaseAiTextGeneration; - "@hf/nexusflow/starling-lm-7b-beta": BaseAiTextGeneration; - "@hf/google/gemma-7b-it": BaseAiTextGeneration; - "@cf/meta-llama/llama-2-7b-chat-hf-lora": BaseAiTextGeneration; - "@cf/google/gemma-2b-it-lora": BaseAiTextGeneration; - "@cf/google/gemma-7b-it-lora": BaseAiTextGeneration; - "@hf/mistral/mistral-7b-instruct-v0.2": BaseAiTextGeneration; - "@cf/meta/llama-3-8b-instruct": BaseAiTextGeneration; - "@cf/fblgit/una-cybertron-7b-v2-bf16": BaseAiTextGeneration; - "@cf/meta/llama-3-8b-instruct-awq": BaseAiTextGeneration; - "@cf/meta/llama-3.1-8b-instruct-fp8": BaseAiTextGeneration; - "@cf/meta/llama-3.1-8b-instruct-awq": BaseAiTextGeneration; - "@cf/meta/llama-3.2-3b-instruct": BaseAiTextGeneration; - "@cf/meta/llama-3.2-1b-instruct": BaseAiTextGeneration; - "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b": BaseAiTextGeneration; - "@cf/ibm-granite/granite-4.0-h-micro": BaseAiTextGeneration; - "@cf/facebook/bart-large-cnn": BaseAiSummarization; - "@cf/llava-hf/llava-1.5-7b-hf": BaseAiImageToText; - "@cf/baai/bge-base-en-v1.5": Base_Ai_Cf_Baai_Bge_Base_En_V1_5; - "@cf/openai/whisper": Base_Ai_Cf_Openai_Whisper; - "@cf/meta/m2m100-1.2b": Base_Ai_Cf_Meta_M2M100_1_2B; - "@cf/baai/bge-small-en-v1.5": Base_Ai_Cf_Baai_Bge_Small_En_V1_5; - "@cf/baai/bge-large-en-v1.5": Base_Ai_Cf_Baai_Bge_Large_En_V1_5; - "@cf/unum/uform-gen2-qwen-500m": Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M; - "@cf/openai/whisper-tiny-en": Base_Ai_Cf_Openai_Whisper_Tiny_En; - "@cf/openai/whisper-large-v3-turbo": Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo; - "@cf/baai/bge-m3": Base_Ai_Cf_Baai_Bge_M3; - "@cf/black-forest-labs/flux-1-schnell": Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell; - "@cf/meta/llama-3.2-11b-vision-instruct": Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct; - "@cf/meta/llama-3.3-70b-instruct-fp8-fast": Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast; - "@cf/meta/llama-guard-3-8b": Base_Ai_Cf_Meta_Llama_Guard_3_8B; - "@cf/baai/bge-reranker-base": Base_Ai_Cf_Baai_Bge_Reranker_Base; - "@cf/qwen/qwen2.5-coder-32b-instruct": Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct; - "@cf/qwen/qwq-32b": Base_Ai_Cf_Qwen_Qwq_32B; - "@cf/mistralai/mistral-small-3.1-24b-instruct": Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct; - "@cf/google/gemma-3-12b-it": Base_Ai_Cf_Google_Gemma_3_12B_It; - "@cf/meta/llama-4-scout-17b-16e-instruct": Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct; - "@cf/qwen/qwen3-30b-a3b-fp8": Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8; - "@cf/deepgram/nova-3": Base_Ai_Cf_Deepgram_Nova_3; - "@cf/qwen/qwen3-embedding-0.6b": Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B; - "@cf/pipecat-ai/smart-turn-v2": Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2; - "@cf/openai/gpt-oss-120b": Base_Ai_Cf_Openai_Gpt_Oss_120B; - "@cf/openai/gpt-oss-20b": Base_Ai_Cf_Openai_Gpt_Oss_20B; - "@cf/leonardo/phoenix-1.0": Base_Ai_Cf_Leonardo_Phoenix_1_0; - "@cf/leonardo/lucid-origin": Base_Ai_Cf_Leonardo_Lucid_Origin; - "@cf/deepgram/aura-1": Base_Ai_Cf_Deepgram_Aura_1; - "@cf/ai4bharat/indictrans2-en-indic-1B": Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B; - "@cf/aisingapore/gemma-sea-lion-v4-27b-it": Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It; - "@cf/pfnet/plamo-embedding-1b": Base_Ai_Cf_Pfnet_Plamo_Embedding_1B; - "@cf/deepgram/flux": Base_Ai_Cf_Deepgram_Flux; - "@cf/deepgram/aura-2-en": Base_Ai_Cf_Deepgram_Aura_2_En; - "@cf/deepgram/aura-2-es": Base_Ai_Cf_Deepgram_Aura_2_Es; -} -type AiOptions = { - /** - * Send requests as an asynchronous batch job, only works for supported models - * https://developers.cloudflare.com/workers-ai/features/batch-api - */ - queueRequest?: boolean; - /** - * Establish websocket connections, only works for supported models - */ - websocket?: boolean; - /** - * Tag your requests to group and view them in Cloudflare dashboard. - * - * Rules: - * Tags must only contain letters, numbers, and the symbols: : - . / @ - * Each tag can have maximum 50 characters. - * Maximum 5 tags are allowed each request. - * Duplicate tags will removed. - */ - tags?: string[]; - gateway?: GatewayOptions; - returnRawResponse?: boolean; - prefix?: string; - extraHeaders?: object; -}; -type AiModelsSearchParams = { - author?: string; - hide_experimental?: boolean; - page?: number; - per_page?: number; - search?: string; - source?: number; - task?: string; -}; -type AiModelsSearchObject = { - id: string; - source: number; - name: string; - description: string; - task: { - id: string; - name: string; - description: string; - }; - tags: string[]; - properties: { - property_id: string; - value: string; - }[]; -}; -interface InferenceUpstreamError extends Error { -} -interface AiInternalError extends Error { -} -type AiModelListType = Record; -declare abstract class Ai { - aiGatewayLogId: string | null; - gateway(gatewayId: string): AiGateway; - /** - * Access the AI Search API for managing AI-powered search instances. - * - * This is the new API that replaces AutoRAG with better namespace separation: - * - Account-level operations: `list()`, `create()` - * - Instance-level operations: `get(id).search()`, `get(id).chatCompletions()`, `get(id).delete()` - * - * @example - * ```typescript - * // List all AI Search instances - * const instances = await env.AI.aiSearch.list(); - * - * // Search an instance - * const results = await env.AI.aiSearch.get('my-search').search({ - * messages: [{ role: 'user', content: 'What is the policy?' }], - * ai_search_options: { - * retrieval: { max_num_results: 10 } - * } - * }); - * - * // Generate chat completions with AI Search context - * const response = await env.AI.aiSearch.get('my-search').chatCompletions({ - * messages: [{ role: 'user', content: 'What is the policy?' }], - * model: '@cf/meta/llama-3.3-70b-instruct-fp8-fast' - * }); - * ``` - */ - aiSearch(): AiSearchAccountService; - /** - * @deprecated AutoRAG has been replaced by AI Search. - * Use `env.AI.aiSearch` instead for better API design and new features. - * - * Migration guide: - * - `env.AI.autorag().list()` → `env.AI.aiSearch.list()` - * - `env.AI.autorag('id').search({ query: '...' })` → `env.AI.aiSearch.get('id').search({ messages: [{ role: 'user', content: '...' }] })` - * - `env.AI.autorag('id').aiSearch(...)` → `env.AI.aiSearch.get('id').chatCompletions(...)` - * - * Note: The old API continues to work for backwards compatibility, but new projects should use AI Search. - * - * @see AiSearchAccountService - * @param autoragId Optional instance ID (omit for account-level operations) - */ - autorag(autoragId: string): AutoRAG; - run(model: Name, inputs: InputOptions, options?: Options): Promise; - models(params?: AiModelsSearchParams): Promise; - toMarkdown(): ToMarkdownService; - toMarkdown(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise; - toMarkdown(files: MarkdownDocument, options?: ConversionRequestOptions): Promise; -} -type GatewayRetries = { - maxAttempts?: 1 | 2 | 3 | 4 | 5; - retryDelayMs?: number; - backoff?: 'constant' | 'linear' | 'exponential'; -}; -type GatewayOptions = { - id: string; - cacheKey?: string; - cacheTtl?: number; - skipCache?: boolean; - metadata?: Record; - collectLog?: boolean; - eventId?: string; - requestTimeoutMs?: number; - retries?: GatewayRetries; -}; -type UniversalGatewayOptions = Exclude & { - /** - ** @deprecated - */ - id?: string; -}; -type AiGatewayPatchLog = { - score?: number | null; - feedback?: -1 | 1 | null; - metadata?: Record | null; -}; -type AiGatewayLog = { - id: string; - provider: string; - model: string; - model_type?: string; - path: string; - duration: number; - request_type?: string; - request_content_type?: string; - status_code: number; - response_content_type?: string; - success: boolean; - cached: boolean; - tokens_in?: number; - tokens_out?: number; - metadata?: Record; - step?: number; - cost?: number; - custom_cost?: boolean; - request_size: number; - request_head?: string; - request_head_complete: boolean; - response_size: number; - response_head?: string; - response_head_complete: boolean; - created_at: Date; -}; -type AIGatewayProviders = 'workers-ai' | 'anthropic' | 'aws-bedrock' | 'azure-openai' | 'google-vertex-ai' | 'huggingface' | 'openai' | 'perplexity-ai' | 'replicate' | 'groq' | 'cohere' | 'google-ai-studio' | 'mistral' | 'grok' | 'openrouter' | 'deepseek' | 'cerebras' | 'cartesia' | 'elevenlabs' | 'adobe-firefly'; -type AIGatewayHeaders = { - 'cf-aig-metadata': Record | string; - 'cf-aig-custom-cost': { - per_token_in?: number; - per_token_out?: number; - } | { - total_cost?: number; - } | string; - 'cf-aig-cache-ttl': number | string; - 'cf-aig-skip-cache': boolean | string; - 'cf-aig-cache-key': string; - 'cf-aig-event-id': string; - 'cf-aig-request-timeout': number | string; - 'cf-aig-max-attempts': number | string; - 'cf-aig-retry-delay': number | string; - 'cf-aig-backoff': string; - 'cf-aig-collect-log': boolean | string; - Authorization: string; - 'Content-Type': string; - [key: string]: string | number | boolean | object; -}; -type AIGatewayUniversalRequest = { - provider: AIGatewayProviders | string; // eslint-disable-line - endpoint: string; - headers: Partial; - query: unknown; -}; -interface AiGatewayInternalError extends Error { -} -interface AiGatewayLogNotFound extends Error { -} -declare abstract class AiGateway { - patchLog(logId: string, data: AiGatewayPatchLog): Promise; - getLog(logId: string): Promise; - run(data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[], options?: { - gateway?: UniversalGatewayOptions; - extraHeaders?: object; - }): Promise; - getUrl(provider?: AIGatewayProviders | string): Promise; // eslint-disable-line -} -/** - * @deprecated AutoRAG has been replaced by AI Search. Use AiSearchInternalError instead. - * @see AiSearchInternalError - */ -interface AutoRAGInternalError extends Error { -} -/** - * @deprecated AutoRAG has been replaced by AI Search. Use AiSearchNotFoundError instead. - * @see AiSearchNotFoundError - */ -interface AutoRAGNotFoundError extends Error { -} -/** - * @deprecated This error type is no longer used in the AI Search API. - */ -interface AutoRAGUnauthorizedError extends Error { -} -/** - * @deprecated AutoRAG has been replaced by AI Search. Use AiSearchNameNotSetError instead. - * @see AiSearchNameNotSetError - */ -interface AutoRAGNameNotSetError extends Error { -} -type ComparisonFilter = { - key: string; - type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte'; - value: string | number | boolean; -}; -type CompoundFilter = { - type: 'and' | 'or'; - filters: ComparisonFilter[]; -}; -/** - * @deprecated AutoRAG has been replaced by AI Search. - * Use AiSearchSearchRequest with the new API instead. - * @see AiSearchSearchRequest - */ -type AutoRagSearchRequest = { - query: string; - filters?: CompoundFilter | ComparisonFilter; - max_num_results?: number; - ranking_options?: { - ranker?: string; - score_threshold?: number; - }; - reranking?: { - enabled?: boolean; - model?: string; - }; - rewrite_query?: boolean; -}; -/** - * @deprecated AutoRAG has been replaced by AI Search. - * Use AiSearchChatCompletionsRequest with the new API instead. - * @see AiSearchChatCompletionsRequest - */ -type AutoRagAiSearchRequest = AutoRagSearchRequest & { - stream?: boolean; - system_prompt?: string; -}; -/** - * @deprecated AutoRAG has been replaced by AI Search. - * Use AiSearchChatCompletionsRequest with stream: true instead. - * @see AiSearchChatCompletionsRequest - */ -type AutoRagAiSearchRequestStreaming = Omit & { - stream: true; -}; -/** - * @deprecated AutoRAG has been replaced by AI Search. - * Use AiSearchSearchResponse with the new API instead. - * @see AiSearchSearchResponse - */ -type AutoRagSearchResponse = { - object: 'vector_store.search_results.page'; - search_query: string; - data: { - file_id: string; - filename: string; - score: number; - attributes: Record; - content: { - type: 'text'; - text: string; - }[]; - }[]; - has_more: boolean; - next_page: string | null; -}; -/** - * @deprecated AutoRAG has been replaced by AI Search. - * Use AiSearchListResponse with the new API instead. - * @see AiSearchListResponse - */ -type AutoRagListResponse = { - id: string; - enable: boolean; - type: string; - source: string; - vectorize_name: string; - paused: boolean; - status: string; -}[]; -/** - * @deprecated AutoRAG has been replaced by AI Search. - * The new API returns different response formats for chat completions. - */ -type AutoRagAiSearchResponse = AutoRagSearchResponse & { - response: string; -}; -/** - * @deprecated AutoRAG has been replaced by AI Search. - * Use the new AI Search API instead: `env.AI.aiSearch` - * - * Migration guide: - * - `env.AI.autorag().list()` → `env.AI.aiSearch.list()` - * - `env.AI.autorag('id').search(...)` → `env.AI.aiSearch.get('id').search(...)` - * - `env.AI.autorag('id').aiSearch(...)` → `env.AI.aiSearch.get('id').chatCompletions(...)` - * - * @see AiSearchAccountService - * @see AiSearchInstanceService - */ -declare abstract class AutoRAG { - /** - * @deprecated Use `env.AI.aiSearch.list()` instead. - * @see AiSearchAccountService.list - */ - list(): Promise; - /** - * @deprecated Use `env.AI.aiSearch.get(id).search(...)` instead. - * Note: The new API uses a messages array instead of a query string. - * @see AiSearchInstanceService.search - */ - search(params: AutoRagSearchRequest): Promise; - /** - * @deprecated Use `env.AI.aiSearch.get(id).chatCompletions(...)` instead. - * @see AiSearchInstanceService.chatCompletions - */ - aiSearch(params: AutoRagAiSearchRequestStreaming): Promise; - /** - * @deprecated Use `env.AI.aiSearch.get(id).chatCompletions(...)` instead. - * @see AiSearchInstanceService.chatCompletions - */ - aiSearch(params: AutoRagAiSearchRequest): Promise; - /** - * @deprecated Use `env.AI.aiSearch.get(id).chatCompletions(...)` instead. - * @see AiSearchInstanceService.chatCompletions - */ - aiSearch(params: AutoRagAiSearchRequest): Promise; -} -interface BasicImageTransformations { - /** - * Maximum width in image pixels. The value must be an integer. - */ - width?: number; - /** - * Maximum height in image pixels. The value must be an integer. - */ - height?: number; - /** - * Resizing mode as a string. It affects interpretation of width and height - * options: - * - scale-down: Similar to contain, but the image is never enlarged. If - * the image is larger than given width or height, it will be resized. - * Otherwise its original size will be kept. - * - contain: Resizes to maximum size that fits within the given width and - * height. If only a single dimension is given (e.g. only width), the - * image will be shrunk or enlarged to exactly match that dimension. - * Aspect ratio is always preserved. - * - cover: Resizes (shrinks or enlarges) to fill the entire area of width - * and height. If the image has an aspect ratio different from the ratio - * of width and height, it will be cropped to fit. - * - crop: The image will be shrunk and cropped to fit within the area - * specified by width and height. The image will not be enlarged. For images - * smaller than the given dimensions it's the same as scale-down. For - * images larger than the given dimensions, it's the same as cover. - * See also trim. - * - pad: Resizes to the maximum size that fits within the given width and - * height, and then fills the remaining area with a background color - * (white by default). Use of this mode is not recommended, as the same - * effect can be more efficiently achieved with the contain mode and the - * CSS object-fit: contain property. - * - squeeze: Stretches and deforms to the width and height given, even if it - * breaks aspect ratio - */ - fit?: "scale-down" | "contain" | "cover" | "crop" | "pad" | "squeeze"; - /** - * Image segmentation using artificial intelligence models. Sets pixels not - * within selected segment area to transparent e.g "foreground" sets every - * background pixel as transparent. - */ - segment?: "foreground"; - /** - * When cropping with fit: "cover", this defines the side or point that should - * be left uncropped. The value is either a string - * "left", "right", "top", "bottom", "auto", or "center" (the default), - * or an object {x, y} containing focal point coordinates in the original - * image expressed as fractions ranging from 0.0 (top or left) to 1.0 - * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will - * crop bottom or left and right sides as necessary, but won’t crop anything - * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to - * preserve as much as possible around a point at 20% of the height of the - * source image. - */ - gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | BasicImageTransformationsGravityCoordinates; - /** - * Background color to add underneath the image. Applies only to images with - * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), - * hsl(…), etc.) - */ - background?: string; - /** - * Number of degrees (90, 180, 270) to rotate the image by. width and height - * options refer to axes after rotation. - */ - rotate?: 0 | 90 | 180 | 270 | 360; -} -interface BasicImageTransformationsGravityCoordinates { - x?: number; - y?: number; - mode?: 'remainder' | 'box-center'; -} -/** - * In addition to the properties you can set in the RequestInit dict - * that you pass as an argument to the Request constructor, you can - * set certain properties of a `cf` object to control how Cloudflare - * features are applied to that new Request. - * - * Note: Currently, these properties cannot be tested in the - * playground. - */ -interface RequestInitCfProperties extends Record { - cacheEverything?: boolean; - /** - * A request's cache key is what determines if two requests are - * "the same" for caching purposes. If a request has the same cache key - * as some previous request, then we can serve the same cached response for - * both. (e.g. 'some-key') - * - * Only available for Enterprise customers. - */ - cacheKey?: string; - /** - * This allows you to append additional Cache-Tag response headers - * to the origin response without modifications to the origin server. - * This will allow for greater control over the Purge by Cache Tag feature - * utilizing changes only in the Workers process. - * - * Only available for Enterprise customers. - */ - cacheTags?: string[]; - /** - * Force response to be cached for a given number of seconds. (e.g. 300) - */ - cacheTtl?: number; - /** - * Force response to be cached for a given number of seconds based on the Origin status code. - * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) - */ - cacheTtlByStatus?: Record; - scrapeShield?: boolean; - apps?: boolean; - image?: RequestInitCfPropertiesImage; - minify?: RequestInitCfPropertiesImageMinify; - mirage?: boolean; - polish?: "lossy" | "lossless" | "off"; - r2?: RequestInitCfPropertiesR2; - /** - * Redirects the request to an alternate origin server. You can use this, - * for example, to implement load balancing across several origins. - * (e.g.us-east.example.com) - * - * Note - For security reasons, the hostname set in resolveOverride must - * be proxied on the same Cloudflare zone of the incoming request. - * Otherwise, the setting is ignored. CNAME hosts are allowed, so to - * resolve to a host under a different domain or a DNS only domain first - * declare a CNAME record within your own zone’s DNS mapping to the - * external hostname, set proxy on Cloudflare, then set resolveOverride - * to point to that CNAME record. - */ - resolveOverride?: string; -} -interface RequestInitCfPropertiesImageDraw extends BasicImageTransformations { - /** - * Absolute URL of the image file to use for the drawing. It can be any of - * the supported file formats. For drawing of watermarks or non-rectangular - * overlays we recommend using PNG or WebP images. - */ - url: string; - /** - * Floating-point number between 0 (transparent) and 1 (opaque). - * For example, opacity: 0.5 makes overlay semitransparent. - */ - opacity?: number; - /** - * - If set to true, the overlay image will be tiled to cover the entire - * area. This is useful for stock-photo-like watermarks. - * - If set to "x", the overlay image will be tiled horizontally only - * (form a line). - * - If set to "y", the overlay image will be tiled vertically only - * (form a line). - */ - repeat?: true | "x" | "y"; - /** - * Position of the overlay image relative to a given edge. Each property is - * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 - * positions left side of the overlay 10 pixels from the left edge of the - * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom - * of the background image. - * - * Setting both left & right, or both top & bottom is an error. - * - * If no position is specified, the image will be centered. - */ - top?: number; - left?: number; - bottom?: number; - right?: number; -} -interface RequestInitCfPropertiesImage extends BasicImageTransformations { - /** - * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it - * easier to specify higher-DPI sizes in . - */ - dpr?: number; - /** - * Allows you to trim your image. Takes dpr into account and is performed before - * resizing or rotation. - * - * It can be used as: - * - left, top, right, bottom - it will specify the number of pixels to cut - * off each side - * - width, height - the width/height you'd like to end up with - can be used - * in combination with the properties above - * - border - this will automatically trim the surroundings of an image based on - * it's color. It consists of three properties: - * - color: rgb or hex representation of the color you wish to trim (todo: verify the rgba bit) - * - tolerance: difference from color to treat as color - * - keep: the number of pixels of border to keep - */ - trim?: "border" | { - top?: number; - bottom?: number; - left?: number; - right?: number; - width?: number; - height?: number; - border?: boolean | { - color?: string; - tolerance?: number; - keep?: number; - }; - }; - /** - * Quality setting from 1-100 (useful values are in 60-90 range). Lower values - * make images look worse, but load faster. The default is 85. It applies only - * to JPEG and WebP images. It doesn’t have any effect on PNG. - */ - quality?: number | "low" | "medium-low" | "medium-high" | "high"; - /** - * Output format to generate. It can be: - * - avif: generate images in AVIF format. - * - webp: generate images in Google WebP format. Set quality to 100 to get - * the WebP-lossless format. - * - json: instead of generating an image, outputs information about the - * image, in JSON format. The JSON object will contain image size - * (before and after resizing), source image’s MIME type, file size, etc. - * - jpeg: generate images in JPEG format. - * - png: generate images in PNG format. - */ - format?: "avif" | "webp" | "json" | "jpeg" | "png" | "baseline-jpeg" | "png-force" | "svg"; - /** - * Whether to preserve animation frames from input files. Default is true. - * Setting it to false reduces animations to still images. This setting is - * recommended when enlarging images or processing arbitrary user content, - * because large GIF animations can weigh tens or even hundreds of megabytes. - * It is also useful to set anim:false when using format:"json" to get the - * response quicker without the number of frames. - */ - anim?: boolean; - /** - * What EXIF data should be preserved in the output image. Note that EXIF - * rotation and embedded color profiles are always applied ("baked in" into - * the image), and aren't affected by this option. Note that if the Polish - * feature is enabled, all metadata may have been removed already and this - * option may have no effect. - * - keep: Preserve most of EXIF metadata, including GPS location if there's - * any. - * - copyright: Only keep the copyright tag, and discard everything else. - * This is the default behavior for JPEG files. - * - none: Discard all invisible EXIF metadata. Currently WebP and PNG - * output formats always discard metadata. - */ - metadata?: "keep" | "copyright" | "none"; - /** - * Strength of sharpening filter to apply to the image. Floating-point - * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a - * recommended value for downscaled images. - */ - sharpen?: number; - /** - * Radius of a blur filter (approximate gaussian). Maximum supported radius - * is 250. - */ - blur?: number; - /** - * Overlays are drawn in the order they appear in the array (last array - * entry is the topmost layer). - */ - draw?: RequestInitCfPropertiesImageDraw[]; - /** - * Fetching image from authenticated origin. Setting this property will - * pass authentication headers (Authorization, Cookie, etc.) through to - * the origin. - */ - "origin-auth"?: "share-publicly"; - /** - * Adds a border around the image. The border is added after resizing. Border - * width takes dpr into account, and can be specified either using a single - * width property, or individually for each side. - */ - border?: { - color: string; - width: number; - } | { - color: string; - top: number; - right: number; - bottom: number; - left: number; - }; - /** - * Increase brightness by a factor. A value of 1.0 equals no change, a value - * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. - * 0 is ignored. - */ - brightness?: number; - /** - * Increase contrast by a factor. A value of 1.0 equals no change, a value of - * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is - * ignored. - */ - contrast?: number; - /** - * Increase exposure by a factor. A value of 1.0 equals no change, a value of - * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. - */ - gamma?: number; - /** - * Increase contrast by a factor. A value of 1.0 equals no change, a value of - * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is - * ignored. - */ - saturation?: number; - /** - * Flips the images horizontally, vertically, or both. Flipping is applied before - * rotation, so if you apply flip=h,rotate=90 then the image will be flipped - * horizontally, then rotated by 90 degrees. - */ - flip?: 'h' | 'v' | 'hv'; - /** - * Slightly reduces latency on a cache miss by selecting a - * quickest-to-compress file format, at a cost of increased file size and - * lower image quality. It will usually override the format option and choose - * JPEG over WebP or AVIF. We do not recommend using this option, except in - * unusual circumstances like resizing uncacheable dynamically-generated - * images. - */ - compression?: "fast"; -} -interface RequestInitCfPropertiesImageMinify { - javascript?: boolean; - css?: boolean; - html?: boolean; -} -interface RequestInitCfPropertiesR2 { - /** - * Colo id of bucket that an object is stored in - */ - bucketColoId?: number; -} -/** - * Request metadata provided by Cloudflare's edge. - */ -type IncomingRequestCfProperties = IncomingRequestCfPropertiesBase & IncomingRequestCfPropertiesBotManagementEnterprise & IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & IncomingRequestCfPropertiesGeographicInformation & IncomingRequestCfPropertiesCloudflareAccessOrApiShield; -interface IncomingRequestCfPropertiesBase extends Record { - /** - * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. - * - * @example 395747 - */ - asn?: number; - /** - * The organization which owns the ASN of the incoming request. - * - * @example "Google Cloud" - */ - asOrganization?: string; - /** - * The original value of the `Accept-Encoding` header if Cloudflare modified it. - * - * @example "gzip, deflate, br" - */ - clientAcceptEncoding?: string; - /** - * The number of milliseconds it took for the request to reach your worker. - * - * @example 22 - */ - clientTcpRtt?: number; - /** - * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) - * airport code of the data center that the request hit. - * - * @example "DFW" - */ - colo: string; - /** - * Represents the upstream's response to a - * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) - * from cloudflare. - * - * For workers with no upstream, this will always be `1`. - * - * @example 3 - */ - edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; - /** - * The HTTP Protocol the request used. - * - * @example "HTTP/2" - */ - httpProtocol: string; - /** - * The browser-requested prioritization information in the request object. - * - * If no information was set, defaults to the empty string `""` - * - * @example "weight=192;exclusive=0;group=3;group-weight=127" - * @default "" - */ - requestPriority: string; - /** - * The TLS version of the connection to Cloudflare. - * In requests served over plaintext (without TLS), this property is the empty string `""`. - * - * @example "TLSv1.3" - */ - tlsVersion: string; - /** - * The cipher for the connection to Cloudflare. - * In requests served over plaintext (without TLS), this property is the empty string `""`. - * - * @example "AEAD-AES128-GCM-SHA256" - */ - tlsCipher: string; - /** - * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. - * - * If the incoming request was served over plaintext (without TLS) this field is undefined. - */ - tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; -} -interface IncomingRequestCfPropertiesBotManagementBase { - /** - * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, - * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). - * - * @example 54 - */ - score: number; - /** - * A boolean value that is true if the request comes from a good bot, like Google or Bing. - * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). - */ - verifiedBot: boolean; - /** - * A boolean value that is true if the request originates from a - * Cloudflare-verified proxy service. - */ - corporateProxy: boolean; - /** - * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. - */ - staticResource: boolean; - /** - * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). - */ - detectionIds: number[]; -} -interface IncomingRequestCfPropertiesBotManagement { - /** - * Results of Cloudflare's Bot Management analysis - */ - botManagement: IncomingRequestCfPropertiesBotManagementBase; - /** - * Duplicate of `botManagement.score`. - * - * @deprecated - */ - clientTrustScore: number; -} -interface IncomingRequestCfPropertiesBotManagementEnterprise extends IncomingRequestCfPropertiesBotManagement { - /** - * Results of Cloudflare's Bot Management analysis - */ - botManagement: IncomingRequestCfPropertiesBotManagementBase & { - /** - * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients - * across different destination IPs, Ports, and X509 certificates. - */ - ja3Hash: string; - }; -} -interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise { - /** - * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). - * - * This field is only present if you have Cloudflare for SaaS enabled on your account - * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). - */ - hostMetadata?: HostMetadata; -} -interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { - /** - * Information about the client certificate presented to Cloudflare. - * - * This is populated when the incoming request is served over TLS using - * either Cloudflare Access or API Shield (mTLS) - * and the presented SSL certificate has a valid - * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) - * (i.e., not `null` or `""`). - * - * Otherwise, a set of placeholder values are used. - * - * The property `certPresented` will be set to `"1"` when - * the object is populated (i.e. the above conditions were met). - */ - tlsClientAuth: IncomingRequestCfPropertiesTLSClientAuth | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; -} -/** - * Metadata about the request's TLS handshake - */ -interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { - /** - * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal - * - * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" - */ - clientHandshake: string; - /** - * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal - * - * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" - */ - serverHandshake: string; - /** - * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal - * - * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" - */ - clientFinished: string; - /** - * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal - * - * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" - */ - serverFinished: string; -} -/** - * Geographic data about the request's origin. - */ -interface IncomingRequestCfPropertiesGeographicInformation { - /** - * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. - * - * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. - * - * If Cloudflare is unable to determine where the request originated this property is omitted. - * - * The country code `"T1"` is used for requests originating on TOR. - * - * @example "GB" - */ - country?: Iso3166Alpha2Code | "T1"; - /** - * If present, this property indicates that the request originated in the EU - * - * @example "1" - */ - isEUCountry?: "1"; - /** - * A two-letter code indicating the continent the request originated from. - * - * @example "AN" - */ - continent?: ContinentCode; - /** - * The city the request originated from - * - * @example "Austin" - */ - city?: string; - /** - * Postal code of the incoming request - * - * @example "78701" - */ - postalCode?: string; - /** - * Latitude of the incoming request - * - * @example "30.27130" - */ - latitude?: string; - /** - * Longitude of the incoming request - * - * @example "-97.74260" - */ - longitude?: string; - /** - * Timezone of the incoming request - * - * @example "America/Chicago" - */ - timezone?: string; - /** - * If known, the ISO 3166-2 name for the first level region associated with - * the IP address of the incoming request - * - * @example "Texas" - */ - region?: string; - /** - * If known, the ISO 3166-2 code for the first-level region associated with - * the IP address of the incoming request - * - * @example "TX" - */ - regionCode?: string; - /** - * Metro code (DMA) of the incoming request - * - * @example "635" - */ - metroCode?: string; -} -/** Data about the incoming request's TLS certificate */ -interface IncomingRequestCfPropertiesTLSClientAuth { - /** Always `"1"`, indicating that the certificate was presented */ - certPresented: "1"; - /** - * Result of certificate verification. - * - * @example "FAILED:self signed certificate" - */ - certVerified: Exclude; - /** The presented certificate's revokation status. - * - * - A value of `"1"` indicates the certificate has been revoked - * - A value of `"0"` indicates the certificate has not been revoked - */ - certRevoked: "1" | "0"; - /** - * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) - * - * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" - */ - certIssuerDN: string; - /** - * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) - * - * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" - */ - certSubjectDN: string; - /** - * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) - * - * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" - */ - certIssuerDNRFC2253: string; - /** - * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) - * - * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" - */ - certSubjectDNRFC2253: string; - /** The certificate issuer's distinguished name (legacy policies) */ - certIssuerDNLegacy: string; - /** The certificate subject's distinguished name (legacy policies) */ - certSubjectDNLegacy: string; - /** - * The certificate's serial number - * - * @example "00936EACBE07F201DF" - */ - certSerial: string; - /** - * The certificate issuer's serial number - * - * @example "2489002934BDFEA34" - */ - certIssuerSerial: string; - /** - * The certificate's Subject Key Identifier - * - * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" - */ - certSKI: string; - /** - * The certificate issuer's Subject Key Identifier - * - * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" - */ - certIssuerSKI: string; - /** - * The certificate's SHA-1 fingerprint - * - * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" - */ - certFingerprintSHA1: string; - /** - * The certificate's SHA-256 fingerprint - * - * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" - */ - certFingerprintSHA256: string; - /** - * The effective starting date of the certificate - * - * @example "Dec 22 19:39:00 2018 GMT" - */ - certNotBefore: string; - /** - * The effective expiration date of the certificate - * - * @example "Dec 22 19:39:00 2018 GMT" - */ - certNotAfter: string; -} -/** Placeholder values for TLS Client Authorization */ -interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { - certPresented: "0"; - certVerified: "NONE"; - certRevoked: "0"; - certIssuerDN: ""; - certSubjectDN: ""; - certIssuerDNRFC2253: ""; - certSubjectDNRFC2253: ""; - certIssuerDNLegacy: ""; - certSubjectDNLegacy: ""; - certSerial: ""; - certIssuerSerial: ""; - certSKI: ""; - certIssuerSKI: ""; - certFingerprintSHA1: ""; - certFingerprintSHA256: ""; - certNotBefore: ""; - certNotAfter: ""; -} -/** Possible outcomes of TLS verification */ -declare type CertVerificationStatus = -/** Authentication succeeded */ -"SUCCESS" -/** No certificate was presented */ - | "NONE" -/** Failed because the certificate was self-signed */ - | "FAILED:self signed certificate" -/** Failed because the certificate failed a trust chain check */ - | "FAILED:unable to verify the first certificate" -/** Failed because the certificate not yet valid */ - | "FAILED:certificate is not yet valid" -/** Failed because the certificate is expired */ - | "FAILED:certificate has expired" -/** Failed for another unspecified reason */ - | "FAILED"; -/** - * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. - */ -declare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = 0 /** Unknown */ | 1 /** no keepalives (not found) */ | 2 /** no connection re-use, opening keepalive connection failed */ | 3 /** no connection re-use, keepalive accepted and saved */ | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ | 5; /** connection re-use, accepted by the origin server */ -/** ISO 3166-1 Alpha-2 codes */ -declare type Iso3166Alpha2Code = "AD" | "AE" | "AF" | "AG" | "AI" | "AL" | "AM" | "AO" | "AQ" | "AR" | "AS" | "AT" | "AU" | "AW" | "AX" | "AZ" | "BA" | "BB" | "BD" | "BE" | "BF" | "BG" | "BH" | "BI" | "BJ" | "BL" | "BM" | "BN" | "BO" | "BQ" | "BR" | "BS" | "BT" | "BV" | "BW" | "BY" | "BZ" | "CA" | "CC" | "CD" | "CF" | "CG" | "CH" | "CI" | "CK" | "CL" | "CM" | "CN" | "CO" | "CR" | "CU" | "CV" | "CW" | "CX" | "CY" | "CZ" | "DE" | "DJ" | "DK" | "DM" | "DO" | "DZ" | "EC" | "EE" | "EG" | "EH" | "ER" | "ES" | "ET" | "FI" | "FJ" | "FK" | "FM" | "FO" | "FR" | "GA" | "GB" | "GD" | "GE" | "GF" | "GG" | "GH" | "GI" | "GL" | "GM" | "GN" | "GP" | "GQ" | "GR" | "GS" | "GT" | "GU" | "GW" | "GY" | "HK" | "HM" | "HN" | "HR" | "HT" | "HU" | "ID" | "IE" | "IL" | "IM" | "IN" | "IO" | "IQ" | "IR" | "IS" | "IT" | "JE" | "JM" | "JO" | "JP" | "KE" | "KG" | "KH" | "KI" | "KM" | "KN" | "KP" | "KR" | "KW" | "KY" | "KZ" | "LA" | "LB" | "LC" | "LI" | "LK" | "LR" | "LS" | "LT" | "LU" | "LV" | "LY" | "MA" | "MC" | "MD" | "ME" | "MF" | "MG" | "MH" | "MK" | "ML" | "MM" | "MN" | "MO" | "MP" | "MQ" | "MR" | "MS" | "MT" | "MU" | "MV" | "MW" | "MX" | "MY" | "MZ" | "NA" | "NC" | "NE" | "NF" | "NG" | "NI" | "NL" | "NO" | "NP" | "NR" | "NU" | "NZ" | "OM" | "PA" | "PE" | "PF" | "PG" | "PH" | "PK" | "PL" | "PM" | "PN" | "PR" | "PS" | "PT" | "PW" | "PY" | "QA" | "RE" | "RO" | "RS" | "RU" | "RW" | "SA" | "SB" | "SC" | "SD" | "SE" | "SG" | "SH" | "SI" | "SJ" | "SK" | "SL" | "SM" | "SN" | "SO" | "SR" | "SS" | "ST" | "SV" | "SX" | "SY" | "SZ" | "TC" | "TD" | "TF" | "TG" | "TH" | "TJ" | "TK" | "TL" | "TM" | "TN" | "TO" | "TR" | "TT" | "TV" | "TW" | "TZ" | "UA" | "UG" | "UM" | "US" | "UY" | "UZ" | "VA" | "VC" | "VE" | "VG" | "VI" | "VN" | "VU" | "WF" | "WS" | "YE" | "YT" | "ZA" | "ZM" | "ZW"; -/** The 2-letter continent codes Cloudflare uses */ -declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; -type CfProperties = IncomingRequestCfProperties | RequestInitCfProperties; -interface D1Meta { - duration: number; - size_after: number; - rows_read: number; - rows_written: number; - last_row_id: number; - changed_db: boolean; - changes: number; - /** - * The region of the database instance that executed the query. - */ - served_by_region?: string; - /** - * The three letters airport code of the colo that executed the query. - */ - served_by_colo?: string; - /** - * True if-and-only-if the database instance that executed the query was the primary. - */ - served_by_primary?: boolean; - timings?: { - /** - * The duration of the SQL query execution by the database instance. It doesn't include any network time. - */ - sql_duration_ms: number; - }; - /** - * Number of total attempts to execute the query, due to automatic retries. - * Note: All other fields in the response like `timings` only apply to the last attempt. - */ - total_attempts?: number; -} -interface D1Response { - success: true; - meta: D1Meta & Record; - error?: never; -} -type D1Result = D1Response & { - results: T[]; -}; -interface D1ExecResult { - count: number; - duration: number; -} -type D1SessionConstraint = -// Indicates that the first query should go to the primary, and the rest queries -// using the same D1DatabaseSession will go to any replica that is consistent with -// the bookmark maintained by the session (returned by the first query). -'first-primary' -// Indicates that the first query can go anywhere (primary or replica), and the rest queries -// using the same D1DatabaseSession will go to any replica that is consistent with -// the bookmark maintained by the session (returned by the first query). - | 'first-unconstrained'; -type D1SessionBookmark = string; -declare abstract class D1Database { - prepare(query: string): D1PreparedStatement; - batch(statements: D1PreparedStatement[]): Promise[]>; - exec(query: string): Promise; - /** - * Creates a new D1 Session anchored at the given constraint or the bookmark. - * All queries executed using the created session will have sequential consistency, - * meaning that all writes done through the session will be visible in subsequent reads. - * - * @param constraintOrBookmark Either the session constraint or the explicit bookmark to anchor the created session. - */ - withSession(constraintOrBookmark?: D1SessionBookmark | D1SessionConstraint): D1DatabaseSession; - /** - * @deprecated dump() will be removed soon, only applies to deprecated alpha v1 databases. - */ - dump(): Promise; -} -declare abstract class D1DatabaseSession { - prepare(query: string): D1PreparedStatement; - batch(statements: D1PreparedStatement[]): Promise[]>; - /** - * @returns The latest session bookmark across all executed queries on the session. - * If no query has been executed yet, `null` is returned. - */ - getBookmark(): D1SessionBookmark | null; -} -declare abstract class D1PreparedStatement { - bind(...values: unknown[]): D1PreparedStatement; - first(colName: string): Promise; - first>(): Promise; - run>(): Promise>; - all>(): Promise>; - raw(options: { - columnNames: true; - }): Promise<[ - string[], - ...T[] - ]>; - raw(options?: { - columnNames?: false; - }): Promise; -} -// `Disposable` was added to TypeScript's standard lib types in version 5.2. -// To support older TypeScript versions, define an empty `Disposable` interface. -// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, -// but this will ensure type checking on older versions still passes. -// TypeScript's interface merging will ensure our empty interface is effectively -// ignored when `Disposable` is included in the standard lib. -interface Disposable { -} -/** - * The returned data after sending an email - */ -interface EmailSendResult { - /** - * The Email Message ID - */ - messageId: string; -} -/** - * An email message that can be sent from a Worker. - */ -interface EmailMessage { - /** - * Envelope From attribute of the email message. - */ - readonly from: string; - /** - * Envelope To attribute of the email message. - */ - readonly to: string; -} -/** - * An email message that is sent to a consumer Worker and can be rejected/forwarded. - */ -interface ForwardableEmailMessage extends EmailMessage { - /** - * Stream of the email message content. - */ - readonly raw: ReadableStream; - /** - * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). - */ - readonly headers: Headers; - /** - * Size of the email message content. - */ - readonly rawSize: number; - /** - * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. - * @param reason The reject reason. - * @returns void - */ - setReject(reason: string): void; - /** - * Forward this email message to a verified destination address of the account. - * @param rcptTo Verified destination address. - * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). - * @returns A promise that resolves when the email message is forwarded. - */ - forward(rcptTo: string, headers?: Headers): Promise; - /** - * Reply to the sender of this email message with a new EmailMessage object. - * @param message The reply message. - * @returns A promise that resolves when the email message is replied. - */ - reply(message: EmailMessage): Promise; -} -/** A file attachment for an email message */ -type EmailAttachment = { - disposition: 'inline'; - contentId: string; - filename: string; - type: string; - content: string | ArrayBuffer | ArrayBufferView; -} | { - disposition: 'attachment'; - contentId?: undefined; - filename: string; - type: string; - content: string | ArrayBuffer | ArrayBufferView; -}; -/** An Email Address */ -interface EmailAddress { - name: string; - email: string; -} -/** - * A binding that allows a Worker to send email messages. - */ -interface SendEmail { - send(message: EmailMessage): Promise; - send(builder: { - from: string | EmailAddress; - to: string | string[]; - subject: string; - replyTo?: string | EmailAddress; - cc?: string | string[]; - bcc?: string | string[]; - headers?: Record; - text?: string; - html?: string; - attachments?: EmailAttachment[]; - }): Promise; -} -declare abstract class EmailEvent extends ExtendableEvent { - readonly message: ForwardableEmailMessage; -} -declare type EmailExportedHandler = (message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext) => void | Promise; -declare module "cloudflare:email" { - let _EmailMessage: { - prototype: EmailMessage; - new (from: string, to: string, raw: ReadableStream | string): EmailMessage; - }; - export { _EmailMessage as EmailMessage }; -} -/** - * Hello World binding to serve as an explanatory example. DO NOT USE - */ -interface HelloWorldBinding { - /** - * Retrieve the current stored value - */ - get(): Promise<{ - value: string; - ms?: number; - }>; - /** - * Set a new stored value - */ - set(value: string): Promise; -} -interface Hyperdrive { - /** - * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. - * - * Calling this method returns an identical socket to if you call - * `connect("host:port")` using the `host` and `port` fields from this object. - * Pick whichever approach works better with your preferred DB client library. - * - * Note that this socket is not yet authenticated -- it's expected that your - * code (or preferably, the client library of your choice) will authenticate - * using the information in this class's readonly fields. - */ - connect(): Socket; - /** - * A valid DB connection string that can be passed straight into the typical - * client library/driver/ORM. This will typically be the easiest way to use - * Hyperdrive. - */ - readonly connectionString: string; - /* - * A randomly generated hostname that is only valid within the context of the - * currently running Worker which, when passed into `connect()` function from - * the "cloudflare:sockets" module, will connect to the Hyperdrive instance - * for your database. - */ - readonly host: string; - /* - * The port that must be paired the the host field when connecting. - */ - readonly port: number; - /* - * The username to use when authenticating to your database via Hyperdrive. - * Unlike the host and password, this will be the same every time - */ - readonly user: string; - /* - * The randomly generated password to use when authenticating to your - * database via Hyperdrive. Like the host field, this password is only valid - * within the context of the currently running Worker instance from which - * it's read. - */ - readonly password: string; - /* - * The name of the database to connect to. - */ - readonly database: string; -} -// Copyright (c) 2024 Cloudflare, Inc. -// Licensed under the Apache 2.0 license found in the LICENSE file or at: -// https://opensource.org/licenses/Apache-2.0 -type ImageInfoResponse = { - format: 'image/svg+xml'; -} | { - format: string; - fileSize: number; - width: number; - height: number; -}; -type ImageTransform = { - width?: number; - height?: number; - background?: string; - blur?: number; - border?: { - color?: string; - width?: number; - } | { - top?: number; - bottom?: number; - left?: number; - right?: number; - }; - brightness?: number; - contrast?: number; - fit?: 'scale-down' | 'contain' | 'pad' | 'squeeze' | 'cover' | 'crop'; - flip?: 'h' | 'v' | 'hv'; - gamma?: number; - segment?: 'foreground'; - gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | { - x?: number; - y?: number; - mode: 'remainder' | 'box-center'; - }; - rotate?: 0 | 90 | 180 | 270; - saturation?: number; - sharpen?: number; - trim?: 'border' | { - top?: number; - bottom?: number; - left?: number; - right?: number; - width?: number; - height?: number; - border?: boolean | { - color?: string; - tolerance?: number; - keep?: number; - }; - }; -}; -type ImageDrawOptions = { - opacity?: number; - repeat?: boolean | string; - top?: number; - left?: number; - bottom?: number; - right?: number; -}; -type ImageInputOptions = { - encoding?: 'base64'; -}; -type ImageOutputOptions = { - format: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp' | 'image/avif' | 'rgb' | 'rgba'; - quality?: number; - background?: string; - anim?: boolean; -}; -interface ImageMetadata { - id: string; - filename?: string; - uploaded?: string; - requireSignedURLs: boolean; - meta?: Record; - variants: string[]; - draft?: boolean; - creator?: string; -} -interface ImageUploadOptions { - id?: string; - filename?: string; - requireSignedURLs?: boolean; - metadata?: Record; - creator?: string; - encoding?: 'base64'; -} -interface ImageUpdateOptions { - requireSignedURLs?: boolean; - metadata?: Record; - creator?: string; -} -interface ImageListOptions { - limit?: number; - cursor?: string; - sortOrder?: 'asc' | 'desc'; - creator?: string; -} -interface ImageList { - images: ImageMetadata[]; - cursor?: string; - listComplete: boolean; -} -interface HostedImagesBinding { - /** - * Get detailed metadata for a hosted image - * @param imageId The ID of the image (UUID or custom ID) - * @returns Image metadata, or null if not found - */ - details(imageId: string): Promise; - /** - * Get the raw image data for a hosted image - * @param imageId The ID of the image (UUID or custom ID) - * @returns ReadableStream of image bytes, or null if not found - */ - image(imageId: string): Promise | null>; - /** - * Upload a new hosted image - * @param image The image file to upload - * @param options Upload configuration - * @returns Metadata for the uploaded image - * @throws {@link ImagesError} if upload fails - */ - upload(image: ReadableStream | ArrayBuffer, options?: ImageUploadOptions): Promise; - /** - * Update hosted image metadata - * @param imageId The ID of the image - * @param options Properties to update - * @returns Updated image metadata - * @throws {@link ImagesError} if update fails - */ - update(imageId: string, options: ImageUpdateOptions): Promise; - /** - * Delete a hosted image - * @param imageId The ID of the image - * @returns True if deleted, false if not found - */ - delete(imageId: string): Promise; - /** - * List hosted images with pagination - * @param options List configuration - * @returns List of images with pagination info - * @throws {@link ImagesError} if list fails - */ - list(options?: ImageListOptions): Promise; -} -interface ImagesBinding { - /** - * Get image metadata (type, width and height) - * @throws {@link ImagesError} with code 9412 if input is not an image - * @param stream The image bytes - */ - info(stream: ReadableStream, options?: ImageInputOptions): Promise; - /** - * Begin applying a series of transformations to an image - * @param stream The image bytes - * @returns A transform handle - */ - input(stream: ReadableStream, options?: ImageInputOptions): ImageTransformer; - /** - * Access hosted images CRUD operations - */ - readonly hosted: HostedImagesBinding; -} -interface ImageTransformer { - /** - * Apply transform next, returning a transform handle. - * You can then apply more transformations, draw, or retrieve the output. - * @param transform - */ - transform(transform: ImageTransform): ImageTransformer; - /** - * Draw an image on this transformer, returning a transform handle. - * You can then apply more transformations, draw, or retrieve the output. - * @param image The image (or transformer that will give the image) to draw - * @param options The options configuring how to draw the image - */ - draw(image: ReadableStream | ImageTransformer, options?: ImageDrawOptions): ImageTransformer; - /** - * Retrieve the image that results from applying the transforms to the - * provided input - * @param options Options that apply to the output e.g. output format - */ - output(options: ImageOutputOptions): Promise; -} -type ImageTransformationOutputOptions = { - encoding?: 'base64'; -}; -interface ImageTransformationResult { - /** - * The image as a response, ready to store in cache or return to users - */ - response(): Response; - /** - * The content type of the returned image - */ - contentType(): string; - /** - * The bytes of the response - */ - image(options?: ImageTransformationOutputOptions): ReadableStream; -} -interface ImagesError extends Error { - readonly code: number; - readonly message: string; - readonly stack?: string; -} -/** - * Media binding for transforming media streams. - * Provides the entry point for media transformation operations. - */ -interface MediaBinding { - /** - * Creates a media transformer from an input stream. - * @param media - The input media bytes - * @returns A MediaTransformer instance for applying transformations - */ - input(media: ReadableStream): MediaTransformer; -} -/** - * Media transformer for applying transformation operations to media content. - * Handles sizing, fitting, and other input transformation parameters. - */ -interface MediaTransformer { - /** - * Applies transformation options to the media content. - * @param transform - Configuration for how the media should be transformed - * @returns A generator for producing the transformed media output - */ - transform(transform?: MediaTransformationInputOptions): MediaTransformationGenerator; - /** - * Generates the final media output with specified options. - * @param output - Configuration for the output format and parameters - * @returns The final transformation result containing the transformed media - */ - output(output?: MediaTransformationOutputOptions): MediaTransformationResult; -} -/** - * Generator for producing media transformation results. - * Configures the output format and parameters for the transformed media. - */ -interface MediaTransformationGenerator { - /** - * Generates the final media output with specified options. - * @param output - Configuration for the output format and parameters - * @returns The final transformation result containing the transformed media - */ - output(output?: MediaTransformationOutputOptions): MediaTransformationResult; -} -/** - * Result of a media transformation operation. - * Provides multiple ways to access the transformed media content. - */ -interface MediaTransformationResult { - /** - * Returns the transformed media as a readable stream of bytes. - * @returns A promise containing a readable stream with the transformed media - */ - media(): Promise>; - /** - * Returns the transformed media as an HTTP response object. - * @returns The transformed media as a Promise, ready to store in cache or return to users - */ - response(): Promise; - /** - * Returns the MIME type of the transformed media. - * @returns A promise containing the content type string (e.g., 'image/jpeg', 'video/mp4') - */ - contentType(): Promise; -} -/** - * Configuration options for transforming media input. - * Controls how the media should be resized and fitted. - */ -type MediaTransformationInputOptions = { - /** How the media should be resized to fit the specified dimensions */ - fit?: 'contain' | 'cover' | 'scale-down'; - /** Target width in pixels */ - width?: number; - /** Target height in pixels */ - height?: number; -}; -/** - * Configuration options for Media Transformations output. - * Controls the format, timing, and type of the generated output. - */ -type MediaTransformationOutputOptions = { - /** - * Output mode determining the type of media to generate - */ - mode?: 'video' | 'spritesheet' | 'frame' | 'audio'; - /** Whether to include audio in the output */ - audio?: boolean; - /** - * Starting timestamp for frame extraction or start time for clips. (e.g. '2s'). - */ - time?: string; - /** - * Duration for video clips, audio extraction, and spritesheet generation (e.g. '5s'). - */ - duration?: string; - /** - * Number of frames in the spritesheet. - */ - imageCount?: number; - /** - * Output format for the generated media. - */ - format?: 'jpg' | 'png' | 'm4a'; -}; -/** - * Error object for media transformation operations. - * Extends the standard Error interface with additional media-specific information. - */ -interface MediaError extends Error { - readonly code: number; - readonly message: string; - readonly stack?: string; -} -declare module 'cloudflare:node' { - interface NodeStyleServer { - listen(...args: unknown[]): this; - address(): { - port?: number | null | undefined; - }; - } - export function httpServerHandler(port: number): ExportedHandler; - export function httpServerHandler(options: { - port: number; - }): ExportedHandler; - export function httpServerHandler(server: NodeStyleServer): ExportedHandler; -} -type Params

= Record; -type EventContext = { - request: Request>; - functionPath: string; - waitUntil: (promise: Promise) => void; - passThroughOnException: () => void; - next: (input?: Request | string, init?: RequestInit) => Promise; - env: Env & { - ASSETS: { - fetch: typeof fetch; - }; - }; - params: Params

; - data: Data; -}; -type PagesFunction = Record> = (context: EventContext) => Response | Promise; -type EventPluginContext = { - request: Request>; - functionPath: string; - waitUntil: (promise: Promise) => void; - passThroughOnException: () => void; - next: (input?: Request | string, init?: RequestInit) => Promise; - env: Env & { - ASSETS: { - fetch: typeof fetch; - }; - }; - params: Params

; - data: Data; - pluginArgs: PluginArgs; -}; -type PagesPluginFunction = Record, PluginArgs = unknown> = (context: EventPluginContext) => Response | Promise; -declare module "assets:*" { - export const onRequest: PagesFunction; -} -// Copyright (c) 2022-2023 Cloudflare, Inc. -// Licensed under the Apache 2.0 license found in the LICENSE file or at: -// https://opensource.org/licenses/Apache-2.0 -declare module "cloudflare:pipelines" { - export abstract class PipelineTransformationEntrypoint { - protected env: Env; - protected ctx: ExecutionContext; - constructor(ctx: ExecutionContext, env: Env); - /** - * run receives an array of PipelineRecord which can be - * transformed and returned to the pipeline - * @param records Incoming records from the pipeline to be transformed - * @param metadata Information about the specific pipeline calling the transformation entrypoint - * @returns A promise containing the transformed PipelineRecord array - */ - public run(records: I[], metadata: PipelineBatchMetadata): Promise; - } - export type PipelineRecord = Record; - export type PipelineBatchMetadata = { - pipelineId: string; - pipelineName: string; - }; - export interface Pipeline { - /** - * The Pipeline interface represents the type of a binding to a Pipeline - * - * @param records The records to send to the pipeline - */ - send(records: T[]): Promise; - } -} -// PubSubMessage represents an incoming PubSub message. -// The message includes metadata about the broker, the client, and the payload -// itself. -// https://developers.cloudflare.com/pub-sub/ -interface PubSubMessage { - // Message ID - readonly mid: number; - // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT - readonly broker: string; - // The MQTT topic the message was sent on. - readonly topic: string; - // The client ID of the client that published this message. - readonly clientId: string; - // The unique identifier (JWT ID) used by the client to authenticate, if token - // auth was used. - readonly jti?: string; - // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker - // received the message from the client. - readonly receivedAt: number; - // An (optional) string with the MIME type of the payload, if set by the - // client. - readonly contentType: string; - // Set to 1 when the payload is a UTF-8 string - // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 - readonly payloadFormatIndicator: number; - // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. - // You can use payloadFormatIndicator to inspect this before decoding. - payload: string | Uint8Array; -} -// JsonWebKey extended by kid parameter -interface JsonWebKeyWithKid extends JsonWebKey { - // Key Identifier of the JWK - readonly kid: string; -} -interface RateLimitOptions { - key: string; -} -interface RateLimitOutcome { - success: boolean; -} -interface RateLimit { - /** - * Rate limit a request based on the provided options. - * @see https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/ - * @returns A promise that resolves with the outcome of the rate limit. - */ - limit(options: RateLimitOptions): Promise; -} -// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need -// to referenced by `Fetcher`. This is included in the "importable" version of the types which -// strips all `module` blocks. -declare namespace Rpc { - // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. - // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. - // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to - // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) - export const __RPC_STUB_BRAND: '__RPC_STUB_BRAND'; - export const __RPC_TARGET_BRAND: '__RPC_TARGET_BRAND'; - export const __WORKER_ENTRYPOINT_BRAND: '__WORKER_ENTRYPOINT_BRAND'; - export const __DURABLE_OBJECT_BRAND: '__DURABLE_OBJECT_BRAND'; - export const __WORKFLOW_ENTRYPOINT_BRAND: '__WORKFLOW_ENTRYPOINT_BRAND'; - export interface RpcTargetBranded { - [__RPC_TARGET_BRAND]: never; - } - export interface WorkerEntrypointBranded { - [__WORKER_ENTRYPOINT_BRAND]: never; - } - export interface DurableObjectBranded { - [__DURABLE_OBJECT_BRAND]: never; - } - export interface WorkflowEntrypointBranded { - [__WORKFLOW_ENTRYPOINT_BRAND]: never; - } - export type EntrypointBranded = WorkerEntrypointBranded | DurableObjectBranded | WorkflowEntrypointBranded; - // Types that can be used through `Stub`s - export type Stubable = RpcTargetBranded | ((...args: any[]) => any); - // Types that can be passed over RPC - // The reason for using a generic type here is to build a serializable subset of structured - // cloneable composite types. This allows types defined with the "interface" keyword to pass the - // serializable check as well. Otherwise, only types defined with the "type" keyword would pass. - type Serializable = - // Structured cloneables - BaseType - // Structured cloneable composites - | Map ? Serializable : never, T extends Map ? Serializable : never> | Set ? Serializable : never> | ReadonlyArray ? Serializable : never> | { - [K in keyof T]: K extends number | string ? Serializable : never; - } - // Special types - | Stub - // Serialized as stubs, see `Stubify` - | Stubable; - // Base type for all RPC stubs, including common memory management methods. - // `T` is used as a marker type for unwrapping `Stub`s later. - interface StubBase extends Disposable { - [__RPC_STUB_BRAND]: T; - dup(): this; - } - export type Stub = Provider & StubBase; - // This represents all the types that can be sent as-is over an RPC boundary - type BaseType = void | undefined | null | boolean | number | bigint | string | TypedArray | ArrayBuffer | DataView | Date | Error | RegExp | ReadableStream | WritableStream | Request | Response | Headers; - // Recursively rewrite all `Stubable` types with `Stub`s - // prettier-ignore - type Stubify = T extends Stubable ? Stub : T extends Map ? Map, Stubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { - [key: string | number]: any; - } ? { - [K in keyof T]: Stubify; - } : T; - // Recursively rewrite all `Stub`s with the corresponding `T`s. - // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: - // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. - // prettier-ignore - type Unstubify = T extends StubBase ? V : T extends Map ? Map, Unstubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { - [key: string | number]: unknown; - } ? { - [K in keyof T]: Unstubify; - } : T; - type UnstubifyAll = { - [I in keyof A]: Unstubify; - }; - // Utility type for adding `Provider`/`Disposable`s to `object` types only. - // Note `unknown & T` is equivalent to `T`. - type MaybeProvider = T extends object ? Provider : unknown; - type MaybeDisposable = T extends object ? Disposable : unknown; - // Type for method return or property on an RPC interface. - // - Stubable types are replaced by stubs. - // - Serializable types are passed by value, with stubable types replaced by stubs - // and a top-level `Disposer`. - // Everything else can't be passed over PRC. - // Technically, we use custom thenables here, but they quack like `Promise`s. - // Intersecting with `(Maybe)Provider` allows pipelining. - // prettier-ignore - type Result = R extends Stubable ? Promise> & Provider : R extends Serializable ? Promise & MaybeDisposable> & MaybeProvider : never; - // Type for method or property on an RPC interface. - // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. - // Unwrapping `Stub`s allows calling with `Stubable` arguments. - // For properties, rewrite types to be `Result`s. - // In each case, unwrap `Promise`s. - type MethodOrProperty = V extends (...args: infer P) => infer R ? (...args: UnstubifyAll

) => Result> : Result>; - // Type for the callable part of an `Provider` if `T` is callable. - // This is intersected with methods/properties. - type MaybeCallableProvider = T extends (...args: any[]) => any ? MethodOrProperty : unknown; - // Base type for all other types providing RPC-like interfaces. - // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. - // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. - export type Provider = MaybeCallableProvider & Pick<{ - [K in keyof T]: MethodOrProperty; - }, Exclude>>; -} -declare namespace Cloudflare { - // Type of `env`. - // - // The specific project can extend `Env` by redeclaring it in project-specific files. Typescript - // will merge all declarations. - // - // You can use `wrangler types` to generate the `Env` type automatically. - interface Env { - } - // Project-specific parameters used to inform types. - // - // This interface is, again, intended to be declared in project-specific files, and then that - // declaration will be merged with this one. - // - // A project should have a declaration like this: - // - // interface GlobalProps { - // // Declares the main module's exports. Used to populate Cloudflare.Exports aka the type - // // of `ctx.exports`. - // mainModule: typeof import("my-main-module"); - // - // // Declares which of the main module's exports are configured with durable storage, and - // // thus should behave as Durable Object namsepace bindings. - // durableNamespaces: "MyDurableObject" | "AnotherDurableObject"; - // } - // - // You can use `wrangler types` to generate `GlobalProps` automatically. - interface GlobalProps { - } - // Evaluates to the type of a property in GlobalProps, defaulting to `Default` if it is not - // present. - type GlobalProp = K extends keyof GlobalProps ? GlobalProps[K] : Default; - // The type of the program's main module exports, if known. Requires `GlobalProps` to declare the - // `mainModule` property. - type MainModule = GlobalProp<"mainModule", {}>; - // The type of ctx.exports, which contains loopback bindings for all top-level exports. - type Exports = { - [K in keyof MainModule]: LoopbackForExport - // If the export is listed in `durableNamespaces`, then it is also a - // DurableObjectNamespace. - & (K extends GlobalProp<"durableNamespaces", never> ? MainModule[K] extends new (...args: any[]) => infer DoInstance ? DoInstance extends Rpc.DurableObjectBranded ? DurableObjectNamespace : DurableObjectNamespace : DurableObjectNamespace : {}); - }; -} -declare namespace CloudflareWorkersModule { - export type RpcStub = Rpc.Stub; - export const RpcStub: { - new (value: T): Rpc.Stub; - }; - export abstract class RpcTarget implements Rpc.RpcTargetBranded { - [Rpc.__RPC_TARGET_BRAND]: never; - } - // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC - export abstract class WorkerEntrypoint implements Rpc.WorkerEntrypointBranded { - [Rpc.__WORKER_ENTRYPOINT_BRAND]: never; - protected ctx: ExecutionContext; - protected env: Env; - constructor(ctx: ExecutionContext, env: Env); - email?(message: ForwardableEmailMessage): void | Promise; - fetch?(request: Request): Response | Promise; - queue?(batch: MessageBatch): void | Promise; - scheduled?(controller: ScheduledController): void | Promise; - tail?(events: TraceItem[]): void | Promise; - tailStream?(event: TailStream.TailEvent): TailStream.TailEventHandlerType | Promise; - test?(controller: TestController): void | Promise; - trace?(traces: TraceItem[]): void | Promise; - } - export abstract class DurableObject implements Rpc.DurableObjectBranded { - [Rpc.__DURABLE_OBJECT_BRAND]: never; - protected ctx: DurableObjectState; - protected env: Env; - constructor(ctx: DurableObjectState, env: Env); - alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; - fetch?(request: Request): Response | Promise; - webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; - webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise; - webSocketError?(ws: WebSocket, error: unknown): void | Promise; - } - export type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; - export type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number; - export type WorkflowDelayDuration = WorkflowSleepDuration; - export type WorkflowTimeoutDuration = WorkflowSleepDuration; - export type WorkflowRetentionDuration = WorkflowSleepDuration; - export type WorkflowBackoff = 'constant' | 'linear' | 'exponential'; - export type WorkflowStepConfig = { - retries?: { - limit: number; - delay: WorkflowDelayDuration | number; - backoff?: WorkflowBackoff; - }; - timeout?: WorkflowTimeoutDuration | number; - }; - export type WorkflowEvent = { - payload: Readonly; - timestamp: Date; - instanceId: string; - }; - export type WorkflowStepEvent = { - payload: Readonly; - timestamp: Date; - type: string; - }; - export type WorkflowStepContext = { - attempt: number; - }; - export abstract class WorkflowStep { - do>(name: string, callback: (ctx: WorkflowStepContext) => Promise): Promise; - do>(name: string, config: WorkflowStepConfig, callback: (ctx: WorkflowStepContext) => Promise): Promise; - sleep: (name: string, duration: WorkflowSleepDuration) => Promise; - sleepUntil: (name: string, timestamp: Date | number) => Promise; - waitForEvent>(name: string, options: { - type: string; - timeout?: WorkflowTimeoutDuration | number; - }): Promise>; - } - export type WorkflowInstanceStatus = 'queued' | 'running' | 'paused' | 'errored' | 'terminated' | 'complete' | 'waiting' | 'waitingForPause' | 'unknown'; - export abstract class WorkflowEntrypoint | unknown = unknown> implements Rpc.WorkflowEntrypointBranded { - [Rpc.__WORKFLOW_ENTRYPOINT_BRAND]: never; - protected ctx: ExecutionContext; - protected env: Env; - constructor(ctx: ExecutionContext, env: Env); - run(event: Readonly>, step: WorkflowStep): Promise; - } - export function waitUntil(promise: Promise): void; - export function withEnv(newEnv: unknown, fn: () => unknown): unknown; - export function withExports(newExports: unknown, fn: () => unknown): unknown; - export function withEnvAndExports(newEnv: unknown, newExports: unknown, fn: () => unknown): unknown; - export const env: Cloudflare.Env; - export const exports: Cloudflare.Exports; -} -declare module 'cloudflare:workers' { - export = CloudflareWorkersModule; -} -interface SecretsStoreSecret { - /** - * Get a secret from the Secrets Store, returning a string of the secret value - * if it exists, or throws an error if it does not exist - */ - get(): Promise; -} -declare module "cloudflare:sockets" { - function _connect(address: string | SocketAddress, options?: SocketOptions): Socket; - export { _connect as connect }; -} -/** - * Binding entrypoint for Cloudflare Stream. - * - * Usage: - * - Binding-level operations: - * `await env.STREAM.videos.upload` - * `await env.STREAM.videos.createDirectUpload` - * `await env.STREAM.videos.*` - * `await env.STREAM.watermarks.*` - * - Per-video operations: - * `await env.STREAM.video(id).downloads.*` - * `await env.STREAM.video(id).captions.*` - * - * Example usage: - * ```ts - * await env.STREAM.video(id).downloads.generate(); - * - * const video = env.STREAM.video(id) - * const captions = video.captions.list(); - * const videoDetails = video.details() - * ``` - */ -interface StreamBinding { - /** - * Returns a handle scoped to a single video for per-video operations. - * @param id The unique identifier for the video. - * @returns A handle for per-video operations. - */ - video(id: string): StreamVideoHandle; - /** - * Uploads a new video from a File. - * @param file The video file to upload. - * @returns The uploaded video details. - * @throws {BadRequestError} if the upload parameter is invalid - * @throws {QuotaReachedError} if the account storage capacity is exceeded - * @throws {MaxFileSizeError} if the file size is too large - * @throws {RateLimitedError} if the server received too many requests - * @throws {InternalError} if an unexpected error occurs - */ - upload(file: File): Promise; - /** - * Uploads a new video from a provided URL. - * @param url The URL to upload from. - * @param params Optional upload parameters. - * @returns The uploaded video details. - * @throws {BadRequestError} if the upload parameter is invalid or the URL is invalid - * @throws {QuotaReachedError} if the account storage capacity is exceeded - * @throws {MaxFileSizeError} if the file size is too large - * @throws {RateLimitedError} if the server received too many requests - * @throws {AlreadyUploadedError} if a video was already uploaded to this URL - * @throws {InternalError} if an unexpected error occurs - */ - upload(url: string, params?: StreamUrlUploadParams): Promise; - /** - * Creates a direct upload that allows video uploads without an API key. - * @param params Parameters for the direct upload - * @returns The direct upload details. - * @throws {BadRequestError} if the parameters are invalid - * @throws {RateLimitedError} if the server received too many requests - * @throws {InternalError} if an unexpected error occurs - */ - createDirectUpload(params: StreamDirectUploadCreateParams): Promise; - videos: StreamVideos; - watermarks: StreamWatermarks; -} -/** - * Handle for operations scoped to a single Stream video. - */ -interface StreamVideoHandle { - /** - * The unique identifier for the video. - */ - id: string; - /** - * Get a full videos details - * @returns The full video details. - * @throws {NotFoundError} if the video is not found - * @throws {InternalError} if an unexpected error occurs - */ - details(): Promise; - /** - * Update details for a single video. - * @param params The fields to update for the video. - * @returns The updated video details. - * @throws {NotFoundError} if the video is not found - * @throws {BadRequestError} if the parameters are invalid - * @throws {InternalError} if an unexpected error occurs - */ - update(params: StreamUpdateVideoParams): Promise; - /** - * Deletes a video and its copies from Cloudflare Stream. - * @returns A promise that resolves when deletion completes. - * @throws {NotFoundError} if the video is not found - * @throws {InternalError} if an unexpected error occurs - */ - delete(): Promise; - /** - * Creates a signed URL token for a video. - * @returns The signed token that was created. - * @throws {InternalError} if the signing key cannot be retrieved or the token cannot be signed - */ - generateToken(): Promise; - downloads: StreamScopedDownloads; - captions: StreamScopedCaptions; -} -interface StreamVideo { - /** - * The unique identifier for the video. - */ - id: string; - /** - * A user-defined identifier for the media creator. - */ - creator: string | null; - /** - * The thumbnail URL for the video. - */ - thumbnail: string; - /** - * The thumbnail timestamp percentage. - */ - thumbnailTimestampPct: number; - /** - * Indicates whether the video is ready to stream. - */ - readyToStream: boolean; - /** - * The date and time the video became ready to stream. - */ - readyToStreamAt: string | null; - /** - * Processing status information. - */ - status: StreamVideoStatus; - /** - * A user modifiable key-value store. - */ - meta: Record; - /** - * The date and time the video was created. - */ - created: string; - /** - * The date and time the video was last modified. - */ - modified: string; - /** - * The date and time at which the video will be deleted. - */ - scheduledDeletion: string | null; - /** - * The size of the video in bytes. - */ - size: number; - /** - * The preview URL for the video. - */ - preview?: string; - /** - * Origins allowed to display the video. - */ - allowedOrigins: Array; - /** - * Indicates whether signed URLs are required. - */ - requireSignedURLs: boolean | null; - /** - * The date and time the video was uploaded. - */ - uploaded: string | null; - /** - * The date and time when the upload URL expires. - */ - uploadExpiry: string | null; - /** - * The maximum size in bytes for direct uploads. - */ - maxSizeBytes: number | null; - /** - * The maximum duration in seconds for direct uploads. - */ - maxDurationSeconds: number | null; - /** - * The video duration in seconds. -1 indicates unknown. - */ - duration: number; - /** - * Input metadata for the original upload. - */ - input: StreamVideoInput; - /** - * Playback URLs for the video. - */ - hlsPlaybackUrl: string; - dashPlaybackUrl: string; - /** - * The watermark applied to the video, if any. - */ - watermark: StreamWatermark | null; - /** - * The live input id associated with the video, if any. - */ - liveInputId?: string | null; - /** - * The source video id if this is a clip. - */ - clippedFromId: string | null; - /** - * Public details associated with the video. - */ - publicDetails: StreamPublicDetails | null; -} -type StreamVideoStatus = { - /** - * The current processing state. - */ - state: string; - /** - * The current processing step. - */ - step?: string; - /** - * The percent complete as a string. - */ - pctComplete?: string; - /** - * An error reason code, if applicable. - */ - errorReasonCode: string; - /** - * An error reason text, if applicable. - */ - errorReasonText: string; -}; -type StreamVideoInput = { - /** - * The input width in pixels. - */ - width: number; - /** - * The input height in pixels. - */ - height: number; -}; -type StreamPublicDetails = { - /** - * The public title for the video. - */ - title: string | null; - /** - * The public share link. - */ - share_link: string | null; - /** - * The public channel link. - */ - channel_link: string | null; - /** - * The public logo URL. - */ - logo: string | null; -}; -type StreamDirectUpload = { - /** - * The URL an unauthenticated upload can use for a single multipart request. - */ - uploadURL: string; - /** - * A Cloudflare-generated unique identifier for a media item. - */ - id: string; - /** - * The watermark profile applied to the upload. - */ - watermark: StreamWatermark | null; - /** - * The scheduled deletion time, if any. - */ - scheduledDeletion: string | null; -}; -type StreamDirectUploadCreateParams = { - /** - * The maximum duration in seconds for a video upload. - */ - maxDurationSeconds: number; - /** - * The date and time after upload when videos will not be accepted. - */ - expiry?: string; - /** - * A user-defined identifier for the media creator. - */ - creator?: string; - /** - * A user modifiable key-value store used to reference other systems of record for - * managing videos. - */ - meta?: Record; - /** - * Lists the origins allowed to display the video. - */ - allowedOrigins?: Array; - /** - * Indicates whether the video can be accessed using the id. When set to `true`, - * a signed token must be generated with a signing key to view the video. - */ - requireSignedURLs?: boolean; - /** - * The thumbnail timestamp percentage. - */ - thumbnailTimestampPct?: number; - /** - * The date and time at which the video will be deleted. Include `null` to remove - * a scheduled deletion. - */ - scheduledDeletion?: string | null; - /** - * The watermark profile to apply. - */ - watermark?: StreamDirectUploadWatermark; -}; -type StreamDirectUploadWatermark = { - /** - * The unique identifier for the watermark profile. - */ - id: string; -}; -type StreamUrlUploadParams = { - /** - * Lists the origins allowed to display the video. Enter allowed origin - * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the - * video to be viewed on any origin. - */ - allowedOrigins?: Array; - /** - * A user-defined identifier for the media creator. - */ - creator?: string; - /** - * A user modifiable key-value store used to reference other systems of - * record for managing videos. - */ - meta?: Record; - /** - * Indicates whether the video can be a accessed using the id. When - * set to `true`, a signed token must be generated with a signing key to view the - * video. - */ - requireSignedURLs?: boolean; - /** - * Indicates the date and time at which the video will be deleted. Omit - * the field to indicate no change, or include with a `null` value to remove an - * existing scheduled deletion. If specified, must be at least 30 days from upload - * time. - */ - scheduledDeletion?: string | null; - /** - * The timestamp for a thumbnail image calculated as a percentage value - * of the video's duration. To convert from a second-wise timestamp to a - * percentage, divide the desired timestamp by the total duration of the video. If - * this value is not set, the default thumbnail image is taken from 0s of the - * video. - */ - thumbnailTimestampPct?: number; - /** - * The identifier for the watermark profile - */ - watermarkId?: string; -}; -interface StreamScopedCaptions { - /** - * Uploads the caption or subtitle file to the endpoint for a specific BCP47 language. - * One caption or subtitle file per language is allowed. - * @param language The BCP 47 language tag for the caption or subtitle. - * @param file The caption or subtitle file to upload. - * @returns The created caption entry. - * @throws {NotFoundError} if the video is not found - * @throws {BadRequestError} if the language or file is invalid - * @throws {MaxFileSizeError} if the file size is too large - * @throws {InternalError} if an unexpected error occurs - */ - upload(language: string, file: File): Promise; - /** - * Generate captions or subtitles for the provided language via AI. - * @param language The BCP 47 language tag to generate. - * @returns The generated caption entry. - * @throws {NotFoundError} if the video is not found - * @throws {BadRequestError} if the language is invalid - * @throws {StreamError} if a generated caption already exists - * @throws {StreamError} if the video duration is too long - * @throws {StreamError} if the video is missing audio - * @throws {StreamError} if the requested language is not supported - * @throws {InternalError} if an unexpected error occurs - */ - generate(language: string): Promise; - /** - * Lists the captions or subtitles. - * Use the language parameter to filter by a specific language. - * @param language The optional BCP 47 language tag to filter by. - * @returns The list of captions or subtitles. - * @throws {NotFoundError} if the video or caption is not found - * @throws {InternalError} if an unexpected error occurs - */ - list(language?: string): Promise; - /** - * Removes the captions or subtitles from a video. - * @param language The BCP 47 language tag to remove. - * @returns A promise that resolves when deletion completes. - * @throws {NotFoundError} if the video or caption is not found - * @throws {InternalError} if an unexpected error occurs - */ - delete(language: string): Promise; -} -interface StreamScopedDownloads { - /** - * Generates a download for a video when a video is ready to view. Available - * types are `default` and `audio`. Defaults to `default` when omitted. - * @param downloadType The download type to create. - * @returns The current downloads for the video. - * @throws {NotFoundError} if the video is not found - * @throws {BadRequestError} if the download type is invalid - * @throws {StreamError} if the video duration is too long to generate a download - * @throws {StreamError} if the video is not ready to stream - * @throws {InternalError} if an unexpected error occurs - */ - generate(downloadType?: StreamDownloadType): Promise; - /** - * Lists the downloads created for a video. - * @returns The current downloads for the video. - * @throws {NotFoundError} if the video or downloads are not found - * @throws {InternalError} if an unexpected error occurs - */ - get(): Promise; - /** - * Delete the downloads for a video. Available types are `default` and `audio`. - * Defaults to `default` when omitted. - * @param downloadType The download type to delete. - * @returns A promise that resolves when deletion completes. - * @throws {NotFoundError} if the video or downloads are not found - * @throws {InternalError} if an unexpected error occurs - */ - delete(downloadType?: StreamDownloadType): Promise; -} -interface StreamVideos { - /** - * Lists all videos in a users account. - * @returns The list of videos. - * @throws {BadRequestError} if the parameters are invalid - * @throws {InternalError} if an unexpected error occurs - */ - list(params?: StreamVideosListParams): Promise; -} -interface StreamWatermarks { - /** - * Generate a new watermark profile - * @param file The image file to upload - * @param params The watermark creation parameters. - * @returns The created watermark profile. - * @throws {BadRequestError} if the parameters are invalid - * @throws {InvalidURLError} if the URL is invalid - * @throws {MaxFileSizeError} if the file size is too large - * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached - * @throws {InternalError} if an unexpected error occurs - */ - generate(file: File, params: StreamWatermarkCreateParams): Promise; - /** - * Generate a new watermark profile - * @param url The image url to upload - * @param params The watermark creation parameters. - * @returns The created watermark profile. - * @throws {BadRequestError} if the parameters are invalid - * @throws {InvalidURLError} if the URL is invalid - * @throws {MaxFileSizeError} if the file size is too large - * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached - * @throws {InternalError} if an unexpected error occurs - */ - generate(url: string, params: StreamWatermarkCreateParams): Promise; - /** - * Lists all watermark profiles for an account. - * @returns The list of watermark profiles. - * @throws {InternalError} if an unexpected error occurs - */ - list(): Promise; - /** - * Retrieves details for a single watermark profile. - * @param watermarkId The watermark profile identifier. - * @returns The watermark profile details. - * @throws {NotFoundError} if the watermark is not found - * @throws {InternalError} if an unexpected error occurs - */ - get(watermarkId: string): Promise; - /** - * Deletes a watermark profile. - * @param watermarkId The watermark profile identifier. - * @returns A promise that resolves when deletion completes. - * @throws {NotFoundError} if the watermark is not found - * @throws {InternalError} if an unexpected error occurs - */ - delete(watermarkId: string): Promise; -} -type StreamUpdateVideoParams = { - /** - * Lists the origins allowed to display the video. Enter allowed origin - * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the - * video to be viewed on any origin. - */ - allowedOrigins?: Array; - /** - * A user-defined identifier for the media creator. - */ - creator?: string; - /** - * The maximum duration in seconds for a video upload. Can be set for a - * video that is not yet uploaded to limit its duration. Uploads that exceed the - * specified duration will fail during processing. A value of `-1` means the value - * is unknown. - */ - maxDurationSeconds?: number; - /** - * A user modifiable key-value store used to reference other systems of - * record for managing videos. - */ - meta?: Record; - /** - * Indicates whether the video can be a accessed using the id. When - * set to `true`, a signed token must be generated with a signing key to view the - * video. - */ - requireSignedURLs?: boolean; - /** - * Indicates the date and time at which the video will be deleted. Omit - * the field to indicate no change, or include with a `null` value to remove an - * existing scheduled deletion. If specified, must be at least 30 days from upload - * time. - */ - scheduledDeletion?: string | null; - /** - * The timestamp for a thumbnail image calculated as a percentage value - * of the video's duration. To convert from a second-wise timestamp to a - * percentage, divide the desired timestamp by the total duration of the video. If - * this value is not set, the default thumbnail image is taken from 0s of the - * video. - */ - thumbnailTimestampPct?: number; -}; -type StreamCaption = { - /** - * Whether the caption was generated via AI. - */ - generated?: boolean; - /** - * The language label displayed in the native language to users. - */ - label: string; - /** - * The language tag in BCP 47 format. - */ - language: string; - /** - * The status of a generated caption. - */ - status?: 'ready' | 'inprogress' | 'error'; -}; -type StreamDownloadStatus = 'ready' | 'inprogress' | 'error'; -type StreamDownloadType = 'default' | 'audio'; -type StreamDownload = { - /** - * Indicates the progress as a percentage between 0 and 100. - */ - percentComplete: number; - /** - * The status of a generated download. - */ - status: StreamDownloadStatus; - /** - * The URL to access the generated download. - */ - url?: string; -}; -/** - * An object with download type keys. Each key is optional and only present if that - * download type has been created. - */ -type StreamDownloadGetResponse = { - /** - * The audio-only download. Only present if this download type has been created. - */ - audio?: StreamDownload; - /** - * The default video download. Only present if this download type has been created. - */ - default?: StreamDownload; -}; -type StreamWatermarkPosition = 'upperRight' | 'upperLeft' | 'lowerLeft' | 'lowerRight' | 'center'; -type StreamWatermark = { - /** - * The unique identifier for a watermark profile. - */ - id: string; - /** - * The size of the image in bytes. - */ - size: number; - /** - * The height of the image in pixels. - */ - height: number; - /** - * The width of the image in pixels. - */ - width: number; - /** - * The date and a time a watermark profile was created. - */ - created: string; - /** - * The source URL for a downloaded image. If the watermark profile was created via - * direct upload, this field is null. - */ - downloadedFrom: string | null; - /** - * A short description of the watermark profile. - */ - name: string; - /** - * The translucency of the image. A value of `0.0` makes the image completely - * transparent, and `1.0` makes the image completely opaque. Note that if the image - * is already semi-transparent, setting this to `1.0` will not make the image - * completely opaque. - */ - opacity: number; - /** - * The whitespace between the adjacent edges (determined by position) of the video - * and the image. `0.0` indicates no padding, and `1.0` indicates a fully padded - * video width or length, as determined by the algorithm. - */ - padding: number; - /** - * The size of the image relative to the overall size of the video. This parameter - * will adapt to horizontal and vertical videos automatically. `0.0` indicates no - * scaling (use the size of the image as-is), and `1.0 `fills the entire video. - */ - scale: number; - /** - * The location of the image. Valid positions are: `upperRight`, `upperLeft`, - * `lowerLeft`, `lowerRight`, and `center`. Note that `center` ignores the - * `padding` parameter. - */ - position: StreamWatermarkPosition; -}; -type StreamWatermarkCreateParams = { - /** - * A short description of the watermark profile. - */ - name?: string; - /** - * The translucency of the image. A value of `0.0` makes the image completely - * transparent, and `1.0` makes the image completely opaque. Note that if the - * image is already semi-transparent, setting this to `1.0` will not make the - * image completely opaque. - */ - opacity?: number; - /** - * The whitespace between the adjacent edges (determined by position) of the - * video and the image. `0.0` indicates no padding, and `1.0` indicates a fully - * padded video width or length, as determined by the algorithm. - */ - padding?: number; - /** - * The size of the image relative to the overall size of the video. This - * parameter will adapt to horizontal and vertical videos automatically. `0.0` - * indicates no scaling (use the size of the image as-is), and `1.0 `fills the - * entire video. - */ - scale?: number; - /** - * The location of the image. - */ - position?: StreamWatermarkPosition; -}; -type StreamVideosListParams = { - /** - * The maximum number of videos to return. - */ - limit?: number; - /** - * Return videos created before this timestamp. - * (RFC3339/RFC3339Nano) - */ - before?: string; - /** - * Comparison operator for the `before` field. - * @default 'lt' - */ - beforeComp?: StreamPaginationComparison; - /** - * Return videos created after this timestamp. - * (RFC3339/RFC3339Nano) - */ - after?: string; - /** - * Comparison operator for the `after` field. - * @default 'gte' - */ - afterComp?: StreamPaginationComparison; -}; -type StreamPaginationComparison = 'eq' | 'gt' | 'gte' | 'lt' | 'lte'; -/** - * Error object for Stream binding operations. - */ -interface StreamError extends Error { - readonly code: number; - readonly statusCode: number; - readonly message: string; - readonly stack?: string; -} -interface InternalError extends StreamError { - name: 'InternalError'; -} -interface BadRequestError extends StreamError { - name: 'BadRequestError'; -} -interface NotFoundError extends StreamError { - name: 'NotFoundError'; -} -interface ForbiddenError extends StreamError { - name: 'ForbiddenError'; -} -interface RateLimitedError extends StreamError { - name: 'RateLimitedError'; -} -interface QuotaReachedError extends StreamError { - name: 'QuotaReachedError'; -} -interface MaxFileSizeError extends StreamError { - name: 'MaxFileSizeError'; -} -interface InvalidURLError extends StreamError { - name: 'InvalidURLError'; -} -interface AlreadyUploadedError extends StreamError { - name: 'AlreadyUploadedError'; -} -interface TooManyWatermarksError extends StreamError { - name: 'TooManyWatermarksError'; -} -type MarkdownDocument = { - name: string; - blob: Blob; -}; -type ConversionResponse = { - id: string; - name: string; - mimeType: string; - format: 'markdown'; - tokens: number; - data: string; -} | { - id: string; - name: string; - mimeType: string; - format: 'error'; - error: string; -}; -type ImageConversionOptions = { - descriptionLanguage?: 'en' | 'es' | 'fr' | 'it' | 'pt' | 'de'; -}; -type EmbeddedImageConversionOptions = ImageConversionOptions & { - convert?: boolean; - maxConvertedImages?: number; -}; -type ConversionOptions = { - html?: { - images?: EmbeddedImageConversionOptions & { - convertOGImage?: boolean; - }; - hostname?: string; - cssSelector?: string; - }; - docx?: { - images?: EmbeddedImageConversionOptions; - }; - image?: ImageConversionOptions; - pdf?: { - images?: EmbeddedImageConversionOptions; - metadata?: boolean; - }; -}; -type ConversionRequestOptions = { - gateway?: GatewayOptions; - extraHeaders?: object; - conversionOptions?: ConversionOptions; -}; -type SupportedFileFormat = { - mimeType: string; - extension: string; -}; -declare abstract class ToMarkdownService { - transform(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise; - transform(files: MarkdownDocument, options?: ConversionRequestOptions): Promise; - supported(): Promise; -} -declare namespace TailStream { - interface Header { - readonly name: string; - readonly value: string; - } - interface FetchEventInfo { - readonly type: "fetch"; - readonly method: string; - readonly url: string; - readonly cfJson?: object; - readonly headers: Header[]; - } - interface JsRpcEventInfo { - readonly type: "jsrpc"; - } - interface ScheduledEventInfo { - readonly type: "scheduled"; - readonly scheduledTime: Date; - readonly cron: string; - } - interface AlarmEventInfo { - readonly type: "alarm"; - readonly scheduledTime: Date; - } - interface QueueEventInfo { - readonly type: "queue"; - readonly queueName: string; - readonly batchSize: number; - } - interface EmailEventInfo { - readonly type: "email"; - readonly mailFrom: string; - readonly rcptTo: string; - readonly rawSize: number; - } - interface TraceEventInfo { - readonly type: "trace"; - readonly traces: (string | null)[]; - } - interface HibernatableWebSocketEventInfoMessage { - readonly type: "message"; - } - interface HibernatableWebSocketEventInfoError { - readonly type: "error"; - } - interface HibernatableWebSocketEventInfoClose { - readonly type: "close"; - readonly code: number; - readonly wasClean: boolean; - } - interface HibernatableWebSocketEventInfo { - readonly type: "hibernatableWebSocket"; - readonly info: HibernatableWebSocketEventInfoClose | HibernatableWebSocketEventInfoError | HibernatableWebSocketEventInfoMessage; - } - interface CustomEventInfo { - readonly type: "custom"; - } - interface FetchResponseInfo { - readonly type: "fetch"; - readonly statusCode: number; - } - type EventOutcome = "ok" | "canceled" | "exception" | "unknown" | "killSwitch" | "daemonDown" | "exceededCpu" | "exceededMemory" | "loadShed" | "responseStreamDisconnected" | "scriptNotFound"; - interface ScriptVersion { - readonly id: string; - readonly tag?: string; - readonly message?: string; - } - interface Onset { - readonly type: "onset"; - readonly attributes: Attribute[]; - // id for the span being opened by this Onset event. - readonly spanId: string; - readonly dispatchNamespace?: string; - readonly entrypoint?: string; - readonly executionModel: string; - readonly scriptName?: string; - readonly scriptTags?: string[]; - readonly scriptVersion?: ScriptVersion; - readonly info: FetchEventInfo | JsRpcEventInfo | ScheduledEventInfo | AlarmEventInfo | QueueEventInfo | EmailEventInfo | TraceEventInfo | HibernatableWebSocketEventInfo | CustomEventInfo; - } - interface Outcome { - readonly type: "outcome"; - readonly outcome: EventOutcome; - readonly cpuTime: number; - readonly wallTime: number; - } - interface SpanOpen { - readonly type: "spanOpen"; - readonly name: string; - // id for the span being opened by this SpanOpen event. - readonly spanId: string; - readonly info?: FetchEventInfo | JsRpcEventInfo | Attributes; - } - interface SpanClose { - readonly type: "spanClose"; - readonly outcome: EventOutcome; - } - interface DiagnosticChannelEvent { - readonly type: "diagnosticChannel"; - readonly channel: string; - readonly message: any; - } - interface Exception { - readonly type: "exception"; - readonly name: string; - readonly message: string; - readonly stack?: string; - } - interface Log { - readonly type: "log"; - readonly level: "debug" | "error" | "info" | "log" | "warn"; - readonly message: object; - } - interface DroppedEventsDiagnostic { - readonly diagnosticsType: "droppedEvents"; - readonly count: number; - } - interface StreamDiagnostic { - readonly type: 'streamDiagnostic'; - // To add new diagnostic types, define a new interface and add it to this union type. - readonly diagnostic: DroppedEventsDiagnostic; - } - // This marks the worker handler return information. - // This is separate from Outcome because the worker invocation can live for a long time after - // returning. For example - Websockets that return an http upgrade response but then continue - // streaming information or SSE http connections. - interface Return { - readonly type: "return"; - readonly info?: FetchResponseInfo; - } - interface Attribute { - readonly name: string; - readonly value: string | string[] | boolean | boolean[] | number | number[] | bigint | bigint[]; - } - interface Attributes { - readonly type: "attributes"; - readonly info: Attribute[]; - } - type EventType = Onset | Outcome | SpanOpen | SpanClose | DiagnosticChannelEvent | Exception | Log | StreamDiagnostic | Return | Attributes; - // Context in which this trace event lives. - interface SpanContext { - // Single id for the entire top-level invocation - // This should be a new traceId for the first worker stage invoked in the eyeball request and then - // same-account service-bindings should reuse the same traceId but cross-account service-bindings - // should use a new traceId. - readonly traceId: string; - // spanId in which this event is handled - // for Onset and SpanOpen events this would be the parent span id - // for Outcome and SpanClose these this would be the span id of the opening Onset and SpanOpen events - // For Hibernate and Mark this would be the span under which they were emitted. - // spanId is not set ONLY if: - // 1. This is an Onset event - // 2. We are not inheriting any SpanContext. (e.g. this is a cross-account service binding or a new top-level invocation) - readonly spanId?: string; - } - interface TailEvent { - // invocation id of the currently invoked worker stage. - // invocation id will always be unique to every Onset event and will be the same until the Outcome event. - readonly invocationId: string; - // Inherited spanContext for this event. - readonly spanContext: SpanContext; - readonly timestamp: Date; - readonly sequence: number; - readonly event: Event; - } - type TailEventHandler = (event: TailEvent) => void | Promise; - type TailEventHandlerObject = { - outcome?: TailEventHandler; - spanOpen?: TailEventHandler; - spanClose?: TailEventHandler; - diagnosticChannel?: TailEventHandler; - exception?: TailEventHandler; - log?: TailEventHandler; - return?: TailEventHandler; - attributes?: TailEventHandler; - }; - type TailEventHandlerType = TailEventHandler | TailEventHandlerObject; -} -// Copyright (c) 2022-2023 Cloudflare, Inc. -// Licensed under the Apache 2.0 license found in the LICENSE file or at: -// https://opensource.org/licenses/Apache-2.0 -/** - * Data types supported for holding vector metadata. - */ -type VectorizeVectorMetadataValue = string | number | boolean | string[]; -/** - * Additional information to associate with a vector. - */ -type VectorizeVectorMetadata = VectorizeVectorMetadataValue | Record; -type VectorFloatArray = Float32Array | Float64Array; -interface VectorizeError { - code?: number; - error: string; -} -/** - * Comparison logic/operation to use for metadata filtering. - * - * This list is expected to grow as support for more operations are released. - */ -type VectorizeVectorMetadataFilterOp = '$eq' | '$ne' | '$lt' | '$lte' | '$gt' | '$gte'; -type VectorizeVectorMetadataFilterCollectionOp = '$in' | '$nin'; -/** - * Filter criteria for vector metadata used to limit the retrieved query result set. - */ -type VectorizeVectorMetadataFilter = { - [field: string]: Exclude | null | { - [Op in VectorizeVectorMetadataFilterOp]?: Exclude | null; - } | { - [Op in VectorizeVectorMetadataFilterCollectionOp]?: Exclude[]; - }; -}; -/** - * Supported distance metrics for an index. - * Distance metrics determine how other "similar" vectors are determined. - */ -type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; -/** - * Metadata return levels for a Vectorize query. - * - * Default to "none". - * - * @property all Full metadata for the vector return set, including all fields (including those un-indexed) without truncation. This is a more expensive retrieval, as it requires additional fetching & reading of un-indexed data. - * @property indexed Return all metadata fields configured for indexing in the vector return set. This level of retrieval is "free" in that no additional overhead is incurred returning this data. However, note that indexed metadata is subject to truncation (especially for larger strings). - * @property none No indexed metadata will be returned. - */ -type VectorizeMetadataRetrievalLevel = "all" | "indexed" | "none"; -interface VectorizeQueryOptions { - topK?: number; - namespace?: string; - returnValues?: boolean; - returnMetadata?: boolean | VectorizeMetadataRetrievalLevel; - filter?: VectorizeVectorMetadataFilter; -} -/** - * Information about the configuration of an index. - */ -type VectorizeIndexConfig = { - dimensions: number; - metric: VectorizeDistanceMetric; -} | { - preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity -}; -/** - * Metadata about an existing index. - * - * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released. - * See {@link VectorizeIndexInfo} for its post-beta equivalent. - */ -interface VectorizeIndexDetails { - /** The unique ID of the index */ - readonly id: string; - /** The name of the index. */ - name: string; - /** (optional) A human readable description for the index. */ - description?: string; - /** The index configuration, including the dimension size and distance metric. */ - config: VectorizeIndexConfig; - /** The number of records containing vectors within the index. */ - vectorsCount: number; -} -/** - * Metadata about an existing index. - */ -interface VectorizeIndexInfo { - /** The number of records containing vectors within the index. */ - vectorCount: number; - /** Number of dimensions the index has been configured for. */ - dimensions: number; - /** ISO 8601 datetime of the last processed mutation on in the index. All changes before this mutation will be reflected in the index state. */ - processedUpToDatetime: number; - /** UUIDv4 of the last mutation processed by the index. All changes before this mutation will be reflected in the index state. */ - processedUpToMutation: number; -} -/** - * Represents a single vector value set along with its associated metadata. - */ -interface VectorizeVector { - /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ - id: string; - /** The vector values */ - values: VectorFloatArray | number[]; - /** The namespace this vector belongs to. */ - namespace?: string; - /** Metadata associated with the vector. Includes the values of other fields and potentially additional details. */ - metadata?: Record; -} -/** - * Represents a matched vector for a query along with its score and (if specified) the matching vector information. - */ -type VectorizeMatch = Pick, "values"> & Omit & { - /** The score or rank for similarity, when returned as a result */ - score: number; -}; -/** - * A set of matching {@link VectorizeMatch} for a particular query. - */ -interface VectorizeMatches { - matches: VectorizeMatch[]; - count: number; -} -/** - * Results of an operation that performed a mutation on a set of vectors. - * Here, `ids` is a list of vectors that were successfully processed. - * - * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released. - * See {@link VectorizeAsyncMutation} for its post-beta equivalent. - */ -interface VectorizeVectorMutation { - /* List of ids of vectors that were successfully processed. */ - ids: string[]; - /* Total count of the number of processed vectors. */ - count: number; -} -/** - * Result type indicating a mutation on the Vectorize Index. - * Actual mutations are processed async where the `mutationId` is the unique identifier for the operation. - */ -interface VectorizeAsyncMutation { - /** The unique identifier for the async mutation operation containing the changeset. */ - mutationId: string; -} -/** - * A Vectorize Vector Search Index for querying vectors/embeddings. - * - * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released. - * See {@link Vectorize} for its new implementation. - */ -declare abstract class VectorizeIndex { - /** - * Get information about the currently bound index. - * @returns A promise that resolves with information about the current index. - */ - public describe(): Promise; - /** - * Use the provided vector to perform a similarity search across the index. - * @param vector Input vector that will be used to drive the similarity search. - * @param options Configuration options to massage the returned data. - * @returns A promise that resolves with matched and scored vectors. - */ - public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise; - /** - * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. - * @param vectors List of vectors that will be inserted. - * @returns A promise that resolves with the ids & count of records that were successfully processed. - */ - public insert(vectors: VectorizeVector[]): Promise; - /** - * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. - * @param vectors List of vectors that will be upserted. - * @returns A promise that resolves with the ids & count of records that were successfully processed. - */ - public upsert(vectors: VectorizeVector[]): Promise; - /** - * Delete a list of vectors with a matching id. - * @param ids List of vector ids that should be deleted. - * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). - */ - public deleteByIds(ids: string[]): Promise; - /** - * Get a list of vectors with a matching id. - * @param ids List of vector ids that should be returned. - * @returns A promise that resolves with the raw unscored vectors matching the id set. - */ - public getByIds(ids: string[]): Promise; -} -/** - * A Vectorize Vector Search Index for querying vectors/embeddings. - * - * Mutations in this version are async, returning a mutation id. - */ -declare abstract class Vectorize { - /** - * Get information about the currently bound index. - * @returns A promise that resolves with information about the current index. - */ - public describe(): Promise; - /** - * Use the provided vector to perform a similarity search across the index. - * @param vector Input vector that will be used to drive the similarity search. - * @param options Configuration options to massage the returned data. - * @returns A promise that resolves with matched and scored vectors. - */ - public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise; - /** - * Use the provided vector-id to perform a similarity search across the index. - * @param vectorId Id for a vector in the index against which the index should be queried. - * @param options Configuration options to massage the returned data. - * @returns A promise that resolves with matched and scored vectors. - */ - public queryById(vectorId: string, options?: VectorizeQueryOptions): Promise; - /** - * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. - * @param vectors List of vectors that will be inserted. - * @returns A promise that resolves with a unique identifier of a mutation containing the insert changeset. - */ - public insert(vectors: VectorizeVector[]): Promise; - /** - * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. - * @param vectors List of vectors that will be upserted. - * @returns A promise that resolves with a unique identifier of a mutation containing the upsert changeset. - */ - public upsert(vectors: VectorizeVector[]): Promise; - /** - * Delete a list of vectors with a matching id. - * @param ids List of vector ids that should be deleted. - * @returns A promise that resolves with a unique identifier of a mutation containing the delete changeset. - */ - public deleteByIds(ids: string[]): Promise; - /** - * Get a list of vectors with a matching id. - * @param ids List of vector ids that should be returned. - * @returns A promise that resolves with the raw unscored vectors matching the id set. - */ - public getByIds(ids: string[]): Promise; -} -/** - * The interface for "version_metadata" binding - * providing metadata about the Worker Version using this binding. - */ -type WorkerVersionMetadata = { - /** The ID of the Worker Version using this binding */ - id: string; - /** The tag of the Worker Version using this binding */ - tag: string; - /** The timestamp of when the Worker Version was uploaded */ - timestamp: string; -}; -interface DynamicDispatchLimits { - /** - * Limit CPU time in milliseconds. - */ - cpuMs?: number; - /** - * Limit number of subrequests. - */ - subRequests?: number; -} -interface DynamicDispatchOptions { - /** - * Limit resources of invoked Worker script. - */ - limits?: DynamicDispatchLimits; - /** - * Arguments for outbound Worker script, if configured. - */ - outbound?: { - [key: string]: any; - }; -} -interface DispatchNamespace { - /** - * @param name Name of the Worker script. - * @param args Arguments to Worker script. - * @param options Options for Dynamic Dispatch invocation. - * @returns A Fetcher object that allows you to send requests to the Worker script. - * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. - */ - get(name: string, args?: { - [key: string]: any; - }, options?: DynamicDispatchOptions): Fetcher; -} -declare module 'cloudflare:workflows' { - /** - * NonRetryableError allows for a user to throw a fatal error - * that makes a Workflow instance fail immediately without triggering a retry - */ - export class NonRetryableError extends Error { - public constructor(message: string, name?: string); - } -} -declare abstract class Workflow { - /** - * Get a handle to an existing instance of the Workflow. - * @param id Id for the instance of this Workflow - * @returns A promise that resolves with a handle for the Instance - */ - public get(id: string): Promise; - /** - * Create a new instance and return a handle to it. If a provided id exists, an error will be thrown. - * @param options Options when creating an instance including id and params - * @returns A promise that resolves with a handle for the Instance - */ - public create(options?: WorkflowInstanceCreateOptions): Promise; - /** - * Create a batch of instances and return handle for all of them. If a provided id exists, an error will be thrown. - * `createBatch` is limited at 100 instances at a time or when the RPC limit for the batch (1MiB) is reached. - * @param batch List of Options when creating an instance including name and params - * @returns A promise that resolves with a list of handles for the created instances. - */ - public createBatch(batch: WorkflowInstanceCreateOptions[]): Promise; -} -type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; -type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number; -type WorkflowRetentionDuration = WorkflowSleepDuration; -interface WorkflowInstanceCreateOptions { - /** - * An id for your Workflow instance. Must be unique within the Workflow. - */ - id?: string; - /** - * The event payload the Workflow instance is triggered with - */ - params?: PARAMS; - /** - * The retention policy for Workflow instance. - * Defaults to the maximum retention period available for the owner's account. - */ - retention?: { - successRetention?: WorkflowRetentionDuration; - errorRetention?: WorkflowRetentionDuration; - }; -} -type InstanceStatus = { - status: 'queued' // means that instance is waiting to be started (see concurrency limits) - | 'running' | 'paused' | 'errored' | 'terminated' // user terminated the instance while it was running - | 'complete' | 'waiting' // instance is hibernating and waiting for sleep or event to finish - | 'waitingForPause' // instance is finishing the current work to pause - | 'unknown'; - error?: { - name: string; - message: string; - }; - output?: unknown; -}; -interface WorkflowError { - code?: number; - message: string; -} -declare abstract class WorkflowInstance { - public id: string; - /** - * Pause the instance. - */ - public pause(): Promise; - /** - * Resume the instance. If it is already running, an error will be thrown. - */ - public resume(): Promise; - /** - * Terminate the instance. If it is errored, terminated or complete, an error will be thrown. - */ - public terminate(): Promise; - /** - * Restart the instance. - */ - public restart(): Promise; - /** - * Returns the current status of the instance. - */ - public status(): Promise; - /** - * Send an event to this instance. - */ - public sendEvent({ type, payload, }: { - type: string; - payload: unknown; - }): Promise; -} diff --git a/examples/react/start-basic-cloudflare/wrangler.jsonc b/examples/react/start-basic-cloudflare/wrangler.jsonc deleted file mode 100644 index 05aca667af..0000000000 --- a/examples/react/start-basic-cloudflare/wrangler.jsonc +++ /dev/null @@ -1,10 +0,0 @@ -{ - "$schema": "node_modules/wrangler/config-schema.json", - "name": "tanstack-start-app", - "compatibility_date": "2025-09-24", - "compatibility_flags": ["nodejs_compat"], - "main": "@tanstack/react-start/server-entry", - "vars": { - "MY_VAR": "Hello from Cloudflare", - }, -} diff --git a/examples/react/start-basic-react-query/.devcontainer/devcontainer.json b/examples/react/start-basic-react-query/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/start-basic-react-query/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/start-basic-react-query/.gitignore b/examples/react/start-basic-react-query/.gitignore deleted file mode 100644 index ca63f49885..0000000000 --- a/examples/react/start-basic-react-query/.gitignore +++ /dev/null @@ -1,18 +0,0 @@ -node_modules -package-lock.json -yarn.lock - -.DS_Store -.cache -.env -.vercel -.output -/build/ -/api/ -/server/build -/public/build# Sentry Config File -.env.sentry-build-plugin -/test-results/ -/playwright-report/ -/blob-report/ -/playwright/.cache/ diff --git a/examples/react/start-basic-react-query/.prettierignore b/examples/react/start-basic-react-query/.prettierignore deleted file mode 100644 index 2be5eaa6ec..0000000000 --- a/examples/react/start-basic-react-query/.prettierignore +++ /dev/null @@ -1,4 +0,0 @@ -**/build -**/public -pnpm-lock.yaml -routeTree.gen.ts \ No newline at end of file diff --git a/examples/react/start-basic-react-query/.vscode/settings.json b/examples/react/start-basic-react-query/.vscode/settings.json deleted file mode 100644 index 00b5278e58..0000000000 --- a/examples/react/start-basic-react-query/.vscode/settings.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "files.watcherExclude": { - "**/routeTree.gen.ts": true - }, - "search.exclude": { - "**/routeTree.gen.ts": true - }, - "files.readonlyInclude": { - "**/routeTree.gen.ts": true - } -} diff --git a/examples/react/start-basic-react-query/README.md b/examples/react/start-basic-react-query/README.md index 70cc728ae4..95a31b0dda 100644 --- a/examples/react/start-basic-react-query/README.md +++ b/examples/react/start-basic-react-query/README.md @@ -1,55 +1,17 @@ -# TanStack Start - Basic React Query Example +# Deprecated: TanStack Start React Example (`start-basic-react-query`) -A TanStack Start example demonstrating integration with TanStack Query (React Query). +This example is retained for compatibility and historical reference. -- [TanStack Router Docs](https://tanstack.com/router) -- [TanStack Query Docs](https://tanstack.com/query) +For new projects, use: -## Start a new project based on this example +- [TanStack Builder](https://tanstack.com/builder) +- `npx @tanstack/cli create` -To start a new project based on this example, run: +For topic-specific setup, use the Start guides: -```sh -npx gitpick TanStack/router/tree/main/examples/react/start-basic-react-query start-basic-react-query -``` +- [Start React Quick Start](https://tanstack.com/router/latest/docs/framework/react/start/quick-start) +- [TanStack Query Docs](https://tanstack.com/query/latest) -## Getting Started +Canonical issue reproduction baseline: -From your terminal: - -```sh -pnpm install -pnpm dev -``` - -This starts your app in development mode, rebuilding assets on file changes. - -## Build - -To build the app for production: - -```sh -pnpm build -``` - -## TanStack Query Integration - -This example demonstrates how to use TanStack Query with TanStack Start for: - -- Server-side data fetching -- Client-side caching and synchronization -- Confirmed server mutations followed by query invalidation -- Explicit freshness and automatic refetching - -## SSR and mutation checks - -Read the [Start + TanStack Query guide](https://tanstack.com/start/latest/docs/framework/react/guide/tanstack-query). The `/preferences` page stores a harmless display name in a cookie, so its tests need no account or external API. This cookie is not authentication. The other post/user examples use JSONPlaceholder. - -```sh -pnpm exec playwright install chromium -pnpm test:e2e -pnpm build -QUERY_EXAMPLE_PRODUCTION=1 pnpm test:e2e -``` - -The tests check concurrent SSR request isolation, no duplicate hydration read, one refetch after mutation invalidation, and persistence on reload. Query data is fresh for 30 seconds by default in this example; choose a window appropriate for your application. +- [React `start-basic`](https://github.com/TanStack/router/tree/main/examples/react/start-basic) diff --git a/examples/react/start-basic-react-query/package.json b/examples/react/start-basic-react-query/package.json deleted file mode 100644 index 9d819d4390..0000000000 --- a/examples/react/start-basic-react-query/package.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "tanstack-start-example-basic-react-query", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "vite dev", - "build": "vite build && tsc --noEmit", - "preview": "vite preview", - "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "playwright test" - }, - "dependencies": { - "@tanstack/react-query": "^5.102.0", - "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-router-ssr-query": "^1.167.3", - "@tanstack/react-start": "^1.169.6", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "redaxios": "^0.5.1", - "tailwind-merge": "^3.6.0" - }, - "devDependencies": { - "@tailwindcss/vite": "^4.2.2", - "@types/node": "^22.5.4", - "@types/react": "^19.0.8", - "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "@playwright/test": "^1.61.0" - } -} diff --git a/examples/react/start-basic-react-query/playwright.config.ts b/examples/react/start-basic-react-query/playwright.config.ts deleted file mode 100644 index 298a1133e9..0000000000 --- a/examples/react/start-basic-react-query/playwright.config.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { defineConfig } from '@playwright/test' - -export default defineConfig({ - testDir: './tests', - use: { baseURL: 'http://localhost:3110', browserName: 'chromium' }, - webServer: { - command: - process.env.QUERY_EXAMPLE_PRODUCTION === '1' - ? 'PORT=3110 pnpm start' - : 'pnpm dev --port 3110', - url: 'http://localhost:3110/preferences', - timeout: 120_000, - }, -}) diff --git a/examples/react/start-basic-react-query/public/android-chrome-192x192.png b/examples/react/start-basic-react-query/public/android-chrome-192x192.png deleted file mode 100644 index 09c8324f8c..0000000000 Binary files a/examples/react/start-basic-react-query/public/android-chrome-192x192.png and /dev/null differ diff --git a/examples/react/start-basic-react-query/public/android-chrome-512x512.png b/examples/react/start-basic-react-query/public/android-chrome-512x512.png deleted file mode 100644 index 11d626ea3d..0000000000 Binary files a/examples/react/start-basic-react-query/public/android-chrome-512x512.png and /dev/null differ diff --git a/examples/react/start-basic-react-query/public/apple-touch-icon.png b/examples/react/start-basic-react-query/public/apple-touch-icon.png deleted file mode 100644 index 5a9423cc02..0000000000 Binary files a/examples/react/start-basic-react-query/public/apple-touch-icon.png and /dev/null differ diff --git a/examples/react/start-basic-react-query/public/favicon-16x16.png b/examples/react/start-basic-react-query/public/favicon-16x16.png deleted file mode 100644 index e3389b0044..0000000000 Binary files a/examples/react/start-basic-react-query/public/favicon-16x16.png and /dev/null differ diff --git a/examples/react/start-basic-react-query/public/favicon-32x32.png b/examples/react/start-basic-react-query/public/favicon-32x32.png deleted file mode 100644 index 900c77d444..0000000000 Binary files a/examples/react/start-basic-react-query/public/favicon-32x32.png and /dev/null differ diff --git a/examples/react/start-basic-react-query/public/favicon.ico b/examples/react/start-basic-react-query/public/favicon.ico deleted file mode 100644 index 1a1751676f..0000000000 Binary files a/examples/react/start-basic-react-query/public/favicon.ico and /dev/null differ diff --git a/examples/react/start-basic-react-query/public/favicon.png b/examples/react/start-basic-react-query/public/favicon.png deleted file mode 100644 index 1e77bc0609..0000000000 Binary files a/examples/react/start-basic-react-query/public/favicon.png and /dev/null differ diff --git a/examples/react/start-basic-react-query/public/site.webmanifest b/examples/react/start-basic-react-query/public/site.webmanifest deleted file mode 100644 index fa99de77db..0000000000 --- a/examples/react/start-basic-react-query/public/site.webmanifest +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "", - "short_name": "", - "icons": [ - { - "src": "/android-chrome-192x192.png", - "sizes": "192x192", - "type": "image/png" - }, - { - "src": "/android-chrome-512x512.png", - "sizes": "512x512", - "type": "image/png" - } - ], - "theme_color": "#ffffff", - "background_color": "#ffffff", - "display": "standalone" -} diff --git a/examples/react/start-basic-react-query/src/components/DefaultCatchBoundary.tsx b/examples/react/start-basic-react-query/src/components/DefaultCatchBoundary.tsx deleted file mode 100644 index 405fb5f4a7..0000000000 --- a/examples/react/start-basic-react-query/src/components/DefaultCatchBoundary.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { - ErrorComponent, - Link, - useLocation, - useRouter, -} from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' - -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - - console.error(error) - - return ( -

- ) -} diff --git a/examples/react/start-basic-react-query/src/components/NotFound.tsx b/examples/react/start-basic-react-query/src/components/NotFound.tsx deleted file mode 100644 index fd4e75befe..0000000000 --- a/examples/react/start-basic-react-query/src/components/NotFound.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { Link } from '@tanstack/react-router' - -export function NotFound({ children }: { children?: any }) { - return ( -
-
- {children ||

The page you are looking for does not exist.

} -
-

- - - Start Over - -

-
- ) -} diff --git a/examples/react/start-basic-react-query/src/routeTree.gen.ts b/examples/react/start-basic-react-query/src/routeTree.gen.ts deleted file mode 100644 index 0c7a90d4a1..0000000000 --- a/examples/react/start-basic-react-query/src/routeTree.gen.ts +++ /dev/null @@ -1,452 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as 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' -import { Route as ApiUsersRouteImport } from './routes/api/users' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' -import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRouteRoute = PostsRouteRouteImport.update({ - id: '/posts', - 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', - getParentRoute: () => rootRouteImport, -} as any) -const UsersRouteRoute = UsersRouteRouteImport.update({ - id: '/users', - path: '/users', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, - } as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', - getParentRoute: () => rootRouteImport, -} as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRouteRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRouteRoute, -} as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRouteRoute, -} as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRouteRoute, -} as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) -const PathlessLayoutNestedLayoutRouteBRoute = - PathlessLayoutNestedLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) -const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => ApiUsersRoute, -} as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/posts': typeof PostsRouteRouteWithChildren - '/users': typeof UsersRouteRouteWithChildren - '/deferred': typeof DeferredRoute - '/preferences': typeof PreferencesRoute - '/redirect': typeof RedirectRoute - '/api/users': typeof ApiUsersRouteWithChildren - '/posts/$postId': typeof PostsPostIdRoute - '/users/$userId': typeof UsersUserIdRoute - '/posts/': typeof PostsIndexRoute - '/users/': typeof UsersIndexRoute - '/route-a': typeof PathlessLayoutNestedLayoutRouteARoute - '/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute - '/api/users/$id': typeof ApiUsersIdRoute - '/posts/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/deferred': typeof DeferredRoute - '/preferences': typeof PreferencesRoute - '/redirect': typeof RedirectRoute - '/api/users': typeof ApiUsersRouteWithChildren - '/posts/$postId': typeof PostsPostIdRoute - '/users/$userId': typeof UsersUserIdRoute - '/posts': typeof PostsIndexRoute - '/users': typeof UsersIndexRoute - '/route-a': typeof PathlessLayoutNestedLayoutRouteARoute - '/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute - '/api/users/$id': typeof ApiUsersIdRoute - '/posts/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/posts': typeof PostsRouteRouteWithChildren - '/users': typeof UsersRouteRouteWithChildren - '/_pathlessLayout': typeof PathlessLayoutRouteWithChildren - '/deferred': typeof DeferredRoute - '/preferences': typeof PreferencesRoute - '/redirect': typeof RedirectRoute - '/_pathlessLayout/_nested-layout': typeof PathlessLayoutNestedLayoutRouteWithChildren - '/api/users': typeof ApiUsersRouteWithChildren - '/posts/$postId': typeof PostsPostIdRoute - '/users/$userId': typeof UsersUserIdRoute - '/posts/': typeof PostsIndexRoute - '/users/': typeof UsersIndexRoute - '/_pathlessLayout/_nested-layout/route-a': typeof PathlessLayoutNestedLayoutRouteARoute - '/_pathlessLayout/_nested-layout/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute - '/api/users/$id': typeof ApiUsersIdRoute - '/posts_/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/posts' - | '/users' - | '/deferred' - | '/preferences' - | '/redirect' - | '/api/users' - | '/posts/$postId' - | '/users/$userId' - | '/posts/' - | '/users/' - | '/route-a' - | '/route-b' - | '/api/users/$id' - | '/posts/$postId/deep' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/deferred' - | '/preferences' - | '/redirect' - | '/api/users' - | '/posts/$postId' - | '/users/$userId' - | '/posts' - | '/users' - | '/route-a' - | '/route-b' - | '/api/users/$id' - | '/posts/$postId/deep' - id: - | '__root__' - | '/' - | '/posts' - | '/users' - | '/_pathlessLayout' - | '/deferred' - | '/preferences' - | '/redirect' - | '/_pathlessLayout/_nested-layout' - | '/api/users' - | '/posts/$postId' - | '/users/$userId' - | '/posts/' - | '/users/' - | '/_pathlessLayout/_nested-layout/route-a' - | '/_pathlessLayout/_nested-layout/route-b' - | '/api/users/$id' - | '/posts_/$postId/deep' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - PostsRouteRoute: typeof PostsRouteRouteWithChildren - UsersRouteRoute: typeof UsersRouteRouteWithChildren - PathlessLayoutRoute: typeof PathlessLayoutRouteWithChildren - DeferredRoute: typeof DeferredRoute - PreferencesRoute: typeof PreferencesRoute - RedirectRoute: typeof RedirectRoute - ApiUsersRoute: typeof ApiUsersRouteWithChildren - PostsPostIdDeepRoute: typeof PostsPostIdDeepRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout': { - id: '/_pathlessLayout' - path: '' - fullPath: '/' - preLoaderRoute: typeof PathlessLayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/preferences': { - id: '/preferences' - path: '/preferences' - fullPath: '/preferences' - preLoaderRoute: typeof PreferencesRouteImport - parentRoute: typeof rootRouteImport - } - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport - parentRoute: typeof rootRouteImport - } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute - } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport - parentRoute: typeof rootRouteImport - } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRouteRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRouteRoute - } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRouteRoute - } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRouteRoute - } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } - '/_pathlessLayout/_nested-layout/route-b': { - id: '/_pathlessLayout/_nested-layout/route-b' - path: '/route-b' - fullPath: '/route-b' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } - '/api/users/$id': { - id: '/api/users/$id' - path: '/$id' - fullPath: '/api/users/$id' - preLoaderRoute: typeof ApiUsersIdRouteImport - parentRoute: typeof ApiUsersRoute - } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -interface PostsRouteRouteChildren { - PostsPostIdRoute: typeof PostsPostIdRoute - PostsIndexRoute: typeof PostsIndexRoute -} - -const PostsRouteRouteChildren: PostsRouteRouteChildren = { - PostsPostIdRoute: PostsPostIdRoute, - PostsIndexRoute: PostsIndexRoute, -} - -const PostsRouteRouteWithChildren = PostsRouteRoute._addFileChildren( - PostsRouteRouteChildren, -) - -interface UsersRouteRouteChildren { - UsersUserIdRoute: typeof UsersUserIdRoute - UsersIndexRoute: typeof UsersIndexRoute -} - -const UsersRouteRouteChildren: UsersRouteRouteChildren = { - UsersUserIdRoute: UsersUserIdRoute, - UsersIndexRoute: UsersIndexRoute, -} - -const UsersRouteRouteWithChildren = UsersRouteRoute._addFileChildren( - UsersRouteRouteChildren, -) - -interface PathlessLayoutNestedLayoutRouteChildren { - PathlessLayoutNestedLayoutRouteARoute: typeof PathlessLayoutNestedLayoutRouteARoute - PathlessLayoutNestedLayoutRouteBRoute: typeof PathlessLayoutNestedLayoutRouteBRoute -} - -const PathlessLayoutNestedLayoutRouteChildren: PathlessLayoutNestedLayoutRouteChildren = - { - PathlessLayoutNestedLayoutRouteARoute: - PathlessLayoutNestedLayoutRouteARoute, - PathlessLayoutNestedLayoutRouteBRoute: - PathlessLayoutNestedLayoutRouteBRoute, - } - -const PathlessLayoutNestedLayoutRouteWithChildren = - PathlessLayoutNestedLayoutRoute._addFileChildren( - PathlessLayoutNestedLayoutRouteChildren, - ) - -interface PathlessLayoutRouteChildren { - PathlessLayoutNestedLayoutRoute: typeof PathlessLayoutNestedLayoutRouteWithChildren -} - -const PathlessLayoutRouteChildren: PathlessLayoutRouteChildren = { - PathlessLayoutNestedLayoutRoute: PathlessLayoutNestedLayoutRouteWithChildren, -} - -const PathlessLayoutRouteWithChildren = PathlessLayoutRoute._addFileChildren( - PathlessLayoutRouteChildren, -) - -interface ApiUsersRouteChildren { - ApiUsersIdRoute: typeof ApiUsersIdRoute -} - -const ApiUsersRouteChildren: ApiUsersRouteChildren = { - ApiUsersIdRoute: ApiUsersIdRoute, -} - -const ApiUsersRouteWithChildren = ApiUsersRoute._addFileChildren( - ApiUsersRouteChildren, -) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - PostsRouteRoute: PostsRouteRouteWithChildren, - UsersRouteRoute: UsersRouteRouteWithChildren, - PathlessLayoutRoute: PathlessLayoutRouteWithChildren, - DeferredRoute: DeferredRoute, - PreferencesRoute: PreferencesRoute, - RedirectRoute: RedirectRoute, - ApiUsersRoute: ApiUsersRouteWithChildren, - PostsPostIdDeepRoute: PostsPostIdDeepRoute, -} -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-basic-react-query/src/router.tsx b/examples/react/start-basic-react-query/src/router.tsx deleted file mode 100644 index 345055c116..0000000000 --- a/examples/react/start-basic-react-query/src/router.tsx +++ /dev/null @@ -1,33 +0,0 @@ -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' -import { DefaultCatchBoundary } from './components/DefaultCatchBoundary' -import { NotFound } from './components/NotFound' - -export function getRouter() { - const queryClient = new QueryClient({ - defaultOptions: { queries: { staleTime: 30_000 } }, - }) - - const router = createRouter({ - routeTree, - context: { queryClient }, - defaultPreload: 'intent', - defaultPreloadStaleTime: 0, - defaultErrorComponent: DefaultCatchBoundary, - defaultNotFoundComponent: () => , - }) - setupRouterSsrQueryIntegration({ - router, - queryClient, - }) - - return router -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/examples/react/start-basic-react-query/src/routes/__root.tsx b/examples/react/start-basic-react-query/src/routes/__root.tsx deleted file mode 100644 index 71c19b2c6f..0000000000 --- a/examples/react/start-basic-react-query/src/routes/__root.tsx +++ /dev/null @@ -1,146 +0,0 @@ -/// -import { - HeadContent, - Link, - Outlet, - Scripts, - createRootRouteWithContext, -} from '@tanstack/react-router' -import { ReactQueryDevtools } from '@tanstack/react-query-devtools' -import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' -import * as React from 'react' -import type { QueryClient } from '@tanstack/react-query' -import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary' -import { NotFound } from '~/components/NotFound' -import appCss from '~/styles/app.css?url' -import { seo } from '~/utils/seo' - -export const Route = createRootRouteWithContext<{ - queryClient: QueryClient -}>()({ - head: () => ({ - meta: [ - { - charSet: 'utf-8', - }, - { - name: 'viewport', - content: 'width=device-width, initial-scale=1', - }, - ...seo({ - title: - 'TanStack Start | Type-Safe, Client-First, Full-Stack React Framework', - description: `TanStack Start is a type-safe, client-first, full-stack React framework. `, - }), - ], - links: [ - { rel: 'stylesheet', href: appCss }, - { - rel: 'apple-touch-icon', - sizes: '180x180', - href: '/apple-touch-icon.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '32x32', - href: '/favicon-32x32.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '16x16', - href: '/favicon-16x16.png', - }, - { rel: 'manifest', href: '/site.webmanifest', color: '#fffff' }, - { rel: 'icon', href: '/favicon.ico' }, - ], - }), - errorComponent: (props) => { - return ( - - - - ) - }, - notFoundComponent: () => , - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - ) -} - -function RootDocument({ children }: { children: React.ReactNode }) { - return ( - - - - - -
- Preferences - - Home - {' '} - - Posts - {' '} - - Users - {' '} - - Pathless Layout - {' '} - - Deferred - {' '} - - This Route Does Not Exist - -
-
- {children} - - - - - - ) -} diff --git a/examples/react/start-basic-react-query/src/routes/_pathlessLayout.tsx b/examples/react/start-basic-react-query/src/routes/_pathlessLayout.tsx deleted file mode 100644 index 3353841595..0000000000 --- a/examples/react/start-basic-react-query/src/routes/_pathlessLayout.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_pathlessLayout')({ - component: PathlessLayoutComponent, -}) - -function PathlessLayoutComponent() { - return ( -
-
I'm a pathless layout
-
- -
-
- ) -} diff --git a/examples/react/start-basic-react-query/src/routes/_pathlessLayout/_nested-layout.tsx b/examples/react/start-basic-react-query/src/routes/_pathlessLayout/_nested-layout.tsx deleted file mode 100644 index 0dcb1270ad..0000000000 --- a/examples/react/start-basic-react-query/src/routes/_pathlessLayout/_nested-layout.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_pathlessLayout/_nested-layout')({ - component: PathlessLayoutComponent, -}) - -function PathlessLayoutComponent() { - return ( -
-
I'm a nested pathless layout
-
- - Go to route A - - - Go to route B - -
-
- -
-
- ) -} diff --git a/examples/react/start-basic-react-query/src/routes/_pathlessLayout/_nested-layout/route-a.tsx b/examples/react/start-basic-react-query/src/routes/_pathlessLayout/_nested-layout/route-a.tsx deleted file mode 100644 index 0213f1516f..0000000000 --- a/examples/react/start-basic-react-query/src/routes/_pathlessLayout/_nested-layout/route-a.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/_pathlessLayout/_nested-layout/route-a')( - { - component: LayoutAComponent, - }, -) - -function LayoutAComponent() { - return
I'm A!
-} diff --git a/examples/react/start-basic-react-query/src/routes/_pathlessLayout/_nested-layout/route-b.tsx b/examples/react/start-basic-react-query/src/routes/_pathlessLayout/_nested-layout/route-b.tsx deleted file mode 100644 index 3d909523fb..0000000000 --- a/examples/react/start-basic-react-query/src/routes/_pathlessLayout/_nested-layout/route-b.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/_pathlessLayout/_nested-layout/route-b')( - { - component: LayoutBComponent, - }, -) - -function LayoutBComponent() { - return
I'm B!
-} diff --git a/examples/react/start-basic-react-query/src/routes/api/users.$id.ts b/examples/react/start-basic-react-query/src/routes/api/users.$id.ts deleted file mode 100644 index fd2becb76c..0000000000 --- a/examples/react/start-basic-react-query/src/routes/api/users.$id.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import axios from 'redaxios' -import type { User } from '../../utils/users' - -export const Route = createFileRoute('/api/users/$id')({ - server: { - handlers: { - GET: async ({ request, params }) => { - console.info(`Fetching users by id=${params.id}... @`, request.url) - try { - const res = await axios.get( - 'https://jsonplaceholder.typicode.com/users/' + params.id, - ) - return Response.json({ - id: res.data.id, - name: res.data.name, - email: res.data.email, - }) - } catch (e) { - console.error(e) - return Response.json({ error: 'User not found' }, { status: 404 }) - } - }, - }, - }, -}) diff --git a/examples/react/start-basic-react-query/src/routes/api/users.ts b/examples/react/start-basic-react-query/src/routes/api/users.ts deleted file mode 100644 index 68fbdfcff0..0000000000 --- a/examples/react/start-basic-react-query/src/routes/api/users.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import axios from 'redaxios' -import type { User } from '../../utils/users' - -export const Route = createFileRoute('/api/users')({ - server: { - handlers: { - GET: async ({ request }) => { - console.info('Fetching users... @', request.url) - const res = await axios.get>( - 'https://jsonplaceholder.typicode.com/users', - ) - const list = res.data.slice(0, 10) - return Response.json( - list.map((u) => ({ id: u.id, name: u.name, email: u.email })), - ) - }, - }, - }, -}) diff --git a/examples/react/start-basic-react-query/src/routes/deferred.tsx b/examples/react/start-basic-react-query/src/routes/deferred.tsx deleted file mode 100644 index 11af82ed27..0000000000 --- a/examples/react/start-basic-react-query/src/routes/deferred.tsx +++ /dev/null @@ -1,53 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { queryOptions, useSuspenseQuery } from '@tanstack/react-query' -import { Suspense, useState } from 'react' - -const deferredQueryOptions = () => - queryOptions({ - queryKey: ['deferred'], - queryFn: async () => { - await new Promise((r) => setTimeout(r, 3000)) - return { - message: `Hello deferred from the server!`, - status: 'success', - time: new Date(), - } - }, - }) - -export const Route = createFileRoute('/deferred')({ - loader: ({ context }) => { - // Kick off loading as early as possible! - context.queryClient.prefetchQuery(deferredQueryOptions()) - }, - component: Deferred, -}) - -function Deferred() { - const [count, setCount] = useState(0) - - return ( -
- - - -
Count: {count}
-
- -
-
- ) -} - -function DeferredQuery() { - const deferredQuery = useSuspenseQuery(deferredQueryOptions()) - - return ( -
-

Deferred Query

-
Status: {deferredQuery.data.status}
-
Message: {deferredQuery.data.message}
-
Time: {deferredQuery.data.time.toISOString()}
-
- ) -} diff --git a/examples/react/start-basic-react-query/src/routes/index.tsx b/examples/react/start-basic-react-query/src/routes/index.tsx deleted file mode 100644 index 37c8d237bd..0000000000 --- a/examples/react/start-basic-react-query/src/routes/index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/')({ - component: Home, -}) - -function Home() { - return ( -
-

Welcome Home!!!

-
- ) -} diff --git a/examples/react/start-basic-react-query/src/routes/posts.$postId.tsx b/examples/react/start-basic-react-query/src/routes/posts.$postId.tsx deleted file mode 100644 index e9e58e5541..0000000000 --- a/examples/react/start-basic-react-query/src/routes/posts.$postId.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { ErrorComponent, Link, createFileRoute } from '@tanstack/react-router' -import { useSuspenseQuery } from '@tanstack/react-query' -import { postQueryOptions } from '../utils/posts' -import type { ErrorComponentProps } from '@tanstack/react-router' -import { NotFound } from '~/components/NotFound' - -export const Route = createFileRoute('/posts/$postId')({ - loader: async ({ params: { postId }, context }) => { - const data = await context.queryClient.ensureQueryData( - postQueryOptions(postId), - ) - - return { - title: data.title, - } - }, - head: ({ loaderData }) => ({ - meta: loaderData ? [{ title: loaderData.title }] : undefined, - }), - errorComponent: PostErrorComponent, - notFoundComponent: () => { - return Post not found - }, - component: PostComponent, -}) - -export function PostErrorComponent({ error }: ErrorComponentProps) { - return -} - -function PostComponent() { - const { postId } = Route.useParams() - const postQuery = useSuspenseQuery(postQueryOptions(postId)) - - return ( -
-

{postQuery.data.title}

-
{postQuery.data.body}
- - Deep View - -
- ) -} diff --git a/examples/react/start-basic-react-query/src/routes/posts.route.tsx b/examples/react/start-basic-react-query/src/routes/posts.route.tsx deleted file mode 100644 index b545663be2..0000000000 --- a/examples/react/start-basic-react-query/src/routes/posts.route.tsx +++ /dev/null @@ -1,45 +0,0 @@ -import { useSuspenseQuery } from '@tanstack/react-query' -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' -import { postsQueryOptions } from '../utils/posts' - -export const Route = createFileRoute('/posts')({ - loader: async ({ context }) => { - await context.queryClient.ensureQueryData(postsQueryOptions()) - }, - head: () => ({ - meta: [{ title: 'Posts' }], - }), - component: PostsComponent, -}) - -function PostsComponent() { - const postsQuery = useSuspenseQuery(postsQueryOptions()) - - return ( -
-
    - {[ - ...postsQuery.data, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
-
- -
- ) -} diff --git a/examples/react/start-basic-react-query/src/routes/posts_.$postId.deep.tsx b/examples/react/start-basic-react-query/src/routes/posts_.$postId.deep.tsx deleted file mode 100644 index 33f6475a55..0000000000 --- a/examples/react/start-basic-react-query/src/routes/posts_.$postId.deep.tsx +++ /dev/null @@ -1,39 +0,0 @@ -import { Link, createFileRoute } from '@tanstack/react-router' -import { useSuspenseQuery } from '@tanstack/react-query' -import { postQueryOptions } from '../utils/posts' -import { PostErrorComponent } from './posts.$postId' - -export const Route = createFileRoute('/posts_/$postId/deep')({ - loader: async ({ params: { postId }, context }) => { - const data = await context.queryClient.ensureQueryData( - postQueryOptions(postId), - ) - - return { - title: data.title, - } - }, - head: ({ loaderData }) => ({ - meta: loaderData ? [{ title: loaderData.title }] : undefined, - }), - errorComponent: PostErrorComponent, - component: PostDeepComponent, -}) - -function PostDeepComponent() { - const { postId } = Route.useParams() - const postQuery = useSuspenseQuery(postQueryOptions(postId)) - - return ( -
- - ← All Posts - -

{postQuery.data.title}

-
{postQuery.data.body}
-
- ) -} diff --git a/examples/react/start-basic-react-query/src/routes/preferences.tsx b/examples/react/start-basic-react-query/src/routes/preferences.tsx deleted file mode 100644 index 603257fc0f..0000000000 --- a/examples/react/start-basic-react-query/src/routes/preferences.tsx +++ /dev/null @@ -1,68 +0,0 @@ -import { - useMutation, - useQueryClient, - useSuspenseQuery, -} from '@tanstack/react-query' -import { createFileRoute, useHydrated } from '@tanstack/react-router' -import { useServerFn } from '@tanstack/react-start' -import { readerNameOptions, saveReaderName } from '../utils/preferences' - -export const Route = createFileRoute('/preferences')({ - loader: async ({ context }) => { - 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/routes/redirect.tsx b/examples/react/start-basic-react-query/src/routes/redirect.tsx deleted file mode 100644 index fa220b5097..0000000000 --- a/examples/react/start-basic-react-query/src/routes/redirect.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { redirect, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/redirect')({ - beforeLoad: async () => { - throw redirect({ - to: '/posts', - }) - }, -}) diff --git a/examples/react/start-basic-react-query/src/routes/users.$userId.tsx b/examples/react/start-basic-react-query/src/routes/users.$userId.tsx deleted file mode 100644 index 0750a01568..0000000000 --- a/examples/react/start-basic-react-query/src/routes/users.$userId.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import { useSuspenseQuery } from '@tanstack/react-query' -import { ErrorComponent, createFileRoute } from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' -import { NotFound } from '~/components/NotFound' -import { userQueryOptions } from '~/utils/users' - -export const Route = createFileRoute('/users/$userId')({ - loader: async ({ context, params: { userId } }) => { - await context.queryClient.ensureQueryData(userQueryOptions(userId)) - }, - errorComponent: UserErrorComponent, - component: UserComponent, - notFoundComponent: () => { - return User not found - }, -}) - -export function UserErrorComponent({ error }: ErrorComponentProps) { - return -} - -function UserComponent() { - const params = Route.useParams() - const userQuery = useSuspenseQuery(userQueryOptions(params.userId)) - const user = userQuery.data - - return ( -
-

{user.name}

-
{user.email}
-
- ) -} diff --git a/examples/react/start-basic-react-query/src/routes/users.index.tsx b/examples/react/start-basic-react-query/src/routes/users.index.tsx deleted file mode 100644 index ea814e2cbf..0000000000 --- a/examples/react/start-basic-react-query/src/routes/users.index.tsx +++ /dev/null @@ -1,8 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/users/')({ - component: UsersIndexComponent, -}) - -function UsersIndexComponent() { - return
Select a user.
-} diff --git a/examples/react/start-basic-react-query/src/routes/users.route.tsx b/examples/react/start-basic-react-query/src/routes/users.route.tsx deleted file mode 100644 index 2f3c72cb7b..0000000000 --- a/examples/react/start-basic-react-query/src/routes/users.route.tsx +++ /dev/null @@ -1,42 +0,0 @@ -import { useSuspenseQuery } from '@tanstack/react-query' -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' -import { usersQueryOptions } from '../utils/users' - -export const Route = createFileRoute('/users')({ - loader: async ({ context }) => { - await context.queryClient.ensureQueryData(usersQueryOptions()) - }, - component: UsersComponent, -}) - -function UsersComponent() { - const usersQuery = useSuspenseQuery(usersQueryOptions()) - - return ( -
-
    - {[ - ...usersQuery.data, - { id: 'i-do-not-exist', name: 'Non-existent User', email: '' }, - ].map((user) => { - return ( -
  • - -
    {user.name}
    - -
  • - ) - })} -
-
- -
- ) -} diff --git a/examples/react/start-basic-react-query/src/start.ts b/examples/react/start-basic-react-query/src/start.ts deleted file mode 100644 index 5fb1e247fb..0000000000 --- a/examples/react/start-basic-react-query/src/start.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { createCsrfMiddleware, createStart } from '@tanstack/react-start' - -export const startInstance = createStart(() => ({ - requestMiddleware: [ - createCsrfMiddleware({ - filter: (ctx) => ctx.handlerType === 'serverFn', - }), - ], -})) diff --git a/examples/react/start-basic-react-query/src/styles/app.css b/examples/react/start-basic-react-query/src/styles/app.css deleted file mode 100644 index 37c1f5a6e2..0000000000 --- a/examples/react/start-basic-react-query/src/styles/app.css +++ /dev/null @@ -1,30 +0,0 @@ -@import 'tailwindcss' source('../'); - -@layer base { - *, - ::after, - ::before, - ::backdrop, - ::file-selector-button { - border-color: var(--color-gray-200, currentcolor); - } -} - -@layer base { - html { - color-scheme: light dark; - } - - * { - @apply border-gray-200 dark:border-gray-800; - } - - html, - body { - @apply text-gray-900 bg-gray-50 dark:bg-gray-950 dark:text-gray-200; - } - - .using-mouse * { - outline: none !important; - } -} diff --git a/examples/react/start-basic-react-query/src/utils/posts.tsx b/examples/react/start-basic-react-query/src/utils/posts.tsx deleted file mode 100644 index dc6979005e..0000000000 --- a/examples/react/start-basic-react-query/src/utils/posts.tsx +++ /dev/null @@ -1,49 +0,0 @@ -import { queryOptions } from '@tanstack/react-query' -import { notFound } from '@tanstack/react-router' -import { createServerFn } from '@tanstack/react-start' -import axios from 'redaxios' - -export type PostType = { - id: string - title: string - body: string -} - -export const fetchPosts = createServerFn({ method: 'GET' }).handler( - async () => { - console.info('Fetching posts...') - return axios - .get>('https://jsonplaceholder.typicode.com/posts') - .then((r) => r.data.slice(0, 10)) - }, -) - -export const postsQueryOptions = () => - queryOptions({ - queryKey: ['posts'], - queryFn: () => fetchPosts(), - }) - -export const fetchPost = createServerFn({ method: 'GET' }) - .validator((d: string) => d) - .handler(async ({ data }) => { - console.info(`Fetching post with id ${data}...`) - const post = await axios - .get(`https://jsonplaceholder.typicode.com/posts/${data}`) - .then((r) => r.data) - .catch((err) => { - console.error(err) - if (err.status === 404) { - throw notFound() - } - throw err - }) - - return post - }) - -export const postQueryOptions = (postId: string) => - queryOptions({ - queryKey: ['post', postId], - queryFn: () => fetchPost({ data: postId }), - }) diff --git a/examples/react/start-basic-react-query/src/utils/preferences.ts b/examples/react/start-basic-react-query/src/utils/preferences.ts deleted file mode 100644 index 74c33e5848..0000000000 --- a/examples/react/start-basic-react-query/src/utils/preferences.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { queryOptions } from '@tanstack/react-query' -import { createServerFn } from '@tanstack/react-start' -import { - getCookie, - setCookie, - setResponseHeader, -} from '@tanstack/react-start/server' - -export const getReaderName = createServerFn({ method: 'GET' }).handler(() => { - setResponseHeader('Cache-Control', 'private, no-store') - return getCookie('reader-name') || 'Guest' -}) - -export const saveReaderName = createServerFn({ method: 'POST' }) - .validator((name: string) => { - if (typeof name !== 'string' || !name.trim() || name.length > 40) { - throw new Error('Enter a name between 1 and 40 characters') - } - return name.trim() - }) - .handler(({ data }) => { - setResponseHeader('Cache-Control', 'private, no-store') - setCookie('reader-name', data, { - httpOnly: true, - sameSite: 'lax', - secure: process.env.NODE_ENV === 'production', - path: '/', - }) - }) - -export const readerNameOptions = queryOptions({ - queryKey: ['reader-name'], - queryFn: () => getReaderName(), -}) diff --git a/examples/react/start-basic-react-query/src/utils/seo.ts b/examples/react/start-basic-react-query/src/utils/seo.ts deleted file mode 100644 index d18ad84b74..0000000000 --- a/examples/react/start-basic-react-query/src/utils/seo.ts +++ /dev/null @@ -1,33 +0,0 @@ -export const seo = ({ - title, - description, - keywords, - image, -}: { - title: string - description?: string - image?: string - keywords?: string -}) => { - const tags = [ - { title }, - { name: 'description', content: description }, - { name: 'keywords', content: keywords }, - { name: 'twitter:title', content: title }, - { name: 'twitter:description', content: description }, - { name: 'twitter:creator', content: '@tannerlinsley' }, - { name: 'twitter:site', content: '@tannerlinsley' }, - { name: 'og:type', content: 'website' }, - { name: 'og:title', content: title }, - { name: 'og:description', content: description }, - ...(image - ? [ - { name: 'twitter:image', content: image }, - { name: 'twitter:card', content: 'summary_large_image' }, - { name: 'og:image', content: image }, - ] - : []), - ] - - return tags -} diff --git a/examples/react/start-basic-react-query/src/utils/users.tsx b/examples/react/start-basic-react-query/src/utils/users.tsx deleted file mode 100644 index 9b6760bfa7..0000000000 --- a/examples/react/start-basic-react-query/src/utils/users.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import { queryOptions } from '@tanstack/react-query' -import axios from 'redaxios' - -export type User = { - id: number - name: string - email: string -} - -export const DEPLOY_URL = 'http://localhost:3000' - -export const usersQueryOptions = () => - queryOptions({ - queryKey: ['users'], - queryFn: () => - axios - .get>(DEPLOY_URL + '/api/users') - .then((r) => r.data) - .catch(() => { - throw new Error('Failed to fetch users') - }), - }) - -export const userQueryOptions = (id: string) => - queryOptions({ - queryKey: ['users', id], - queryFn: () => - axios - .get(DEPLOY_URL + '/api/users/' + id) - .then((r) => r.data) - .catch(() => { - throw new Error('Failed to fetch user') - }), - }) diff --git a/examples/react/start-basic-react-query/tests/preferences.spec.ts b/examples/react/start-basic-react-query/tests/preferences.spec.ts deleted file mode 100644 index 309c402798..0000000000 --- a/examples/react/start-basic-react-query/tests/preferences.spec.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { expect, test } from '@playwright/test' - -test('concurrent SSR requests keep the same query key isolated by request', async ({ - request, -}) => { - const names = ['Lucia', 'Omar', 'Maya', 'Felix'] - const responses = await Promise.all( - names.map((name) => - request.get('/preferences', { - headers: { Cookie: `reader-name=${name}` }, - }), - ), - ) - for (const [index, response] of responses.entries()) { - expect(response.status()).toBe(200) - expect(response.headers()['cache-control']).toContain('no-store') - const html = await response.text() - expect(html).toContain(names[index]) - for (const other of names.filter((_, otherIndex) => otherIndex !== index)) { - expect(html).not.toContain(other) - } - } -}) - -test('hydration reuses SSR data and mutation invalidation refetches once', async ({ - page, -}) => { - const reads: string[] = [] - page.on('request', (request) => { - if ( - request.method() === 'GET' && - new URL(request.url()).pathname.startsWith('/_serverFn/') - ) { - reads.push(request.url()) - } - }) - await page.goto('/preferences') - await expect(page.getByTestId('reader-name')).toHaveText('Hello, Guest') - await expect(page.getByLabel('Display name')).toBeEnabled() - await page.waitForLoadState('networkidle') - expect(reads).toHaveLength(0) - - await page.getByLabel('Display name').fill('Ada') - const mutation = page.waitForRequest((request) => request.method() === 'POST') - await page.getByRole('button', { name: 'Save name' }).click() - await expect(page.getByTestId('reader-name')).toHaveText('Hello, Ada') - await expect(page.getByRole('button', { name: 'Save name' })).toBeEnabled() - await page.waitForLoadState('networkidle') - expect(reads).toHaveLength(1) - - const savedRequest = await mutation - const headers = await savedRequest.allHeaders() - delete headers['content-length'] - headers.origin = 'https://untrusted.example' - headers['sec-fetch-site'] = 'cross-site' - const denied = await page.request.post(savedRequest.url(), { - headers, - data: savedRequest.postData() ?? '', - }) - expect(denied.status()).toBe(403) - - await page.reload() - await expect(page.getByTestId('reader-name')).toHaveText('Hello, Ada') - await expect(page.getByLabel('Display name')).toBeEnabled() - await page.waitForLoadState('networkidle') - expect(reads).toHaveLength(1) -}) diff --git a/examples/react/start-basic-react-query/tsconfig.json b/examples/react/start-basic-react-query/tsconfig.json deleted file mode 100644 index cef9369516..0000000000 --- a/examples/react/start-basic-react-query/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "include": ["**/*.ts", "**/*.tsx"], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "react-jsx", - "module": "ESNext", - "moduleResolution": "Bundler", - "lib": ["DOM", "DOM.Iterable", "ES2022"], - "isolatedModules": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "target": "ES2022", - "allowJs": true, - "forceConsistentCasingInFileNames": true, - "paths": { - "~/*": ["./src/*"] - }, - "noEmit": true - } -} diff --git a/examples/react/start-basic-react-query/vite.config.ts b/examples/react/start-basic-react-query/vite.config.ts deleted file mode 100644 index ed6799764a..0000000000 --- a/examples/react/start-basic-react-query/vite.config.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { tanstackStart } from '@tanstack/react-start/plugin/vite' -import { defineConfig } from 'vite' -import viteReact from '@vitejs/plugin-react' -import tailwindcss from '@tailwindcss/vite' - -export default defineConfig({ - server: { - port: 3000, - }, - resolve: { - tsconfigPaths: true, - }, - plugins: [tailwindcss(), tanstackStart(), viteReact()], -}) diff --git a/examples/react/start-basic-rsbuild/.devcontainer/devcontainer.json b/examples/react/start-basic-rsbuild/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/start-basic-rsbuild/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/start-basic-rsbuild/.gitignore b/examples/react/start-basic-rsbuild/.gitignore deleted file mode 100644 index 1f189d9bc0..0000000000 --- a/examples/react/start-basic-rsbuild/.gitignore +++ /dev/null @@ -1,19 +0,0 @@ -node_modules -package-lock.json -yarn.lock - -.DS_Store -.cache -.env -.vercel -dist -/build/ -/api/ -/server/build -/public/build# Sentry Config File -.env.sentry-build-plugin -/test-results/ -/playwright-report/ -/blob-report/ -/playwright/.cache/ -.tanstack diff --git a/examples/react/start-basic-rsbuild/.prettierignore b/examples/react/start-basic-rsbuild/.prettierignore deleted file mode 100644 index 2be5eaa6ec..0000000000 --- a/examples/react/start-basic-rsbuild/.prettierignore +++ /dev/null @@ -1,4 +0,0 @@ -**/build -**/public -pnpm-lock.yaml -routeTree.gen.ts \ No newline at end of file diff --git a/examples/react/start-basic-rsbuild/.vscode/settings.json b/examples/react/start-basic-rsbuild/.vscode/settings.json deleted file mode 100644 index 00b5278e58..0000000000 --- a/examples/react/start-basic-rsbuild/.vscode/settings.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "files.watcherExclude": { - "**/routeTree.gen.ts": true - }, - "search.exclude": { - "**/routeTree.gen.ts": true - }, - "files.readonlyInclude": { - "**/routeTree.gen.ts": true - } -} diff --git a/examples/react/start-basic-rsbuild/README.md b/examples/react/start-basic-rsbuild/README.md deleted file mode 100644 index 64117c915b..0000000000 --- a/examples/react/start-basic-rsbuild/README.md +++ /dev/null @@ -1,36 +0,0 @@ -# TanStack Start - Basic Rsbuild Example - -This is the basic TanStack Start Rsbuild example, demonstrating the fundamentals of building applications with TanStack Router and TanStack Start. - -- [TanStack Router Docs](https://tanstack.com/router) - -It's deployed automagically with Netlify! - -- [Netlify](https://netlify.com/) - -## Start a new project based on this example - -To start a new project based on this example, run: - -```sh -npx gitpick TanStack/router/tree/main/examples/react/start-basic-rsbuild start-basic-rsbuild -``` - -## Getting Started - -From your terminal: - -```sh -pnpm install -pnpm dev -``` - -This starts your app in development mode, rebuilding assets on file changes. - -## Build - -To build the app for production: - -```sh -pnpm build -``` diff --git a/examples/react/start-basic-rsbuild/package.json b/examples/react/start-basic-rsbuild/package.json deleted file mode 100644 index bea4ba26ef..0000000000 --- a/examples/react/start-basic-rsbuild/package.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "name": "tanstack-start-example-basic-rsbuild", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "rsbuild dev --port 3000", - "build": "rsbuild build && tsc --noEmit", - "preview": "rsbuild preview", - "start": "srvx --prod -s ../client dist/server/index.js" - }, - "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", - "react": "^19.2.3", - "react-dom": "^19.2.3", - "tailwind-merge": "^3.6.0", - "zod": "^4.4.3" - }, - "devDependencies": { - "@rsbuild/core": "^2.3.1", - "@rsbuild/plugin-react": "^2.0.0", - "@rsbuild/plugin-tailwindcss": "^2.0.3", - "@types/node": "25.0.9", - "@types/react": "^19.2.8", - "@types/react-dom": "^19.2.3", - "srvx": "^1.0.0", - "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-rsbuild/public/android-chrome-192x192.png b/examples/react/start-basic-rsbuild/public/android-chrome-192x192.png deleted file mode 100644 index 09c8324f8c..0000000000 Binary files a/examples/react/start-basic-rsbuild/public/android-chrome-192x192.png and /dev/null differ diff --git a/examples/react/start-basic-rsbuild/public/android-chrome-512x512.png b/examples/react/start-basic-rsbuild/public/android-chrome-512x512.png deleted file mode 100644 index 11d626ea3d..0000000000 Binary files a/examples/react/start-basic-rsbuild/public/android-chrome-512x512.png and /dev/null differ diff --git a/examples/react/start-basic-rsbuild/public/apple-touch-icon.png b/examples/react/start-basic-rsbuild/public/apple-touch-icon.png deleted file mode 100644 index 5a9423cc02..0000000000 Binary files a/examples/react/start-basic-rsbuild/public/apple-touch-icon.png and /dev/null differ diff --git a/examples/react/start-basic-rsbuild/public/favicon-16x16.png b/examples/react/start-basic-rsbuild/public/favicon-16x16.png deleted file mode 100644 index e3389b0044..0000000000 Binary files a/examples/react/start-basic-rsbuild/public/favicon-16x16.png and /dev/null differ diff --git a/examples/react/start-basic-rsbuild/public/favicon-32x32.png b/examples/react/start-basic-rsbuild/public/favicon-32x32.png deleted file mode 100644 index 900c77d444..0000000000 Binary files a/examples/react/start-basic-rsbuild/public/favicon-32x32.png and /dev/null differ diff --git a/examples/react/start-basic-rsbuild/public/favicon.ico b/examples/react/start-basic-rsbuild/public/favicon.ico deleted file mode 100644 index 1a1751676f..0000000000 Binary files a/examples/react/start-basic-rsbuild/public/favicon.ico and /dev/null differ diff --git a/examples/react/start-basic-rsbuild/public/favicon.png b/examples/react/start-basic-rsbuild/public/favicon.png deleted file mode 100644 index 1e77bc0609..0000000000 Binary files a/examples/react/start-basic-rsbuild/public/favicon.png and /dev/null differ diff --git a/examples/react/start-basic-rsbuild/public/site.webmanifest b/examples/react/start-basic-rsbuild/public/site.webmanifest deleted file mode 100644 index fa99de77db..0000000000 --- a/examples/react/start-basic-rsbuild/public/site.webmanifest +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "", - "short_name": "", - "icons": [ - { - "src": "/android-chrome-192x192.png", - "sizes": "192x192", - "type": "image/png" - }, - { - "src": "/android-chrome-512x512.png", - "sizes": "512x512", - "type": "image/png" - } - ], - "theme_color": "#ffffff", - "background_color": "#ffffff", - "display": "standalone" -} diff --git a/examples/react/start-basic-rsbuild/rsbuild.config.ts b/examples/react/start-basic-rsbuild/rsbuild.config.ts deleted file mode 100644 index 3705696818..0000000000 --- a/examples/react/start-basic-rsbuild/rsbuild.config.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' -import { defineConfig } from '@rsbuild/core' -import { pluginReact } from '@rsbuild/plugin-react' -import { pluginTailwindcss } from '@rsbuild/plugin-tailwindcss' - -export default defineConfig({ - server: { - port: 3000, - }, - plugins: [ - pluginTailwindcss(), - pluginReact(), - tanstackStart({ - srcDirectory: 'src', - }), - ], -}) diff --git a/examples/react/start-basic-rsbuild/src/components/DefaultCatchBoundary.tsx b/examples/react/start-basic-rsbuild/src/components/DefaultCatchBoundary.tsx deleted file mode 100644 index 4a22649ed4..0000000000 --- a/examples/react/start-basic-rsbuild/src/components/DefaultCatchBoundary.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { - ErrorComponent, - Link, - useLocation, - useRouter, -} from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' - -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - - console.error('DefaultCatchBoundary Error:', error) - - return ( -
- -
- - {isRoot ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) -} diff --git a/examples/react/start-basic-rsbuild/src/components/NotFound.tsx b/examples/react/start-basic-rsbuild/src/components/NotFound.tsx deleted file mode 100644 index fd4e75befe..0000000000 --- a/examples/react/start-basic-rsbuild/src/components/NotFound.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { Link } from '@tanstack/react-router' - -export function NotFound({ children }: { children?: any }) { - return ( -
-
- {children ||

The page you are looking for does not exist.

} -
-

- - - Start Over - -

-
- ) -} diff --git a/examples/react/start-basic-rsbuild/src/components/PostError.tsx b/examples/react/start-basic-rsbuild/src/components/PostError.tsx deleted file mode 100644 index 271f2d1de1..0000000000 --- a/examples/react/start-basic-rsbuild/src/components/PostError.tsx +++ /dev/null @@ -1,6 +0,0 @@ -import { ErrorComponent } from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' - -export function PostErrorComponent({ error }: ErrorComponentProps) { - return -} diff --git a/examples/react/start-basic-rsbuild/src/components/UserError.tsx b/examples/react/start-basic-rsbuild/src/components/UserError.tsx deleted file mode 100644 index af5d0c6f16..0000000000 --- a/examples/react/start-basic-rsbuild/src/components/UserError.tsx +++ /dev/null @@ -1,6 +0,0 @@ -import { ErrorComponent } from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' - -export function UserErrorComponent({ error }: ErrorComponentProps) { - return -} diff --git a/examples/react/start-basic-rsbuild/src/env.d.ts b/examples/react/start-basic-rsbuild/src/env.d.ts deleted file mode 100644 index b0ac762b09..0000000000 --- a/examples/react/start-basic-rsbuild/src/env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/start-basic-rsbuild/src/routeTree.gen.ts b/examples/react/start-basic-rsbuild/src/routeTree.gen.ts deleted file mode 100644 index 57b849492d..0000000000 --- a/examples/react/start-basic-rsbuild/src/routeTree.gen.ts +++ /dev/null @@ -1,447 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' -import { Route as CustomScriptDotjsRouteImport } from './routes/customScript[.]js' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as RedirectRouteImport } from './routes/redirect' -import { Route as UsersRouteImport } from './routes/users' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as ApiUsersRouteImport } from './routes/api/users' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' -import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', - getParentRoute: () => rootRouteImport, -} as any) -const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ - id: '/customScript.js', - path: '/customScript.js', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', - getParentRoute: () => rootRouteImport, -} as any) -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, - } as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', - getParentRoute: () => rootRouteImport, -} as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, -} as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, -} as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) -const PathlessLayoutNestedLayoutRouteBRoute = - PathlessLayoutNestedLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) -const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => ApiUsersRoute, -} as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/customScript.js': typeof CustomScriptDotjsRoute - '/deferred': typeof DeferredRoute - '/posts': typeof PostsRouteWithChildren - '/redirect': typeof RedirectRoute - '/users': typeof UsersRouteWithChildren - '/api/users': typeof ApiUsersRouteWithChildren - '/posts/$postId': typeof PostsPostIdRoute - '/users/$userId': typeof UsersUserIdRoute - '/posts/': typeof PostsIndexRoute - '/users/': typeof UsersIndexRoute - '/route-a': typeof PathlessLayoutNestedLayoutRouteARoute - '/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute - '/api/users/$userId': typeof ApiUsersUserIdRoute - '/posts/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/customScript.js': typeof CustomScriptDotjsRoute - '/deferred': typeof DeferredRoute - '/redirect': typeof RedirectRoute - '/api/users': typeof ApiUsersRouteWithChildren - '/posts/$postId': typeof PostsPostIdRoute - '/users/$userId': typeof UsersUserIdRoute - '/posts': typeof PostsIndexRoute - '/users': typeof UsersIndexRoute - '/route-a': typeof PathlessLayoutNestedLayoutRouteARoute - '/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute - '/api/users/$userId': typeof ApiUsersUserIdRoute - '/posts/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/_pathlessLayout': typeof PathlessLayoutRouteWithChildren - '/customScript.js': typeof CustomScriptDotjsRoute - '/deferred': typeof DeferredRoute - '/posts': typeof PostsRouteWithChildren - '/redirect': typeof RedirectRoute - '/users': typeof UsersRouteWithChildren - '/_pathlessLayout/_nested-layout': typeof PathlessLayoutNestedLayoutRouteWithChildren - '/api/users': typeof ApiUsersRouteWithChildren - '/posts/$postId': typeof PostsPostIdRoute - '/users/$userId': typeof UsersUserIdRoute - '/posts/': typeof PostsIndexRoute - '/users/': typeof UsersIndexRoute - '/_pathlessLayout/_nested-layout/route-a': typeof PathlessLayoutNestedLayoutRouteARoute - '/_pathlessLayout/_nested-layout/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute - '/api/users/$userId': typeof ApiUsersUserIdRoute - '/posts_/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/customScript.js' - | '/deferred' - | '/posts' - | '/redirect' - | '/users' - | '/api/users' - | '/posts/$postId' - | '/users/$userId' - | '/posts/' - | '/users/' - | '/route-a' - | '/route-b' - | '/api/users/$userId' - | '/posts/$postId/deep' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/customScript.js' - | '/deferred' - | '/redirect' - | '/api/users' - | '/posts/$postId' - | '/users/$userId' - | '/posts' - | '/users' - | '/route-a' - | '/route-b' - | '/api/users/$userId' - | '/posts/$postId/deep' - id: - | '__root__' - | '/' - | '/_pathlessLayout' - | '/customScript.js' - | '/deferred' - | '/posts' - | '/redirect' - | '/users' - | '/_pathlessLayout/_nested-layout' - | '/api/users' - | '/posts/$postId' - | '/users/$userId' - | '/posts/' - | '/users/' - | '/_pathlessLayout/_nested-layout/route-a' - | '/_pathlessLayout/_nested-layout/route-b' - | '/api/users/$userId' - | '/posts_/$postId/deep' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - PathlessLayoutRoute: typeof PathlessLayoutRouteWithChildren - CustomScriptDotjsRoute: typeof CustomScriptDotjsRoute - DeferredRoute: typeof DeferredRoute - PostsRoute: typeof PostsRouteWithChildren - RedirectRoute: typeof RedirectRoute - UsersRoute: typeof UsersRouteWithChildren - ApiUsersRoute: typeof ApiUsersRouteWithChildren - PostsPostIdDeepRoute: typeof PostsPostIdDeepRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout': { - id: '/_pathlessLayout' - path: '' - fullPath: '/' - preLoaderRoute: typeof PathlessLayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/customScript.js': { - id: '/customScript.js' - path: '/customScript.js' - fullPath: '/customScript.js' - preLoaderRoute: typeof CustomScriptDotjsRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport - parentRoute: typeof rootRouteImport - } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute - } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport - parentRoute: typeof rootRouteImport - } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute - } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute - } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } - '/_pathlessLayout/_nested-layout/route-b': { - id: '/_pathlessLayout/_nested-layout/route-b' - path: '/route-b' - fullPath: '/route-b' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } - '/api/users/$userId': { - id: '/api/users/$userId' - path: '/$userId' - fullPath: '/api/users/$userId' - preLoaderRoute: typeof ApiUsersUserIdRouteImport - parentRoute: typeof ApiUsersRoute - } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -interface PathlessLayoutNestedLayoutRouteChildren { - PathlessLayoutNestedLayoutRouteARoute: typeof PathlessLayoutNestedLayoutRouteARoute - PathlessLayoutNestedLayoutRouteBRoute: typeof PathlessLayoutNestedLayoutRouteBRoute -} - -const PathlessLayoutNestedLayoutRouteChildren: PathlessLayoutNestedLayoutRouteChildren = - { - PathlessLayoutNestedLayoutRouteARoute: - PathlessLayoutNestedLayoutRouteARoute, - PathlessLayoutNestedLayoutRouteBRoute: - PathlessLayoutNestedLayoutRouteBRoute, - } - -const PathlessLayoutNestedLayoutRouteWithChildren = - PathlessLayoutNestedLayoutRoute._addFileChildren( - PathlessLayoutNestedLayoutRouteChildren, - ) - -interface PathlessLayoutRouteChildren { - PathlessLayoutNestedLayoutRoute: typeof PathlessLayoutNestedLayoutRouteWithChildren -} - -const PathlessLayoutRouteChildren: PathlessLayoutRouteChildren = { - PathlessLayoutNestedLayoutRoute: PathlessLayoutNestedLayoutRouteWithChildren, -} - -const PathlessLayoutRouteWithChildren = PathlessLayoutRoute._addFileChildren( - PathlessLayoutRouteChildren, -) - -interface PostsRouteChildren { - PostsPostIdRoute: typeof PostsPostIdRoute - PostsIndexRoute: typeof PostsIndexRoute -} - -const PostsRouteChildren: PostsRouteChildren = { - PostsPostIdRoute: PostsPostIdRoute, - PostsIndexRoute: PostsIndexRoute, -} - -const PostsRouteWithChildren = PostsRoute._addFileChildren(PostsRouteChildren) - -interface UsersRouteChildren { - UsersUserIdRoute: typeof UsersUserIdRoute - UsersIndexRoute: typeof UsersIndexRoute -} - -const UsersRouteChildren: UsersRouteChildren = { - UsersUserIdRoute: UsersUserIdRoute, - UsersIndexRoute: UsersIndexRoute, -} - -const UsersRouteWithChildren = UsersRoute._addFileChildren(UsersRouteChildren) - -interface ApiUsersRouteChildren { - ApiUsersUserIdRoute: typeof ApiUsersUserIdRoute -} - -const ApiUsersRouteChildren: ApiUsersRouteChildren = { - ApiUsersUserIdRoute: ApiUsersUserIdRoute, -} - -const ApiUsersRouteWithChildren = ApiUsersRoute._addFileChildren( - ApiUsersRouteChildren, -) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - PathlessLayoutRoute: PathlessLayoutRouteWithChildren, - CustomScriptDotjsRoute: CustomScriptDotjsRoute, - DeferredRoute: DeferredRoute, - PostsRoute: PostsRouteWithChildren, - RedirectRoute: RedirectRoute, - UsersRoute: UsersRouteWithChildren, - ApiUsersRoute: ApiUsersRouteWithChildren, - PostsPostIdDeepRoute: PostsPostIdDeepRoute, -} -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/examples/react/start-basic-rsbuild/src/router.tsx b/examples/react/start-basic-rsbuild/src/router.tsx deleted file mode 100644 index f380f73be7..0000000000 --- a/examples/react/start-basic-rsbuild/src/router.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' -import { DefaultCatchBoundary } from './components/DefaultCatchBoundary' -import { NotFound } from './components/NotFound' - -export function getRouter() { - const router = createRouter({ - routeTree, - defaultPreload: 'intent', - defaultErrorComponent: DefaultCatchBoundary, - defaultNotFoundComponent: () => , - scrollRestoration: true, - }) - return router -} diff --git a/examples/react/start-basic-rsbuild/src/routes/__root.tsx b/examples/react/start-basic-rsbuild/src/routes/__root.tsx deleted file mode 100644 index 6d4aed1fe0..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/__root.tsx +++ /dev/null @@ -1,130 +0,0 @@ -import { - HeadContent, - Link, - Scripts, - createRootRoute, -} from '@tanstack/react-router' -import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' -import * as React from 'react' -import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary' -import { NotFound } from '~/components/NotFound' -import appCss from '~/styles/app.css?url' -import { seo } from '~/utils/seo' - -export const Route = createRootRoute({ - head: () => ({ - meta: [ - { - charSet: 'utf-8', - }, - { - name: 'viewport', - content: 'width=device-width, initial-scale=1', - }, - ...seo({ - title: - 'TanStack Start | Type-Safe, Client-First, Full-Stack React Framework', - description: `TanStack Start is a type-safe, client-first, full-stack React framework. `, - }), - ], - links: [ - { rel: 'stylesheet', href: appCss }, - { - rel: 'apple-touch-icon', - sizes: '180x180', - href: '/apple-touch-icon.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '32x32', - href: '/favicon-32x32.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '16x16', - href: '/favicon-16x16.png', - }, - { rel: 'manifest', href: '/site.webmanifest', color: '#fffff' }, - { rel: 'icon', href: '/favicon.ico' }, - ], - scripts: [ - { - src: '/customScript.js', - type: 'text/javascript', - }, - ], - }), - errorComponent: DefaultCatchBoundary, - notFoundComponent: () => , - shellComponent: RootDocument, -}) - -function RootDocument({ children }: { children: React.ReactNode }) { - return ( - - - - - -
- - Home - {' '} - - Posts - {' '} - - Users - {' '} - - Pathless Layout - {' '} - - Deferred - {' '} - - This Route Does Not Exist - -
-
- {children} - - - - - ) -} diff --git a/examples/react/start-basic-rsbuild/src/routes/_pathlessLayout.tsx b/examples/react/start-basic-rsbuild/src/routes/_pathlessLayout.tsx deleted file mode 100644 index c3b12442b8..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/_pathlessLayout.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_pathlessLayout')({ - component: LayoutComponent, -}) - -function LayoutComponent() { - return ( -
-
I'm a layout
-
- -
-
- ) -} diff --git a/examples/react/start-basic-rsbuild/src/routes/_pathlessLayout/_nested-layout.tsx b/examples/react/start-basic-rsbuild/src/routes/_pathlessLayout/_nested-layout.tsx deleted file mode 100644 index 9a48b73a46..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/_pathlessLayout/_nested-layout.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_pathlessLayout/_nested-layout')({ - component: LayoutComponent, -}) - -function LayoutComponent() { - return ( -
-
I'm a nested layout
-
- - Go to route A - - - Go to route B - -
-
- -
-
- ) -} diff --git a/examples/react/start-basic-rsbuild/src/routes/_pathlessLayout/_nested-layout/route-a.tsx b/examples/react/start-basic-rsbuild/src/routes/_pathlessLayout/_nested-layout/route-a.tsx deleted file mode 100644 index 426a8fe486..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/_pathlessLayout/_nested-layout/route-a.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_pathlessLayout/_nested-layout/route-a')( - { - component: LayoutAComponent, - }, -) - -function LayoutAComponent() { - return
I'm A!
-} diff --git a/examples/react/start-basic-rsbuild/src/routes/_pathlessLayout/_nested-layout/route-b.tsx b/examples/react/start-basic-rsbuild/src/routes/_pathlessLayout/_nested-layout/route-b.tsx deleted file mode 100644 index 20facf2daf..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/_pathlessLayout/_nested-layout/route-b.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_pathlessLayout/_nested-layout/route-b')( - { - component: LayoutBComponent, - }, -) - -function LayoutBComponent() { - return
I'm B!
-} diff --git a/examples/react/start-basic-rsbuild/src/routes/api/users.$userId.ts b/examples/react/start-basic-rsbuild/src/routes/api/users.$userId.ts deleted file mode 100644 index ee34d7a189..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/api/users.$userId.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import type { User } from '~/utils/users' - -export const Route = createFileRoute('/api/users/$userId')({ - server: { - handlers: { - GET: async ({ params, request }) => { - console.info(`Fetching users by id=${params.userId}... @`, request.url) - try { - const res = await fetch( - 'https://jsonplaceholder.typicode.com/users/' + params.userId, - ) - if (!res.ok) { - throw new Error('Failed to fetch user') - } - - const user = (await res.json()) as User - - return Response.json({ - id: user.id, - name: user.name, - email: user.email, - }) - } catch (e) { - console.error(e) - return Response.json({ error: 'User not found' }, { status: 404 }) - } - }, - }, - }, -}) diff --git a/examples/react/start-basic-rsbuild/src/routes/api/users.ts b/examples/react/start-basic-rsbuild/src/routes/api/users.ts deleted file mode 100644 index 4cecd01852..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/api/users.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { getRequestHeaders } from '@tanstack/react-start/server' -import { createMiddleware } from '@tanstack/react-start' -import type { User } from '~/utils/users' - -const userLoggerMiddleware = createMiddleware().server(async ({ next }) => { - console.info('In: /users') - console.info('Request Headers:', getRequestHeaders()) - const result = await next() - result.response.headers.set('x-users', 'true') - console.info('Out: /users') - return result -}) - -const testParentMiddleware = createMiddleware().server(async ({ next }) => { - console.info('In: testParentMiddleware') - const result = await next() - result.response.headers.set('x-test-parent', 'true') - console.info('Out: testParentMiddleware') - return result -}) - -const testMiddleware = createMiddleware() - .middleware([testParentMiddleware]) - .server(async ({ next }) => { - console.info('In: testMiddleware') - const result = await next() - result.response.headers.set('x-test', 'true') - - // if (Math.random() > 0.5) { - // throw new Response(null, { - // status: 302, - // headers: { Location: 'https://www.google.com' }, - // }) - // } - - console.info('Out: testMiddleware') - return result - }) - -export const Route = createFileRoute('/api/users')({ - server: { - middleware: [testMiddleware, userLoggerMiddleware], - handlers: { - GET: async ({ request }) => { - console.info('GET /api/users @', request.url) - console.info('Fetching users... @', request.url) - const res = await fetch('https://jsonplaceholder.typicode.com/users') - if (!res.ok) { - throw new Error('Failed to fetch users') - } - - const data = (await res.json()) as Array - - const list = data.slice(0, 10) - - return Response.json( - list.map((u) => ({ id: u.id, name: u.name, email: u.email })), - ) - }, - }, - }, -}) diff --git a/examples/react/start-basic-rsbuild/src/routes/customScript[.]js.ts b/examples/react/start-basic-rsbuild/src/routes/customScript[.]js.ts deleted file mode 100644 index 811471ac15..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/customScript[.]js.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/customScript.js')({ - server: { - handlers: { - GET: () => { - return new Response('console.log("Hello from customScript.js!")', { - headers: { - 'Content-Type': 'application/javascript', - }, - }) - }, - }, - }, -}) diff --git a/examples/react/start-basic-rsbuild/src/routes/deferred.tsx b/examples/react/start-basic-rsbuild/src/routes/deferred.tsx deleted file mode 100644 index f3e09d1d4e..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/deferred.tsx +++ /dev/null @@ -1,62 +0,0 @@ -import { Await, createFileRoute } from '@tanstack/react-router' -import { createServerFn } from '@tanstack/react-start' -import { Suspense, useState } from 'react' - -const personServerFn = createServerFn({ method: 'GET' }) - .validator((d: string) => d) - .handler(({ data: name }) => { - return { name, randomNumber: Math.floor(Math.random() * 100) } - }) - -const slowServerFn = createServerFn({ method: 'GET' }) - .validator((d: string) => d) - .handler(async ({ data: name }) => { - await new Promise((r) => setTimeout(r, 1000)) - return { name, randomNumber: Math.floor(Math.random() * 100) } - }) - -export const Route = createFileRoute('/deferred')({ - loader: async () => { - return { - deferredStuff: new Promise((r) => - setTimeout(() => r('Hello deferred!'), 2000), - ), - deferredPerson: slowServerFn({ data: 'Tanner Linsley' }), - person: await personServerFn({ data: 'John Doe' }), - } - }, - component: Deferred, -}) - -function Deferred() { - const [count, setCount] = useState(0) - const { deferredStuff, deferredPerson, person } = Route.useLoaderData() - - return ( -
-
- {person.name} - {person.randomNumber} -
- Loading person...
}> - ( -
- {data.name} - {data.randomNumber} -
- )} - /> - - Loading stuff...
}> -

{data}

} - /> - -
Count: {count}
-
- -
-
- ) -} diff --git a/examples/react/start-basic-rsbuild/src/routes/index.tsx b/examples/react/start-basic-rsbuild/src/routes/index.tsx deleted file mode 100644 index 09a907cb18..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/index.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: Home, -}) - -function Home() { - return ( -
-

Welcome Home!!!

-
- ) -} diff --git a/examples/react/start-basic-rsbuild/src/routes/posts.$postId.tsx b/examples/react/start-basic-rsbuild/src/routes/posts.$postId.tsx deleted file mode 100644 index 65905bf8c4..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/posts.$postId.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import { Link, createFileRoute } from '@tanstack/react-router' -import { fetchPost } from '../utils/posts' -import { NotFound } from '~/components/NotFound' -import { PostErrorComponent } from '~/components/PostError' - -export const Route = createFileRoute('/posts/$postId')({ - loader: ({ params: { postId } }) => fetchPost({ data: postId }), - errorComponent: PostErrorComponent, - component: PostComponent, - notFoundComponent: () => { - return Post not found - }, -}) - -function PostComponent() { - const post = Route.useLoaderData() - - return ( -
-

{post.title}

-
{post.body}
- - Deep View - -
- ) -} diff --git a/examples/react/start-basic-rsbuild/src/routes/posts.index.tsx b/examples/react/start-basic-rsbuild/src/routes/posts.index.tsx deleted file mode 100644 index 5b5f08f95b..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/posts.index.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/posts/')({ - component: PostsIndexComponent, -}) - -function PostsIndexComponent() { - return
Select a post.
-} diff --git a/examples/react/start-basic-rsbuild/src/routes/posts.tsx b/examples/react/start-basic-rsbuild/src/routes/posts.tsx deleted file mode 100644 index 9b9162be7c..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/posts.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' -import { fetchPosts } from '../utils/posts' - -export const Route = createFileRoute('/posts')({ - loader: async () => fetchPosts(), - component: PostsComponent, -}) - -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[...posts, { id: 'i-do-not-exist', title: 'Non-existent Post' }].map( - (post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - }, - )} -
-
- -
- ) -} diff --git a/examples/react/start-basic-rsbuild/src/routes/posts_.$postId.deep.tsx b/examples/react/start-basic-rsbuild/src/routes/posts_.$postId.deep.tsx deleted file mode 100644 index 29e6c39b5a..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/posts_.$postId.deep.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { Link, createFileRoute } from '@tanstack/react-router' -import { fetchPost } from '../utils/posts' -import { PostErrorComponent } from '~/components/PostError' - -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.title}

-
{post.body}
-
- ) -} diff --git a/examples/react/start-basic-rsbuild/src/routes/redirect.tsx b/examples/react/start-basic-rsbuild/src/routes/redirect.tsx deleted file mode 100644 index ea34b6e420..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/redirect.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { createFileRoute, redirect } from '@tanstack/react-router' - -export const Route = createFileRoute('/redirect')({ - beforeLoad: () => { - throw redirect({ - to: '/posts', - }) - }, -}) diff --git a/examples/react/start-basic-rsbuild/src/routes/users.$userId.tsx b/examples/react/start-basic-rsbuild/src/routes/users.$userId.tsx deleted file mode 100644 index 4e4d470075..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/users.$userId.tsx +++ /dev/null @@ -1,45 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { NotFound } from '../components/NotFound' -import { UserErrorComponent } from '../components/UserError' -import type { User } from '../utils/users' - -export const Route = createFileRoute('/users/$userId')({ - loader: async ({ params: { userId } }) => { - try { - const res = await fetch('/api/users/' + userId) - if (!res.ok) { - throw new Error('Unexpected status code') - } - - const data = await res.json() - - return data as User - } catch { - throw new Error('Failed to fetch user') - } - }, - errorComponent: UserErrorComponent, - component: UserComponent, - notFoundComponent: () => { - return User not found - }, -}) - -function UserComponent() { - const user = Route.useLoaderData() - - return ( -
- ) -} diff --git a/examples/react/start-basic-rsbuild/src/routes/users.index.tsx b/examples/react/start-basic-rsbuild/src/routes/users.index.tsx deleted file mode 100644 index 27d136987e..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/users.index.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/users/')({ - component: UsersIndexComponent, -}) - -function UsersIndexComponent() { - return ( -
- Select a user or{' '} - - view as JSON - -
- ) -} diff --git a/examples/react/start-basic-rsbuild/src/routes/users.tsx b/examples/react/start-basic-rsbuild/src/routes/users.tsx deleted file mode 100644 index 64ca3ce156..0000000000 --- a/examples/react/start-basic-rsbuild/src/routes/users.tsx +++ /dev/null @@ -1,49 +0,0 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' -import type { User } from '../utils/users' - -export const Route = createFileRoute('/users')({ - loader: async () => { - const res = await fetch('/api/users') - - if (!res.ok) { - throw new Error('Unexpected status code') - } - - const data = await res.json() - - return data as Array - }, - component: UsersComponent, -}) - -function UsersComponent() { - const users = Route.useLoaderData() - - return ( -
-
    - {[ - ...users, - { id: 'i-do-not-exist', name: 'Non-existent User', email: '' }, - ].map((user) => { - return ( -
  • - -
    {user.name}
    - -
  • - ) - })} -
-
- -
- ) -} diff --git a/examples/react/start-basic-rsbuild/src/styles/app.css b/examples/react/start-basic-rsbuild/src/styles/app.css deleted file mode 100644 index 37c1f5a6e2..0000000000 --- a/examples/react/start-basic-rsbuild/src/styles/app.css +++ /dev/null @@ -1,30 +0,0 @@ -@import 'tailwindcss' source('../'); - -@layer base { - *, - ::after, - ::before, - ::backdrop, - ::file-selector-button { - border-color: var(--color-gray-200, currentcolor); - } -} - -@layer base { - html { - color-scheme: light dark; - } - - * { - @apply border-gray-200 dark:border-gray-800; - } - - html, - body { - @apply text-gray-900 bg-gray-50 dark:bg-gray-950 dark:text-gray-200; - } - - .using-mouse * { - outline: none !important; - } -} diff --git a/examples/react/start-basic-rsbuild/src/utils/loggingMiddleware.tsx b/examples/react/start-basic-rsbuild/src/utils/loggingMiddleware.tsx deleted file mode 100644 index 3ea9a06439..0000000000 --- a/examples/react/start-basic-rsbuild/src/utils/loggingMiddleware.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import { createMiddleware } from '@tanstack/react-start' - -const preLogMiddleware = createMiddleware({ type: 'function' }) - .client(async (ctx) => { - const clientTime = new Date() - - return ctx.next({ - context: { - clientTime, - }, - sendContext: { - clientTime, - }, - }) - }) - .server(async (ctx) => { - const serverTime = new Date() - - return ctx.next({ - sendContext: { - serverTime, - durationToServer: - serverTime.getTime() - ctx.context.clientTime.getTime(), - }, - }) - }) - -export const logMiddleware = createMiddleware({ type: 'function' }) - .middleware([preLogMiddleware]) - .client(async (ctx) => { - const res = await ctx.next() - - const now = new Date() - console.log('Client Req/Res:', { - duration: now.getTime() - res.context.clientTime.getTime(), - durationToServer: res.context.durationToServer, - durationFromServer: now.getTime() - res.context.serverTime.getTime(), - }) - - return res - }) diff --git a/examples/react/start-basic-rsbuild/src/utils/posts.tsx b/examples/react/start-basic-rsbuild/src/utils/posts.tsx deleted file mode 100644 index ea7dd0a721..0000000000 --- a/examples/react/start-basic-rsbuild/src/utils/posts.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import { notFound } from '@tanstack/react-router' -import { createServerFn } from '@tanstack/react-start' - -export type PostType = { - id: number - title: string - body: string -} - -export const fetchPost = createServerFn({ method: 'POST' }) - .validator((d: string) => d) - .handler(async ({ data }) => { - console.info(`Fetching post with id ${data}...`) - const res = await fetch( - `https://jsonplaceholder.typicode.com/posts/${data}`, - ) - if (!res.ok) { - if (res.status === 404) { - throw notFound() - } - - throw new Error('Failed to fetch post') - } - - const post = await res.json() - - return post as PostType - }) - -export const fetchPosts = createServerFn().handler(async () => { - console.info('Fetching posts...') - const res = await fetch('https://jsonplaceholder.typicode.com/posts') - if (!res.ok) { - throw new Error('Failed to fetch posts') - } - - const posts = await res.json() - - return (posts as Array).slice(0, 10) -}) diff --git a/examples/react/start-basic-rsbuild/src/utils/seo.ts b/examples/react/start-basic-rsbuild/src/utils/seo.ts deleted file mode 100644 index d18ad84b74..0000000000 --- a/examples/react/start-basic-rsbuild/src/utils/seo.ts +++ /dev/null @@ -1,33 +0,0 @@ -export const seo = ({ - title, - description, - keywords, - image, -}: { - title: string - description?: string - image?: string - keywords?: string -}) => { - const tags = [ - { title }, - { name: 'description', content: description }, - { name: 'keywords', content: keywords }, - { name: 'twitter:title', content: title }, - { name: 'twitter:description', content: description }, - { name: 'twitter:creator', content: '@tannerlinsley' }, - { name: 'twitter:site', content: '@tannerlinsley' }, - { name: 'og:type', content: 'website' }, - { name: 'og:title', content: title }, - { name: 'og:description', content: description }, - ...(image - ? [ - { name: 'twitter:image', content: image }, - { name: 'twitter:card', content: 'summary_large_image' }, - { name: 'og:image', content: image }, - ] - : []), - ] - - return tags -} diff --git a/examples/react/start-basic-rsbuild/src/utils/users.tsx b/examples/react/start-basic-rsbuild/src/utils/users.tsx deleted file mode 100644 index 7ba645b383..0000000000 --- a/examples/react/start-basic-rsbuild/src/utils/users.tsx +++ /dev/null @@ -1,5 +0,0 @@ -export type User = { - id: number - name: string - email: string -} diff --git a/examples/react/start-basic-rsbuild/tsconfig.json b/examples/react/start-basic-rsbuild/tsconfig.json deleted file mode 100644 index cc479423a1..0000000000 --- a/examples/react/start-basic-rsbuild/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "include": ["**/*.ts", "**/*.tsx", "**/*.d.ts"], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "react-jsx", - "module": "ESNext", - "moduleResolution": "Bundler", - "lib": ["DOM", "DOM.Iterable", "ES2024"], - "isolatedModules": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "target": "ES2024", - "allowJs": true, - "forceConsistentCasingInFileNames": true, - "paths": { - "~/*": ["./src/*"] - }, - "noEmit": true - } -} diff --git a/examples/react/start-basic-rsc/.devcontainer/devcontainer.json b/examples/react/start-basic-rsc/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/start-basic-rsc/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/start-basic-rsc/README.md b/examples/react/start-basic-rsc/README.md new file mode 100644 index 0000000000..a08a08413d --- /dev/null +++ b/examples/react/start-basic-rsc/README.md @@ -0,0 +1,17 @@ +# Deprecated: TanStack Start React Example (`start-basic-rsc`) + +This example is retained for compatibility and historical reference. + +For new projects, use: + +- [TanStack Builder](https://tanstack.com/builder) +- `npx @tanstack/cli create` + +For topic-specific setup, use the Start guides: + +- [Start React Quick Start](https://tanstack.com/router/latest/docs/framework/react/start/quick-start) +- [Start React Guides](https://tanstack.com/router/latest/docs/framework/react/start/guide/routing) + +Canonical issue reproduction baseline: + +- [React `start-basic`](https://github.com/TanStack/router/tree/main/examples/react/start-basic) diff --git a/examples/react/start-basic-static/.devcontainer/devcontainer.json b/examples/react/start-basic-static/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/start-basic-static/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/start-basic-static/.gitignore b/examples/react/start-basic-static/.gitignore deleted file mode 100644 index ca63f49885..0000000000 --- a/examples/react/start-basic-static/.gitignore +++ /dev/null @@ -1,18 +0,0 @@ -node_modules -package-lock.json -yarn.lock - -.DS_Store -.cache -.env -.vercel -.output -/build/ -/api/ -/server/build -/public/build# Sentry Config File -.env.sentry-build-plugin -/test-results/ -/playwright-report/ -/blob-report/ -/playwright/.cache/ diff --git a/examples/react/start-basic-static/.prettierignore b/examples/react/start-basic-static/.prettierignore deleted file mode 100644 index 2be5eaa6ec..0000000000 --- a/examples/react/start-basic-static/.prettierignore +++ /dev/null @@ -1,4 +0,0 @@ -**/build -**/public -pnpm-lock.yaml -routeTree.gen.ts \ No newline at end of file diff --git a/examples/react/start-basic-static/README.md b/examples/react/start-basic-static/README.md index 9f05a92695..3dc335dfae 100644 --- a/examples/react/start-basic-static/README.md +++ b/examples/react/start-basic-static/README.md @@ -1,44 +1,17 @@ -# TanStack Start - Static Example +# Deprecated: TanStack Start React Example (`start-basic-static`) -This site is built with TanStack Router! +This example is retained for compatibility and historical reference. -- [TanStack Router Docs](https://tanstack.com/router) +For new projects, use: -## Start a new project based on this example +- [TanStack Builder](https://tanstack.com/builder) +- `npx @tanstack/cli create` -To start a new project based on this example, run: +For topic-specific setup, use the Start guides: -```sh -npx gitpick TanStack/router/tree/main/examples/react/start-basic-static start-basic-static -``` +- [Start React Quick Start](https://tanstack.com/router/latest/docs/framework/react/start/quick-start) +- [Static Prerendering](https://tanstack.com/router/latest/docs/framework/react/start/guide/static-prerendering) -## Deployment +Canonical issue reproduction baseline: -It's deployed automagically with Vercel! - -- [Vercel](https://vercel.com/) - -## Getting Started - -From your terminal: - -```sh -pnpm install -pnpm dev -``` - -## Build - -Build for production: - -```sh -pnpm build -``` - -## About This Example - -This example demonstrates: - -- Static Site Generation (SSG) with TanStack Start -- Prerendering routes -- Static export +- [React `start-basic`](https://github.com/TanStack/router/tree/main/examples/react/start-basic) diff --git a/examples/react/start-basic-static/package.json b/examples/react/start-basic-static/package.json deleted file mode 100644 index 58d573ca36..0000000000 --- a/examples/react/start-basic-static/package.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "name": "tanstack-start-example-basic-static", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "vite dev", - "build": "vite build && tsc --noEmit", - "preview": "vite preview", - "start": "pnpx srvx --prod -s ../client dist/server/server.js" - }, - "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", - "@tanstack/start-static-server-functions": "^1.167.44", - "@vitejs/plugin-react": "^6.0.1", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "redaxios": "^0.5.1", - "tailwind-merge": "^3.6.0" - }, - "devDependencies": { - "@tailwindcss/vite": "^4.2.2", - "@types/node": "^22.5.4", - "@types/react": "^19.0.8", - "@types/react-dom": "^19.0.3", - "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" - } -} diff --git a/examples/react/start-basic-static/public/android-chrome-192x192.png b/examples/react/start-basic-static/public/android-chrome-192x192.png deleted file mode 100644 index 09c8324f8c..0000000000 Binary files a/examples/react/start-basic-static/public/android-chrome-192x192.png and /dev/null differ diff --git a/examples/react/start-basic-static/public/android-chrome-512x512.png b/examples/react/start-basic-static/public/android-chrome-512x512.png deleted file mode 100644 index 11d626ea3d..0000000000 Binary files a/examples/react/start-basic-static/public/android-chrome-512x512.png and /dev/null differ diff --git a/examples/react/start-basic-static/public/apple-touch-icon.png b/examples/react/start-basic-static/public/apple-touch-icon.png deleted file mode 100644 index 5a9423cc02..0000000000 Binary files a/examples/react/start-basic-static/public/apple-touch-icon.png and /dev/null differ diff --git a/examples/react/start-basic-static/public/favicon-16x16.png b/examples/react/start-basic-static/public/favicon-16x16.png deleted file mode 100644 index e3389b0044..0000000000 Binary files a/examples/react/start-basic-static/public/favicon-16x16.png and /dev/null differ diff --git a/examples/react/start-basic-static/public/favicon-32x32.png b/examples/react/start-basic-static/public/favicon-32x32.png deleted file mode 100644 index 900c77d444..0000000000 Binary files a/examples/react/start-basic-static/public/favicon-32x32.png and /dev/null differ diff --git a/examples/react/start-basic-static/public/favicon.ico b/examples/react/start-basic-static/public/favicon.ico deleted file mode 100644 index 1a1751676f..0000000000 Binary files a/examples/react/start-basic-static/public/favicon.ico and /dev/null differ diff --git a/examples/react/start-basic-static/public/favicon.png b/examples/react/start-basic-static/public/favicon.png deleted file mode 100644 index 1e77bc0609..0000000000 Binary files a/examples/react/start-basic-static/public/favicon.png and /dev/null differ diff --git a/examples/react/start-basic-static/public/site.webmanifest b/examples/react/start-basic-static/public/site.webmanifest deleted file mode 100644 index fa99de77db..0000000000 --- a/examples/react/start-basic-static/public/site.webmanifest +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "", - "short_name": "", - "icons": [ - { - "src": "/android-chrome-192x192.png", - "sizes": "192x192", - "type": "image/png" - }, - { - "src": "/android-chrome-512x512.png", - "sizes": "512x512", - "type": "image/png" - } - ], - "theme_color": "#ffffff", - "background_color": "#ffffff", - "display": "standalone" -} diff --git a/examples/react/start-basic-static/src/components/DefaultCatchBoundary.tsx b/examples/react/start-basic-static/src/components/DefaultCatchBoundary.tsx deleted file mode 100644 index 4a22649ed4..0000000000 --- a/examples/react/start-basic-static/src/components/DefaultCatchBoundary.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { - ErrorComponent, - Link, - useLocation, - useRouter, -} from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' - -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - - console.error('DefaultCatchBoundary Error:', error) - - return ( -
- -
- - {isRoot ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) -} diff --git a/examples/react/start-basic-static/src/components/NotFound.tsx b/examples/react/start-basic-static/src/components/NotFound.tsx deleted file mode 100644 index fd4e75befe..0000000000 --- a/examples/react/start-basic-static/src/components/NotFound.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { Link } from '@tanstack/react-router' - -export function NotFound({ children }: { children?: any }) { - return ( -
-
- {children ||

The page you are looking for does not exist.

} -
-

- - - Start Over - -

-
- ) -} diff --git a/examples/react/start-basic-static/src/routeTree.gen.ts b/examples/react/start-basic-static/src/routeTree.gen.ts deleted file mode 100644 index d4a8e72343..0000000000 --- a/examples/react/start-basic-static/src/routeTree.gen.ts +++ /dev/null @@ -1,374 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as RedirectRouteImport } from './routes/redirect' -import { Route as UsersRouteImport } from './routes/users' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', - getParentRoute: () => rootRouteImport, -} as any) -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, - } as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, -} as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, -} as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) -const PathlessLayoutNestedLayoutRouteBRoute = - PathlessLayoutNestedLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/deferred': typeof DeferredRoute - '/posts': typeof PostsRouteWithChildren - '/redirect': typeof RedirectRoute - '/users': typeof UsersRouteWithChildren - '/posts/$postId': typeof PostsPostIdRoute - '/users/$userId': typeof UsersUserIdRoute - '/posts/': typeof PostsIndexRoute - '/users/': typeof UsersIndexRoute - '/route-a': typeof PathlessLayoutNestedLayoutRouteARoute - '/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute - '/posts/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/deferred': typeof DeferredRoute - '/redirect': typeof RedirectRoute - '/posts/$postId': typeof PostsPostIdRoute - '/users/$userId': typeof UsersUserIdRoute - '/posts': typeof PostsIndexRoute - '/users': typeof UsersIndexRoute - '/route-a': typeof PathlessLayoutNestedLayoutRouteARoute - '/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute - '/posts/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/_pathlessLayout': typeof PathlessLayoutRouteWithChildren - '/deferred': typeof DeferredRoute - '/posts': typeof PostsRouteWithChildren - '/redirect': typeof RedirectRoute - '/users': typeof UsersRouteWithChildren - '/_pathlessLayout/_nested-layout': typeof PathlessLayoutNestedLayoutRouteWithChildren - '/posts/$postId': typeof PostsPostIdRoute - '/users/$userId': typeof UsersUserIdRoute - '/posts/': typeof PostsIndexRoute - '/users/': typeof UsersIndexRoute - '/_pathlessLayout/_nested-layout/route-a': typeof PathlessLayoutNestedLayoutRouteARoute - '/_pathlessLayout/_nested-layout/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute - '/posts_/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/deferred' - | '/posts' - | '/redirect' - | '/users' - | '/posts/$postId' - | '/users/$userId' - | '/posts/' - | '/users/' - | '/route-a' - | '/route-b' - | '/posts/$postId/deep' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/deferred' - | '/redirect' - | '/posts/$postId' - | '/users/$userId' - | '/posts' - | '/users' - | '/route-a' - | '/route-b' - | '/posts/$postId/deep' - id: - | '__root__' - | '/' - | '/_pathlessLayout' - | '/deferred' - | '/posts' - | '/redirect' - | '/users' - | '/_pathlessLayout/_nested-layout' - | '/posts/$postId' - | '/users/$userId' - | '/posts/' - | '/users/' - | '/_pathlessLayout/_nested-layout/route-a' - | '/_pathlessLayout/_nested-layout/route-b' - | '/posts_/$postId/deep' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - PathlessLayoutRoute: typeof PathlessLayoutRouteWithChildren - DeferredRoute: typeof DeferredRoute - PostsRoute: typeof PostsRouteWithChildren - RedirectRoute: typeof RedirectRoute - UsersRoute: typeof UsersRouteWithChildren - PostsPostIdDeepRoute: typeof PostsPostIdDeepRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout': { - id: '/_pathlessLayout' - path: '' - fullPath: '/' - preLoaderRoute: typeof PathlessLayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport - parentRoute: typeof rootRouteImport - } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute - } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute - } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute - } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } - '/_pathlessLayout/_nested-layout/route-b': { - id: '/_pathlessLayout/_nested-layout/route-b' - path: '/route-b' - fullPath: '/route-b' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -interface PathlessLayoutNestedLayoutRouteChildren { - PathlessLayoutNestedLayoutRouteARoute: typeof PathlessLayoutNestedLayoutRouteARoute - PathlessLayoutNestedLayoutRouteBRoute: typeof PathlessLayoutNestedLayoutRouteBRoute -} - -const PathlessLayoutNestedLayoutRouteChildren: PathlessLayoutNestedLayoutRouteChildren = - { - PathlessLayoutNestedLayoutRouteARoute: - PathlessLayoutNestedLayoutRouteARoute, - PathlessLayoutNestedLayoutRouteBRoute: - PathlessLayoutNestedLayoutRouteBRoute, - } - -const PathlessLayoutNestedLayoutRouteWithChildren = - PathlessLayoutNestedLayoutRoute._addFileChildren( - PathlessLayoutNestedLayoutRouteChildren, - ) - -interface PathlessLayoutRouteChildren { - PathlessLayoutNestedLayoutRoute: typeof PathlessLayoutNestedLayoutRouteWithChildren -} - -const PathlessLayoutRouteChildren: PathlessLayoutRouteChildren = { - PathlessLayoutNestedLayoutRoute: PathlessLayoutNestedLayoutRouteWithChildren, -} - -const PathlessLayoutRouteWithChildren = PathlessLayoutRoute._addFileChildren( - PathlessLayoutRouteChildren, -) - -interface PostsRouteChildren { - PostsPostIdRoute: typeof PostsPostIdRoute - PostsIndexRoute: typeof PostsIndexRoute -} - -const PostsRouteChildren: PostsRouteChildren = { - PostsPostIdRoute: PostsPostIdRoute, - PostsIndexRoute: PostsIndexRoute, -} - -const PostsRouteWithChildren = PostsRoute._addFileChildren(PostsRouteChildren) - -interface UsersRouteChildren { - UsersUserIdRoute: typeof UsersUserIdRoute - UsersIndexRoute: typeof UsersIndexRoute -} - -const UsersRouteChildren: UsersRouteChildren = { - UsersUserIdRoute: UsersUserIdRoute, - UsersIndexRoute: UsersIndexRoute, -} - -const UsersRouteWithChildren = UsersRoute._addFileChildren(UsersRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - PathlessLayoutRoute: PathlessLayoutRouteWithChildren, - DeferredRoute: DeferredRoute, - PostsRoute: PostsRouteWithChildren, - RedirectRoute: RedirectRoute, - UsersRoute: UsersRouteWithChildren, - PostsPostIdDeepRoute: PostsPostIdDeepRoute, -} -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/examples/react/start-basic-static/src/router.tsx b/examples/react/start-basic-static/src/router.tsx deleted file mode 100644 index 5b15fa1059..0000000000 --- a/examples/react/start-basic-static/src/router.tsx +++ /dev/null @@ -1,17 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' -import { DefaultCatchBoundary } from './components/DefaultCatchBoundary' -import { NotFound } from './components/NotFound' - -export function getRouter() { - const router = createRouter({ - routeTree, - basepath: '/test/', - defaultPreload: 'intent', - defaultErrorComponent: DefaultCatchBoundary, - defaultNotFoundComponent: () => , - scrollRestoration: true, - }) - - return router -} diff --git a/examples/react/start-basic-static/src/routes/__root.tsx b/examples/react/start-basic-static/src/routes/__root.tsx deleted file mode 100644 index 5a5c051bbe..0000000000 --- a/examples/react/start-basic-static/src/routes/__root.tsx +++ /dev/null @@ -1,140 +0,0 @@ -/// -import { - HeadContent, - Link, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' -import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' -import * as React from 'react' -import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary' -import { NotFound } from '~/components/NotFound' -import appCss from '~/styles/app.css?url' -import { seo } from '~/utils/seo' - -export const Route = createRootRoute({ - head: () => ({ - meta: [ - { - charSet: 'utf-8', - }, - { - name: 'viewport', - content: 'width=device-width, initial-scale=1', - }, - ...seo({ - title: - 'TanStack Start | Type-Safe, Client-First, Full-Stack React Framework', - description: `TanStack Start is a type-safe, client-first, full-stack React framework. `, - }), - ], - links: [ - { rel: 'stylesheet', href: appCss }, - { - rel: 'apple-touch-icon', - sizes: '180x180', - href: '/apple-touch-icon.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '32x32', - href: '/favicon-32x32.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '16x16', - href: '/favicon-16x16.png', - }, - { rel: 'manifest', href: '/site.webmanifest', color: '#fffff' }, - { rel: 'icon', href: '/favicon.ico' }, - ], - }), - errorComponent: (props) => { - return ( - - - - ) - }, - notFoundComponent: () => , - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - ) -} - -function RootLayout({ children }: { children: React.ReactNode }) { - return ( - - - - - -
- - Home - {' '} - - Posts - {' '} - - Users - {' '} - - Pathless Layout - {' '} - - Deferred - {' '} - - This Route Does Not Exist - -
-
- {children} - - - - - ) -} diff --git a/examples/react/start-basic-static/src/routes/_pathlessLayout.tsx b/examples/react/start-basic-static/src/routes/_pathlessLayout.tsx deleted file mode 100644 index 29d3477145..0000000000 --- a/examples/react/start-basic-static/src/routes/_pathlessLayout.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_pathlessLayout')({ - component: PathlessLayoutComponent, -}) - -function PathlessLayoutComponent() { - return ( -
-
I'm a pathless layout
-
- -
-
- ) -} diff --git a/examples/react/start-basic-static/src/routes/_pathlessLayout/_nested-layout.tsx b/examples/react/start-basic-static/src/routes/_pathlessLayout/_nested-layout.tsx deleted file mode 100644 index 9a48b73a46..0000000000 --- a/examples/react/start-basic-static/src/routes/_pathlessLayout/_nested-layout.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_pathlessLayout/_nested-layout')({ - component: LayoutComponent, -}) - -function LayoutComponent() { - return ( -
-
I'm a nested layout
-
- - Go to route A - - - Go to route B - -
-
- -
-
- ) -} diff --git a/examples/react/start-basic-static/src/routes/_pathlessLayout/_nested-layout/route-a.tsx b/examples/react/start-basic-static/src/routes/_pathlessLayout/_nested-layout/route-a.tsx deleted file mode 100644 index 0213f1516f..0000000000 --- a/examples/react/start-basic-static/src/routes/_pathlessLayout/_nested-layout/route-a.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/_pathlessLayout/_nested-layout/route-a')( - { - component: LayoutAComponent, - }, -) - -function LayoutAComponent() { - return
I'm A!
-} diff --git a/examples/react/start-basic-static/src/routes/_pathlessLayout/_nested-layout/route-b.tsx b/examples/react/start-basic-static/src/routes/_pathlessLayout/_nested-layout/route-b.tsx deleted file mode 100644 index 3d909523fb..0000000000 --- a/examples/react/start-basic-static/src/routes/_pathlessLayout/_nested-layout/route-b.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/_pathlessLayout/_nested-layout/route-b')( - { - component: LayoutBComponent, - }, -) - -function LayoutBComponent() { - return
I'm B!
-} diff --git a/examples/react/start-basic-static/src/routes/deferred.tsx b/examples/react/start-basic-static/src/routes/deferred.tsx deleted file mode 100644 index 07810ddc39..0000000000 --- a/examples/react/start-basic-static/src/routes/deferred.tsx +++ /dev/null @@ -1,65 +0,0 @@ -import { Await, createFileRoute } from '@tanstack/react-router' -import { createServerFn } from '@tanstack/react-start' -import { Suspense, useState } from 'react' -import { staticFunctionMiddleware } from '@tanstack/start-static-server-functions' - -const personServerFn = createServerFn({ method: 'GET' }) - .middleware([staticFunctionMiddleware]) - .validator((d: string) => d) - .handler(({ data: name }) => { - return { name, randomNumber: Math.floor(Math.random() * 100) } - }) - -const slowServerFn = createServerFn({ method: 'GET' }) - .middleware([staticFunctionMiddleware]) - .validator((d: string) => d) - .handler(async ({ data: name }) => { - await new Promise((r) => setTimeout(r, 1000)) - return { name, randomNumber: Math.floor(Math.random() * 100) } - }) - -export const Route = createFileRoute('/deferred')({ - loader: async () => { - return { - deferredStuff: new Promise((r) => - setTimeout(() => r('Hello deferred!'), 2000), - ), - deferredPerson: slowServerFn({ data: 'Tanner Linsley' }), - person: await personServerFn({ data: 'John Doe' }), - } - }, - component: Deferred, -}) - -function Deferred() { - const [count, setCount] = useState(0) - const { deferredStuff, deferredPerson, person } = Route.useLoaderData() - - return ( -
-
- {person.name} - {person.randomNumber} -
- Loading person...
}> - ( -
- {data.name} - {data.randomNumber} -
- )} - /> - - Loading stuff...
}> -

{data}

} - /> - -
Count: {count}
-
- -
-
- ) -} diff --git a/examples/react/start-basic-static/src/routes/index.tsx b/examples/react/start-basic-static/src/routes/index.tsx deleted file mode 100644 index 37c8d237bd..0000000000 --- a/examples/react/start-basic-static/src/routes/index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/')({ - component: Home, -}) - -function Home() { - return ( -
-

Welcome Home!!!

-
- ) -} diff --git a/examples/react/start-basic-static/src/routes/posts.$postId.tsx b/examples/react/start-basic-static/src/routes/posts.$postId.tsx deleted file mode 100644 index 301f675142..0000000000 --- a/examples/react/start-basic-static/src/routes/posts.$postId.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import { ErrorComponent, Link, createFileRoute } from '@tanstack/react-router' -import { fetchPost } from '../utils/posts' -import type { ErrorComponentProps } from '@tanstack/react-router' -import { NotFound } from '~/components/NotFound' - -export const Route = createFileRoute('/posts/$postId')({ - loader: ({ params: { postId } }) => fetchPost({ data: postId }), - errorComponent: PostErrorComponent, - component: PostComponent, - notFoundComponent: () => { - return Post not found - }, -}) - -export function PostErrorComponent({ error }: ErrorComponentProps) { - return -} - -function PostComponent() { - const post = Route.useLoaderData() - - return ( -
-

{post.title}

-
{post.body}
- - Deep View - -
- ) -} diff --git a/examples/react/start-basic-static/src/routes/posts.index.tsx b/examples/react/start-basic-static/src/routes/posts.index.tsx deleted file mode 100644 index c659274567..0000000000 --- a/examples/react/start-basic-static/src/routes/posts.index.tsx +++ /dev/null @@ -1,8 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/posts/')({ - component: PostsIndexComponent, -}) - -function PostsIndexComponent() { - return
Select a post.
-} diff --git a/examples/react/start-basic-static/src/routes/posts.tsx b/examples/react/start-basic-static/src/routes/posts.tsx deleted file mode 100644 index ae49032459..0000000000 --- a/examples/react/start-basic-static/src/routes/posts.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' -import { fetchPosts } from '../utils/posts' - -export const Route = createFileRoute('/posts')({ - loader: async () => fetchPosts(), - component: PostsComponent, -}) - -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[...posts, { id: 'i-do-not-exist', title: 'Non-existent Post' }].map( - (post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - }, - )} -
-
- -
- ) -} diff --git a/examples/react/start-basic-static/src/routes/posts_.$postId.deep.tsx b/examples/react/start-basic-static/src/routes/posts_.$postId.deep.tsx deleted file mode 100644 index a82d2e3211..0000000000 --- a/examples/react/start-basic-static/src/routes/posts_.$postId.deep.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { Link, createFileRoute } from '@tanstack/react-router' -import { fetchPost } from '../utils/posts' -import { PostErrorComponent } from './posts.$postId' - -export const Route = createFileRoute('/posts_/$postId/deep')({ - loader: ({ params: { postId } }) => - fetchPost({ - data: postId, - }), - errorComponent: PostErrorComponent, - component: PostDeepComponent, -}) - -function PostDeepComponent() { - const post = Route.useLoaderData() - - return ( -
- - ← All Posts - -

{post.title}

-
{post.body}
-
- ) -} diff --git a/examples/react/start-basic-static/src/routes/redirect.tsx b/examples/react/start-basic-static/src/routes/redirect.tsx deleted file mode 100644 index fa220b5097..0000000000 --- a/examples/react/start-basic-static/src/routes/redirect.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { redirect, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/redirect')({ - beforeLoad: async () => { - throw redirect({ - to: '/posts', - }) - }, -}) diff --git a/examples/react/start-basic-static/src/routes/users.$userId.tsx b/examples/react/start-basic-static/src/routes/users.$userId.tsx deleted file mode 100644 index 2d2d32279d..0000000000 --- a/examples/react/start-basic-static/src/routes/users.$userId.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { ErrorComponent, createFileRoute } from '@tanstack/react-router' -import axios from 'redaxios' -import { createServerFn } from '@tanstack/react-start' -import type { ErrorComponentProps } from '@tanstack/react-router' -import type { User } from '~/utils/users' -import { NotFound } from '~/components/NotFound' -import { staticFunctionMiddleware } from '@tanstack/start-static-server-functions' - -const fetchUser = createServerFn({ method: 'GET' }) - .middleware([staticFunctionMiddleware]) - .validator((d: string) => d) - .handler(async ({ data: userId }) => { - return axios - .get('https://jsonplaceholder.typicode.com/users/' + userId) - .then((d) => ({ - id: d.data.id, - name: d.data.name, - email: d.data.email, - })) - .catch((e) => { - throw new Error('Failed to fetch user') - }) - }) - -export const Route = createFileRoute('/users/$userId')({ - loader: ({ params: { userId } }) => fetchUser({ data: userId }), - errorComponent: UserErrorComponent, - component: UserComponent, - notFoundComponent: () => { - return User not found - }, -}) - -export function UserErrorComponent({ error }: ErrorComponentProps) { - return -} - -function UserComponent() { - const user = Route.useLoaderData() - - if ('error' in user) { - return User not found - } - - return ( -
-

{user.name}

-
{user.email}
-
- ) -} diff --git a/examples/react/start-basic-static/src/routes/users.index.tsx b/examples/react/start-basic-static/src/routes/users.index.tsx deleted file mode 100644 index ea814e2cbf..0000000000 --- a/examples/react/start-basic-static/src/routes/users.index.tsx +++ /dev/null @@ -1,8 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/users/')({ - component: UsersIndexComponent, -}) - -function UsersIndexComponent() { - return
Select a user.
-} diff --git a/examples/react/start-basic-static/src/routes/users.tsx b/examples/react/start-basic-static/src/routes/users.tsx deleted file mode 100644 index 98fb79518b..0000000000 --- a/examples/react/start-basic-static/src/routes/users.tsx +++ /dev/null @@ -1,55 +0,0 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' -import axios from 'redaxios' -import { createServerFn } from '@tanstack/react-start' -import type { User } from '../utils/users' -import { staticFunctionMiddleware } from '@tanstack/start-static-server-functions' - -const fetchUsers = createServerFn({ method: 'GET' }) - .middleware([staticFunctionMiddleware]) - .handler(async () => { - console.info('Fetching users...') - const res = await axios.get>( - 'https://jsonplaceholder.typicode.com/users', - ) - - return res.data - .slice(0, 10) - .map((u) => ({ id: u.id, name: u.name, email: u.email })) - }) - -export const Route = createFileRoute('/users')({ - loader: async () => fetchUsers(), - component: UsersComponent, -}) - -function UsersComponent() { - const users = Route.useLoaderData() - - return ( -
-
    - {[ - ...users, - { id: 'i-do-not-exist', name: 'Non-existent User', email: '' }, - ].map((user) => { - return ( -
  • - -
    {user.name}
    - -
  • - ) - })} -
-
- -
- ) -} diff --git a/examples/react/start-basic-static/src/styles/app.css b/examples/react/start-basic-static/src/styles/app.css deleted file mode 100644 index fa96982706..0000000000 --- a/examples/react/start-basic-static/src/styles/app.css +++ /dev/null @@ -1,32 +0,0 @@ -@import 'tailwindcss' source('../'); - -@source '../**/*.{js,jsx,ts,tsx}'; - -/* - The default border color has changed to `currentcolor` in Tailwind CSS v4, - so we've added these compatibility styles to make sure everything still - looks the same as it did with Tailwind CSS v3. - - If we ever want to remove these styles, we need to add an explicit border - color utility to any element that depends on these defaults. -*/ -@layer base { - *, - ::after, - ::before, - ::backdrop, - ::file-selector-button { - border-color: var(--color-gray-200, currentcolor); - } -} - -@layer base { - html, - body { - @apply text-gray-900 bg-gray-50 dark:bg-gray-950 dark:text-gray-200; - } - - .using-mouse * { - outline: none !important; - } -} diff --git a/examples/react/start-basic-static/src/utils/loggingMiddleware.tsx b/examples/react/start-basic-static/src/utils/loggingMiddleware.tsx deleted file mode 100644 index 80ef49b306..0000000000 --- a/examples/react/start-basic-static/src/utils/loggingMiddleware.tsx +++ /dev/null @@ -1,42 +0,0 @@ -import { createMiddleware } from '@tanstack/react-start' - -export const logMiddleware = createMiddleware({ type: 'function' }) - .middleware([ - createMiddleware({ type: 'function' }) - .client(async (ctx) => { - const clientTime = new Date() - - return await ctx.next({ - context: { - clientTime, - }, - sendContext: { - clientTime, - }, - }) - }) - .server(async (ctx) => { - const serverTime = new Date() - - return await ctx.next({ - sendContext: { - serverTime, - durationToServer: - serverTime.getTime() - ctx.context.clientTime.getTime(), - }, - }) - }), - ]) - .client(async (options) => { - const result = await options.next() - - const now = new Date() - - console.log('Client Req/Res:', { - duration: result.context.clientTime.getTime() - now.getTime(), - durationToServer: result.context.durationToServer, - durationFromServer: now.getTime() - result.context.serverTime.getTime(), - }) - - return result - }) diff --git a/examples/react/start-basic-static/src/utils/posts.tsx b/examples/react/start-basic-static/src/utils/posts.tsx deleted file mode 100644 index 82e568ceef..0000000000 --- a/examples/react/start-basic-static/src/utils/posts.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import { createServerFn } from '@tanstack/react-start' -import axios from 'redaxios' -import { notFound } from '@tanstack/react-router' -import { logMiddleware } from './loggingMiddleware' -import { staticFunctionMiddleware } from '@tanstack/start-static-server-functions' - -export type PostType = { - id: string - title: string - body: string -} - -export const fetchPost = createServerFn({ method: 'GET' }) - .middleware([logMiddleware, staticFunctionMiddleware]) - .validator((d: string) => d) - .handler(async ({ data }) => { - console.info(`Fetching post with id ${data}...`) - const post = await axios - .get(`https://jsonplaceholder.typicode.com/posts/${data}`) - .catch((err) => { - if (err.status === 404) { - throw notFound() - } - throw err - }) - .then((r) => r.data) - - return post - }) - -export const fetchPosts = createServerFn({ method: 'GET' }) - .middleware([logMiddleware, staticFunctionMiddleware]) - .handler(async () => { - console.info('Fetching posts...') - return axios - .get>('https://jsonplaceholder.typicode.com/posts') - .then((r) => r.data.slice(0, 10)) - }) diff --git a/examples/react/start-basic-static/src/utils/seo.ts b/examples/react/start-basic-static/src/utils/seo.ts deleted file mode 100644 index d18ad84b74..0000000000 --- a/examples/react/start-basic-static/src/utils/seo.ts +++ /dev/null @@ -1,33 +0,0 @@ -export const seo = ({ - title, - description, - keywords, - image, -}: { - title: string - description?: string - image?: string - keywords?: string -}) => { - const tags = [ - { title }, - { name: 'description', content: description }, - { name: 'keywords', content: keywords }, - { name: 'twitter:title', content: title }, - { name: 'twitter:description', content: description }, - { name: 'twitter:creator', content: '@tannerlinsley' }, - { name: 'twitter:site', content: '@tannerlinsley' }, - { name: 'og:type', content: 'website' }, - { name: 'og:title', content: title }, - { name: 'og:description', content: description }, - ...(image - ? [ - { name: 'twitter:image', content: image }, - { name: 'twitter:card', content: 'summary_large_image' }, - { name: 'og:image', content: image }, - ] - : []), - ] - - return tags -} diff --git a/examples/react/start-basic-static/src/utils/users.tsx b/examples/react/start-basic-static/src/utils/users.tsx deleted file mode 100644 index b810f455fe..0000000000 --- a/examples/react/start-basic-static/src/utils/users.tsx +++ /dev/null @@ -1,7 +0,0 @@ -export type User = { - id: number - name: string - email: string -} - -export const DEPLOY_URL = 'http://localhost:3000' diff --git a/examples/react/start-basic-static/tsconfig.json b/examples/react/start-basic-static/tsconfig.json deleted file mode 100644 index cef9369516..0000000000 --- a/examples/react/start-basic-static/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "include": ["**/*.ts", "**/*.tsx"], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "react-jsx", - "module": "ESNext", - "moduleResolution": "Bundler", - "lib": ["DOM", "DOM.Iterable", "ES2022"], - "isolatedModules": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "target": "ES2022", - "allowJs": true, - "forceConsistentCasingInFileNames": true, - "paths": { - "~/*": ["./src/*"] - }, - "noEmit": true - } -} diff --git a/examples/react/start-basic-static/vite.config.ts b/examples/react/start-basic-static/vite.config.ts deleted file mode 100644 index d7ecaddd27..0000000000 --- a/examples/react/start-basic-static/vite.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { tanstackStart } from '@tanstack/react-start/plugin/vite' -import { defineConfig } from 'vite' -import viteReact from '@vitejs/plugin-react' -import tailwindcss from '@tailwindcss/vite' - -export default defineConfig({ - base: '/test/', - server: { - port: 3000, - }, - resolve: { - tsconfigPaths: true, - }, - plugins: [ - tailwindcss(), - tanstackStart({ - spa: { - enabled: true, - prerender: { - crawlLinks: true, - }, - }, - sitemap: { - host: 'https://localhost:3000', - }, - prerender: { - failOnError: false, - }, - }), - viteReact(), - ], -}) diff --git a/examples/react/start-basic/.devcontainer/devcontainer.json b/examples/react/start-basic/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/start-basic/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/start-basic/package.json b/examples/react/start-basic/package.json index 46df8e4650..1a66a2487d 100644 --- a/examples/react/start-basic/package.json +++ b/examples/react/start-basic/package.json @@ -10,24 +10,24 @@ "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.161.1", + "@tanstack/react-router-devtools": "^1.161.1", + "@tanstack/react-start": "^1.161.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "tailwind-merge": "^3.6.0", - "zod": "^4.4.3" + "tailwind-merge": "^2.6.0", + "zod": "^3.24.2" }, "devDependencies": { - "@tailwindcss/vite": "^4.2.2", + "@tailwindcss/vite": "^4.1.18", "@types/node": "^22.5.4", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "nitro": "^3.0.260903-beta", - "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" + "@vitejs/plugin-react": "^4.6.0", + "nitro": "3.0.1-alpha.2", + "tailwindcss": "^4.1.18", + "typescript": "^5.7.2", + "vite": "^7.3.1", + "vite-tsconfig-paths": "^5.1.4" } } diff --git a/examples/react/start-basic/src/components/DefaultCatchBoundary.tsx b/examples/react/start-basic/src/components/DefaultCatchBoundary.tsx index 4a22649ed4..260c2ea41f 100644 --- a/examples/react/start-basic/src/components/DefaultCatchBoundary.tsx +++ b/examples/react/start-basic/src/components/DefaultCatchBoundary.tsx @@ -1,15 +1,17 @@ import { ErrorComponent, Link, - useLocation, + rootRouteId, + useMatch, useRouter, } from '@tanstack/react-router' import type { ErrorComponentProps } from '@tanstack/react-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', + const isRoot = useMatch({ + strict: false, + select: (state) => state.id === rootRouteId, }) console.error('DefaultCatchBoundary Error:', error) diff --git a/examples/react/start-basic/src/routeTree.gen.ts b/examples/react/start-basic/src/routeTree.gen.ts index 57b849492d..06a64190d7 100644 --- a/examples/react/start-basic/src/routeTree.gen.ts +++ b/examples/react/start-basic/src/routeTree.gen.ts @@ -9,46 +9,27 @@ // 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 PathlessLayoutRouteImport } from './routes/_pathlessLayout' -import { Route as CustomScriptDotjsRouteImport } from './routes/customScript[.]js' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as RedirectRouteImport } from './routes/redirect' import { Route as UsersRouteImport } from './routes/users' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as ApiUsersRouteImport } from './routes/api/users' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as RedirectRouteImport } from './routes/redirect' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as CustomScriptDotjsRouteImport } from './routes/customScript[.]js' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as IndexRouteImport } from './routes/index' import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' -import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' +import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', - getParentRoute: () => rootRouteImport, -} as any) -const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ - id: '/customScript.js', - path: '/customScript.js', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const RedirectRoute = RedirectRouteImport.update({ @@ -56,9 +37,53 @@ const RedirectRoute = RedirectRouteImport.update({ path: '/redirect', getParentRoute: () => rootRouteImport, } as any) -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', + getParentRoute: () => rootRouteImport, +} as any) +const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ + id: '/customScript.js', + path: '/customScript.js', + getParentRoute: () => rootRouteImport, +} as any) +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, +} as any) +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) +const UsersUserIdRoute = UsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => UsersRoute, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutNestedLayoutRoute = @@ -66,53 +91,28 @@ const PathlessLayoutNestedLayoutRoute = id: '/_nested-layout', getParentRoute: () => PathlessLayoutRoute, } as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', getParentRoute: () => rootRouteImport, } as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, -} as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ +const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ id: '/$userId', path: '/$userId', - getParentRoute: () => UsersRoute, + getParentRoute: () => ApiUsersRoute, } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ id: '/route-b', path: '/route-b', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) -const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => ApiUsersRoute, -} as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, -} as any) +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -234,39 +234,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout': { - id: '/_pathlessLayout' - path: '' - fullPath: '/' - preLoaderRoute: typeof PathlessLayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/customScript.js': { - id: '/customScript.js' - path: '/customScript.js' - fullPath: '/customScript.js' - preLoaderRoute: typeof CustomScriptDotjsRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/redirect': { @@ -276,40 +248,40 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof RedirectRouteImport parentRoute: typeof rootRouteImport } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/customScript.js': { + id: '/customScript.js' + path: '/customScript.js' + fullPath: '/customScript.js' + preLoaderRoute: typeof CustomScriptDotjsRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout': { + id: '/_pathlessLayout' path: '' - fullPath: '/' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute - } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + fullPath: '' + preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' + '/': { + id: '/' path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/users/': { id: '/users/' @@ -318,6 +290,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof UsersIndexRouteImport parentRoute: typeof UsersRoute } + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute + } '/users/$userId': { id: '/users/$userId' path: '/$userId' @@ -325,19 +304,33 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof UsersUserIdRouteImport parentRoute: typeof UsersRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute } - '/_pathlessLayout/_nested-layout/route-b': { - id: '/_pathlessLayout/_nested-layout/route-b' - path: '/route-b' - fullPath: '/route-b' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' + path: '' + fullPath: '' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute + } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport } '/api/users/$userId': { id: '/api/users/$userId' @@ -346,12 +339,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ApiUsersUserIdRouteImport parentRoute: typeof ApiUsersRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport + '/_pathlessLayout/_nested-layout/route-b': { + id: '/_pathlessLayout/_nested-layout/route-b' + path: '/route-b' + fullPath: '/route-b' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute + } + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } } } diff --git a/examples/react/start-basic/src/routes/deferred.tsx b/examples/react/start-basic/src/routes/deferred.tsx index f3e09d1d4e..c38808243e 100644 --- a/examples/react/start-basic/src/routes/deferred.tsx +++ b/examples/react/start-basic/src/routes/deferred.tsx @@ -3,13 +3,13 @@ import { createServerFn } from '@tanstack/react-start' import { Suspense, useState } from 'react' const personServerFn = createServerFn({ method: 'GET' }) - .validator((d: string) => d) + .inputValidator((d: string) => d) .handler(({ data: name }) => { return { name, randomNumber: Math.floor(Math.random() * 100) } }) const slowServerFn = createServerFn({ method: 'GET' }) - .validator((d: string) => d) + .inputValidator((d: string) => d) .handler(async ({ data: name }) => { await new Promise((r) => setTimeout(r, 1000)) return { name, randomNumber: Math.floor(Math.random() * 100) } diff --git a/examples/react/start-basic/src/routes/users.$userId.tsx b/examples/react/start-basic/src/routes/users.$userId.tsx index 4e4d470075..1df768344d 100644 --- a/examples/react/start-basic/src/routes/users.$userId.tsx +++ b/examples/react/start-basic/src/routes/users.$userId.tsx @@ -1,6 +1,6 @@ import { createFileRoute } from '@tanstack/react-router' -import { NotFound } from '../components/NotFound' -import { UserErrorComponent } from '../components/UserError' +import { NotFound } from 'src/components/NotFound' +import { UserErrorComponent } from 'src/components/UserError' import type { User } from '../utils/users' export const Route = createFileRoute('/users/$userId')({ diff --git a/examples/react/start-basic/src/utils/posts.tsx b/examples/react/start-basic/src/utils/posts.tsx index ea7dd0a721..098542fd74 100644 --- a/examples/react/start-basic/src/utils/posts.tsx +++ b/examples/react/start-basic/src/utils/posts.tsx @@ -8,7 +8,7 @@ export type PostType = { } export const fetchPost = createServerFn({ method: 'POST' }) - .validator((d: string) => d) + .inputValidator((d: string) => d) .handler(async ({ data }) => { console.info(`Fetching post with id ${data}...`) const res = await fetch( diff --git a/examples/react/start-basic/tsconfig.json b/examples/react/start-basic/tsconfig.json index cc479423a1..3a9fb7cd71 100644 --- a/examples/react/start-basic/tsconfig.json +++ b/examples/react/start-basic/tsconfig.json @@ -1,18 +1,19 @@ { - "include": ["**/*.ts", "**/*.tsx", "**/*.d.ts"], + "include": ["**/*.ts", "**/*.tsx"], "compilerOptions": { "strict": true, "esModuleInterop": true, "jsx": "react-jsx", "module": "ESNext", "moduleResolution": "Bundler", - "lib": ["DOM", "DOM.Iterable", "ES2024"], + "lib": ["DOM", "DOM.Iterable", "ES2022"], "isolatedModules": true, "resolveJsonModule": true, "skipLibCheck": true, - "target": "ES2024", + "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, + "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/react/start-basic/vite.config.ts b/examples/react/start-basic/vite.config.ts index 65fa77fd66..ad18174847 100644 --- a/examples/react/start-basic/vite.config.ts +++ b/examples/react/start-basic/vite.config.ts @@ -1,18 +1,18 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { defineConfig } from 'vite' +import tsConfigPaths from 'vite-tsconfig-paths' import viteReact from '@vitejs/plugin-react' import tailwindcss from '@tailwindcss/vite' import { nitro } from 'nitro/vite' - export default defineConfig({ server: { port: 3000, }, - resolve: { - tsconfigPaths: true, - }, plugins: [ tailwindcss(), + tsConfigPaths({ + projects: ['./tsconfig.json'], + }), tanstackStart({ srcDirectory: 'src', }), diff --git a/examples/react/start-bun/.devcontainer/devcontainer.json b/examples/react/start-bun/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/start-bun/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/start-bun/.gitignore b/examples/react/start-bun/.gitignore deleted file mode 100644 index 029f7fba9a..0000000000 --- a/examples/react/start-bun/.gitignore +++ /dev/null @@ -1,12 +0,0 @@ -node_modules -.DS_Store -dist -dist-ssr -*.local -count.txt -.env -.nitro -.tanstack -.output -.vinxi -todos.json diff --git a/examples/react/start-bun/.prettierignore b/examples/react/start-bun/.prettierignore deleted file mode 100644 index 5322d7feea..0000000000 --- a/examples/react/start-bun/.prettierignore +++ /dev/null @@ -1,3 +0,0 @@ -package-lock.json -pnpm-lock.yaml -yarn.lock \ No newline at end of file diff --git a/examples/react/start-bun/.vscode/settings.json b/examples/react/start-bun/.vscode/settings.json deleted file mode 100644 index 00b5278e58..0000000000 --- a/examples/react/start-bun/.vscode/settings.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "files.watcherExclude": { - "**/routeTree.gen.ts": true - }, - "search.exclude": { - "**/routeTree.gen.ts": true - }, - "files.readonlyInclude": { - "**/routeTree.gen.ts": true - } -} diff --git a/examples/react/start-bun/README.md b/examples/react/start-bun/README.md index 04920e8796..73c4f8ca11 100644 --- a/examples/react/start-bun/README.md +++ b/examples/react/start-bun/README.md @@ -1,209 +1,16 @@ -# TanStack Start + Bun Production Server +# Deprecated: TanStack Start React Example (`start-bun`) -An optimized production server for TanStack Start applications using Bun, implementing intelligent static asset loading with configurable memory management. +This example is retained for compatibility and historical reference. -- [TanStack Router Docs](https://tanstack.com/router) -- [Bun Documentation](https://bun.sh/docs) +For new projects, use: -## Start a new project based on this example +- [TanStack Builder](https://tanstack.com/builder) +- `npx @tanstack/cli create` -To start a new project based on this example, run: +For topic-specific setup, use the Start guides: -```sh -npx gitpick TanStack/router/tree/main/examples/react/start-bun start-bun -``` +- [Start React Hosting Guide](https://tanstack.com/router/latest/docs/framework/react/start/guide/hosting) -## 🚀 Features +Canonical issue reproduction baseline: -- **Hybrid Loading Strategy**: Small files are preloaded into memory, large files are served on-demand -- **Configurable File Filtering**: Include/Exclude patterns for precise control -- **Memory-efficient Response Generation**: Optimized for high performance -- **Production-ready Caching Headers**: Automatic Cache-Control headers for optimal performance -- **Detailed Logging**: Vite-like output for better overview - -## 📦 Installation - -This project was created with TanStack Start: - -```bash -bunx create-start-app@latest -``` - -Install dependencies: - -```bash -bun install -``` - -## 🏃‍♂️ Development - -For development: - -```bash -bun run dev -``` - -## 🔨 Production Build - -Build the application for production: - -```bash -bun run build -``` - -## 🚀 Production Server with server.ts - -### Quick Start - Use in Your Project - -You can easily use this production server in your own TanStack Start project: - -1. **Copy the `server.ts` file** into your project root -2. **Build your project** with `bun run build` -3. **Start the server** directly with: - ```bash - bun run server.ts - ``` - -Or add it to your `package.json` scripts: - -```json -{ - "scripts": { - "start": "bun run server.ts" - } -} -``` - -Then run with: - -```bash -bun run start -``` - -### Server Features - -The `server.ts` implements a high-performance production server with the following features: - -#### 1. Intelligent Asset Loading - -The server automatically decides which files to preload into memory and which to serve on-demand: - -- **In-Memory Loading**: Small files (default < 5MB) are loaded into memory at startup -- **On-Demand Loading**: Large files are loaded from disk only when requested -- **Optimized Performance**: Frequently used assets are served from memory - -#### 2. Configuration via Environment Variables - -```bash -# Server Port (default: 3000) -PORT=3000 - -# Maximum file size for in-memory loading (in bytes, default: 5MB) -STATIC_PRELOAD_MAX_BYTES=5242880 - -# Include patterns (comma-separated, only these files will be preloaded) -STATIC_PRELOAD_INCLUDE="*.js,*.css,*.woff2" - -# Exclude patterns (comma-separated, these files will be excluded) -STATIC_PRELOAD_EXCLUDE="*.map,*.txt" - -# Enable detailed logging -STATIC_PRELOAD_VERBOSE=true -``` - -### Example Configurations - -#### Minimal Memory Footprint - -```bash -# Preload only critical assets -STATIC_PRELOAD_MAX_BYTES=1048576 \ -STATIC_PRELOAD_INCLUDE="*.js,*.css" \ -STATIC_PRELOAD_EXCLUDE="*.map,vendor-*" \ -bun run start -``` - -#### Maximum Performance - -```bash -# Preload all small assets -STATIC_PRELOAD_MAX_BYTES=10485760 \ -bun run start -``` - -#### Debug Mode - -```bash -# With detailed logging -STATIC_PRELOAD_VERBOSE=true \ -bun run start -``` - -### Server Output - -The server displays a clear overview of all loaded assets at startup: - -```txt -📦 Loading static assets from ./dist/client... - Max preload size: 5.00 MB - Include patterns: *.js,*.css,*.woff2 - -📁 Preloaded into memory: - /assets/index-a1b2c3d4.js 45.23 kB │ gzip: 15.83 kB - /assets/index-e5f6g7h8.css 12.45 kB │ gzip: 4.36 kB - -💾 Served on-demand: - /assets/vendor-i9j0k1l2.js 245.67 kB │ gzip: 86.98 kB - -✅ Preloaded 2 files (57.68 KB) into memory -ℹ️ 1 files will be served on-demand (1 too large, 0 filtered) - -🚀 Server running at http://localhost:3000 -``` - -## Getting Started - -From your terminal: - -```sh -pnpm install -pnpm dev -``` - -## Build - -Build for production: - -```sh -pnpm build -``` - -## Production - -Start the production server: - -```sh -pnpm start -``` - -## Testing - -This project uses [Vitest](https://vitest.dev/) for testing. You can run the tests with: - -```bash -bun run test -``` - -## Styling - -This project uses [Tailwind CSS](https://tailwindcss.com/) for styling. - -## Linting & Formatting - -This project uses [eslint](https://eslint.org/) and [prettier](https://prettier.io/) for linting and formatting. Eslint is configured using [tanstack/eslint-config](https://tanstack.com/config/latest/docs/eslint). The following scripts are available: - -```bash -bun run lint -bun run format -bun run check -``` +- [React `start-basic`](https://github.com/TanStack/router/tree/main/examples/react/start-basic) diff --git a/examples/react/start-bun/eslint.config.js b/examples/react/start-bun/eslint.config.js deleted file mode 100644 index 676b32a87f..0000000000 --- a/examples/react/start-bun/eslint.config.js +++ /dev/null @@ -1,5 +0,0 @@ -// @ts-check - -import { tanstackConfig } from '@tanstack/eslint-config' - -export default [...tanstackConfig] diff --git a/examples/react/start-bun/package.json b/examples/react/start-bun/package.json deleted file mode 100644 index 24f7113912..0000000000 --- a/examples/react/start-bun/package.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "name": "tanstack-start-bun-hosting", - "private": true, - "type": "module", - "scripts": { - "dev": "vite dev --port 3000", - "start": "bun run server.ts", - "build": "vite build", - "preview": "vite preview", - "test": "vitest run", - "lint": "eslint", - "format": "prettier", - "check": "prettier --write . && eslint --fix" - }, - "dependencies": { - "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-devtools": "^0.7.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-router-ssr-query": "^1.167.3", - "@tanstack/react-start": "^1.169.6", - "@tanstack/router-plugin": "^1.169.0", - "react": "^19.1.1", - "react-dom": "^19.1.1", - "tailwindcss": "^4.2.2" - }, - "devDependencies": { - "@tanstack/eslint-config": "^0.3.2", - "@testing-library/dom": "^10.4.1", - "@testing-library/react": "^16.3.0", - "@types/bun": "^1.2.22", - "@types/node": "22.10.2", - "@types/react": "^19.1.13", - "@types/react-dom": "^19.1.9", - "@vitejs/plugin-react": "^6.0.1", - "jsdom": "^27.0.0", - "prettier": "^3.6.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "vitest": "^5.0.4", - "web-vitals": "^5.1.0" - } -} diff --git a/examples/react/start-bun/prettier.config.js b/examples/react/start-bun/prettier.config.js deleted file mode 100644 index f7279f7ba5..0000000000 --- a/examples/react/start-bun/prettier.config.js +++ /dev/null @@ -1,10 +0,0 @@ -// @ts-check - -/** @type {import('prettier').Config} */ -const config = { - semi: false, - singleQuote: true, - trailingComma: 'all', -} - -export default config diff --git a/examples/react/start-bun/public/favicon.ico b/examples/react/start-bun/public/favicon.ico deleted file mode 100644 index a11777cc47..0000000000 Binary files a/examples/react/start-bun/public/favicon.ico and /dev/null differ diff --git a/examples/react/start-bun/public/logo192.png b/examples/react/start-bun/public/logo192.png deleted file mode 100644 index fc44b0a379..0000000000 Binary files a/examples/react/start-bun/public/logo192.png and /dev/null differ diff --git a/examples/react/start-bun/public/logo512.png b/examples/react/start-bun/public/logo512.png deleted file mode 100644 index a4e47a6545..0000000000 Binary files a/examples/react/start-bun/public/logo512.png and /dev/null differ diff --git a/examples/react/start-bun/public/manifest.json b/examples/react/start-bun/public/manifest.json deleted file mode 100644 index 078ef50116..0000000000 --- a/examples/react/start-bun/public/manifest.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "short_name": "TanStack App", - "name": "Create TanStack App Sample", - "icons": [ - { - "src": "favicon.ico", - "sizes": "64x64 32x32 24x24 16x16", - "type": "image/x-icon" - }, - { - "src": "logo192.png", - "type": "image/png", - "sizes": "192x192" - }, - { - "src": "logo512.png", - "type": "image/png", - "sizes": "512x512" - } - ], - "start_url": ".", - "display": "standalone", - "theme_color": "#000000", - "background_color": "#ffffff" -} diff --git a/examples/react/start-bun/public/robots.txt b/examples/react/start-bun/public/robots.txt deleted file mode 100644 index e9e57dc4d4..0000000000 --- a/examples/react/start-bun/public/robots.txt +++ /dev/null @@ -1,3 +0,0 @@ -# https://www.robotstxt.org/robotstxt.html -User-agent: * -Disallow: diff --git a/examples/react/start-bun/server.ts b/examples/react/start-bun/server.ts deleted file mode 100644 index be8d3b1ed5..0000000000 --- a/examples/react/start-bun/server.ts +++ /dev/null @@ -1,556 +0,0 @@ -/** - * TanStack Start Production Server with Bun - * - * A high-performance production server for TanStack Start applications that - * implements intelligent static asset loading with configurable memory management. - * - * Features: - * - Hybrid loading strategy (preload small files, serve large files on-demand) - * - Configurable file filtering with include/exclude patterns - * - Memory-efficient response generation - * - Production-ready caching headers - * - * Environment Variables: - * - * PORT (number) - * - Server port number - * - Default: 3000 - * - * ASSET_PRELOAD_MAX_SIZE (number) - * - Maximum file size in bytes to preload into memory - * - Files larger than this will be served on-demand from disk - * - Default: 5242880 (5MB) - * - Example: ASSET_PRELOAD_MAX_SIZE=5242880 (5MB) - * - * ASSET_PRELOAD_INCLUDE_PATTERNS (string) - * - Comma-separated list of glob patterns for files to include - * - If specified, only matching files are eligible for preloading - * - Patterns are matched against filenames only, not full paths - * - Example: ASSET_PRELOAD_INCLUDE_PATTERNS="*.js,*.css,*.woff2" - * - * ASSET_PRELOAD_EXCLUDE_PATTERNS (string) - * - Comma-separated list of glob patterns for files to exclude - * - Applied after include patterns - * - Patterns are matched against filenames only, not full paths - * - Example: ASSET_PRELOAD_EXCLUDE_PATTERNS="*.map,*.txt" - * - * ASSET_PRELOAD_VERBOSE_LOGGING (boolean) - * - Enable detailed logging of loaded and skipped files - * - Default: false - * - Set to "true" to enable verbose output - * - * ASSET_PRELOAD_ENABLE_ETAG (boolean) - * - Enable ETag generation for preloaded assets - * - Default: true - * - Set to "false" to disable ETag support - * - * ASSET_PRELOAD_ENABLE_GZIP (boolean) - * - Enable Gzip compression for eligible assets - * - Default: true - * - Set to "false" to disable Gzip compression - * - * ASSET_PRELOAD_GZIP_MIN_SIZE (number) - * - Minimum file size in bytes required for Gzip compression - * - Files smaller than this will not be compressed - * - Default: 1024 (1KB) - * - * ASSET_PRELOAD_GZIP_MIME_TYPES (string) - * - Comma-separated list of MIME types eligible for Gzip compression - * - Supports partial matching for types ending with "/" - * - Default: text/,application/javascript,application/json,application/xml,image/svg+xml - * - * Usage: - * bun run server.ts - */ - -import path from 'node:path' - -// Configuration -const SERVER_PORT = Number(process.env.PORT ?? 3000) -const CLIENT_DIRECTORY = './dist/client' -const SERVER_ENTRY_POINT = './dist/server/server.js' - -// Logging utilities for professional output -const log = { - info: (message: string) => { - console.log(`[INFO] ${message}`) - }, - success: (message: string) => { - console.log(`[SUCCESS] ${message}`) - }, - warning: (message: string) => { - console.log(`[WARNING] ${message}`) - }, - error: (message: string) => { - console.log(`[ERROR] ${message}`) - }, - header: (message: string) => { - console.log(`\n${message}\n`) - }, -} - -// Preloading configuration from environment variables -const MAX_PRELOAD_BYTES = Number( - process.env.ASSET_PRELOAD_MAX_SIZE ?? 5 * 1024 * 1024, // 5MB default -) - -// Parse comma-separated include patterns (no defaults) -const INCLUDE_PATTERNS = (process.env.ASSET_PRELOAD_INCLUDE_PATTERNS ?? '') - .split(',') - .map((s) => s.trim()) - .filter(Boolean) - .map((pattern: string) => convertGlobToRegExp(pattern)) - -// Parse comma-separated exclude patterns (no defaults) -const EXCLUDE_PATTERNS = (process.env.ASSET_PRELOAD_EXCLUDE_PATTERNS ?? '') - .split(',') - .map((s) => s.trim()) - .filter(Boolean) - .map((pattern: string) => convertGlobToRegExp(pattern)) - -// Verbose logging flag -const VERBOSE = process.env.ASSET_PRELOAD_VERBOSE_LOGGING === 'true' - -// Optional ETag feature -const ENABLE_ETAG = (process.env.ASSET_PRELOAD_ENABLE_ETAG ?? 'true') === 'true' - -// Optional Gzip feature -const ENABLE_GZIP = (process.env.ASSET_PRELOAD_ENABLE_GZIP ?? 'true') === 'true' -const GZIP_MIN_BYTES = Number(process.env.ASSET_PRELOAD_GZIP_MIN_SIZE ?? 1024) // 1KB -const GZIP_TYPES = ( - process.env.ASSET_PRELOAD_GZIP_MIME_TYPES ?? - 'text/,application/javascript,application/json,application/xml,image/svg+xml' -) - .split(',') - .map((v) => v.trim()) - .filter(Boolean) - -/** - * Convert a simple glob pattern to a regular expression - * Supports * wildcard for matching any characters - */ -function convertGlobToRegExp(globPattern: string): RegExp { - // Escape regex special chars except *, then replace * with .* - const escapedPattern = globPattern - .replace(/[-/\\^$+?.()|[\]{}]/g, '\\$&') - .replace(/\*/g, '.*') - return new RegExp(`^${escapedPattern}$`, 'i') -} - -/** - * Compute ETag for a given data buffer - */ -function computeEtag(data: Uint8Array): string { - const hash = Bun.hash(data) - return `W/"${hash.toString(16)}-${data.byteLength.toString()}"` -} - -/** - * Metadata for preloaded static assets - */ -interface AssetMetadata { - route: string - size: number - type: string -} - -/** - * In-memory asset with ETag and Gzip support - */ -interface InMemoryAsset { - raw: Uint8Array - gz?: Uint8Array - etag?: string - type: string - immutable: boolean - size: number -} - -/** - * Result of static asset preloading process - */ -interface PreloadResult { - routes: Record Response | Promise> - loaded: AssetMetadata[] - skipped: AssetMetadata[] -} - -/** - * Check if a file is eligible for preloading based on configured patterns - */ -function isFileEligibleForPreloading(relativePath: string): boolean { - const fileName = relativePath.split(/[/\\]/).pop() ?? relativePath - - // If include patterns are specified, file must match at least one - if (INCLUDE_PATTERNS.length > 0) { - if (!INCLUDE_PATTERNS.some((pattern) => pattern.test(fileName))) { - return false - } - } - - // If exclude patterns are specified, file must not match any - if (EXCLUDE_PATTERNS.some((pattern) => pattern.test(fileName))) { - return false - } - - return true -} - -/** - * Check if a MIME type is compressible - */ -function isMimeTypeCompressible(mimeType: string): boolean { - return GZIP_TYPES.some((type) => - type.endsWith('/') ? mimeType.startsWith(type) : mimeType === type, - ) -} - -/** - * Conditionally compress data based on size and MIME type - */ -function compressDataIfAppropriate( - data: Uint8Array, - mimeType: string, -): Uint8Array | undefined { - if (!ENABLE_GZIP) return undefined - if (data.byteLength < GZIP_MIN_BYTES) return undefined - if (!isMimeTypeCompressible(mimeType)) return undefined - try { - return Bun.gzipSync(data.buffer as ArrayBuffer) - } catch { - return undefined - } -} - -/** - * Create response handler function with ETag and Gzip support - */ -function createResponseHandler( - asset: InMemoryAsset, -): (req: Request) => Response { - return (req: Request) => { - const headers: Record = { - 'Content-Type': asset.type, - 'Cache-Control': asset.immutable - ? 'public, max-age=31536000, immutable' - : 'public, max-age=3600', - } - - if (ENABLE_ETAG && asset.etag) { - const ifNone = req.headers.get('if-none-match') - if (ifNone && ifNone === asset.etag) { - return new Response(null, { - status: 304, - headers: { ETag: asset.etag }, - }) - } - headers.ETag = asset.etag - } - - if ( - ENABLE_GZIP && - asset.gz && - req.headers.get('accept-encoding')?.includes('gzip') - ) { - headers['Content-Encoding'] = 'gzip' - headers['Content-Length'] = String(asset.gz.byteLength) - const gzCopy = new Uint8Array(asset.gz) - return new Response(gzCopy, { status: 200, headers }) - } - - headers['Content-Length'] = String(asset.raw.byteLength) - const rawCopy = new Uint8Array(asset.raw) - return new Response(rawCopy, { status: 200, headers }) - } -} - -/** - * Create composite glob pattern from include patterns - */ -function createCompositeGlobPattern(): Bun.Glob { - const raw = (process.env.ASSET_PRELOAD_INCLUDE_PATTERNS ?? '') - .split(',') - .map((s) => s.trim()) - .filter(Boolean) - if (raw.length === 0) return new Bun.Glob('**/*') - if (raw.length === 1) return new Bun.Glob(raw[0]) - return new Bun.Glob(`{${raw.join(',')}}`) -} - -/** - * Initialize static routes with intelligent preloading strategy - * Small files are loaded into memory, large files are served on-demand - */ -async function initializeStaticRoutes( - clientDirectory: string, -): Promise { - const routes: Record Response | Promise> = - {} - const loaded: AssetMetadata[] = [] - const skipped: AssetMetadata[] = [] - - log.info(`Loading static assets from ${clientDirectory}...`) - if (VERBOSE) { - console.log( - `Max preload size: ${(MAX_PRELOAD_BYTES / 1024 / 1024).toFixed(2)} MB`, - ) - if (INCLUDE_PATTERNS.length > 0) { - console.log( - `Include patterns: ${process.env.ASSET_PRELOAD_INCLUDE_PATTERNS ?? ''}`, - ) - } - if (EXCLUDE_PATTERNS.length > 0) { - console.log( - `Exclude patterns: ${process.env.ASSET_PRELOAD_EXCLUDE_PATTERNS ?? ''}`, - ) - } - } - - let totalPreloadedBytes = 0 - - try { - const glob = createCompositeGlobPattern() - for await (const relativePath of glob.scan({ cwd: clientDirectory })) { - const filepath = path.join(clientDirectory, relativePath) - const route = `/${relativePath.split(path.sep).join(path.posix.sep)}` - - try { - // Get file metadata - const file = Bun.file(filepath) - - // Skip if file doesn't exist or is empty - if (!(await file.exists()) || file.size === 0) { - continue - } - - const metadata: AssetMetadata = { - route, - size: file.size, - type: file.type || 'application/octet-stream', - } - - // Determine if file should be preloaded - const matchesPattern = isFileEligibleForPreloading(relativePath) - const withinSizeLimit = file.size <= MAX_PRELOAD_BYTES - - if (matchesPattern && withinSizeLimit) { - // Preload small files into memory with ETag and Gzip support - const bytes = new Uint8Array(await file.arrayBuffer()) - const gz = compressDataIfAppropriate(bytes, metadata.type) - const etag = ENABLE_ETAG ? computeEtag(bytes) : undefined - const asset: InMemoryAsset = { - raw: bytes, - gz, - etag, - type: metadata.type, - immutable: true, - size: bytes.byteLength, - } - routes[route] = createResponseHandler(asset) - - loaded.push({ ...metadata, size: bytes.byteLength }) - totalPreloadedBytes += bytes.byteLength - } else { - // Serve large or filtered files on-demand - routes[route] = () => { - const fileOnDemand = Bun.file(filepath) - return new Response(fileOnDemand, { - headers: { - 'Content-Type': metadata.type, - 'Cache-Control': 'public, max-age=3600', - }, - }) - } - - skipped.push(metadata) - } - } catch (error: unknown) { - if (error instanceof Error && error.name !== 'EISDIR') { - log.error(`Failed to load ${filepath}: ${error.message}`) - } - } - } - - // Show detailed file overview only when verbose mode is enabled - if (VERBOSE && (loaded.length > 0 || skipped.length > 0)) { - const allFiles = [...loaded, ...skipped].sort((a, b) => - a.route.localeCompare(b.route), - ) - - // Calculate max path length for alignment - const maxPathLength = Math.min( - Math.max(...allFiles.map((f) => f.route.length)), - 60, - ) - - // Format file size with KB and actual gzip size - const formatFileSize = (bytes: number, gzBytes?: number) => { - const kb = bytes / 1024 - const sizeStr = kb < 100 ? kb.toFixed(2) : kb.toFixed(1) - - if (gzBytes !== undefined) { - const gzKb = gzBytes / 1024 - const gzStr = gzKb < 100 ? gzKb.toFixed(2) : gzKb.toFixed(1) - return { - size: sizeStr, - gzip: gzStr, - } - } - - // Rough gzip estimation (typically 30-70% compression) if no actual gzip data - const gzipKb = kb * 0.35 - return { - size: sizeStr, - gzip: gzipKb < 100 ? gzipKb.toFixed(2) : gzipKb.toFixed(1), - } - } - - if (loaded.length > 0) { - console.log('\n📁 Preloaded into memory:') - console.log( - 'Path │ Size │ Gzip Size', - ) - loaded - .sort((a, b) => a.route.localeCompare(b.route)) - .forEach((file) => { - const { size, gzip } = formatFileSize(file.size) - const paddedPath = file.route.padEnd(maxPathLength) - const sizeStr = `${size.padStart(7)} kB` - const gzipStr = `${gzip.padStart(7)} kB` - console.log(`${paddedPath} │ ${sizeStr} │ ${gzipStr}`) - }) - } - - if (skipped.length > 0) { - console.log('\n💾 Served on-demand:') - console.log( - 'Path │ Size │ Gzip Size', - ) - skipped - .sort((a, b) => a.route.localeCompare(b.route)) - .forEach((file) => { - const { size, gzip } = formatFileSize(file.size) - const paddedPath = file.route.padEnd(maxPathLength) - const sizeStr = `${size.padStart(7)} kB` - const gzipStr = `${gzip.padStart(7)} kB` - console.log(`${paddedPath} │ ${sizeStr} │ ${gzipStr}`) - }) - } - } - - // Show detailed verbose info if enabled - if (VERBOSE) { - if (loaded.length > 0 || skipped.length > 0) { - const allFiles = [...loaded, ...skipped].sort((a, b) => - a.route.localeCompare(b.route), - ) - console.log('\n📊 Detailed file information:') - console.log( - 'Status │ Path │ MIME Type │ Reason', - ) - allFiles.forEach((file) => { - const isPreloaded = loaded.includes(file) - const status = isPreloaded ? 'MEMORY' : 'ON-DEMAND' - const reason = - !isPreloaded && file.size > MAX_PRELOAD_BYTES - ? 'too large' - : !isPreloaded - ? 'filtered' - : 'preloaded' - const route = - file.route.length > 30 - ? file.route.substring(0, 27) + '...' - : file.route - console.log( - `${status.padEnd(12)} │ ${route.padEnd(30)} │ ${file.type.padEnd(28)} │ ${reason.padEnd(10)}`, - ) - }) - } else { - console.log('\n📊 No files found to display') - } - } - - // Log summary after the file list - console.log() // Empty line for separation - if (loaded.length > 0) { - log.success( - `Preloaded ${String(loaded.length)} files (${(totalPreloadedBytes / 1024 / 1024).toFixed(2)} MB) into memory`, - ) - } else { - log.info('No files preloaded into memory') - } - - if (skipped.length > 0) { - const tooLarge = skipped.filter((f) => f.size > MAX_PRELOAD_BYTES).length - const filtered = skipped.length - tooLarge - log.info( - `${String(skipped.length)} files will be served on-demand (${String(tooLarge)} too large, ${String(filtered)} filtered)`, - ) - } - } catch (error) { - log.error( - `Failed to load static files from ${clientDirectory}: ${String(error)}`, - ) - } - - return { routes, loaded, skipped } -} - -/** - * Initialize the server - */ -async function initializeServer() { - log.header('Starting Production Server') - - // Load TanStack Start server handler - let handler: { fetch: (request: Request) => Response | Promise } - try { - const serverModule = (await import(SERVER_ENTRY_POINT)) as { - default: { fetch: (request: Request) => Response | Promise } - } - handler = serverModule.default - log.success('TanStack Start application handler initialized') - } catch (error) { - log.error(`Failed to load server handler: ${String(error)}`) - process.exit(1) - } - - // Build static routes with intelligent preloading - const { routes } = await initializeStaticRoutes(CLIENT_DIRECTORY) - - // Create Bun server - const server = Bun.serve({ - port: SERVER_PORT, - - routes: { - // Serve static assets (preloaded or on-demand) - ...routes, - - // Fallback to TanStack Start handler for all other routes - '/*': (req: Request) => { - try { - return handler.fetch(req) - } catch (error) { - log.error(`Server handler error: ${String(error)}`) - return new Response('Internal Server Error', { status: 500 }) - } - }, - }, - - // Global error handler - error(error) { - log.error( - `Uncaught server error: ${error instanceof Error ? error.message : String(error)}`, - ) - return new Response('Internal Server Error', { status: 500 }) - }, - }) - - log.success(`Server listening on http://localhost:${String(server.port)}`) -} - -// Initialize the server -initializeServer().catch((error: unknown) => { - log.error(`Failed to start server: ${String(error)}`) - process.exit(1) -}) diff --git a/examples/react/start-bun/src/components/Header.tsx b/examples/react/start-bun/src/components/Header.tsx deleted file mode 100644 index 8a138a0a42..0000000000 --- a/examples/react/start-bun/src/components/Header.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import { Link } from '@tanstack/react-router' - -export default function Header() { - return ( -
- -
- ) -} diff --git a/examples/react/start-bun/src/logo.svg b/examples/react/start-bun/src/logo.svg deleted file mode 100644 index fe53fe8d0d..0000000000 --- a/examples/react/start-bun/src/logo.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - logo - - \ No newline at end of file diff --git a/examples/react/start-bun/src/routeTree.gen.ts b/examples/react/start-bun/src/routeTree.gen.ts deleted file mode 100644 index 77415f9088..0000000000 --- a/examples/react/start-bun/src/routeTree.gen.ts +++ /dev/null @@ -1,135 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as ApiDemoNamesRouteImport } from './routes/api.demo-names' -import { Route as DemoStartApiRequestRouteImport } from './routes/demo.start.api-request' -import { Route as DemoStartServerFuncsRouteImport } from './routes/demo.start.server-funcs' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ApiDemoNamesRoute = ApiDemoNamesRouteImport.update({ - id: '/api/demo-names', - path: '/api/demo-names', - getParentRoute: () => rootRouteImport, -} as any) -const DemoStartApiRequestRoute = DemoStartApiRequestRouteImport.update({ - id: '/demo/start/api-request', - path: '/demo/start/api-request', - getParentRoute: () => rootRouteImport, -} as any) -const DemoStartServerFuncsRoute = DemoStartServerFuncsRouteImport.update({ - id: '/demo/start/server-funcs', - path: '/demo/start/server-funcs', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/api/demo-names': typeof ApiDemoNamesRoute - '/demo/start/api-request': typeof DemoStartApiRequestRoute - '/demo/start/server-funcs': typeof DemoStartServerFuncsRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/api/demo-names': typeof ApiDemoNamesRoute - '/demo/start/api-request': typeof DemoStartApiRequestRoute - '/demo/start/server-funcs': typeof DemoStartServerFuncsRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/api/demo-names': typeof ApiDemoNamesRoute - '/demo/start/api-request': typeof DemoStartApiRequestRoute - '/demo/start/server-funcs': typeof DemoStartServerFuncsRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/api/demo-names' - | '/demo/start/api-request' - | '/demo/start/server-funcs' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/api/demo-names' - | '/demo/start/api-request' - | '/demo/start/server-funcs' - id: - | '__root__' - | '/' - | '/api/demo-names' - | '/demo/start/api-request' - | '/demo/start/server-funcs' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ApiDemoNamesRoute: typeof ApiDemoNamesRoute - DemoStartApiRequestRoute: typeof DemoStartApiRequestRoute - DemoStartServerFuncsRoute: typeof DemoStartServerFuncsRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/api/demo-names': { - id: '/api/demo-names' - path: '/api/demo-names' - fullPath: '/api/demo-names' - preLoaderRoute: typeof ApiDemoNamesRouteImport - parentRoute: typeof rootRouteImport - } - '/demo/start/api-request': { - id: '/demo/start/api-request' - path: '/demo/start/api-request' - fullPath: '/demo/start/api-request' - preLoaderRoute: typeof DemoStartApiRequestRouteImport - parentRoute: typeof rootRouteImport - } - '/demo/start/server-funcs': { - id: '/demo/start/server-funcs' - path: '/demo/start/server-funcs' - fullPath: '/demo/start/server-funcs' - preLoaderRoute: typeof DemoStartServerFuncsRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ApiDemoNamesRoute: ApiDemoNamesRoute, - DemoStartApiRequestRoute: DemoStartApiRequestRoute, - DemoStartServerFuncsRoute: DemoStartServerFuncsRoute, -} -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/examples/react/start-bun/src/router.tsx b/examples/react/start-bun/src/router.tsx deleted file mode 100644 index ee1edab88c..0000000000 --- a/examples/react/start-bun/src/router.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { createRouter } from '@tanstack/react-router' - -// Import the generated route tree -import { routeTree } from './routeTree.gen' - -// Create a new router instance -export const getRouter = () => { - return createRouter({ - routeTree, - scrollRestoration: true, - defaultPreloadStaleTime: 0, - }) -} diff --git a/examples/react/start-bun/src/routes/__root.tsx b/examples/react/start-bun/src/routes/__root.tsx deleted file mode 100644 index cf53f185c5..0000000000 --- a/examples/react/start-bun/src/routes/__root.tsx +++ /dev/null @@ -1,58 +0,0 @@ -import { TanStackDevtools } from '@tanstack/react-devtools' -import { HeadContent, Scripts, createRootRoute } from '@tanstack/react-router' -import { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools' - -import Header from '../components/Header' - -import appCss from '../styles.css?url' - -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, - }, - ], - }), - - shellComponent: RootDocument, -}) - -function RootDocument({ children }: { children: React.ReactNode }) { - return ( - - - - - -
- {children} - , - }, - ]} - /> - - - - ) -} diff --git a/examples/react/start-bun/src/routes/api.demo-names.ts b/examples/react/start-bun/src/routes/api.demo-names.ts deleted file mode 100644 index ecf045c018..0000000000 --- a/examples/react/start-bun/src/routes/api.demo-names.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/api/demo-names')({ - server: { - handlers: { - GET: () => { - return new Response(JSON.stringify(['Alice', 'Bob', 'Charlie']), { - headers: { - 'Content-Type': 'application/json', - }, - }) - }, - }, - }, -}) diff --git a/examples/react/start-bun/src/routes/demo.start.api-request.tsx b/examples/react/start-bun/src/routes/demo.start.api-request.tsx deleted file mode 100644 index b3fadbaa2d..0000000000 --- a/examples/react/start-bun/src/routes/demo.start.api-request.tsx +++ /dev/null @@ -1,44 +0,0 @@ -import { useEffect, useState } from 'react' - -import { createFileRoute } from '@tanstack/react-router' - -function getNames() { - return fetch('/api/demo-names').then((res) => res.json()) -} - -export const Route = createFileRoute('/demo/start/api-request')({ - component: Home, -}) - -function Home() { - const [names, setNames] = useState>([]) - - useEffect(() => { - getNames().then(setNames) - }, []) - - return ( -
-
-

Start API Request Demo - Names List

-
    - {names.map((name) => ( -
  • - {name} -
  • - ))} -
-
-
- ) -} diff --git a/examples/react/start-bun/src/routes/demo.start.server-funcs.tsx b/examples/react/start-bun/src/routes/demo.start.server-funcs.tsx deleted file mode 100644 index 64629c0bdc..0000000000 --- a/examples/react/start-bun/src/routes/demo.start.server-funcs.tsx +++ /dev/null @@ -1,97 +0,0 @@ -import fs from 'node:fs' -import { useCallback, useState } from 'react' -import { createFileRoute, useRouter } from '@tanstack/react-router' -import { createServerFn } from '@tanstack/react-start' - -const filePath = 'todos.json' - -async function readTodos() { - return JSON.parse( - await fs.promises.readFile(filePath, 'utf-8').catch(() => - JSON.stringify( - [ - { id: 1, name: 'Get groceries' }, - { id: 2, name: 'Buy a new phone' }, - ], - null, - 2, - ), - ), - ) -} - -const getTodos = createServerFn({ - method: 'GET', -}).handler(async () => await readTodos()) - -const addTodo = createServerFn({ method: 'POST' }) - .validator((d: string) => d) - .handler(async ({ data }) => { - const todos = await readTodos() - todos.push({ id: todos.length + 1, name: data }) - await fs.promises.writeFile(filePath, JSON.stringify(todos, null, 2)) - return todos - }) - -export const Route = createFileRoute('/demo/start/server-funcs')({ - component: Home, - loader: async () => await getTodos(), -}) - -function Home() { - const router = useRouter() - let todos = Route.useLoaderData() - - const [todo, setTodo] = useState('') - - const submitTodo = useCallback(async () => { - todos = await addTodo({ data: todo }) - setTodo('') - router.invalidate() - }, [addTodo, todo]) - - return ( -
-
-

Start Server Functions - Todo Example

-
    - {todos?.map((t) => ( -
  • - {t.name} -
  • - ))} -
-
- setTodo(e.target.value)} - onKeyDown={(e) => { - if (e.key === 'Enter') { - submitTodo() - } - }} - placeholder="Enter a new todo..." - className="w-full px-4 py-3 rounded-lg border border-white/20 bg-white/10 backdrop-blur-sm text-white placeholder-white/60 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-transparent" - /> - -
-
-
- ) -} diff --git a/examples/react/start-bun/src/routes/index.tsx b/examples/react/start-bun/src/routes/index.tsx deleted file mode 100644 index b285335dfb..0000000000 --- a/examples/react/start-bun/src/routes/index.tsx +++ /dev/null @@ -1,39 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import logo from '../logo.svg' - -export const Route = createFileRoute('/')({ - component: App, -}) - -function App() { - return ( -
-
- logo -

- Edit src/routes/index.tsx and save to reload. -

- - Learn React - - - Learn TanStack - -
-
- ) -} diff --git a/examples/react/start-bun/src/styles.css b/examples/react/start-bun/src/styles.css deleted file mode 100644 index f59c071ef6..0000000000 --- a/examples/react/start-bun/src/styles.css +++ /dev/null @@ -1,15 +0,0 @@ -@import 'tailwindcss' source('../'); - -body { - @apply m-0; - font-family: - -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', - 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; -} - -code { - font-family: - source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace; -} diff --git a/examples/react/start-bun/src/vite-env.d.ts b/examples/react/start-bun/src/vite-env.d.ts deleted file mode 100644 index 11f02fe2a0..0000000000 --- a/examples/react/start-bun/src/vite-env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/examples/react/start-bun/tsconfig.json b/examples/react/start-bun/tsconfig.json deleted file mode 100644 index 2f09fb43be..0000000000 --- a/examples/react/start-bun/tsconfig.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "include": [ - "**/*.ts", - "**/*.tsx", - "eslint.config.js", - "prettier.config.js", - "vite.config.js" - ], - - "compilerOptions": { - "target": "ES2022", - "jsx": "react-jsx", - "module": "ESNext", - "lib": ["ES2022", "DOM", "DOM.Iterable"], - "types": ["vite/client", "bun"], - - /* Bundler mode */ - "moduleResolution": "bundler", - "allowImportingTsExtensions": true, - "verbatimModuleSyntax": false, - "noEmit": true, - - /* Linting */ - "skipLibCheck": true, - "strict": true, - "noUnusedLocals": true, - "noUnusedParameters": true, - "noFallthroughCasesInSwitch": true, - "noUncheckedSideEffectImports": true, - "paths": { - "@/*": ["./src/*"] - } - } -} diff --git a/examples/react/start-bun/vite.config.ts b/examples/react/start-bun/vite.config.ts deleted file mode 100644 index 1e5ca9d8db..0000000000 --- a/examples/react/start-bun/vite.config.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { defineConfig } from 'vite' -import { tanstackStart } from '@tanstack/react-start/plugin/vite' -import viteReact from '@vitejs/plugin-react' -import tailwindcss from '@tailwindcss/vite' - -const config = defineConfig({ - resolve: { - tsconfigPaths: true, - }, - plugins: [tailwindcss(), tanstackStart(), viteReact()], -}) - -export default config diff --git a/examples/react/start-clerk-basic/.devcontainer/devcontainer.json b/examples/react/start-clerk-basic/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/start-clerk-basic/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/start-clerk-basic/.env b/examples/react/start-clerk-basic/.env deleted file mode 100644 index 5e3b005f2d..0000000000 --- a/examples/react/start-clerk-basic/.env +++ /dev/null @@ -1,2 +0,0 @@ -VITE_CLERK_PUBLISHABLE_KEY=[YOUR_CLERK_PUBLISHABLE_KEY] -CLERK_SECRET_KEY=[YOUR_CLERK_SECRET_KEY] \ No newline at end of file diff --git a/examples/react/start-clerk-basic/.gitignore b/examples/react/start-clerk-basic/.gitignore deleted file mode 100644 index bc14f2cea6..0000000000 --- a/examples/react/start-clerk-basic/.gitignore +++ /dev/null @@ -1,20 +0,0 @@ -node_modules -package-lock.json -yarn.lock - -!.env -.DS_Store -.cache -.vercel -.output -.nitro -/build/ -/api/ -/server/build -/public/build# Sentry Config File -.env.sentry-build-plugin -/test-results/ -/playwright-report/ -/blob-report/ -/playwright/.cache/ -.tanstack diff --git a/examples/react/start-clerk-basic/.prettierignore b/examples/react/start-clerk-basic/.prettierignore deleted file mode 100644 index 2be5eaa6ec..0000000000 --- a/examples/react/start-clerk-basic/.prettierignore +++ /dev/null @@ -1,4 +0,0 @@ -**/build -**/public -pnpm-lock.yaml -routeTree.gen.ts \ No newline at end of file diff --git a/examples/react/start-clerk-basic/.vscode/settings.json b/examples/react/start-clerk-basic/.vscode/settings.json deleted file mode 100644 index 00b5278e58..0000000000 --- a/examples/react/start-clerk-basic/.vscode/settings.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "files.watcherExclude": { - "**/routeTree.gen.ts": true - }, - "search.exclude": { - "**/routeTree.gen.ts": true - }, - "files.readonlyInclude": { - "**/routeTree.gen.ts": true - } -} diff --git a/examples/react/start-clerk-basic/README.md b/examples/react/start-clerk-basic/README.md index 896ce58300..23b70ea31a 100644 --- a/examples/react/start-clerk-basic/README.md +++ b/examples/react/start-clerk-basic/README.md @@ -1,46 +1,16 @@ -# TanStack Start - Clerk Authentication Example +# Deprecated: TanStack Start React Example (`start-clerk-basic`) -This site is built with TanStack Router and Clerk Authentication! +This example is retained for compatibility and historical reference. -- [TanStack Router Docs](https://tanstack.com/router) -- [Clerk Documentation](https://clerk.com/docs) +For new projects, use: -## Start a new project based on this example +- [TanStack Builder](https://tanstack.com/builder) +- `npx @tanstack/cli create` -To start a new project based on this example, run: +For topic-specific setup, use the Start guides: -```sh -npx gitpick TanStack/router/tree/main/examples/react/start-clerk-basic start-clerk-basic -``` +- [Authentication Overview](https://tanstack.com/router/latest/docs/framework/react/start/guide/authentication-overview) -## Deployment +Canonical issue reproduction baseline: -It's deployed automagically with Netlify! - -- [Netlify](https://netlify.com/) - -## Getting Started - -From your terminal: - -```sh -pnpm install -pnpm dev -``` - -## Build - -Build for production: - -```sh -pnpm build -``` - -## About This Example - -This example demonstrates: - -- Clerk authentication integration -- Protected routes -- User management -- Authentication UI components +- [React `start-basic`](https://github.com/TanStack/router/tree/main/examples/react/start-basic) diff --git a/examples/react/start-clerk-basic/package.json b/examples/react/start-clerk-basic/package.json deleted file mode 100644 index 022300e159..0000000000 --- a/examples/react/start-clerk-basic/package.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "tanstack-start-example-clerk-basic", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "vite dev", - "build": "vite build && tsc --noEmit", - "preview": "vite preview", - "start": "pnpx srvx --prod -s ../client dist/server/server.js" - }, - "dependencies": { - "@clerk/tanstack-react-start": "^0.27.14", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", - "@vitejs/plugin-react": "^6.0.1", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "redaxios": "^0.5.1", - "srvx": "^1.0.0", - "tailwind-merge": "^3.6.0" - }, - "devDependencies": { - "@tailwindcss/vite": "^4.2.2", - "@types/node": "^22.5.4", - "@types/react": "^19.0.8", - "@types/react-dom": "^19.0.3", - "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" - } -} diff --git a/examples/react/start-clerk-basic/public/android-chrome-192x192.png b/examples/react/start-clerk-basic/public/android-chrome-192x192.png deleted file mode 100644 index 09c8324f8c..0000000000 Binary files a/examples/react/start-clerk-basic/public/android-chrome-192x192.png and /dev/null differ diff --git a/examples/react/start-clerk-basic/public/android-chrome-512x512.png b/examples/react/start-clerk-basic/public/android-chrome-512x512.png deleted file mode 100644 index 11d626ea3d..0000000000 Binary files a/examples/react/start-clerk-basic/public/android-chrome-512x512.png and /dev/null differ diff --git a/examples/react/start-clerk-basic/public/apple-touch-icon.png b/examples/react/start-clerk-basic/public/apple-touch-icon.png deleted file mode 100644 index 5a9423cc02..0000000000 Binary files a/examples/react/start-clerk-basic/public/apple-touch-icon.png and /dev/null differ diff --git a/examples/react/start-clerk-basic/public/favicon-16x16.png b/examples/react/start-clerk-basic/public/favicon-16x16.png deleted file mode 100644 index e3389b0044..0000000000 Binary files a/examples/react/start-clerk-basic/public/favicon-16x16.png and /dev/null differ diff --git a/examples/react/start-clerk-basic/public/favicon-32x32.png b/examples/react/start-clerk-basic/public/favicon-32x32.png deleted file mode 100644 index 900c77d444..0000000000 Binary files a/examples/react/start-clerk-basic/public/favicon-32x32.png and /dev/null differ diff --git a/examples/react/start-clerk-basic/public/favicon.ico b/examples/react/start-clerk-basic/public/favicon.ico deleted file mode 100644 index 1a1751676f..0000000000 Binary files a/examples/react/start-clerk-basic/public/favicon.ico and /dev/null differ diff --git a/examples/react/start-clerk-basic/public/favicon.png b/examples/react/start-clerk-basic/public/favicon.png deleted file mode 100644 index 1e77bc0609..0000000000 Binary files a/examples/react/start-clerk-basic/public/favicon.png and /dev/null differ diff --git a/examples/react/start-clerk-basic/public/site.webmanifest b/examples/react/start-clerk-basic/public/site.webmanifest deleted file mode 100644 index fa99de77db..0000000000 --- a/examples/react/start-clerk-basic/public/site.webmanifest +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "", - "short_name": "", - "icons": [ - { - "src": "/android-chrome-192x192.png", - "sizes": "192x192", - "type": "image/png" - }, - { - "src": "/android-chrome-512x512.png", - "sizes": "512x512", - "type": "image/png" - } - ], - "theme_color": "#ffffff", - "background_color": "#ffffff", - "display": "standalone" -} diff --git a/examples/react/start-clerk-basic/src/components/DefaultCatchBoundary.tsx b/examples/react/start-clerk-basic/src/components/DefaultCatchBoundary.tsx deleted file mode 100644 index 405fb5f4a7..0000000000 --- a/examples/react/start-clerk-basic/src/components/DefaultCatchBoundary.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { - ErrorComponent, - Link, - useLocation, - useRouter, -} from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' - -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - - console.error(error) - - return ( -
- -
- - {isRoot ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) -} diff --git a/examples/react/start-clerk-basic/src/components/NotFound.tsx b/examples/react/start-clerk-basic/src/components/NotFound.tsx deleted file mode 100644 index fd4e75befe..0000000000 --- a/examples/react/start-clerk-basic/src/components/NotFound.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { Link } from '@tanstack/react-router' - -export function NotFound({ children }: { children?: any }) { - return ( -
-
- {children ||

The page you are looking for does not exist.

} -
-

- - - Start Over - -

-
- ) -} diff --git a/examples/react/start-clerk-basic/src/routeTree.gen.ts b/examples/react/start-clerk-basic/src/routeTree.gen.ts deleted file mode 100644 index 87269f2faf..0000000000 --- a/examples/react/start-clerk-basic/src/routeTree.gen.ts +++ /dev/null @@ -1,181 +0,0 @@ -/* eslint-disable */ - -// @ts-nocheck - -// noinspection JSUnusedGlobalSymbols - -// This file was automatically generated by TanStack Router. -// You should NOT make any changes in this file as it will be overwritten. -// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. - -import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as AuthedRouteImport } from './routes/_authed' -import { Route as AuthedPostsRouteImport } from './routes/_authed/posts' -import { Route as AuthedPostsIndexRouteImport } from './routes/_authed/posts.index' -import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' -import { Route as AuthedProfileSplatRouteImport } from './routes/_authed/profile.$' - -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const AuthedRoute = AuthedRouteImport.update({ - id: '/_authed', - getParentRoute: () => rootRouteImport, -} as any) -const AuthedPostsRoute = AuthedPostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => AuthedRoute, -} as any) -const AuthedPostsIndexRoute = AuthedPostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => AuthedPostsRoute, -} as any) -const AuthedPostsPostIdRoute = AuthedPostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => AuthedPostsRoute, -} as any) -const AuthedProfileSplatRoute = AuthedProfileSplatRouteImport.update({ - id: '/profile/$', - path: '/profile/$', - getParentRoute: () => AuthedRoute, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/posts': typeof AuthedPostsRouteWithChildren - '/posts/$postId': typeof AuthedPostsPostIdRoute - '/profile/$': typeof AuthedProfileSplatRoute - '/posts/': typeof AuthedPostsIndexRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/posts/$postId': typeof AuthedPostsPostIdRoute - '/profile/$': typeof AuthedProfileSplatRoute - '/posts': typeof AuthedPostsIndexRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/_authed': typeof AuthedRouteWithChildren - '/_authed/posts': typeof AuthedPostsRouteWithChildren - '/_authed/posts/$postId': typeof AuthedPostsPostIdRoute - '/_authed/profile/$': typeof AuthedProfileSplatRoute - '/_authed/posts/': typeof AuthedPostsIndexRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/posts' | '/posts/$postId' | '/profile/$' | '/posts/' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/posts/$postId' | '/profile/$' | '/posts' - id: - | '__root__' - | '/' - | '/_authed' - | '/_authed/posts' - | '/_authed/posts/$postId' - | '/_authed/profile/$' - | '/_authed/posts/' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - AuthedRoute: typeof AuthedRouteWithChildren -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/_authed': { - id: '/_authed' - path: '' - fullPath: '/' - preLoaderRoute: typeof AuthedRouteImport - parentRoute: typeof rootRouteImport - } - '/_authed/posts': { - id: '/_authed/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof AuthedPostsRouteImport - parentRoute: typeof AuthedRoute - } - '/_authed/posts/': { - id: '/_authed/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof AuthedPostsIndexRouteImport - parentRoute: typeof AuthedPostsRoute - } - '/_authed/posts/$postId': { - id: '/_authed/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof AuthedPostsPostIdRouteImport - parentRoute: typeof AuthedPostsRoute - } - '/_authed/profile/$': { - id: '/_authed/profile/$' - path: '/profile/$' - fullPath: '/profile/$' - preLoaderRoute: typeof AuthedProfileSplatRouteImport - parentRoute: typeof AuthedRoute - } - } -} - -interface AuthedPostsRouteChildren { - AuthedPostsPostIdRoute: typeof AuthedPostsPostIdRoute - AuthedPostsIndexRoute: typeof AuthedPostsIndexRoute -} - -const AuthedPostsRouteChildren: AuthedPostsRouteChildren = { - AuthedPostsPostIdRoute: AuthedPostsPostIdRoute, - AuthedPostsIndexRoute: AuthedPostsIndexRoute, -} - -const AuthedPostsRouteWithChildren = AuthedPostsRoute._addFileChildren( - AuthedPostsRouteChildren, -) - -interface AuthedRouteChildren { - AuthedPostsRoute: typeof AuthedPostsRouteWithChildren - AuthedProfileSplatRoute: typeof AuthedProfileSplatRoute -} - -const AuthedRouteChildren: AuthedRouteChildren = { - AuthedPostsRoute: AuthedPostsRouteWithChildren, - AuthedProfileSplatRoute: AuthedProfileSplatRoute, -} - -const AuthedRouteWithChildren = - AuthedRoute._addFileChildren(AuthedRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - AuthedRoute: AuthedRouteWithChildren, -} -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-clerk-basic/src/router.tsx b/examples/react/start-clerk-basic/src/router.tsx deleted file mode 100644 index 1a1d8822d2..0000000000 --- a/examples/react/start-clerk-basic/src/router.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' -import { DefaultCatchBoundary } from './components/DefaultCatchBoundary' -import { NotFound } from './components/NotFound' - -export function getRouter() { - const router = createRouter({ - routeTree, - defaultPreload: 'intent', - defaultErrorComponent: DefaultCatchBoundary, - defaultNotFoundComponent: () => , - scrollRestoration: true, - }) - - return router -} diff --git a/examples/react/start-clerk-basic/src/routes/__root.tsx b/examples/react/start-clerk-basic/src/routes/__root.tsx deleted file mode 100644 index 8cf05a3835..0000000000 --- a/examples/react/start-clerk-basic/src/routes/__root.tsx +++ /dev/null @@ -1,135 +0,0 @@ -/// -import { - ClerkProvider, - SignInButton, - SignedIn, - SignedOut, - UserButton, -} from '@clerk/tanstack-react-start' -import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' -import { createServerFn } from '@tanstack/react-start' -import { auth } from '@clerk/tanstack-react-start/server' -import * as React from 'react' -import { - HeadContent, - Link, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' -import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary.js' -import { NotFound } from '~/components/NotFound.js' -import appCss from '~/styles/app.css?url' - -const fetchClerkAuth = createServerFn({ method: 'GET' }).handler(async () => { - const { userId } = await auth() - - return { - userId, - } -}) - -export const Route = createRootRoute({ - beforeLoad: async () => { - const { userId } = await fetchClerkAuth() - - return { - userId, - } - }, - head: () => ({ - meta: [ - { - charSet: 'utf-8', - }, - { - name: 'viewport', - content: 'width=device-width, initial-scale=1', - }, - ], - links: [ - { rel: 'stylesheet', href: appCss }, - { - rel: 'apple-touch-icon', - sizes: '180x180', - href: '/apple-touch-icon.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '32x32', - href: '/favicon-32x32.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '16x16', - href: '/favicon-16x16.png', - }, - { rel: 'manifest', href: '/site.webmanifest', color: '#fffff' }, - { rel: 'icon', href: '/favicon.ico' }, - ], - }), - errorComponent: (props) => { - return ( - - - - ) - }, - notFoundComponent: () => , - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - ) -} - -function RootDocument({ children }: { children: React.ReactNode }) { - return ( - - - - - -
- - Home - {' '} - - Posts - -
- - - - - - -
-
-
- {children} - - - - - ) -} diff --git a/examples/react/start-clerk-basic/src/routes/_authed.tsx b/examples/react/start-clerk-basic/src/routes/_authed.tsx deleted file mode 100644 index 04f8196894..0000000000 --- a/examples/react/start-clerk-basic/src/routes/_authed.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import { SignIn } from '@clerk/tanstack-react-start' -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_authed')({ - beforeLoad: ({ context }) => { - if (!context.userId) { - throw new Error('Not authenticated') - } - }, - errorComponent: ({ error }) => { - if (error instanceof Error && error.message === 'Not authenticated') { - return ( -
- -
- ) - } - - throw error - }, -}) diff --git a/examples/react/start-clerk-basic/src/routes/_authed/posts.$postId.tsx b/examples/react/start-clerk-basic/src/routes/_authed/posts.$postId.tsx deleted file mode 100644 index 039271bb89..0000000000 --- a/examples/react/start-clerk-basic/src/routes/_authed/posts.$postId.tsx +++ /dev/null @@ -1,28 +0,0 @@ -import { ErrorComponent, createFileRoute } from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' -import { NotFound } from '~/components/NotFound.js' -import { fetchPost } from '~/utils/posts.js' - -export const Route = createFileRoute('/_authed/posts/$postId')({ - loader: ({ params: { postId } }) => fetchPost({ data: postId }), - errorComponent: PostErrorComponent, - component: PostComponent, - notFoundComponent: () => { - return Post not found - }, -}) - -export function PostErrorComponent({ error }: ErrorComponentProps) { - return -} - -function PostComponent() { - const post = Route.useLoaderData() - - return ( -
-

{post.title}

-
{post.body}
-
- ) -} diff --git a/examples/react/start-clerk-basic/src/routes/_authed/posts.index.tsx b/examples/react/start-clerk-basic/src/routes/_authed/posts.index.tsx deleted file mode 100644 index de01fe5dde..0000000000 --- a/examples/react/start-clerk-basic/src/routes/_authed/posts.index.tsx +++ /dev/null @@ -1,8 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/_authed/posts/')({ - component: PostsIndexComponent, -}) - -function PostsIndexComponent() { - return
Select a post.
-} diff --git a/examples/react/start-clerk-basic/src/routes/_authed/posts.tsx b/examples/react/start-clerk-basic/src/routes/_authed/posts.tsx deleted file mode 100644 index 86c8ef4138..0000000000 --- a/examples/react/start-clerk-basic/src/routes/_authed/posts.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' -import { fetchPosts } from '~/utils/posts.js' - -export const Route = createFileRoute('/_authed/posts')({ - loader: () => fetchPosts(), - component: PostsComponent, -}) - -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[...posts, { id: 'i-do-not-exist', title: 'Non-existent Post' }].map( - (post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - }, - )} -
-
- -
- ) -} diff --git a/examples/react/start-clerk-basic/src/routes/_authed/profile.$.tsx b/examples/react/start-clerk-basic/src/routes/_authed/profile.$.tsx deleted file mode 100644 index 208a38e230..0000000000 --- a/examples/react/start-clerk-basic/src/routes/_authed/profile.$.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' -import { fetchPosts } from '~/utils/posts.js' - -export const Route = createFileRoute('/_authed/profile/$')({ - loader: () => fetchPosts(), - component: PostsComponent, -}) - -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[...posts, { id: 'i-do-not-exist', title: 'Non-existent Post' }].map( - (post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - }, - )} -
-
- -
- ) -} diff --git a/examples/react/start-clerk-basic/src/routes/index.tsx b/examples/react/start-clerk-basic/src/routes/index.tsx deleted file mode 100644 index 00ce18725b..0000000000 --- a/examples/react/start-clerk-basic/src/routes/index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/')({ - component: Home, -}) - -function Home() { - return ( -
-

Hello Clerk!

-
- ) -} diff --git a/examples/react/start-clerk-basic/src/start.ts b/examples/react/start-clerk-basic/src/start.ts deleted file mode 100644 index 7447718f41..0000000000 --- a/examples/react/start-clerk-basic/src/start.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { clerkMiddleware } from '@clerk/tanstack-react-start/server' -import { createStart } from '@tanstack/react-start' - -export const startInstance = createStart(() => { - return { - requestMiddleware: [clerkMiddleware()], - } -}) diff --git a/examples/react/start-clerk-basic/src/styles/app.css b/examples/react/start-clerk-basic/src/styles/app.css deleted file mode 100644 index 37c1f5a6e2..0000000000 --- a/examples/react/start-clerk-basic/src/styles/app.css +++ /dev/null @@ -1,30 +0,0 @@ -@import 'tailwindcss' source('../'); - -@layer base { - *, - ::after, - ::before, - ::backdrop, - ::file-selector-button { - border-color: var(--color-gray-200, currentcolor); - } -} - -@layer base { - html { - color-scheme: light dark; - } - - * { - @apply border-gray-200 dark:border-gray-800; - } - - html, - body { - @apply text-gray-900 bg-gray-50 dark:bg-gray-950 dark:text-gray-200; - } - - .using-mouse * { - outline: none !important; - } -} diff --git a/examples/react/start-clerk-basic/src/utils/posts.ts b/examples/react/start-clerk-basic/src/utils/posts.ts deleted file mode 100644 index a7e0e99cfa..0000000000 --- a/examples/react/start-clerk-basic/src/utils/posts.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { notFound } from '@tanstack/react-router' -import { createServerFn } from '@tanstack/react-start' -import axios from 'redaxios' - -export type PostType = { - id: string - title: string - body: string -} - -export const fetchPost = createServerFn({ method: 'GET' }) - .validator((postId: string) => postId) - .handler(async ({ data }) => { - console.info(`Fetching post with id ${data}...`) - const post = await axios - .get(`https://jsonplaceholder.typicode.com/posts/${data}`) - .then((r) => r.data) - .catch((err) => { - console.error(err) - if (err.status === 404) { - throw notFound() - } - throw err - }) - - return post - }) - -export const fetchPosts = createServerFn({ method: 'GET' }).handler( - async () => { - console.info('Fetching posts...') - await new Promise((r) => setTimeout(r, 1000)) - return axios - .get>('https://jsonplaceholder.typicode.com/posts') - .then((r) => r.data.slice(0, 10)) - }, -) diff --git a/examples/react/start-clerk-basic/src/utils/seo.ts b/examples/react/start-clerk-basic/src/utils/seo.ts deleted file mode 100644 index d18ad84b74..0000000000 --- a/examples/react/start-clerk-basic/src/utils/seo.ts +++ /dev/null @@ -1,33 +0,0 @@ -export const seo = ({ - title, - description, - keywords, - image, -}: { - title: string - description?: string - image?: string - keywords?: string -}) => { - const tags = [ - { title }, - { name: 'description', content: description }, - { name: 'keywords', content: keywords }, - { name: 'twitter:title', content: title }, - { name: 'twitter:description', content: description }, - { name: 'twitter:creator', content: '@tannerlinsley' }, - { name: 'twitter:site', content: '@tannerlinsley' }, - { name: 'og:type', content: 'website' }, - { name: 'og:title', content: title }, - { name: 'og:description', content: description }, - ...(image - ? [ - { name: 'twitter:image', content: image }, - { name: 'twitter:card', content: 'summary_large_image' }, - { name: 'og:image', content: image }, - ] - : []), - ] - - return tags -} diff --git a/examples/react/start-clerk-basic/tsconfig.json b/examples/react/start-clerk-basic/tsconfig.json deleted file mode 100644 index cef9369516..0000000000 --- a/examples/react/start-clerk-basic/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "include": ["**/*.ts", "**/*.tsx"], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "react-jsx", - "module": "ESNext", - "moduleResolution": "Bundler", - "lib": ["DOM", "DOM.Iterable", "ES2022"], - "isolatedModules": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "target": "ES2022", - "allowJs": true, - "forceConsistentCasingInFileNames": true, - "paths": { - "~/*": ["./src/*"] - }, - "noEmit": true - } -} diff --git a/examples/react/start-clerk-basic/vite.config.ts b/examples/react/start-clerk-basic/vite.config.ts deleted file mode 100644 index debc272ace..0000000000 --- a/examples/react/start-clerk-basic/vite.config.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { tanstackStart } from '@tanstack/react-start/plugin/vite' -import { defineConfig } from 'vite' -import viteReact from '@vitejs/plugin-react' -import tailwindcss from '@tailwindcss/vite' - -export default defineConfig({ - server: { - port: 3000, - }, - plugins: [tailwindcss(), tanstackStart(), viteReact()], - // See https://github.com/TanStack/router/issues/5738 - resolve: { - tsconfigPaths: true, - alias: [ - { find: 'use-sync-external-store/shim/index.js', replacement: 'react' }, - ], - }, -}) diff --git a/examples/react/start-convex-trellaux/.devcontainer/devcontainer.json b/examples/react/start-convex-trellaux/.devcontainer/devcontainer.json deleted file mode 100644 index e5dafce188..0000000000 --- a/examples/react/start-convex-trellaux/.devcontainer/devcontainer.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/typescript-node:24" -} diff --git a/examples/react/start-convex-trellaux/.env.local.example b/examples/react/start-convex-trellaux/.env.local.example deleted file mode 100644 index 315dd107e0..0000000000 --- a/examples/react/start-convex-trellaux/.env.local.example +++ /dev/null @@ -1,3 +0,0 @@ -# This is a shared default backend you can't modify the code for. -# In order to create your own backend, run `npx convex dev`. -VITE_CONVEX_URL=https://laudable-anaconda-558.convex.cloud diff --git a/examples/react/start-convex-trellaux/.gitignore b/examples/react/start-convex-trellaux/.gitignore deleted file mode 100644 index ba7dbddfbe..0000000000 --- a/examples/react/start-convex-trellaux/.gitignore +++ /dev/null @@ -1,16 +0,0 @@ -node_modules -package-lock.json -yarn.lock - -.DS_Store -.cache -.env -.vercel -.output -/build/ -/api/ -/server/build -/public/build# Sentry Config File -.env.sentry-build-plugin - -.env.local diff --git a/examples/react/start-convex-trellaux/.prettierignore b/examples/react/start-convex-trellaux/.prettierignore deleted file mode 100644 index 2be5eaa6ec..0000000000 --- a/examples/react/start-convex-trellaux/.prettierignore +++ /dev/null @@ -1,4 +0,0 @@ -**/build -**/public -pnpm-lock.yaml -routeTree.gen.ts \ No newline at end of file diff --git a/examples/react/start-convex-trellaux/.stackblitzrc b/examples/react/start-convex-trellaux/.stackblitzrc deleted file mode 100644 index e616ee3a78..0000000000 --- a/examples/react/start-convex-trellaux/.stackblitzrc +++ /dev/null @@ -1,3 +0,0 @@ -{ - "startCommand": "cp .env.local.example .env.local && npx vite dev" -} diff --git a/examples/react/start-convex-trellaux/.vscode/settings.json b/examples/react/start-convex-trellaux/.vscode/settings.json deleted file mode 100644 index 00b5278e58..0000000000 --- a/examples/react/start-convex-trellaux/.vscode/settings.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "files.watcherExclude": { - "**/routeTree.gen.ts": true - }, - "search.exclude": { - "**/routeTree.gen.ts": true - }, - "files.readonlyInclude": { - "**/routeTree.gen.ts": true - } -} diff --git a/examples/react/start-convex-trellaux/README.md b/examples/react/start-convex-trellaux/README.md index 1eeee3d50a..8c249370a3 100644 --- a/examples/react/start-convex-trellaux/README.md +++ b/examples/react/start-convex-trellaux/README.md @@ -1,52 +1,12 @@ -# Trello-like example using Convex DB +# Deprecated: TanStack Start React Example (`start-convex-trellaux`) -This is a TanStack Start demo using Convex as the database. -It is similar to the [start-trellaux](https://github.com/TanStack/router/tree/main/examples/react/start-trellaux) example but uses a cloud Convex deployment instead of an in-memory database. +This example is retained for compatibility and historical reference. -- [TanStack Router Docs](https://tanstack.com/router) -- [Convex Documentation](https://docs.convex.dev) +For new projects and templates, use: -## Start a new project based on this example +- [TanStack Builder](https://tanstack.com/builder) +- `npx @tanstack/cli create` -To start a new project based on this example, run: +Canonical issue reproduction baseline: -```sh -npx gitpick TanStack/router/tree/main/examples/react/start-convex-trellaux start-convex-trellaux -``` - -## Convex - -Convex is an open-source, reactive backend made by [convex.dev](https://convex.dev/?utm_source=tanstack), a sponsor of TanStack Start. - -This example uses Convex with TanStack Query and TanStack Start to provide: - -- Typesafe TanStack Query options factories like `convexQuery` for use with `useQuery`, `useSuspenseQuery` etc. -- Live-updating queries: updates come in over a WebSocket instead of requiring polling -- Automatic query invalidation: when a mutation succeeds all queries it affects update automatically -- Selective optimistic update rollback: when a mutation succeeds only its update will be rolled back, with other optimistic updates reapplied -- Consistent snapshot reads of database state: /messages will never return a foreign key for a /user that doesn't exist until the next fetch - -## Getting Started - -To run this example: - -```sh -pnpm install -pnpm dev -``` - -## Build - -Build for production: - -```sh -pnpm build -``` - -## About This Example - -This example demonstrates: - -- Convex database integration -- Real-time updates -- Complex UI state management +- [React `start-basic`](https://github.com/TanStack/router/tree/main/examples/react/start-basic) diff --git a/examples/react/start-convex-trellaux/convex/README.md b/examples/react/start-convex-trellaux/convex/README.md deleted file mode 100644 index 896489de6a..0000000000 --- a/examples/react/start-convex-trellaux/convex/README.md +++ /dev/null @@ -1,90 +0,0 @@ -# Welcome to your Convex functions directory! - -Write your Convex functions here. -See https://docs.convex.dev/functions for more. - -A query function that takes two arguments looks like: - -```ts -// functions.js -import { query } from './_generated/server' -import { v } from 'convex/values' - -export const myQueryFunction = query({ - // Validators for arguments. - args: { - first: v.number(), - second: v.string(), - }, - - // Function implementation. - handler: async (ctx, args) => { - // Read the database as many times as you need here. - // See https://docs.convex.dev/database/reading-data. - const documents = await ctx.db.query('tablename').collect() - - // Arguments passed from the client are properties of the args object. - console.log(args.first, args.second) - - // Write arbitrary JavaScript here: filter, aggregate, build derived data, - // remove non-public properties, or create new objects. - return documents - }, -}) -``` - -Using this query function in a React component looks like: - -```ts -const data = useQuery(api.functions.myQueryFunction, { - first: 10, - second: 'hello', -}) -``` - -A mutation function looks like: - -```ts -// functions.js -import { mutation } from './_generated/server' -import { v } from 'convex/values' - -export const myMutationFunction = mutation({ - // Validators for arguments. - args: { - first: v.string(), - second: v.string(), - }, - - // Function implementation. - handler: async (ctx, args) => { - // Insert or modify documents in the database here. - // Mutations can also read from the database like queries. - // See https://docs.convex.dev/database/writing-data. - const message = { body: args.first, author: args.second } - const id = await ctx.db.insert('messages', message) - - // Optionally, return a value from your mutation. - return await ctx.db.get(id) - }, -}) -``` - -Using this mutation function in a React component looks like: - -```ts -const mutation = useMutation(api.functions.myMutationFunction) -function handleButtonPress() { - // fire and forget, the most common way to use mutations - mutation({ first: 'Hello!', second: 'me' }) - // OR - // use the result once the mutation has completed - mutation({ first: 'Hello!', second: 'me' }).then((result) => - console.log(result), - ) -} -``` - -Use the Convex CLI to push your functions to a deployment. See everything -the Convex CLI can do by running `npx convex -h` in your project root -directory. To learn more, launch the docs with `npx convex docs`. diff --git a/examples/react/start-convex-trellaux/convex/_generated/api.d.ts b/examples/react/start-convex-trellaux/convex/_generated/api.d.ts deleted file mode 100644 index a65ecbcce4..0000000000 --- a/examples/react/start-convex-trellaux/convex/_generated/api.d.ts +++ /dev/null @@ -1,38 +0,0 @@ -/* eslint-disable */ -/** - * Generated `api` utility. - * - * THIS CODE IS AUTOMATICALLY GENERATED. - * - * To regenerate, run `npx convex dev`. - * @module - */ - -import type { - ApiFromModules, - FilterApi, - FunctionReference, -} from 'convex/server' -import type * as board from '../board.js' -import type * as crons from '../crons.js' - -/** - * A utility for referencing Convex functions in your app's API. - * - * Usage: - * ```js - * const myFunctionReference = api.myModule.myFunction; - * ``` - */ -declare const fullApi: ApiFromModules<{ - board: typeof board - crons: typeof crons -}> -export declare const api: FilterApi< - typeof fullApi, - FunctionReference -> -export declare const internal: FilterApi< - typeof fullApi, - FunctionReference -> diff --git a/examples/react/start-convex-trellaux/convex/_generated/api.js b/examples/react/start-convex-trellaux/convex/_generated/api.js deleted file mode 100644 index 2b62e6b82f..0000000000 --- a/examples/react/start-convex-trellaux/convex/_generated/api.js +++ /dev/null @@ -1,22 +0,0 @@ -/* eslint-disable */ -/** - * Generated `api` utility. - * - * THIS CODE IS AUTOMATICALLY GENERATED. - * - * To regenerate, run `npx convex dev`. - * @module - */ - -import { anyApi } from 'convex/server' - -/** - * A utility for referencing Convex functions in your app's API. - * - * Usage: - * ```js - * const myFunctionReference = api.myModule.myFunction; - * ``` - */ -export const api = anyApi -export const internal = anyApi diff --git a/examples/react/start-convex-trellaux/convex/_generated/dataModel.d.ts b/examples/react/start-convex-trellaux/convex/_generated/dataModel.d.ts deleted file mode 100644 index 5b936a43a0..0000000000 --- a/examples/react/start-convex-trellaux/convex/_generated/dataModel.d.ts +++ /dev/null @@ -1,60 +0,0 @@ -/* eslint-disable */ -/** - * Generated data model types. - * - * THIS CODE IS AUTOMATICALLY GENERATED. - * - * To regenerate, run `npx convex dev`. - * @module - */ - -import type { - DataModelFromSchemaDefinition, - DocumentByName, - TableNamesInDataModel, - SystemTableNames, -} from 'convex/server' -import type { GenericId } from 'convex/values' -import schema from '../schema.js' - -/** - * The names of all of your Convex tables. - */ -export type TableNames = TableNamesInDataModel - -/** - * The type of a document stored in Convex. - * - * @typeParam TableName - A string literal type of the table name (like "users"). - */ -export type Doc = DocumentByName< - DataModel, - TableName -> - -/** - * An identifier for a document in Convex. - * - * Convex documents are uniquely identified by their `Id`, which is accessible - * on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids). - * - * Documents can be loaded using `db.get(id)` in query and mutation functions. - * - * IDs are just strings at runtime, but this type can be used to distinguish them from other - * strings when type checking. - * - * @typeParam TableName - A string literal type of the table name (like "users"). - */ -export type Id = - GenericId - -/** - * A type describing your Convex data model. - * - * This type includes information about what tables you have, the type of - * documents stored in those tables, and the indexes defined on them. - * - * This type is used to parameterize methods like `queryGeneric` and - * `mutationGeneric` to make them type-safe. - */ -export type DataModel = DataModelFromSchemaDefinition diff --git a/examples/react/start-convex-trellaux/convex/_generated/server.d.ts b/examples/react/start-convex-trellaux/convex/_generated/server.d.ts deleted file mode 100644 index 869a677bc4..0000000000 --- a/examples/react/start-convex-trellaux/convex/_generated/server.d.ts +++ /dev/null @@ -1,142 +0,0 @@ -/* eslint-disable */ -/** - * Generated utilities for implementing server-side Convex query and mutation functions. - * - * THIS CODE IS AUTOMATICALLY GENERATED. - * - * To regenerate, run `npx convex dev`. - * @module - */ - -import { - ActionBuilder, - HttpActionBuilder, - MutationBuilder, - QueryBuilder, - GenericActionCtx, - GenericMutationCtx, - GenericQueryCtx, - GenericDatabaseReader, - GenericDatabaseWriter, -} from 'convex/server' -import type { DataModel } from './dataModel.js' - -/** - * Define a query in this Convex app's public API. - * - * This function will be allowed to read your Convex database and will be accessible from the client. - * - * @param func - The query function. It receives a {@link QueryCtx} as its first argument. - * @returns The wrapped query. Include this as an `export` to name it and make it accessible. - */ -export declare const query: QueryBuilder - -/** - * Define a query that is only accessible from other Convex functions (but not from the client). - * - * This function will be allowed to read from your Convex database. It will not be accessible from the client. - * - * @param func - The query function. It receives a {@link QueryCtx} as its first argument. - * @returns The wrapped query. Include this as an `export` to name it and make it accessible. - */ -export declare const internalQuery: QueryBuilder - -/** - * Define a mutation in this Convex app's public API. - * - * This function will be allowed to modify your Convex database and will be accessible from the client. - * - * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument. - * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible. - */ -export declare const mutation: MutationBuilder - -/** - * Define a mutation that is only accessible from other Convex functions (but not from the client). - * - * This function will be allowed to modify your Convex database. It will not be accessible from the client. - * - * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument. - * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible. - */ -export declare const internalMutation: MutationBuilder - -/** - * Define an action in this Convex app's public API. - * - * An action is a function which can execute any JavaScript code, including non-deterministic - * code and code with side-effects, like calling third-party services. - * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive. - * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}. - * - * @param func - The action. It receives an {@link ActionCtx} as its first argument. - * @returns The wrapped action. Include this as an `export` to name it and make it accessible. - */ -export declare const action: ActionBuilder - -/** - * Define an action that is only accessible from other Convex functions (but not from the client). - * - * @param func - The function. It receives an {@link ActionCtx} as its first argument. - * @returns The wrapped function. Include this as an `export` to name it and make it accessible. - */ -export declare const internalAction: ActionBuilder - -/** - * Define an HTTP action. - * - * This function will be used to respond to HTTP requests received by a Convex - * deployment if the requests matches the path and method where this action - * is routed. Be sure to route your action in `convex/http.js`. - * - * @param func - The function. It receives an {@link ActionCtx} as its first argument. - * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up. - */ -export declare const httpAction: HttpActionBuilder - -/** - * A set of services for use within Convex query functions. - * - * The query context is passed as the first argument to any Convex query - * function run on the server. - * - * This differs from the {@link MutationCtx} because all of the services are - * read-only. - */ -export type QueryCtx = GenericQueryCtx - -/** - * A set of services for use within Convex mutation functions. - * - * The mutation context is passed as the first argument to any Convex mutation - * function run on the server. - */ -export type MutationCtx = GenericMutationCtx - -/** - * A set of services for use within Convex action functions. - * - * The action context is passed as the first argument to any Convex action - * function run on the server. - */ -export type ActionCtx = GenericActionCtx - -/** - * An interface to read from the database within Convex query functions. - * - * The two entry points are {@link DatabaseReader.get}, which fetches a single - * document by its {@link Id}, or {@link DatabaseReader.query}, which starts - * building a query. - */ -export type DatabaseReader = GenericDatabaseReader - -/** - * An interface to read from and write to the database within Convex mutation - * functions. - * - * Convex guarantees that all writes within a single mutation are - * executed atomically, so you never have to worry about partial writes leaving - * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control) - * for the guarantees Convex provides your functions. - */ -export type DatabaseWriter = GenericDatabaseWriter diff --git a/examples/react/start-convex-trellaux/convex/_generated/server.js b/examples/react/start-convex-trellaux/convex/_generated/server.js deleted file mode 100644 index d16f9527d3..0000000000 --- a/examples/react/start-convex-trellaux/convex/_generated/server.js +++ /dev/null @@ -1,89 +0,0 @@ -/* eslint-disable */ -/** - * Generated utilities for implementing server-side Convex query and mutation functions. - * - * THIS CODE IS AUTOMATICALLY GENERATED. - * - * To regenerate, run `npx convex dev`. - * @module - */ - -import { - actionGeneric, - httpActionGeneric, - queryGeneric, - mutationGeneric, - internalActionGeneric, - internalMutationGeneric, - internalQueryGeneric, -} from 'convex/server' - -/** - * Define a query in this Convex app's public API. - * - * This function will be allowed to read your Convex database and will be accessible from the client. - * - * @param func - The query function. It receives a {@link QueryCtx} as its first argument. - * @returns The wrapped query. Include this as an `export` to name it and make it accessible. - */ -export const query = queryGeneric - -/** - * Define a query that is only accessible from other Convex functions (but not from the client). - * - * This function will be allowed to read from your Convex database. It will not be accessible from the client. - * - * @param func - The query function. It receives a {@link QueryCtx} as its first argument. - * @returns The wrapped query. Include this as an `export` to name it and make it accessible. - */ -export const internalQuery = internalQueryGeneric - -/** - * Define a mutation in this Convex app's public API. - * - * This function will be allowed to modify your Convex database and will be accessible from the client. - * - * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument. - * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible. - */ -export const mutation = mutationGeneric - -/** - * Define a mutation that is only accessible from other Convex functions (but not from the client). - * - * This function will be allowed to modify your Convex database. It will not be accessible from the client. - * - * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument. - * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible. - */ -export const internalMutation = internalMutationGeneric - -/** - * Define an action in this Convex app's public API. - * - * An action is a function which can execute any JavaScript code, including non-deterministic - * code and code with side-effects, like calling third-party services. - * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive. - * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}. - * - * @param func - The action. It receives an {@link ActionCtx} as its first argument. - * @returns The wrapped action. Include this as an `export` to name it and make it accessible. - */ -export const action = actionGeneric - -/** - * Define an action that is only accessible from other Convex functions (but not from the client). - * - * @param func - The function. It receives an {@link ActionCtx} as its first argument. - * @returns The wrapped function. Include this as an `export` to name it and make it accessible. - */ -export const internalAction = internalActionGeneric - -/** - * Define a Convex HTTP action. - * - * @param func - The function. It receives an {@link ActionCtx} as its first argument, and a `Request` object - * as its second. - * @returns The wrapped endpoint function. Route a URL path to this function in `convex/http.js`. - */ -export const httpAction = httpActionGeneric diff --git a/examples/react/start-convex-trellaux/convex/board.ts b/examples/react/start-convex-trellaux/convex/board.ts deleted file mode 100644 index f585a01cd3..0000000000 --- a/examples/react/start-convex-trellaux/convex/board.ts +++ /dev/null @@ -1,196 +0,0 @@ -import { invariant } from './invariant' -import { v } from 'convex/values' -import { - type QueryCtx, - internalMutation, - mutation, - query, -} from './_generated/server' -import schema, { - deleteColumnSchema, - deleteItemSchema, - newColumnsSchema, - updateBoardSchema, - updateColumnSchema, -} from './schema' -import type { Doc, Id } from './_generated/dataModel' - -export const seed = internalMutation(async (ctx) => { - const allBoards = await ctx.db.query('boards').collect() - if (allBoards.length > 0) { - return - } - await ctx.db.insert('boards', { - id: '1', - name: 'First board', - color: '#e0e0e0', - }) -}) - -// Clear all boards (do this on a regular cadence for public examples) -export const clear = internalMutation(async (ctx) => { - const allBoards = await ctx.db.query('boards').collect() - for (const board of allBoards) { - await ctx.db.delete(board._id) - } - await ctx.db.insert('boards', { - id: '1', - name: 'First board', - color: '#e0e0e0', - }) -}) - -function withoutSystemFields }>( - doc: T, -) { - const { _id, _creationTime, ...rest } = doc - return rest -} - -async function getFullBoard(ctx: QueryCtx, id: string) { - const board = withoutSystemFields(await ensureBoardExists(ctx, id)) - - const [columns, items] = await Promise.all([ - ctx.db - .query('columns') - .withIndex('board', (q) => q.eq('boardId', board.id)) - .collect(), - ctx.db - .query('items') - .withIndex('board', (q) => q.eq('boardId', board.id)) - .collect(), - ]) - - return { - ...board, - columns: columns.map(withoutSystemFields), - items: items.map(withoutSystemFields), - } -} - -export const getBoards = query(async (ctx) => { - const boards = await ctx.db.query('boards').collect() - return await Promise.all(boards.map((b) => getFullBoard(ctx, b.id))) -}) - -export const getBoard = query({ - args: { id: v.string() }, - handler: async (ctx, { id }) => { - return await getFullBoard(ctx, id) - }, -}) - -async function ensureBoardExists( - ctx: QueryCtx, - boardId: string, -): Promise> { - const board = await ctx.db - .query('boards') - .withIndex('id', (q) => q.eq('id', boardId)) - .unique() - - invariant(board, `missing board ${boardId}`) - return board -} -async function ensureColumnExists( - ctx: QueryCtx, - columnId: string, -): Promise> { - const column = await ctx.db - .query('columns') - .withIndex('id', (q) => q.eq('id', columnId)) - .unique() - - invariant(column, `missing column: ${columnId}`) - return column -} -async function ensureItemExists( - ctx: QueryCtx, - itemId: string, -): Promise> { - const item = await ctx.db - .query('items') - .withIndex('id', (q) => q.eq('id', itemId)) - .unique() - - invariant(item, `missing item: ${itemId}`) - return item -} - -export const createColumn = mutation({ - args: newColumnsSchema, - handler: async (ctx, { boardId, name }) => { - ensureBoardExists(ctx, boardId) - - const existingColumns = await ctx.db - .query('columns') - .withIndex('board', (q) => q.eq('boardId', boardId)) - .collect() - - ctx.db.insert('columns', { - boardId, - name, - order: existingColumns.length + 1, - id: crypto.randomUUID(), - }) - }, -}) - -export const createItem = mutation({ - args: schema.tables.items.validator, - handler: async (ctx, item) => { - await ensureBoardExists(ctx, item.boardId) - await ctx.db.insert('items', item) - }, -}) - -export const deleteItem = mutation({ - args: deleteItemSchema, - handler: async (ctx, { id, boardId }) => { - await ensureBoardExists(ctx, boardId) - const item = await ensureItemExists(ctx, id) - await ctx.db.delete(item._id) - }, -}) - -export const updateItem = mutation({ - args: schema.tables.items.validator, - handler: async (ctx, newItem) => { - const { id, boardId } = newItem - await ensureBoardExists(ctx, boardId) - const item = await ensureItemExists(ctx, id) - await ctx.db.patch(item._id, newItem) - }, -}) - -export const updateColumn = mutation({ - args: updateColumnSchema, - handler: async (ctx, newColumn) => { - const { id, boardId } = newColumn - await ensureBoardExists(ctx, boardId) - const item = await ensureColumnExists(ctx, id) - await ctx.db.patch(item._id, newColumn) - }, -}) - -export const updateBoard = mutation({ - args: updateBoardSchema, - handler: async (ctx, boardUpdate) => { - const board = await ensureBoardExists(ctx, boardUpdate.id) - await ctx.db.patch(board._id, boardUpdate) - }, -}) - -export const deleteColumn = mutation({ - args: deleteColumnSchema, - handler: async (ctx, { boardId, id }) => { - await ensureBoardExists(ctx, boardId) - const column = await ensureColumnExists(ctx, id) - const items = await ctx.db - .query('items') - .withIndex('column', (q) => q.eq('columnId', id)) - .collect() - await Promise.all(items.map((item) => ctx.db.delete(item._id))) - await ctx.db.delete(column._id) - }, -}) diff --git a/examples/react/start-convex-trellaux/convex/crons.ts b/examples/react/start-convex-trellaux/convex/crons.ts deleted file mode 100644 index a11889d5b1..0000000000 --- a/examples/react/start-convex-trellaux/convex/crons.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { cronJobs } from 'convex/server' -import { internal } from './_generated/api' - -const crons = cronJobs() - -crons.cron('clear messages table', '0,20,40 * * * *', internal.board.clear) - -export default crons diff --git a/examples/react/start-convex-trellaux/convex/invariant.ts b/examples/react/start-convex-trellaux/convex/invariant.ts deleted file mode 100644 index 41fcded35e..0000000000 --- a/examples/react/start-convex-trellaux/convex/invariant.ts +++ /dev/null @@ -1,5 +0,0 @@ -export function invariant(value: unknown, message?: string): asserts value { - if (!value) { - throw new Error(message ?? 'Invariant failed') - } -} diff --git a/examples/react/start-convex-trellaux/convex/schema.ts b/examples/react/start-convex-trellaux/convex/schema.ts deleted file mode 100644 index 18dca7862a..0000000000 --- a/examples/react/start-convex-trellaux/convex/schema.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { defineSchema, defineTable } from 'convex/server' -import { type Infer, v } from 'convex/values' - -const schema = defineSchema({ - boards: defineTable({ - id: v.string(), - name: v.string(), - color: v.string(), - }).index('id', ['id']), - - columns: defineTable({ - id: v.string(), - boardId: v.string(), - name: v.string(), - order: v.number(), - }) - .index('id', ['id']) - .index('board', ['boardId']), - - items: defineTable({ - id: v.string(), - title: v.string(), - content: v.optional(v.string()), - order: v.number(), - columnId: v.string(), - boardId: v.string(), - }) - .index('id', ['id']) - .index('column', ['columnId']) - .index('board', ['boardId']), -}) -export default schema - -const board = schema.tables.boards.validator -const column = schema.tables.columns.validator -const item = schema.tables.items.validator - -export const updateBoardSchema = v.object({ - id: board.fields.id, - name: v.optional(board.fields.name), - color: v.optional(v.string()), -}) - -export const updateColumnSchema = v.object({ - id: column.fields.id, - boardId: column.fields.boardId, - name: v.optional(column.fields.name), - order: v.optional(column.fields.order), -}) - -export const deleteItemSchema = v.object({ - id: item.fields.id, - boardId: item.fields.boardId, -}) -const { order, id, ...rest } = column.fields -export const newColumnsSchema = v.object(rest) -export const deleteColumnSchema = v.object({ - boardId: column.fields.boardId, - id: column.fields.id, -}) - -export type Board = Infer -export type Column = Infer -export type Item = Infer diff --git a/examples/react/start-convex-trellaux/convex/tsconfig.json b/examples/react/start-convex-trellaux/convex/tsconfig.json deleted file mode 100644 index 6fa874e816..0000000000 --- a/examples/react/start-convex-trellaux/convex/tsconfig.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - /* This TypeScript project config describes the environment that - * Convex functions run in and is used to typecheck them. - * You can modify it, but some settings required to use Convex. - */ - "compilerOptions": { - /* These settings are not required by Convex and can be modified. */ - "allowJs": true, - "strict": true, - "moduleResolution": "Bundler", - "jsx": "react-jsx", - "skipLibCheck": true, - "allowSyntheticDefaultImports": true, - - /* These compiler options are required by Convex */ - "target": "ESNext", - "lib": ["ES2021", "dom"], - "forceConsistentCasingInFileNames": true, - "module": "ESNext", - "isolatedModules": true, - "noEmit": true - }, - "include": ["./**/*"], - "exclude": ["./_generated"] -} diff --git a/examples/react/start-convex-trellaux/package.json b/examples/react/start-convex-trellaux/package.json deleted file mode 100644 index 3452f910d0..0000000000 --- a/examples/react/start-convex-trellaux/package.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "name": "tanstack-start-example-convex-trellaux", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "npx convex dev --once && concurrently -r npm:dev:web npm:dev:db", - "dev:web": "vite dev", - "dev:db": "convex dev --run board:seed", - "build": "vite build && tsc --noEmit", - "preview": "vite preview", - "start": "pnpx srvx --prod -s ../client dist/server/server.js" - }, - "dependencies": { - "@convex-dev/react-query": "0.0.0-alpha.8", - "@tanstack/react-query": "^5.102.0", - "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-router-ssr-query": "^1.167.3", - "@tanstack/react-start": "^1.169.6", - "concurrently": "^8.2.2", - "convex": "^1.19.0", - "ky": "^1.7.4", - "msw": "^2.7.0", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "react-hot-toast": "^2.5.1", - "redaxios": "^0.5.1", - "tailwind-merge": "^3.6.0", - "zod": "^4.4.3" - }, - "devDependencies": { - "@tailwindcss/vite": "^4.2.2", - "@types/node": "22.10.2", - "@types/react": "^19.0.8", - "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^6.0.1", - "tailwindcss": "^4.2.2", - "@typescript/native": "npm:typescript@^7.0.2", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14" - } -} diff --git a/examples/react/start-convex-trellaux/public/android-chrome-192x192.png b/examples/react/start-convex-trellaux/public/android-chrome-192x192.png deleted file mode 100644 index 09c8324f8c..0000000000 Binary files a/examples/react/start-convex-trellaux/public/android-chrome-192x192.png and /dev/null differ diff --git a/examples/react/start-convex-trellaux/public/android-chrome-512x512.png b/examples/react/start-convex-trellaux/public/android-chrome-512x512.png deleted file mode 100644 index 11d626ea3d..0000000000 Binary files a/examples/react/start-convex-trellaux/public/android-chrome-512x512.png and /dev/null differ diff --git a/examples/react/start-convex-trellaux/public/apple-touch-icon.png b/examples/react/start-convex-trellaux/public/apple-touch-icon.png deleted file mode 100644 index 5a9423cc02..0000000000 Binary files a/examples/react/start-convex-trellaux/public/apple-touch-icon.png and /dev/null differ diff --git a/examples/react/start-convex-trellaux/public/favicon-16x16.png b/examples/react/start-convex-trellaux/public/favicon-16x16.png deleted file mode 100644 index e3389b0044..0000000000 Binary files a/examples/react/start-convex-trellaux/public/favicon-16x16.png and /dev/null differ diff --git a/examples/react/start-convex-trellaux/public/favicon-32x32.png b/examples/react/start-convex-trellaux/public/favicon-32x32.png deleted file mode 100644 index 900c77d444..0000000000 Binary files a/examples/react/start-convex-trellaux/public/favicon-32x32.png and /dev/null differ diff --git a/examples/react/start-convex-trellaux/public/favicon.ico b/examples/react/start-convex-trellaux/public/favicon.ico deleted file mode 100644 index 1a1751676f..0000000000 Binary files a/examples/react/start-convex-trellaux/public/favicon.ico and /dev/null differ diff --git a/examples/react/start-convex-trellaux/public/favicon.png b/examples/react/start-convex-trellaux/public/favicon.png deleted file mode 100644 index 1e77bc0609..0000000000 Binary files a/examples/react/start-convex-trellaux/public/favicon.png and /dev/null differ diff --git a/examples/react/start-convex-trellaux/public/github-mark-white.png b/examples/react/start-convex-trellaux/public/github-mark-white.png deleted file mode 100644 index 50b8175227..0000000000 Binary files a/examples/react/start-convex-trellaux/public/github-mark-white.png and /dev/null differ diff --git a/examples/react/start-convex-trellaux/public/site.webmanifest b/examples/react/start-convex-trellaux/public/site.webmanifest deleted file mode 100644 index fa99de77db..0000000000 --- a/examples/react/start-convex-trellaux/public/site.webmanifest +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "", - "short_name": "", - "icons": [ - { - "src": "/android-chrome-192x192.png", - "sizes": "192x192", - "type": "image/png" - }, - { - "src": "/android-chrome-512x512.png", - "sizes": "512x512", - "type": "image/png" - } - ], - "theme_color": "#ffffff", - "background_color": "#ffffff", - "display": "standalone" -} diff --git a/examples/react/start-convex-trellaux/public/tanstack.png b/examples/react/start-convex-trellaux/public/tanstack.png deleted file mode 100644 index e0b8e2802b..0000000000 Binary files a/examples/react/start-convex-trellaux/public/tanstack.png and /dev/null differ diff --git a/examples/react/start-convex-trellaux/src/components/Board.tsx b/examples/react/start-convex-trellaux/src/components/Board.tsx deleted file mode 100644 index ac78c7baae..0000000000 --- a/examples/react/start-convex-trellaux/src/components/Board.tsx +++ /dev/null @@ -1,116 +0,0 @@ -import { useCallback, useMemo, useRef } from 'react' -import { invariant } from '../invariant' -import { useSuspenseQuery } from '@tanstack/react-query' -import { convexQuery } from '@convex-dev/react-query' -import { api } from '../../convex/_generated/api.js' -import { useUpdateBoardMutation } from '../queries.js' -import { NewColumn } from './NewColumn.js' -import { Column as ColumnComponent } from './Column.js' -import type { Column } from 'convex/schema.js' -import { EditableText } from '~/components/EditableText.js' - -export function Board({ boardId }: { boardId: string }) { - const newColumnAddedRef = useRef(false) - const updateBoardMutation = useUpdateBoardMutation() - const { data: board } = useSuspenseQuery( - convexQuery(api.board.getBoard, { id: boardId }), - ) - - // scroll right when new columns are added - const scrollContainerRef = useRef(null) - const columnRef = useCallback((_node: HTMLElement | null) => { - if (scrollContainerRef.current && newColumnAddedRef.current) { - newColumnAddedRef.current = false - scrollContainerRef.current.scrollLeft = - scrollContainerRef.current.scrollWidth - } - }, []) - - const itemsById = useMemo( - () => new Map(board.items.map((item) => [item.id, item])), - [board.items], - ) - - type ColumnWithItems = Column & { items: typeof board.items } - - const columns = useMemo(() => { - const columnsMap = new Map() - - for (const column of [...board.columns]) { - columnsMap.set(column.id, { ...column, items: [] }) - } - - // add items to their columns - for (const item of itemsById.values()) { - const columnId = item.columnId - const column = columnsMap.get(columnId) - invariant( - column, - `missing column: ${columnId} from ${[...columnsMap.keys()]}`, - ) - column.items.push(item) - } - - return [...columnsMap.values()].sort((a, b) => a.order - b.order) - }, [board.columns, itemsById]) - - return ( -
-

- { - updateBoardMutation.mutate({ - id: board.id, - name: value, - }) - }} - /> -

- -
- {columns.map((col, index) => { - return ( - - ) - })} - { - newColumnAddedRef.current = true - }} - /> -
- - {/* trolling you to add some extra margin to the right of the container with a whole dang div */} -
-
- ) -} diff --git a/examples/react/start-convex-trellaux/src/components/CancelButton.tsx b/examples/react/start-convex-trellaux/src/components/CancelButton.tsx deleted file mode 100644 index 09b92ec15f..0000000000 --- a/examples/react/start-convex-trellaux/src/components/CancelButton.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { forwardRef } from 'react' - -export const CancelButton = forwardRef< - HTMLButtonElement, - React.ButtonHTMLAttributes ->((props, ref) => { - return ( - - -
- - ) - }, -) diff --git a/examples/react/start-convex-trellaux/src/components/Column.tsx b/examples/react/start-convex-trellaux/src/components/Column.tsx deleted file mode 100644 index fdf2916f6b..0000000000 --- a/examples/react/start-convex-trellaux/src/components/Column.tsx +++ /dev/null @@ -1,250 +0,0 @@ -import { forwardRef, useCallback, useMemo, useRef, useState } from 'react' -import { twMerge } from 'tailwind-merge' - -import { flushSync } from 'react-dom' -import { invariant } from '../invariant' -import { CONTENT_TYPES } from '../types' -import { Icon } from '../icons/icons' -import { - useDeleteColumnMutation, - useUpdateCardMutation, - useUpdateColumnMutation, -} from '../queries' -import { EditableText } from './EditableText' -import { NewCard } from './NewCard' -import { Card } from './Card' -import type { RenderedItem } from '../types' - -interface ColumnProps { - name: string - boardId: string - columnId: string - items: Array - nextOrder: number - previousOrder: number - order: number -} - -export const Column = forwardRef( - ( - { name, columnId, boardId, items, nextOrder, previousOrder, order }, - ref, - ) => { - const [acceptCardDrop, setAcceptCardDrop] = useState(false) - const editState = useState(false) - - const [acceptColumnDrop, setAcceptColumnDrop] = useState< - 'none' | 'left' | 'right' - >('none') - - const [edit, setEdit] = useState(false) - - const itemRef = useCallback((node: HTMLElement | null) => { - node?.scrollIntoView({ - block: 'nearest', - }) - }, []) - - const listRef = useRef(null!) - - function scrollList() { - invariant(listRef.current) - listRef.current.scrollTop = listRef.current.scrollHeight - } - - const updateColumnMutation = useUpdateColumnMutation() - const deleteColumnMutation = useDeleteColumnMutation() - const updateCardMutation = useUpdateCardMutation() - - const sortedItems = useMemo( - () => [...items].sort((a, b) => a.order - b.order), - [items], - ) - - const cardDndProps = { - onDragOver: (event: React.DragEvent) => { - if (event.dataTransfer.types.includes(CONTENT_TYPES.card)) { - event.preventDefault() - setAcceptCardDrop(true) - } - }, - onDragLeave: () => { - setAcceptCardDrop(false) - }, - onDrop: (event: React.DragEvent) => { - const transfer = JSON.parse( - event.dataTransfer.getData(CONTENT_TYPES.card) || 'null', - ) - - if (!transfer) { - return - } - - invariant(transfer.id, 'missing transfer.id') - invariant(transfer.title, 'missing transfer.title') - - updateCardMutation.mutate({ - order: (sortedItems[sortedItems.length - 1]?.order ?? 0) + 1, - columnId: columnId, - boardId, - id: transfer.id, - title: transfer.title, - }) - - setAcceptCardDrop(false) - }, - } - - return ( -
{ - if (event.dataTransfer.types.includes(CONTENT_TYPES.column)) { - event.preventDefault() - event.stopPropagation() - const rect = event.currentTarget.getBoundingClientRect() - const midpoint = (rect.left + rect.right) / 2 - setAcceptColumnDrop(event.clientX <= midpoint ? 'left' : 'right') - } - }} - onDragLeave={() => { - setAcceptColumnDrop('none') - }} - onDrop={(event: React.DragEvent) => { - const transfer = JSON.parse( - event.dataTransfer.getData(CONTENT_TYPES.column) || 'null', - ) - - if (!transfer) { - return - } - - invariant(transfer.id, 'missing transfer.id') - - const droppedOrder = - acceptColumnDrop === 'left' ? previousOrder : nextOrder - const moveOrder = (droppedOrder + order) / 2 - - updateColumnMutation.mutate({ - boardId, - id: transfer.id, - order: moveOrder, - }) - - setAcceptColumnDrop('none') - }} - className={twMerge( - 'border-l-transparent border-r-transparent border-l-2 border-r-2 -mr-[2px] last:mr-0 cursor-grab active:cursor-grabbing px-2 shrink-0 flex flex-col max-h-full', - acceptColumnDrop === 'left' - ? 'border-l-red-500 border-r-transparent' - : acceptColumnDrop === 'right' - ? 'border-r-red-500 border-l-transparent' - : '', - )} - > -
{ - event.dataTransfer.effectAllowed = 'move' - event.dataTransfer.setData( - CONTENT_TYPES.column, - JSON.stringify({ id: columnId, name }), - ) - }} - {...(!items.length ? cardDndProps : {})} - className={twMerge( - 'shrink-0 flex flex-col max-h-full w-80 border-slate-400 rounded-xl shadow-xs shadow-slate-400 bg-slate-100 relative', - acceptCardDrop && `outline-solid outline-2 outline-red-500`, - )} - > -
- { - updateColumnMutation.mutate({ - boardId, - id: columnId, - name: value, - }) - }} - /> -
- -
    - {sortedItems.map((item, index, items) => ( - - ))} -
- {edit ? ( - setEdit(false)} - /> - ) : ( -
- -
- )} -
{ - event.preventDefault() - - deleteColumnMutation.mutate({ - id: columnId, - boardId, - }) - }} - > - -
-
-
- ) - }, -) diff --git a/examples/react/start-convex-trellaux/src/components/DefaultCatchBoundary.tsx b/examples/react/start-convex-trellaux/src/components/DefaultCatchBoundary.tsx deleted file mode 100644 index 405fb5f4a7..0000000000 --- a/examples/react/start-convex-trellaux/src/components/DefaultCatchBoundary.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { - ErrorComponent, - Link, - useLocation, - useRouter, -} from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' - -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - - console.error(error) - - return ( -
- -
- - {isRoot ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) -} diff --git a/examples/react/start-convex-trellaux/src/components/EditableText.tsx b/examples/react/start-convex-trellaux/src/components/EditableText.tsx deleted file mode 100644 index aa74b28266..0000000000 --- a/examples/react/start-convex-trellaux/src/components/EditableText.tsx +++ /dev/null @@ -1,85 +0,0 @@ -import { useRef, useState } from 'react' -import { flushSync } from 'react-dom' - -export function EditableText({ - fieldName, - value, - inputClassName, - inputLabel, - buttonClassName, - buttonLabel, - onChange, - editState, -}: { - fieldName: string - value: string - inputClassName: string - inputLabel: string - buttonClassName: string - buttonLabel: string - onChange: (value: string) => void - editState?: [boolean, (value: boolean) => void] -}) { - const localEditState = useState(false) - const [edit, setEdit] = editState || localEditState - const inputRef = useRef(null) - const buttonRef = useRef(null) - - return edit ? ( -
{ - event.preventDefault() - - onChange(inputRef.current!.value) - - flushSync(() => { - setEdit(false) - }) - - buttonRef.current?.focus() - }} - > - { - if (event.key === 'Escape') { - flushSync(() => { - setEdit(false) - }) - buttonRef.current?.focus() - } - }} - onBlur={(event) => { - if ( - inputRef.current?.value !== value && - inputRef.current?.value.trim() !== '' - ) { - onChange(inputRef.current!.value) - } - setEdit(false) - }} - /> -
- ) : ( - - ) -} diff --git a/examples/react/start-convex-trellaux/src/components/IconLink.tsx b/examples/react/start-convex-trellaux/src/components/IconLink.tsx deleted file mode 100644 index 6ab5be2053..0000000000 --- a/examples/react/start-convex-trellaux/src/components/IconLink.tsx +++ /dev/null @@ -1,19 +0,0 @@ -export function IconLink({ - icon, - href, - label, -}: { - icon: string - href: string - label: string -}) { - return ( - - - {label} - - ) -} diff --git a/examples/react/start-convex-trellaux/src/components/Loader.tsx b/examples/react/start-convex-trellaux/src/components/Loader.tsx deleted file mode 100644 index 1058eabde3..0000000000 --- a/examples/react/start-convex-trellaux/src/components/Loader.tsx +++ /dev/null @@ -1,7 +0,0 @@ -export function Loader() { - return ( -
-
-
- ) -} diff --git a/examples/react/start-convex-trellaux/src/components/NewCard.tsx b/examples/react/start-convex-trellaux/src/components/NewCard.tsx deleted file mode 100644 index 99b0b14839..0000000000 --- a/examples/react/start-convex-trellaux/src/components/NewCard.tsx +++ /dev/null @@ -1,87 +0,0 @@ -import { useRef } from 'react' -import { invariant } from '../invariant' - -import { ItemMutationFields } from '../types' -import { useCreateItemMutation } from '../queries' -import { itemSchema } from '../db/schema' -import { SaveButton } from '~/components/SaveButton' -import { CancelButton } from '~/components/CancelButton' - -export function NewCard({ - columnId, - boardId, - nextOrder, - onComplete, -}: { - columnId: string - boardId: string - nextOrder: number - onComplete: () => void -}) { - const textAreaRef = useRef(null) - const buttonRef = useRef(null) - const { mutate } = useCreateItemMutation() - - return ( -
{ - event.preventDefault() - - const formData = new FormData(event.currentTarget) - const id = crypto.randomUUID() - formData.set(ItemMutationFields.id.name, id) - - invariant(textAreaRef.current) - textAreaRef.current.value = '' - - mutate(itemSchema.parse(Object.fromEntries(formData.entries()))) - }} - onBlur={(event) => { - if (!event.currentTarget.contains(event.relatedTarget)) { - onComplete() - } - }} - > - - - - -

+ data: Data + pluginArgs: PluginArgs +} +type PagesPluginFunction< + Env = unknown, + Params extends string = any, + Data extends Record = Record, + PluginArgs = unknown, +> = ( + context: EventPluginContext, +) => Response | Promise +declare module 'assets:*' { + export const onRequest: PagesFunction } // Copyright (c) 2022-2023 Cloudflare, Inc. // Licensed under the Apache 2.0 license found in the LICENSE file or at: // https://opensource.org/licenses/Apache-2.0 -declare module "cloudflare:pipelines" { - export abstract class PipelineTransformationEntrypoint { - protected env: Env; - protected ctx: ExecutionContext; - constructor(ctx: ExecutionContext, env: Env); - /** - * run receives an array of PipelineRecord which can be - * transformed and returned to the pipeline - * @param records Incoming records from the pipeline to be transformed - * @param metadata Information about the specific pipeline calling the transformation entrypoint - * @returns A promise containing the transformed PipelineRecord array - */ - public run(records: I[], metadata: PipelineBatchMetadata): Promise; - } - export type PipelineRecord = Record; - export type PipelineBatchMetadata = { - pipelineId: string; - pipelineName: string; - }; - export interface Pipeline { - /** - * The Pipeline interface represents the type of a binding to a Pipeline - * - * @param records The records to send to the pipeline - */ - send(records: T[]): Promise; - } +declare module 'cloudflare:pipelines' { + export abstract class PipelineTransformationEntrypoint< + Env = unknown, + I extends PipelineRecord = PipelineRecord, + O extends PipelineRecord = PipelineRecord, + > { + protected env: Env + protected ctx: ExecutionContext + constructor(ctx: ExecutionContext, env: Env) + /** + * run recieves an array of PipelineRecord which can be + * transformed and returned to the pipeline + * @param records Incoming records from the pipeline to be transformed + * @param metadata Information about the specific pipeline calling the transformation entrypoint + * @returns A promise containing the transformed PipelineRecord array + */ + public run(records: I[], metadata: PipelineBatchMetadata): Promise + } + export type PipelineRecord = Record + export type PipelineBatchMetadata = { + pipelineId: string + pipelineName: string + } + export interface Pipeline { + /** + * The Pipeline interface represents the type of a binding to a Pipeline + * + * @param records The records to send to the pipeline + */ + send(records: T[]): Promise + } } // PubSubMessage represents an incoming PubSub message. // The message includes metadata about the broker, the client, and the payload // itself. // https://developers.cloudflare.com/pub-sub/ interface PubSubMessage { - // Message ID - readonly mid: number; - // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT - readonly broker: string; - // The MQTT topic the message was sent on. - readonly topic: string; - // The client ID of the client that published this message. - readonly clientId: string; - // The unique identifier (JWT ID) used by the client to authenticate, if token - // auth was used. - readonly jti?: string; - // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker - // received the message from the client. - readonly receivedAt: number; - // An (optional) string with the MIME type of the payload, if set by the - // client. - readonly contentType: string; - // Set to 1 when the payload is a UTF-8 string - // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 - readonly payloadFormatIndicator: number; - // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. - // You can use payloadFormatIndicator to inspect this before decoding. - payload: string | Uint8Array; + // Message ID + readonly mid: number + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string + // The MQTT topic the message was sent on. + readonly topic: string + // The client ID of the client that published this message. + readonly clientId: string + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array } // JsonWebKey extended by kid parameter interface JsonWebKeyWithKid extends JsonWebKey { - // Key Identifier of the JWK - readonly kid: string; + // Key Identifier of the JWK + readonly kid: string } interface RateLimitOptions { - key: string; + key: string } interface RateLimitOutcome { - success: boolean; + success: boolean } interface RateLimit { - /** - * Rate limit a request based on the provided options. - * @see https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/ - * @returns A promise that resolves with the outcome of the rate limit. - */ - limit(options: RateLimitOptions): Promise; + /** + * Rate limit a request based on the provided options. + * @see https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/ + * @returns A promise that resolves with the outcome of the rate limit. + */ + limit(options: RateLimitOptions): Promise } // Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need // to referenced by `Fetcher`. This is included in the "importable" version of the types which // strips all `module` blocks. declare namespace Rpc { - // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. - // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. - // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to - // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) - export const __RPC_STUB_BRAND: '__RPC_STUB_BRAND'; - export const __RPC_TARGET_BRAND: '__RPC_TARGET_BRAND'; - export const __WORKER_ENTRYPOINT_BRAND: '__WORKER_ENTRYPOINT_BRAND'; - export const __DURABLE_OBJECT_BRAND: '__DURABLE_OBJECT_BRAND'; - export const __WORKFLOW_ENTRYPOINT_BRAND: '__WORKFLOW_ENTRYPOINT_BRAND'; - export interface RpcTargetBranded { - [__RPC_TARGET_BRAND]: never; - } - export interface WorkerEntrypointBranded { - [__WORKER_ENTRYPOINT_BRAND]: never; - } - export interface DurableObjectBranded { - [__DURABLE_OBJECT_BRAND]: never; - } - export interface WorkflowEntrypointBranded { - [__WORKFLOW_ENTRYPOINT_BRAND]: never; - } - export type EntrypointBranded = WorkerEntrypointBranded | DurableObjectBranded | WorkflowEntrypointBranded; - // Types that can be used through `Stub`s - export type Stubable = RpcTargetBranded | ((...args: any[]) => any); - // Types that can be passed over RPC - // The reason for using a generic type here is to build a serializable subset of structured - // cloneable composite types. This allows types defined with the "interface" keyword to pass the - // serializable check as well. Otherwise, only types defined with the "type" keyword would pass. - type Serializable = + // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. + // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. + // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to + // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) + export const __RPC_STUB_BRAND: '__RPC_STUB_BRAND' + export const __RPC_TARGET_BRAND: '__RPC_TARGET_BRAND' + export const __WORKER_ENTRYPOINT_BRAND: '__WORKER_ENTRYPOINT_BRAND' + export const __DURABLE_OBJECT_BRAND: '__DURABLE_OBJECT_BRAND' + export const __WORKFLOW_ENTRYPOINT_BRAND: '__WORKFLOW_ENTRYPOINT_BRAND' + export interface RpcTargetBranded { + [__RPC_TARGET_BRAND]: never + } + export interface WorkerEntrypointBranded { + [__WORKER_ENTRYPOINT_BRAND]: never + } + export interface DurableObjectBranded { + [__DURABLE_OBJECT_BRAND]: never + } + export interface WorkflowEntrypointBranded { + [__WORKFLOW_ENTRYPOINT_BRAND]: never + } + export type EntrypointBranded = + | WorkerEntrypointBranded + | DurableObjectBranded + | WorkflowEntrypointBranded + // Types that can be used through `Stub`s + export type Stubable = RpcTargetBranded | ((...args: any[]) => any) + // Types that can be passed over RPC + // The reason for using a generic type here is to build a serializable subset of structured + // cloneable composite types. This allows types defined with the "interface" keyword to pass the + // serializable check as well. Otherwise, only types defined with the "type" keyword would pass. + type Serializable = // Structured cloneables - BaseType + | BaseType // Structured cloneable composites - | Map ? Serializable : never, T extends Map ? Serializable : never> | Set ? Serializable : never> | ReadonlyArray ? Serializable : never> | { - [K in keyof T]: K extends number | string ? Serializable : never; - } + | Map< + T extends Map ? Serializable : never, + T extends Map ? Serializable : never + > + | Set ? Serializable : never> + | ReadonlyArray ? Serializable : never> + | { + [K in keyof T]: K extends number | string ? Serializable : never + } // Special types - | Stub + | Stub // Serialized as stubs, see `Stubify` - | Stubable; - // Base type for all RPC stubs, including common memory management methods. - // `T` is used as a marker type for unwrapping `Stub`s later. - interface StubBase extends Disposable { - [__RPC_STUB_BRAND]: T; - dup(): this; - } - export type Stub = Provider & StubBase; - // This represents all the types that can be sent as-is over an RPC boundary - type BaseType = void | undefined | null | boolean | number | bigint | string | TypedArray | ArrayBuffer | DataView | Date | Error | RegExp | ReadableStream | WritableStream | Request | Response | Headers; - // Recursively rewrite all `Stubable` types with `Stub`s - // prettier-ignore - type Stubify = T extends Stubable ? Stub : T extends Map ? Map, Stubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { + | Stubable + // Base type for all RPC stubs, including common memory management methods. + // `T` is used as a marker type for unwrapping `Stub`s later. + interface StubBase extends Disposable { + [__RPC_STUB_BRAND]: T + dup(): this + } + export type Stub = Provider & StubBase + // This represents all the types that can be sent as-is over an RPC boundary + type BaseType = + | void + | undefined + | null + | boolean + | number + | bigint + | string + | TypedArray + | ArrayBuffer + | DataView + | Date + | Error + | RegExp + | ReadableStream + | WritableStream + | Request + | Response + | Headers + // Recursively rewrite all `Stubable` types with `Stub`s + // prettier-ignore + type Stubify = T extends Stubable ? Stub : T extends Map ? Map, Stubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { [key: string | number]: any; } ? { [K in keyof T]: Stubify; } : T; - // Recursively rewrite all `Stub`s with the corresponding `T`s. - // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: - // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. - // prettier-ignore - type Unstubify = T extends StubBase ? V : T extends Map ? Map, Unstubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { + // Recursively rewrite all `Stub`s with the corresponding `T`s. + // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: + // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. + // prettier-ignore + type Unstubify = T extends StubBase ? V : T extends Map ? Map, Unstubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { [key: string | number]: unknown; } ? { [K in keyof T]: Unstubify; } : T; - type UnstubifyAll = { - [I in keyof A]: Unstubify; - }; - // Utility type for adding `Provider`/`Disposable`s to `object` types only. - // Note `unknown & T` is equivalent to `T`. - type MaybeProvider = T extends object ? Provider : unknown; - type MaybeDisposable = T extends object ? Disposable : unknown; - // Type for method return or property on an RPC interface. - // - Stubable types are replaced by stubs. - // - Serializable types are passed by value, with stubable types replaced by stubs - // and a top-level `Disposer`. - // Everything else can't be passed over PRC. - // Technically, we use custom thenables here, but they quack like `Promise`s. - // Intersecting with `(Maybe)Provider` allows pipelining. - // prettier-ignore - type Result = R extends Stubable ? Promise> & Provider : R extends Serializable ? Promise & MaybeDisposable> & MaybeProvider : never; - // Type for method or property on an RPC interface. - // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. - // Unwrapping `Stub`s allows calling with `Stubable` arguments. - // For properties, rewrite types to be `Result`s. - // In each case, unwrap `Promise`s. - type MethodOrProperty = V extends (...args: infer P) => infer R ? (...args: UnstubifyAll