Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Fix: Handle circular references in Http.request JSON processing#10744

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
alvidofaisal wants to merge2 commits intoNativeScript:main
base:main
Choose a base branch
Loading
fromalvidofaisal:fix-http-circular-json-stringify

Conversation

alvidofaisal
Copy link

@alvidofaisalalvidofaisal commentedJun 14, 2025
edited by coderabbitaibot
Loading

PR Checklist

What is the current behavior?

JSON.stringify crashes when encountering circular references in Android Http.request responses or debug information containing circular structures (e.g., from CSS-like objects). This causes app crashes when processing HTTP responses that contain objects with circular references.

Additionally, thetoJSON() method in HTTP responses had unnecessary performance overhead by converting already-parsed JavaScript objects to JSON strings and parsing them back.

What is the new behavior?

  • Introduced asafeJsonStringify utility that safely handles circular references by replacing them with"[Circular]" placeholders
  • AppliedsafeJsonStringify to HTTP response debug headers and request debug data to prevent crashes
  • Optimized thecontent.toJSON() method to return parsed objects directly without redundant stringify-parse cycles
  • Added comprehensive unit tests covering various circular reference scenarios including direct, nested, array-based, andtoJSON method edge cases

Fixes/Implements/Closes #[Issue Number].

#10712

Summary by CodeRabbit

  • New Features
    • Added a utility for safely converting complex or circular objects to JSON strings.
  • Bug Fixes
    • Improved the reliability of debug information for HTTP requests and responses by ensuring headers and request content are safely serialized.
  • Tests
    • Introduced comprehensive tests to verify safe JSON stringification, especially with circular references and edge cases.

Introduces a `safeJsonStringify` utility to prevent crashes when `JSON.stringify` encounters circular references. This issue was particularly noted in Android when Http.request responses or debug information containing circular structures (e.g., from CSS-like objects) were processed.The `safeJsonStringify` utility replaces circular references with `"[Circular]"`.This commit applies `safeJsonStringify` to:- The `content.toJSON()` method in `packages/core/http/http-request/index.android.ts` to safely parse HTTP response bodies.- The debug data generation in `packages/core/http/http-request/index.android.ts` for `requestWillBeSent` and `responseReceived` events, ensuring headers and FormData content are safely stringified for the debugger.Additionally, unit tests for `safeJsonStringify` have been added in `packages/core/utils/safe-json-stringify.spec.ts` to cover various scenarios, including direct and nested circular references, and handling of `toJSON` methods.
…JSON methodEliminates unnecessary performance overhead by returning parseJSON(str) directly instead of converting the already-parsed JavaScript object to a JSON string and then parsing it back. HTTP response data doesn't contain circular references that would require safeJsonStringify processing.Signed-off-by: alvidofaisal <alvidofaisal@gmail.com>
@coderabbitaicoderabbitai
Copy link

coderabbitaibot commentedJun 14, 2025
edited
Loading

Walkthrough

A new utility,safeJsonStringify, is introduced to serialize JavaScript objects to JSON while safely handling circular references. This utility is used in the Android HTTP request implementation to robustly serialize headers and request content for debugging. Comprehensive tests forsafeJsonStringify are also added.

Changes

File(s)Change Summary
packages/core/utils/safe-json-stringify.tsAddedsafeJsonStringify utility for JSON serialization with circular reference handling.
packages/core/utils/safe-json-stringify.spec.tsAdded test suite covering various scenarios and edge cases forsafeJsonStringify.
packages/core/http/http-request/index.android.tsUpdated to usesafeJsonStringify for serializing headers and request content in debug information.

Sequence Diagram(s)

sequenceDiagram    participant Caller    participant HTTPRequest    participant safeJsonStringify    Caller->>HTTPRequest: Initiate HTTP request    HTTPRequest->>safeJsonStringify: Serialize headers/content for debugging    safeJsonStringify-->>HTTPRequest: Return safe JSON string    HTTPRequest-->>Caller: Complete request with debug info
Loading

Poem

In the warren of code, a bug hops near,
Circular loops once filled us with fear.
Now with safe stringifies,
Our debug info flies—
No more infinite JSON, the path is clear!
🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm errorhttps://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-06-14T21_09_55_736Z-debug-0.log

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat withCodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • 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. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings togenerate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add@coderabbitai 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 theconfiguration 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

Documentation and Community

  • Visit ourDocumentation for detailed information on how to use CodeRabbit.
  • Join ourDiscord Community to get help, request features, and share feedback.
  • Follow us onX/Twitter for updates and announcements.

Copy link

@coderabbitaicoderabbitaibot 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: 2

