summaryrefslogtreecommitdiff
path: root/packages/core/src/utils/safeJsonStringify.ts
diff options
context:
space:
mode:
authorBryan Morgan <[email protected]>2025-07-14 16:20:06 -0400
committerGitHub <[email protected]>2025-07-14 20:20:06 +0000
commitff3722a3a74b09cd25b03de41933944a55db6351 (patch)
tree9777d89dc9f984077a895c3aea2910a34eecf846 /packages/core/src/utils/safeJsonStringify.ts
parent5008aea90d4ea7ac6bb5872f3702f3c7a7878ed0 (diff)
Fix circular reference JSON serialization in telemetry logging (#4150)
Diffstat (limited to 'packages/core/src/utils/safeJsonStringify.ts')
-rw-r--r--packages/core/src/utils/safeJsonStringify.ts32
1 files changed, 32 insertions, 0 deletions
diff --git a/packages/core/src/utils/safeJsonStringify.ts b/packages/core/src/utils/safeJsonStringify.ts
new file mode 100644
index 00000000..f439bcea
--- /dev/null
+++ b/packages/core/src/utils/safeJsonStringify.ts
@@ -0,0 +1,32 @@
+/**
+ * @license
+ * Copyright 2025 Google LLC
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+/**
+ * Safely stringifies an object to JSON, handling circular references by replacing them with [Circular].
+ *
+ * @param obj - The object to stringify
+ * @param space - Optional space parameter for formatting (defaults to no formatting)
+ * @returns JSON string with circular references replaced by [Circular]
+ */
+export function safeJsonStringify(
+ obj: unknown,
+ space?: string | number,
+): string {
+ const seen = new WeakSet();
+ return JSON.stringify(
+ obj,
+ (key, value) => {
+ if (typeof value === 'object' && value !== null) {
+ if (seen.has(value)) {
+ return '[Circular]';
+ }
+ seen.add(value);
+ }
+ return value;
+ },
+ space,
+ );
+}