Skip to content

Conversation

Sheraff
Copy link
Contributor

@Sheraff Sheraff commented Sep 2, 2025

Improve performance of defaultParseSearch and defaultStringifySearch by skipping calling JSON.parse if we know from the 1 char that it cannot be a valid JSON string.

 ✓  @tanstack/router-core  tests/searchParams.bench.ts > defaultStringifySearch 1209ms
     name         hz     min     max    mean     p75     p99    p995    p999     rme  samples
   · new   10,257.92  0.0593  0.7257  0.0975  0.0795  0.3030  0.3619  0.5785  ±1.95%     5130   fastest
   · old    7,636.79  0.0823  0.6418  0.1309  0.1065  0.3945  0.4503  0.5691  ±2.13%     3819

 ✓  @tanstack/router-core  tests/searchParams.bench.ts > defaultParseSearch 1208ms
     name        hz     min     max    mean     p75     p99    p995    p999     rme  samples
   · new   9,709.41  0.0896  0.3881  0.1030  0.1000  0.2121  0.2446  0.2928  ±0.60%     4855   fastest
   · old   7,832.70  0.1157  0.3793  0.1277  0.1280  0.2366  0.2919  0.3616  ±0.50%     3917

 BENCH  Summary

   @tanstack/router-core  new - tests/searchParams.bench.ts > defaultStringifySearch
    1.34x faster than old

   @tanstack/router-core  new - tests/searchParams.bench.ts > defaultParseSearch
    1.24x faster than old

Summary by CodeRabbit

  • Bug Fixes
    • Improved reliability of search parameter parsing and stringifying.
    • Only treats values as JSON when they appear JSON-like, preventing unintended parsing.
    • Preserves plain strings and reduces unexpected value transformations.
    • Lowers risk of errors or crashes when handling non-JSON values in URLs.
  • Refactor
    • Internal logic streamlined to safely apply parsers without altering public APIs.

Copy link
Contributor

coderabbitai bot commented Sep 2, 2025

Walkthrough

Updates search param parsing/stringifying to avoid unconditional JSON.parse. Introduces an internal looksLikeJson helper. parseSearchWith and stringifySearchWith now apply JSON.parse only to values that appear JSON-like; otherwise, values are passed through or to provided parsers. Public API remains unchanged.

Changes

Cohort / File(s) Summary
Search params JSON-guarding
packages/router-core/src/searchParams.ts
Added non-exported looksLikeJson helper; updated parseSearchWith/stringifySearchWith to conditionally use JSON.parse only for JSON-like strings; preserved existing public signatures.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Caller
  participant SP as searchParams.ts
  participant LLJ as looksLikeJson
  participant JP as JSON.parse
  Note over SP: parseSearchWith flow (per value)
  Caller->>SP: parseSearchWith(value, parser)
  SP->>SP: isJsonParser = (parser === JSON.parse)
  alt value is string
    SP->>LLJ: looksLikeJson(value)
    alt isJsonParser AND looksLikeJson
      SP->>JP: JSON.parse(value)
      JP-->>SP: parsed
      SP-->>Caller: parsed
    else isJsonParser AND NOT looksLikeJson
      SP-->>Caller: value (string as-is)
    else not JSON parser
      SP->>SP: parser(value)
      SP-->>Caller: result
    end
  else non-string
    SP-->>Caller: value (unchanged)
  end
Loading
sequenceDiagram
  autonumber
  actor Caller
  participant SP as searchParams.ts
  participant LLJ as looksLikeJson
  participant JP as JSON.parse
  Note over SP: stringifySearchWith flow (per value)
  Caller->>SP: stringifySearchWith(value, parser)
  alt parser exists
    alt value is string
      SP->>LLJ: looksLikeJson(value)
      alt looksLikeJson
        SP->>JP: JSON.parse(value)
        JP-->>SP: obj
        SP->>SP: parser(obj)
        SP-->>Caller: string
      else not JSON-like
        SP-->>Caller: value (string as-is)
      end
    else non-string
      SP->>SP: parser(value)
      SP-->>Caller: string
    end
  else no parser
    SP-->>Caller: default handling (unchanged)
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

package: router-core

Suggested reviewers

  • schiller-manuel
  • SeanCassiere

Poem

I sniff each query, whiskers twitch—
If strings look JSON, I flip the switch.
If not, I hop on, leaving plain text be,
Guarded parses set my data free.
Thump-thump! Safe paths I now traverse—
A bun who won’t let parsers curse. 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor-router-core-stringify-parse-search-json-perf

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

nx-cloud bot commented Sep 2, 2025

View your CI Pipeline Execution ↗ for commit 5bbf768

