@handsforbots/semantic-event-observability 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/LICENSE.md +9 -0
  2. package/README.md +141 -2
  3. package/adapters/genericEventBus.js +20 -0
  4. package/adapters/instrumentChannel.js +22 -0
  5. package/core/CorrelationContext.js +49 -0
  6. package/core/EventBuffer.js +37 -0
  7. package/core/MetricsRegistry.js +200 -0
  8. package/core/PhaseTracker.js +143 -0
  9. package/core/Policy.js +87 -0
  10. package/core/SessionTracker.js +23 -0
  11. package/core/TraceContextBridge.js +74 -0
  12. package/core/TraceMapper.js +167 -0
  13. package/core/TurnMetricsCollector.js +19 -0
  14. package/core/TurnModel.js +87 -0
  15. package/core/baggage.d.ts +12 -0
  16. package/core/baggage.js +68 -0
  17. package/core/bucketEventName.js +11 -0
  18. package/core/createObservability.js +611 -0
  19. package/core/definePhaseModel.js +14 -0
  20. package/core/eventInstrumentation.js +21 -0
  21. package/core/isErrorEvent.js +9 -0
  22. package/core/telemetryAttributes.js +44 -0
  23. package/core/turnSpanNaming.js +73 -0
  24. package/docs/architecture.md +106 -0
  25. package/docs/custom-exporter.md +135 -0
  26. package/docs/exporters.md +180 -0
  27. package/docs/getting-started.md +192 -0
  28. package/docs/grafana-validation.md +71 -0
  29. package/docs/handsforbots-adapter.md +64 -0
  30. package/docs/handsforbots-roadmap.md +193 -0
  31. package/docs/metrics-roadmap.md +145 -0
  32. package/docs/publishing.md +55 -0
  33. package/docs/renaming.md +65 -0
  34. package/docs/roadmap.md +467 -0
  35. package/docs/tail-sampling.md +99 -0
  36. package/exporters/console.js +29 -0
  37. package/exporters/devPanel.js +204 -0
  38. package/exporters/faro.js +71 -0
  39. package/exporters/index.js +58 -0
  40. package/exporters/langfuse.js +161 -0
  41. package/exporters/langsmith.js +168 -0
  42. package/exporters/llmExporterState.js +84 -0
  43. package/exporters/memory.js +18 -0
  44. package/exporters/otel.js +236 -0
  45. package/exporters/otelTraceBackend.js +51 -0
  46. package/exporters/webVitals.js +73 -0
  47. package/grafana/semantic-event-observability.json +250 -0
  48. package/grafana/semantic-event-observability.lgtm.json +399 -0
  49. package/index.d.ts +312 -0
  50. package/index.js +31 -0
  51. package/package.json +80 -3
  52. package/packageIdentity.js +41 -0
  53. package/utils/id.js +10 -0
  54. package/utils/probeOptional.js +42 -0
  55. package/utils/safeJson.js +74 -0
