Skip to content
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions packages/core/src/v3/utils/flattenAttributes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ import { Attributes } from "@opentelemetry/api";
export const NULL_SENTINEL = "$@null((";
export const CIRCULAR_REFERENCE_SENTINEL = "$@circular((";

function escapeKey(key: string): string {
return key.replace(/\./g, '\\.');
}

export function flattenAttributes(
obj: Record<string, unknown> | Array<unknown> | string | boolean | number | null | undefined,
prefix?: string ,
Expand Down Expand Up @@ -53,7 +57,8 @@ export function flattenAttributes(


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

function unescapeKey(key: string): string {
return key.replace(/\\\./g, '.');
}

export function unflattenAttributes(
obj: Attributes
): Record<string, unknown> | string | number | boolean | null | undefined {
Expand All @@ -109,8 +118,10 @@ export function unflattenAttributes(
const result: Record<string, unknown> = {};

for (const [key, value] of Object.entries(obj)) {
const parts = key.split(".").reduce(
(acc, part) => {
const parts = key
.split(/(?<!\\)\./) // Split by unescaped dots
.map(unescapeKey) // Unescape keys
.reduce((acc, part) => {
if (part.startsWith("[") && part.endsWith("]")) {
// Handle array indices more precisely
const match = part.match(/^\[(\d+)\]$/);
Expand Down