Skip to content

Commit d0529a3

Browse files
Update flattenAttributes.ts
1 parent 5825272 commit d0529a3

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

packages/core/src/v3/utils/flattenAttributes.ts

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@ import { Attributes } from "@opentelemetry/api";
33
export const NULL_SENTINEL = "$@null((";
44
export const CIRCULAR_REFERENCE_SENTINEL = "$@circular((";
55

6+
function escapeKey(key: string): string {
7+
return key.replace(/\./g, '\\.');
8+
}
9+
610
export function flattenAttributes(
711
obj: Record<string, unknown> | Array<unknown> | string | boolean | number | null | undefined,
812
prefix?: string ,
@@ -53,7 +57,8 @@ export function flattenAttributes(
5357

5458

5559
for (const [key, value] of Object.entries(obj)) {
56-
const newPrefix = `${prefix ? `${prefix}.` : ""}${Array.isArray(obj) ? `[${key}]` : key}`;
60+
const escapedKey = escapeKey(key);
61+
const newPrefix = `${prefix ? `${prefix}.` : ""}${Array.isArray(obj) ? `[${escapedKey}]` : escapedKey}`;
5762
if (Array.isArray(value)) {
5863
for (let i = 0; i < value.length; i++) {
5964
if (typeof value[i] === "object" && value[i] !== null) {
@@ -86,6 +91,10 @@ function isRecord(value: unknown): value is Record<string, unknown> {
8691
return value !== null && typeof value === "object" && !Array.isArray(value);
8792
}
8893

94+
function unescapeKey(key: string): string {
95+
return key.replace(/\\\./g, '.');
96+
}
97+
8998
export function unflattenAttributes(
9099
obj: Attributes
91100
): Record<string, unknown> | string | number | boolean | null | undefined {
@@ -109,8 +118,10 @@ export function unflattenAttributes(
109118
const result: Record<string, unknown> = {};
110119

111120
for (const [key, value] of Object.entries(obj)) {
112-
const parts = key.split(".").reduce(
113-
(acc, part) => {
121+
const parts = key
122+
.split(/(?<!\\)\./) // Split by unescaped dots
123+
.map(unescapeKey) // Unescape keys
124+
.reduce((acc, part) => {
114125
if (part.startsWith("[") && part.endsWith("]")) {
115126
// Handle array indices more precisely
116127
const match = part.match(/^\[(\d+)\]$/);

0 commit comments

Comments
 (0)