package/index.d.ts ADDED
@@ -0,0 +1,312 @@
1
+ export type PackageIdentity = {
2
+ slug: string
3
+ displayName: string
4
+ packageName: string
5
+ version: string
6
+ globalKey: string
7
+ debugStorageKey: string
8
+ /** localStorage key for the dev panel chrome (`minimized` or absent). */
9
+ panelStorageKey: string
10
+ sessionStorageKey: string
11
+ otelServiceName: string
12
+ grafanaDashboardUid: string
13
+ }
14
+
15
+ export type TurnModelConfig = {
16
+ startEvents?: string[]
17
+ endEvents?: string[]
18
+ start?: string[]
19
+ end?: string[]
20
+ }
21
+
22
+ export type PhaseDefinition = {
23
+ id: string
24
+ startEvent: string
25
+ endEvent: string
26
+ }
27
+
28
+ export type PhaseModel = PhaseDefinition[]
29
+
30
+ export type SemanticEvent = {
31
+ id?: string
32
+ type: string
33
+ name: string
34
+ timestamp?: string
35
+ environment?: string
36
+ sessionId?: string
37
+ turnId?: string | null
38
+ traceId?: string | null
39
+ phase?: string
40
+ source?: string
41
+ durationMs?: number
42
+ payload?: unknown
43
+ payloadSummary?: unknown
44
+ state?: Record<string, unknown>
45
+ turnMetadata?: Record<string, unknown>
46
+ /** Set by `setAttributes()`: on every event and span. */
47
+ attributes?: Readonly<Record<string, AttributeValue>>
48
+ }
49
+
50
+ export type AttributeValue = string | number | boolean
51
+
52
+ export type MetricRecord = {
53
+ name: string
54
+ type: 'histogram' | 'counter' | 'gauge'
55
+ value: number
56
+ labels?: Record<string, string | number | boolean>
57
+ timestamp?: string
58
+ /** Recorded with `recordCounter()`: labels are exported as given. */
59
+ custom?: boolean
60
+ }
61
+
62
+ export type ExporterContext = {
63
+ identity: PackageIdentity
64
+ buffer: unknown
65
+ phases: PhaseModel
66
+ metricsRegistry: MetricsRegistry
67
+ isError: (event: SemanticEvent) => boolean
68
+ traceContextBridge?: TraceContextBridge
69
+ getTimeline: (limit?: number) => SemanticEvent[]
70
+ getMetrics: (limit?: number) => MetricRecord[]
71
+ getPolicyStats: () => PolicyStats
72
+ }
73
+
74
+ export type Exporter = {
75
+ id: string
76
+ available?: boolean
77
+ description?: string
78
+ init?: (context: ExporterContext) => void | Promise<void>
79
+ onEvent?: (event: SemanticEvent) => void
80
+ onMetric?: (metric: MetricRecord) => void
81
+ onPhaseEnd?: (event: SemanticEvent) => void
82
+ destroy?: () => void
83
+ }
84
+
85
+ export type ExporterStatus = {
86
+ id: string
87
+ available: boolean
88
+ description?: string
89
+ error?: string
90
+ }
91
+
92
+ export type PolicyStats = {
93
+ emitted: number
94
+ dropped: number
95
+ dropsByReason: Record<string, number>
96
+ }
97
+
98
+ export type TraceContextBridge = {
99
+ setHeaderInjector: (fn: (() => Record<string, string>) | null) => void
100
+ getTraceHeaders: () => Record<string, string>
101
+ withTraceContext: (input: string | Request, init?: RequestInit) => RequestInit | Request
102
+ withFetch: (input: string | Request, init?: RequestInit) => Promise<Response>
103
+ }
104
+
105
+ export type MetricsRegistry = {
106
+ SEVO_METRICS: typeof SEVO_METRICS
107
+ subscribe: (listener: (metric: MetricRecord) => void) => () => void
108
+ recordTurnDuration: (durationMs: number, labels?: Record<string, string>) => MetricRecord | void
109
+ recordPhaseDuration: (phase: string, durationMs: number, labels?: Record<string, string>) => MetricRecord | void
110
+ recordPhaseWait: (phase: string, waitMs: number, labels?: Record<string, string>) => MetricRecord | void
111
+ recordTurnStatus: (status: string, labels?: Record<string, string>) => MetricRecord | void
112
+ recordEventDropped: (reason: string) => MetricRecord | void
113
+ recordStateGauge: (key: string, value: number, labels?: Record<string, string>) => MetricRecord | void
114
+ recordEventEmitted: (eventType: string, labels?: Record<string, string>) => MetricRecord | void
115
+ recordExporterError: (exporterId: string) => MetricRecord | void
116
+ recordActiveTurns: (count: number) => MetricRecord | void
117
+ recordSessionTurnsRollup: (
118
+ counts: { completed?: number; abandoned?: number },
119
+ labels?: Record<string, string>,
120
+ ) => MetricRecord[] | void
121
+ recordWebVital: (name: string, value: number, labels?: Record<string, string>) => MetricRecord | void
122
+ recordBusEvent: (eventName: string, labels?: Record<string, string>) => MetricRecord | void
123
+ recordCustomMetric: (metricName: string, labels?: Record<string, string>) => MetricRecord | void
124
+ recordListenerDuration: (durationMs: number, labels?: Record<string, string>) => MetricRecord | void
125
+ }
126
+
127
+ export const SEVO_METRICS: {
128
+ readonly TURN_DURATION: 'sevo_turn_duration_ms'
129
+ readonly PHASE_DURATION: 'sevo_phase_duration_ms'
130
+ readonly PHASE_WAIT: 'sevo_phase_wait_ms'
131
+ readonly TURNS_TOTAL: 'sevo_turns_total'
132
+ readonly EVENTS_DROPPED: 'sevo_events_dropped_total'
133
+ readonly STATE_GAUGE: 'sevo_state_gauge'
134
+ readonly EVENTS_EMITTED: 'sevo_events_emitted_total'
135
+ readonly EXPORTER_ERRORS: 'sevo_exporter_errors_total'
136
+ readonly ACTIVE_TURNS: 'sevo_active_turns'
137
+ readonly SESSION_TURNS_TOTAL: 'sevo_session_turns_total'
138
+ readonly WEB_VITAL: 'sevo_web_vital'
139
+ readonly BUS_EVENTS_TOTAL: 'sevo_bus_events_total'
140
+ readonly CUSTOM_METRICS_TOTAL: 'sevo_custom_metrics_total'
141
+ readonly LISTENER_DURATION: 'sevo_listener_duration_ms'
142
+ }
143
+
144
+ /** @deprecated Use SEVO_METRICS */
145
+ export const SEO_METRICS: typeof SEVO_METRICS
146
+
147
+ export type TurnRootSpanConfig =
148
+ | 'semantic'
149
+ | 'invoke_agent'
150
+ | boolean
151
+ | {
152
+ mode?: 'semantic' | 'invoke_agent'
153
+ agentName?: string | ((event: SemanticEvent) => string | undefined)
154
+ providerName?: string
155
+ kind?: 'internal' | 'client' | 'server' | number
156
+ }
157
+
158
+ export type CreateObservabilityOptions = {
159
+ enabled?: boolean
160
+ environment?: string
161
+ sampleRate?: number
162
+ maxEventsPerMinute?: number
163
+ maxPayloadBytes?: number
164
+ denylist?: string[]
165
+ sessionId?: string
166
+ turn?: TurnModelConfig
167
+ turnStartEvents?: string[]
168
+ turnEndEvents?: string[]
169
+ phases?: PhaseModel | PhaseDefinition[]
170
+ isError?: (event: SemanticEvent) => boolean
171
+ eventFilter?: (eventName: string) => boolean
172
+ eventAllowlist?: string[]
173
+ exporters?: string[]
174
+ customExporters?: Exporter[]
175
+ exporterConfig?: Record<string, unknown>
176
+ turnRootSpan?: TurnRootSpanConfig
177
+ sessionEndEvents?: string[]
178
+ customMetricAllowlist?: string[]
179
+ bufferSize?: number
180
+ identity?: Partial<PackageIdentity>
181
+ }
182
+
183
+ export type Observability = {
184
+ identity: PackageIdentity
185
+ policy: unknown
186
+ correlation: unknown
187
+ buffer: unknown
188
+ metricsRegistry: MetricsRegistry
189
+ phases: PhaseModel
190
+ isError: (event: SemanticEvent) => boolean
191
+ eventInstrumentation: { shouldRecord: (eventName: string) => boolean }
192
+ traceContext: TraceContextBridge
193
+ phaseTracker: unknown
194
+ exporters: Exporter[]
195
+ stateProvider?: () => Record<string, unknown>
196
+ init: () => Promise<ExporterStatus[]>
197
+ instrument: (bus: EventBus, options?: InstrumentOptions) => EventBus
198
+ record: (name: string, payload?: unknown, meta?: { type?: string }) => void
199
+ recordMetric: (name: string, value: number, labels?: Record<string, string>) => void
200
+ /** Adds to a counter that is never sampled nor rate-limited; labels are exported as given. */
201
+ recordCounter: (name: string, value?: number, labels?: Record<string, AttributeValue>) => void
202
+ /** Replaces the attributes put on every event and span and sent as W3C `baggage` by getTraceHeaders(). */
203
+ setAttributes: (attributes: Readonly<Record<string, AttributeValue>>) => void
204
+ getAttributes: () => Readonly<Record<string, AttributeValue>>
205
+ attributes: Readonly<Record<string, AttributeValue>>
206
+ startPhase: (phaseId: string, labels?: Record<string, string>) => boolean
207
+ endPhase: (phaseId: string, labels?: Record<string, string>) => boolean
208
+ getTraceHeaders: () => Record<string, string>
209
+ withTraceContext: TraceContextBridge['withTraceContext']
210
+ withFetch: TraceContextBridge['withFetch']
211
+ registerExporter: (exporter: Exporter) => Promise<ExporterStatus>
212
+ endSession: (reason?: string) => { completed: number; abandoned: number }
213
+ getTimeline: (limit?: number) => SemanticEvent[]
214
+ getMetrics: (limit?: number) => MetricRecord[]
215
+ getPolicyStats: () => PolicyStats
216
+ getExporterStatus: () => ExporterStatus[]
217
+ destroy: () => void
218
+ }
219
+
220
+ export type EventBus = {
221
+ on: (name: string | string[], callback: (...args: unknown[]) => void) => void
222
+ trigger: (name: string, args?: unknown) => unknown
223
+ }
224
+
225
+ export type InstrumentOptions = {
226
+ stateProvider?: () => Record<string, unknown>
227
+ wrapListeners?: boolean
228
+ }
229
+
230
+ export const PACKAGE_SLUG: 'semantic-event-observability'
231
+ export const PACKAGE_DISPLAY_NAME: 'Semantic Event Observability'
232
+ export const PACKAGE_SCOPE: '@handsforbots'
233
+ export const PACKAGE_NAME: '@handsforbots/semantic-event-observability'
234
+ export const PACKAGE_VERSION: string
235
+
236
+ export function getPackageIdentity(overrides?: Partial<PackageIdentity>): PackageIdentity
237
+ export function createObservability(options?: CreateObservabilityOptions): Observability
238
+ export function defineTurnModel(model?: TurnModelConfig): TurnModelConfig
239
+ export function definePhaseModel(phases?: PhaseDefinition[]): PhaseModel
240
+ export function isErrorEvent(event: SemanticEvent): boolean
241
+ export function createMetricsRegistry(options?: { environment?: string }): MetricsRegistry
242
+ export function createPhaseTracker(options?: Record<string, unknown>): unknown
243
+ export function createTurnMetricsCollector(options?: Record<string, unknown>): unknown
244
+ export function createTraceMapper(options?: Record<string, unknown>): unknown
245
+ export function createTraceContextBridge(options?: {
246
+ getContext?: () => { traceId?: string | null }
247
+ /** Attributes added to the `baggage` header. */
248
+ getBaggage?: () => Readonly<Record<string, AttributeValue>> | null | undefined
249
+ }): TraceContextBridge
250
+ export const BAGGAGE_MAX_MEMBERS: 64
251
+ export const BAGGAGE_MAX_BYTES: 8192
252
+ /** Encodes attributes as a W3C baggage header value. */
253
+ export function encodeBaggage(attributes?: Readonly<Record<string, AttributeValue | null | undefined>>): string
254
+ /** Parses a W3C baggage header (string, Headers or headers object) into decoded strings. */
255
+ export function parseBaggage(
256
+ source: string | { get(name: string): string | null } | Record<string, string | string[] | undefined> | null | undefined,
257
+ ): Record<string, string>
258
+ /** Adds attributes to a baggage header value; the attributes win on the same key. */
259
+ export function mergeBaggage(existing: string | null | undefined, attributes?: Readonly<Record<string, AttributeValue>>): string
260
+ export function buildTurnRootSpan(
261
+ event: SemanticEvent,
262
+ config?: TurnRootSpanConfig,
263
+ ): { name: string; attributes: Record<string, unknown>; kind?: string | number }
264
+ export function normalizeTurnRootSpanConfig(config?: TurnRootSpanConfig): {
265
+ mode: 'semantic' | 'invoke_agent'
266
+ agentName?: string | ((event: SemanticEvent) => string | undefined)
267
+ providerName?: string
268
+ kind?: string | number
269
+ }
270
+ export function bucketEventName(name: string): string
271
+ export function createEventInstrumentation(options?: {
272
+ eventFilter?: (eventName: string) => boolean
273
+ eventAllowlist?: string[]
274
+ }): { shouldRecord: (eventName: string) => boolean }
275
+ export function createSessionTracker(): {
276
+ recordTurn: (status: string) => void
277
+ getCounts: () => { completed: number; abandoned: number }
278
+ reset: () => void
279
+ }
280
+ export function instrumentEventBus(
281
+ observability: Observability,
282
+ bus: EventBus,
283
+ options?: InstrumentOptions,
284
+ ): EventBus
285
+ export function createInstrumentedBus(
286
+ bus: EventBus,
287
+ options: {
288
+ createObservability: typeof createObservability
289
+ observability?: CreateObservabilityOptions
290
+ instrument?: InstrumentOptions
291
+ },
292
+ ): { observability: Observability; bus: EventBus }
293
+ export function instrumentChannel(
294
+ observability: Observability,
295
+ channel: { postMessage: (data: unknown, transfer?: unknown[]) => void },
296
+ options?: { eventName?: string; type?: string },
297
+ ): typeof channel
298
+ export const BUILTIN_EXPORTERS: Record<string, (config?: Record<string, unknown>) => Exporter>
299
+ export function createExporters(
300
+ requested?: string[],
301
+ config?: Record<string, Record<string, unknown>>,
302
+ ): Promise<Exporter[]>
303
+ export function initExporters(
304
+ exporters: Exporter[],
305
+ context: ExporterContext,
306
+ ): Promise<ExporterStatus[]>
307
+
308
+ export { default as CorrelationContext } from './core/CorrelationContext.js'
309
+ export { default as Policy } from './core/Policy.js'
310
+ export { default as EventBuffer } from './core/EventBuffer.js'
311
+ export { default as TurnModel } from './core/TurnModel.js'
312
+ export { sevoAttributes, sevoMetricLabelAttributes } from './core/telemetryAttributes.js'
package/index.js ADDED
@@ -0,0 +1,31 @@
1
+ export {
2
+ PACKAGE_SLUG,
3
+ PACKAGE_DISPLAY_NAME,
4
+ PACKAGE_NAME,
5
+ PACKAGE_SCOPE,
6
+ PACKAGE_VERSION,
7
+ getPackageIdentity,
8
+ } from './packageIdentity.js'
9
+
10
+ export { createObservability } from './core/createObservability.js'
11
+ export { default as CorrelationContext } from './core/CorrelationContext.js'
12
+ export { default as Policy } from './core/Policy.js'
13
+ export { default as EventBuffer } from './core/EventBuffer.js'
14
+ export { createMetricsRegistry, SEVO_METRICS, SEO_METRICS } from './core/MetricsRegistry.js'
15
+ export { createPhaseTracker } from './core/PhaseTracker.js'
16
+ export { createTurnMetricsCollector } from './core/TurnMetricsCollector.js'
17
+ export { createTraceMapper } from './core/TraceMapper.js'
18
+ export { definePhaseModel } from './core/definePhaseModel.js'
19
+ export { defineTurnModel, default as TurnModel } from './core/TurnModel.js'
20
+ export { createTraceContextBridge } from './core/TraceContextBridge.js'
21
+ export { encodeBaggage, parseBaggage, mergeBaggage, BAGGAGE_MAX_MEMBERS, BAGGAGE_MAX_BYTES } from './core/baggage.js'
22
+ export { createEventInstrumentation } from './core/eventInstrumentation.js'
23
+ export { createSessionTracker } from './core/SessionTracker.js'
24
+ export { buildTurnRootSpan, normalizeTurnRootSpanConfig } from './core/turnSpanNaming.js'
25
+ export { bucketEventName } from './core/bucketEventName.js'
26
+ export { isErrorEvent } from './core/isErrorEvent.js'
27
+
28
+ export { instrumentEventBus, createInstrumentedBus } from './adapters/genericEventBus.js'
29
+ export { instrumentChannel } from './adapters/instrumentChannel.js'
30
+
31
+ export { BUILTIN_EXPORTERS, createExporters, initExporters } from './exporters/index.js'
package/package.json CHANGED
@@ -1,6 +1,83 @@
1
1
  {
2
2
  "name": "@handsforbots/semantic-event-observability",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Semantic observability for async event systems — logs, metrics, and tracing with optional Grafana, Langfuse, and LangSmith exporters.",
5
+ "type": "module",
6
+ "main": "./index.js",
7
+ "types": "./index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./index.d.ts",
11
+ "import": "./index.js"
12
+ },
13
+ "./packageIdentity": "./packageIdentity.js",
14
+ "./adapters/genericEventBus": "./adapters/genericEventBus.js",
15
+ "./baggage": {
16
+ "types": "./core/baggage.d.ts",
17
+ "import": "./core/baggage.js"
18
+ }
19
+ },
20
+ "files": [
21
+ "index.js",
22
+ "index.d.ts",
23
+ "packageIdentity.js",
24
+ "core/",
25
+ "adapters/",
26
+ "exporters/",
27
+ "utils/",
28
+ "grafana/",
29
+ "docs/",
30
+ "README.md"
31
+ ],
32
+ "keywords": [
33
+ "observability",
34
+ "events",
35
+ "async",
36
+ "opentelemetry",
37
+ "grafana",
38
+ "faro",
39
+ "langfuse",
40
+ "langsmith",
41
+ "event-bus"
42
+ ],
43
+ "license": "MIT",
44
+ "homepage": "https://github.com/handsforbots/handsforbots/tree/main/packages/semantic-event-observability#readme",
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "git+https://github.com/handsforbots/handsforbots.git",
48
+ "directory": "packages/semantic-event-observability"
49
+ },
50
+ "bugs": {
51
+ "url": "https://github.com/handsforbots/handsforbots/issues"
52
+ },
53
+ "peerDependencies": {
54
+ "@grafana/faro-web-sdk": ">=1.0.0",
55
+ "@langfuse/tracing": ">=4.0.0",
56
+ "@opentelemetry/api": ">=1.0.0",
57
+ "langsmith": ">=0.3.0",
58
+ "web-vitals": ">=4.0.0"
59
+ },
60
+ "peerDependenciesMeta": {
61
+ "@grafana/faro-web-sdk": {
62
+ "optional": true
63
+ },
64
+ "@langfuse/tracing": {
65
+ "optional": true
66
+ },
67
+ "@opentelemetry/api": {
68
+ "optional": true
69
+ },
70
+ "langsmith": {
71
+ "optional": true
72
+ },
73
+ "web-vitals": {
74
+ "optional": true
75
+ }
76
+ },
77
+ "publishConfig": {
78
+ "access": "public"
79
+ },
80
+ "scripts": {
81
+ "test": "node --test test/*.test.js"
82
+ }
6
83
  }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Single source of truth for package naming.