🧹 Nitpick comments (4)
packages/core/http/http-request/index.android.ts (2)

97-105:Double parse / stringify is wasteful

JSON.parse(safeJsonStringify(headers)) incurs two passes over the same object just to deep-clone & de-circularise.
A shallow header object rarely needs deep traversal and never holds circular refs by spec.

-const safeDebugHeaders = JSON.parse(safeJsonStringify(headers));+const safeDebugHeaders = { ...headers }; // headers are already plain key-value pairs

If genuine circularity is still possible, keep the safer version but gate it behind a cheap check:

constsafeDebugHeaders=Object.values(headers).some(v=>typeofv==='object')    ?JSON.parse(safeJsonStringify(headers))    :{ ...headers};

280-304:Lost request body fidelity

FormData andArrayBuffer are reduced to either an almost empty object ({} after stringify) or the placeholder"[ArrayBuffer]".
This makes network-debugger output far less useful.

Suggestion:

-} else if (options.content instanceof FormData) {-    (request as any).postData = safeJsonStringify(options.content);+} else if (options.content instanceof FormData) {+    // Iterate entries to build a readable representation+    const fd: Record<string, unknown[]> = {};+    options.content.forEach((v, k) => {+        (fd[k] ||= []).push(typeof v === 'object' ? '[Object]' : v);+    });+    (request as any).postData = safeJsonStringify(fd); ...-} else if (options.content instanceof ArrayBuffer) {-    (request as any).postData = '[ArrayBuffer]';+} else if (options.content instanceof ArrayBuffer) {+    (request as any).postData = `ArrayBuffer(${options.content.byteLength} bytes)`; }

This preserves safety while giving developers actionable insight.

packages/core/utils/safe-json-stringify.spec.ts (2)

46-51:Spec comment block can be removed or turned intoit.todo

Lines 47-73 contain in-test commentary explaining potential mismatches; leaving this prose in the production test adds noise.

Convert to separatedescribe/it blocks or delete after deciding desired behaviour.


74-75:Assertion may mask real behaviour

IfsafeJsonStringify(undefined) is changed (see utility review) this expectation will fail.
Either split into its ownit with explicit rationale or assert usingtoBeUndefined() to track intended semantics.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between8979ad8 and8dbda20.

📒 Files selected for processing (3)
  • packages/core/http/http-request/index.android.ts (3 hunks)
  • packages/core/utils/safe-json-stringify.spec.ts (1 hunks)
  • packages/core/utils/safe-json-stringify.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
packages/core/http/http-request/index.android.ts (2)
packages/core/utils/safe-json-stringify.ts (1)
  • safeJsonStringify (1-15)
packages/core/http/http-request/index.ios.ts (1)
  • request (75-233)
packages/core/utils/safe-json-stringify.spec.ts (1)
packages/core/utils/safe-json-stringify.ts (1)
  • safeJsonStringify (1-15)

@CatchABus
Copy link
Contributor

To be frank, I don't see why core needs this handling. Also, are there any http libraries that do this to begin with?
Normally, users should be able to convert the response to text and handle the parsing themselves.

@alvidofaisal
Copy link
Author

I figured since .toJSON() is already there in core, making it tougher against these circular reference crashes would be a good thing. It directly tackles that crash in issue#10712.

Totally agree, you can always grab the raw text. This just makes the helper itself a bit safer for folks who use it, so it doesn't unexpectedly break the app. Just trying to make it a bit more solid for that common case.

@CatchABus
Copy link
Contributor

CatchABus commentedJun 15, 2025
edited
Loading

I figured since .toJSON() is already there in core, making it tougher against these circular reference crashes would be a good thing. It directly tackles that crash in issue#10712.

Totally agree, you can always grab the raw text. This just makes the helper itself a bit safer for folks who use it, so it doesn't unexpectedly break the app. Just trying to make it a bit more solid for that common case.

I see your point here but I believe there's a benefit of leaving the handling of that case to developers.
Let's say your REST API is in production but you have a circular reference in your json response you're not aware of.
The way things are now, client will let you know that something is wrong with your API JSON response and you can decide whether you'll take care of it. App breaking or crashing is not necessarily a bad thing in this case because it informs you about something possibly being wrong on the other side.

Personally, I always avoid circular refs and if I really need them then I try things like defining them as non-enumerable properties in my json objects.

Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Reviewers

@coderabbitaicoderabbitai[bot]coderabbitai[bot] left review comments

Assignees
No one assigned
Labels
None yet
Projects
None yet
Milestone
No milestone
Development

Successfully merging this pull request may close these issues.

2 participants
@alvidofaisal@CatchABus

[8]ページ先頭

©2009-2025 Movatter.jp