UNPKG

autotel

Version:
1 lines 2.52 kB
{"version":3,"file":"correlated-events-kSwLo3mi.cjs","names":[],"sources":["../src/correlated-events.ts"],"sourcesContent":["import type { AttributeValue } from './trace-context';\n\nexport interface CorrelatedEventTarget {\n setAttribute(key: string, value: AttributeValue): unknown;\n setAttributes(attrs: Record<string, AttributeValue>): unknown;\n addEvent?(name: string, attrs?: Record<string, AttributeValue>): unknown;\n}\n\n// OTel attribute keys are dot-namespaced flat strings; we keep `.`/`-`/`_` and\n// drop everything else so user-supplied event names can't break attribute keys.\nfunction sanitizeEventKey(input: string): string {\n return input.replaceAll(/[^a-zA-Z0-9_.-]/g, '_');\n}\n\n// Per-target sequence so the fallback path can encode multiple events with the\n// same name without one overwriting the previous (attributes are\n// last-write-wins; events are not). Today the addEvent path is always taken;\n// this keeps the fallback correct if/when the runtime stops binding addEvent.\nconst sequenceByTarget = new WeakMap<object, number>();\n\nfunction nextSequence(target: object): number {\n const n = (sequenceByTarget.get(target) ?? 0) + 1;\n sequenceByTarget.set(target, n);\n return n;\n}\n\nexport function emitCorrelatedEvent(\n ctx: CorrelatedEventTarget,\n name: string,\n attrs: Record<string, AttributeValue> = {},\n): void {\n const eventName = sanitizeEventKey(name);\n if (typeof ctx.addEvent === 'function') {\n ctx.addEvent.call(ctx, eventName, attrs);\n return;\n }\n const seq = nextSequence(ctx);\n const prefix = `autotel.event.${seq}.${eventName}`;\n const flattened: Record<string, AttributeValue> = {\n [`${prefix}.name`]: eventName,\n [`${prefix}.ts`]: new Date().toISOString(),\n };\n for (const [k, v] of Object.entries(attrs)) {\n flattened[`${prefix}.${sanitizeEventKey(k)}`] = v;\n }\n ctx.setAttributes(flattened);\n}\n"],"mappings":";;AAUA,SAAS,iBAAiB,OAAuB;CAC/C,OAAO,MAAM,WAAW,oBAAoB,GAAG;AACjD;AAMA,MAAM,mCAAmB,IAAI,QAAwB;AAErD,SAAS,aAAa,QAAwB;CAC5C,MAAM,KAAK,iBAAiB,IAAI,MAAM,KAAK,KAAK;CAChD,iBAAiB,IAAI,QAAQ,CAAC;CAC9B,OAAO;AACT;AAEA,SAAgB,oBACd,KACA,MACA,QAAwC,CAAC,GACnC;CACN,MAAM,YAAY,iBAAiB,IAAI;CACvC,IAAI,OAAO,IAAI,aAAa,YAAY;EACtC,IAAI,SAAS,KAAK,KAAK,WAAW,KAAK;EACvC;CACF;CAEA,MAAM,SAAS,iBADH,aAAa,GACS,EAAE,GAAG;CACvC,MAAM,YAA4C;GAC/C,GAAG,OAAO,SAAS;GACnB,GAAG,OAAO,wBAAO,IAAI,KAAK,EAAC,CAAC,YAAY;CAC3C;CACA,KAAK,MAAM,CAAC,GAAG,MAAM,OAAO,QAAQ,KAAK,GACvC,UAAU,GAAG,OAAO,GAAG,iBAAiB,CAAC,OAAO;CAElD,IAAI,cAAc,SAAS;AAC7B"}