3
+ * When the public npm name is chosen, change PACKAGE_SLUG here only.
4
+ * All storage keys, globals, and telemetry service names are derived from it.
5
+ */
6
+
7
+ /** npm package slug (kebab-case). Change this when the final name is decided. */
8
+ export const PACKAGE_SLUG = 'semantic-event-observability'
9
+
10
+ /** Human-readable product name shown in UI and docs. */
11
+ export const PACKAGE_DISPLAY_NAME = 'Semantic Event Observability'
12
+
13
+ /** npm scope placeholder for future publish (optional). */
14
+ export const PACKAGE_SCOPE = '@handsforbots'
15
+
16
+ export const PACKAGE_NAME = `${PACKAGE_SCOPE}/${PACKAGE_SLUG}`
17
+
18
+ /** Semantic version — keep in sync with package.json when publishing. */
19
+ export const PACKAGE_VERSION = '0.1.0'
20
+
21
+ /**
22
+ * Derive stable identifiers from PACKAGE_SLUG.
23
+ * Do not hardcode these strings elsewhere in the codebase.
24
+ */
25
+ export function getPackageIdentity(overrides = {}) {
26
+ const slug = overrides.slug || PACKAGE_SLUG
27
+ const displayName = overrides.displayName || PACKAGE_DISPLAY_NAME
28
+
29
+ return {
30
+ slug,
31
+ displayName,
32
+ packageName: overrides.packageName || `${PACKAGE_SCOPE}/${slug}`,
33
+ version: overrides.version || PACKAGE_VERSION,
34
+ globalKey: `__${slug.replace(/-/g, '_').toUpperCase()}__`,
35
+ debugStorageKey: `${slug}:debug`,
36
+ panelStorageKey: `${slug}:panel`,
37
+ sessionStorageKey: `${slug}:session`,
38
+ otelServiceName: slug,
39
+ grafanaDashboardUid: slug,
40
+ }
41
+ }
package/utils/id.js ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Create a random id suitable for turn/trace correlation.
3
+ */
4
+ export function createId(prefix = 'id') {
5
+ if (typeof crypto !== 'undefined' && crypto.randomUUID) {
6
+ return `${prefix}_${crypto.randomUUID()}`
7
+ }
8
+
9
+ return `${prefix}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`
10
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Probe optional npm packages or globals without throwing.
3
+ * Works in browser ESM environments where packages may not be installed.
4
+ */
5
+
6
+ export async function probeOptionalModule(specifier, globalName = null) {
7
+ if (globalName && typeof globalThis !== 'undefined' && globalThis[globalName]) {
8
+ return { source: 'global', module: globalThis[globalName] }
9
+ }
10
+
11
+ try {
12
+ const module = await import(/* @vite-ignore */ specifier)
13
+ return { source: 'module', module }
14
+ } catch {
15
+ return null
16
+ }
17
+ }
18
+
19
+ export function probeOptionalGlobal(globalName) {
20
+ if (typeof globalThis === 'undefined') return null
21
+ return globalThis[globalName] || null
22
+ }
23
+
24
+ /**
25
+ * Resolve an exporter dependency from config injection first, then global, then dynamic import.
26
+ */
27
+ export async function resolveOptionalDependency(configValue, options = {}) {
28
+ if (configValue) {
29
+ return { source: 'config', module: configValue }
30
+ }
31
+
32
+ const globalValue = probeOptionalGlobal(options.globalName)
33
+ if (globalValue) {
34
+ return { source: 'global', module: globalValue }
35
+ }
36
+
37
+ if (options.moduleSpecifier) {
38
+ return probeOptionalModule(options.moduleSpecifier, options.globalName)
39
+ }
40
+
41
+ return null
42
+ }
@@ -0,0 +1,74 @@
1
+ const DEFAULT_DENYLIST = [
2
+ 'password',
3
+ 'token',
4
+ 'apiKey',
5
+ 'api_key',
6
+ 'authorization',
7
+ 'secret',
8
+ 'cryptoKey',
9
+ 'history',
10
+ 'payload',
11
+ ]
12
+
13
+ /**
14
+ * Safely stringify values for logs and exporters.
15
+ */
16
+ export function safeJson(value, maxBytes = 2048) {
17
+ try {
18
+ const text = JSON.stringify(value, replacer)
19
+ if (text.length <= maxBytes) return text
20
+ return `${text.slice(0, maxBytes)}…[+${text.length - maxBytes} bytes]`
21
+ } catch {
22
+ return '[unserializable]'
23
+ }
24
+ }
25
+
26
+ function replacer(key, value) {
27
+ if (typeof value === 'function') return '[Function]'
28
+ if (value instanceof Error) return { name: value.name, message: value.message }
29
+ return value
30
+ }
31
+
32
+ /**
33
+ * Build a redacted summary object safe for telemetry.
34
+ */
35
+ export function summarizePayload(value, options = {}) {
36
+ const denylist = options.denylist || DEFAULT_DENYLIST
37
+ const maxBytes = options.maxPayloadBytes || 2048
38
+ const maxDepth = options.maxDepth ?? 3
39
+
40
+ const summary = summarizeValue(value, denylist, maxDepth, 0)
41
+ return {
42
+ preview: safeJson(summary, maxBytes),
43
+ kind: Array.isArray(value) ? 'array' : value === null ? 'null' : typeof value,
44
+ size: Array.isArray(value) ? value.length : undefined,
45
+ }
46
+ }
47
+
48
+ function summarizeValue(value, denylist, maxDepth, depth) {
49
+ if (value == null) return value
50
+ if (depth >= maxDepth) return `[${typeof value}]`
51
+
52
+ if (Array.isArray(value)) {
53
+ return value.slice(0, 5).map((item) => summarizeValue(item, denylist, maxDepth, depth + 1))
54
+ }
55
+
56
+ if (typeof value !== 'object') {
57
+ if (typeof value === 'string' && value.length > 200) {
58
+ return `${value.slice(0, 200)}…`
59
+ }
60
+ return value
61
+ }
62
+
63
+ const output = {}
64
+ for (const [key, nested] of Object.entries(value)) {
65
+ if (denylist.some((field) => key.toLowerCase().includes(field.toLowerCase()))) {
66
+ output[key] = '[redacted]'
67
+ continue
68
+ }
69
+ output[key] = summarizeValue(nested, denylist, maxDepth, depth + 1)
70
+ }
71
+ return output
72
+ }
73
+
74
+ export { DEFAULT_DENYLIST }