Command Status Duration Result
nx affected --targets=test:eslint,test:unit,tes... ✅ Succeeded 4m 9s View ↗
nx run-many --target=build --exclude=examples/*... ✅ Succeeded 1m 33s View ↗

☁️ Nx Cloud last updated this comment at 2025-09-02 21:12:51 UTC

Copy link

pkg-pr-new bot commented Sep 2, 2025

More templates

@tanstack/arktype-adapter

npm i https://pkg.pr.new/TanStack/router/@tanstack/arktype-adapter@5071

@tanstack/directive-functions-plugin

npm i https://pkg.pr.new/TanStack/router/@tanstack/directive-functions-plugin@5071

@tanstack/eslint-plugin-router

npm i https://pkg.pr.new/TanStack/router/@tanstack/eslint-plugin-router@5071

@tanstack/history

npm i https://pkg.pr.new/TanStack/router/@tanstack/history@5071

@tanstack/react-router

npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router@5071

@tanstack/react-router-devtools

npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-devtools@5071

@tanstack/react-router-ssr-query

npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-ssr-query@5071

@tanstack/react-start

npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start@5071

@tanstack/react-start-client

npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-client@5071

@tanstack/react-start-plugin

npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-plugin@5071

@tanstack/react-start-server

npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-server@5071

@tanstack/router-cli

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-cli@5071

@tanstack/router-core

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-core@5071

@tanstack/router-devtools

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools@5071

@tanstack/router-devtools-core

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools-core@5071

@tanstack/router-generator

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-generator@5071

@tanstack/router-plugin

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-plugin@5071

@tanstack/router-ssr-query-core

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-ssr-query-core@5071

@tanstack/router-utils

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-utils@5071

@tanstack/router-vite-plugin

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-vite-plugin@5071

@tanstack/server-functions-plugin

npm i https://pkg.pr.new/TanStack/router/@tanstack/server-functions-plugin@5071

@tanstack/solid-router

npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router@5071

@tanstack/solid-router-devtools

npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router-devtools@5071

@tanstack/solid-start

npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start@5071

@tanstack/solid-start-client

npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-client@5071

@tanstack/solid-start-plugin

npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-plugin@5071

@tanstack/solid-start-server

npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-server@5071

@tanstack/start-client-core

npm i https://pkg.pr.new/TanStack/router/@tanstack/start-client-core@5071

@tanstack/start-plugin-core

npm i https://pkg.pr.new/TanStack/router/@tanstack/start-plugin-core@5071

@tanstack/start-server-core

npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-core@5071

@tanstack/start-server-functions-client

npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-client@5071

@tanstack/start-server-functions-fetcher

npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-fetcher@5071

@tanstack/start-server-functions-server

npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-server@5071

@tanstack/start-storage-context

npm i https://pkg.pr.new/TanStack/router/@tanstack/start-storage-context@5071

@tanstack/valibot-adapter

npm i https://pkg.pr.new/TanStack/router/@tanstack/valibot-adapter@5071

@tanstack/virtual-file-routes

npm i https://pkg.pr.new/TanStack/router/@tanstack/virtual-file-routes@5071

@tanstack/zod-adapter

npm i https://pkg.pr.new/TanStack/router/@tanstack/zod-adapter@5071

commit: 5bbf768

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/router-core/src/searchParams.ts (1)

51-63: Bug: stringify(val) double-quotes JSON-like strings and breaks round-trip typing.

When parser succeeds, you’re stringifying the original string instead of the parsed value. Example: "123" becomes ""123"" in the URL, and parses back to the string "123" instead of number 123. Same for "true"/"false". Use stringify(parser(val)).

Apply this diff:

   } else if (
     hasParser &&
     typeof val === 'string' &&
     (!isJsonParser || looksLikeJson(val))
   ) {
     try {
-      // Check if it's a valid parseable string.
-      // If it is, then stringify it again.
-      parser(val)
-      return stringify(val)
+      // If parseable, canonicalize by stringifying the parsed value.
+      const parsed = parser!(val)
+      return stringify(parsed)
     } catch (_err) {
       // silent
     }
   }
🧹 Nitpick comments (3)
packages/router-core/src/searchParams.ts (3)

22-25: Behavior change: strings with leading whitespace won’t be parsed.

looksLikeJson checks only the first char. Values like " 123", "\n[1]" are valid JSON for JSON.parse but will now be skipped and remain strings. Confirm this is acceptable, or trim leading whitespace in looksLikeJson (see suggestion below).


77-81: Doc fix: claim about “no false negatives” is inaccurate.

Leading whitespace produces false negatives with the current heuristic.

Apply this diff:

 /**
- * Fast check to see if the string is a likely to be a JSON value.
- * It could return false positives (returned true but wasn't actually a json),
- * but not false negatives (returned false but was actually a json).
+ * Fast, conservative check to see if the string is likely a JSON value.
+ * May return false positives (true but not actually JSON) and rare false negatives
+ * (e.g. when the string starts with whitespace).
  */

82-95: Optional: skip leading whitespace in looksLikeJson to avoid false negatives.

Small loop; negligible cost, removes a class of surprises.

Apply this diff:

 function looksLikeJson(str: string): boolean {
-  if (!str) return false
-  const c = str.charCodeAt(0)
+  if (!str) return false
+  // Skip leading whitespace: space(32), tab(9), lf(10), cr(13)
+  let i = 0
+  while (i < str.length) {
+    const code = str.charCodeAt(i)
+    if (code !== 32 && code !== 9 && code !== 10 && code !== 13) break
+    i++
+  }
+  if (i >= str.length) return false
+  const c = str.charCodeAt(i)
   return (
     c === 34 || // "
     c === 123 || // {
     c === 91 || // [
     c === 45 || // -
     (c >= 48 && c <= 57) || // 0-9
     c === 116 || // t (true)
     c === 102 || // f (false)
     c === 110 // n (null)
   )
 }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 3178314 and 5bbf768.

📒 Files selected for processing (1)
  • packages/router-core/src/searchParams.ts (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Preview
  • GitHub Check: Test
🔇 Additional comments (2)
packages/router-core/src/searchParams.ts (2)

11-11: LGTM: caching the JSON.parse identity.

Keeps the hot-path branch simple without re-checking inside the loop.


43-43: LGTM: parity with parse path.

Mirrors the parse side’s identity check and keeps the conditionals cheap.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants