fix(analytics-browser): prevent circular reference in logBrowserOptions#1537
Conversation
There was a problem hiding this comment.
Pull request overview
This PR fixes a bug where JSON.stringify was throwing "Converting circular structure to JSON" errors when logging browser configuration. The issue arose because browserConfig objects can contain circular references (e.g., references back to the amplitude instance). The fix replaces the native JSON.stringify with the "safe-json-stringify" library which gracefully handles circular references.
Changes:
- Introduced a new
safeJsonStringifyutility that wraps the "safe-json-stringify" npm package - Replaced
JSON.stringifywithsafeJsonStringifyin thelogBrowserOptionsmethod - Added comprehensive test coverage for the circular reference scenario
Reviewed changes
Copilot reviewed 5 out of 6 changed files in this pull request and generated no comments.
Show a summary per file
| File | Description |
|---|---|
| packages/analytics-core/src/utils/safe-stringify.ts | New utility module that wraps safe-json-stringify with proper type definitions and handles both CommonJS and ES module exports |
| packages/analytics-core/src/index.ts | Exports the safeJsonStringify utility for use in other packages |
| packages/analytics-core/package.json | Adds safe-json-stringify (1.2.0) as a runtime dependency and @types/safe-json-stringify (1.1.5) as a dev dependency |
| packages/analytics-browser/src/browser-client.ts | Updates logBrowserOptions to use safeJsonStringify instead of JSON.stringify |
| packages/analytics-browser/test/browser-client.test.ts | Adds regression test to verify circular references don't cause errors |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Mercy811
left a comment
There was a problem hiding this comment.
LGTM! looks like safe-json-stringify is just pure js code https://github.com/debitoor/safe-json-stringify/blob/master/index.js. And we're pinning the version so no risk of surprisingly upgrading to a bad malicious new version.
|
bugbot run |
Summary
(~40 LOC changes if you exclude lockfile)
resolves #1521
Replace native
JSON.stringifywith "safe-json-stringify".Note: "safe-json-stringify" is a 3rd party package that doesn't have any transitive dependencies. And it's pinned to a specific version. Should be safe from Supply Chain attacks.
Checklist
Note
Low Risk
Small change limited to debug logging plus a new pinned dependency; low behavioral risk outside of log output formatting.
Overview
Prevents
AmplitudeBrowserinitialization logging from throwing whenBrowserOptionscontains circular references by replacingJSON.stringifywith a newsafeJsonStringifywrapper.Adds
safe-json-stringify(and typings) toanalytics-core, re-exports it from the core index, and adds unit/regression tests covering both circular and non-circular stringification and thelogBrowserOptionscall path.Written by Cursor Bugbot for commit 9cdd576. Configure here.