autotel-devtools 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 (43) hide show
  1. package/README.md +156 -0
  2. package/dist/cli.cjs +889 -0
  3. package/dist/cli.cjs.map +1 -0
  4. package/dist/cli.d.cts +1 -0
  5. package/dist/cli.d.ts +1 -0
  6. package/dist/cli.js +886 -0
  7. package/dist/cli.js.map +1 -0
  8. package/dist/error-aggregator-BkO0l8ak.d.ts +147 -0
  9. package/dist/error-aggregator-CtZmjm-k.d.cts +147 -0
  10. package/dist/exporter-qIQPDw29.d.cts +159 -0
  11. package/dist/exporter-qIQPDw29.d.ts +159 -0
  12. package/dist/index.cjs +1242 -0
  13. package/dist/index.cjs.map +1 -0
  14. package/dist/index.d.cts +29 -0
  15. package/dist/index.d.ts +29 -0
  16. package/dist/index.js +1234 -0
  17. package/dist/index.js.map +1 -0
  18. package/dist/server/exporter.cjs +154 -0
  19. package/dist/server/exporter.cjs.map +1 -0
  20. package/dist/server/exporter.d.cts +4 -0
  21. package/dist/server/exporter.d.ts +4 -0
  22. package/dist/server/exporter.js +152 -0
  23. package/dist/server/exporter.js.map +1 -0
  24. package/dist/server/index.cjs +1237 -0
  25. package/dist/server/index.cjs.map +1 -0
  26. package/dist/server/index.d.cts +38 -0
  27. package/dist/server/index.d.ts +38 -0
  28. package/dist/server/index.js +1222 -0
  29. package/dist/server/index.js.map +1 -0
  30. package/dist/server/log-exporter.cjs +111 -0
  31. package/dist/server/log-exporter.cjs.map +1 -0
  32. package/dist/server/log-exporter.d.cts +50 -0
  33. package/dist/server/log-exporter.d.ts +50 -0
  34. package/dist/server/log-exporter.js +109 -0
  35. package/dist/server/log-exporter.js.map +1 -0
  36. package/dist/server/remote-exporter.cjs +219 -0
  37. package/dist/server/remote-exporter.cjs.map +1 -0
  38. package/dist/server/remote-exporter.d.cts +87 -0
  39. package/dist/server/remote-exporter.d.ts +87 -0
  40. package/dist/server/remote-exporter.js +217 -0
  41. package/dist/server/remote-exporter.js.map +1 -0
  42. package/dist/widget.global.js +2 -0
  43. package/package.json +96 -0
package/dist/index.cjs ADDED
@@ -0,0 +1,1242 @@
1
+ 'use strict';
2
+
3
+ var http = require('http');
4
+ var ws = require('ws');
5
+ var fs = require('fs');
6
+ var path = require('path');
7
+ var url = require('url');
8
+ var core = require('@opentelemetry/core');
9
+
10
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
11
+ // src/index.ts
12
+
13
+ // src/server/error-aggregator.ts
14
+ var ErrorAggregator = class {
15
+ errorGroups = /* @__PURE__ */ new Map();
16
+ options;
17
+ constructor(options = {}) {
18
+ this.options = {
19
+ maxGroups: options.maxGroups ?? 100,
20
+ maxAffectedTraces: options.maxAffectedTraces ?? 10,
21
+ maxAffectedSpans: options.maxAffectedSpans ?? 5,
22
+ stackFramesForFingerprint: options.stackFramesForFingerprint ?? 5
23
+ };
24
+ }
25
+ /**
26
+ * Add an error occurrence to the aggregator
27
+ */
28
+ addError(occurrence) {
29
+ const fingerprint = this.generateFingerprint(occurrence);
30
+ const existing = this.errorGroups.get(fingerprint);
31
+ if (existing) {
32
+ existing.count++;
33
+ existing.lastSeen = occurrence.timestamp;
34
+ if (!existing.affectedTraces.includes(occurrence.traceId)) {
35
+ existing.affectedTraces.push(occurrence.traceId);
36
+ if (existing.affectedTraces.length > this.options.maxAffectedTraces) {
37
+ existing.affectedTraces.shift();
38
+ }
39
+ }
40
+ if (!existing.affectedSpans.includes(occurrence.spanName)) {
41
+ existing.affectedSpans.push(occurrence.spanName);
42
+ if (existing.affectedSpans.length > this.options.maxAffectedSpans) {
43
+ existing.affectedSpans.shift();
44
+ }
45
+ }
46
+ return existing;
47
+ }
48
+ const newGroup = {
49
+ fingerprint,
50
+ type: occurrence.error.type,
51
+ message: occurrence.error.message,
52
+ stackTrace: this.normalizeStackTrace(occurrence.error.stackTrace),
53
+ count: 1,
54
+ firstSeen: occurrence.timestamp,
55
+ lastSeen: occurrence.timestamp,
56
+ affectedTraces: [occurrence.traceId],
57
+ affectedSpans: [occurrence.spanName],
58
+ service: occurrence.service,
59
+ attributes: occurrence.attributes
60
+ };
61
+ if (this.errorGroups.size >= this.options.maxGroups) {
62
+ this.evictOldestGroup();
63
+ }
64
+ this.errorGroups.set(fingerprint, newGroup);
65
+ return newGroup;
66
+ }
67
+ /**
68
+ * Extract errors from a trace and add them to the aggregator
69
+ */
70
+ addErrorsFromTrace(trace) {
71
+ const addedGroups = [];
72
+ for (const span of trace.spans) {
73
+ if (span.status.code === "ERROR") {
74
+ const occurrence = this.extractErrorFromSpan(span, trace);
75
+ if (occurrence) {
76
+ const group = this.addError(occurrence);
77
+ addedGroups.push(group);
78
+ }
79
+ }
80
+ }
81
+ return addedGroups;
82
+ }
83
+ /**
84
+ * Extract error occurrence from a span
85
+ */
86
+ extractErrorFromSpan(span, trace) {
87
+ const exceptionEvent = span.events?.find((e) => e.name === "exception");
88
+ const errorType = span.attributes["exception.type"] || span.attributes["error.type"] || exceptionEvent?.attributes?.["exception.type"] || "Error";
89
+ const errorMessage = span.status.message || span.attributes["exception.message"] || span.attributes["error.message"] || "Unknown error";
90
+ const stackTrace = span.attributes["exception.stacktrace"] || span.attributes["exception.stack"] || this.extractStackFromEvents(span);
91
+ return {
92
+ traceId: trace.traceId,
93
+ spanId: span.spanId,
94
+ spanName: span.name,
95
+ service: trace.service,
96
+ timestamp: span.endTime,
97
+ error: {
98
+ type: errorType,
99
+ message: errorMessage,
100
+ stackTrace
101
+ },
102
+ attributes: this.extractRelevantAttributes(span.attributes)
103
+ };
104
+ }
105
+ /**
106
+ * Extract stack trace from span events (exception events)
107
+ */
108
+ extractStackFromEvents(span) {
109
+ if (!span.events) return void 0;
110
+ const exceptionEvent = span.events.find((e) => e.name === "exception");
111
+ if (exceptionEvent?.attributes) {
112
+ return exceptionEvent.attributes["exception.stacktrace"] || exceptionEvent.attributes["exception.stack"];
113
+ }
114
+ return void 0;
115
+ }
116
+ /**
117
+ * Extract relevant attributes for error context
118
+ */
119
+ extractRelevantAttributes(attributes) {
120
+ const relevant = {};
121
+ const keepKeys = [
122
+ "http.method",
123
+ "http.url",
124
+ "http.route",
125
+ "http.status_code",
126
+ "db.system",
127
+ "db.operation",
128
+ "rpc.method",
129
+ "rpc.service",
130
+ "code.function",
131
+ "code.filepath",
132
+ "user.id",
133
+ "operation.name"
134
+ ];
135
+ for (const key of keepKeys) {
136
+ if (key in attributes) {
137
+ relevant[key] = attributes[key];
138
+ }
139
+ }
140
+ return relevant;
141
+ }
142
+ /**
143
+ * Generate a fingerprint for error grouping
144
+ *
145
+ * Uses error type + first N stack frames (normalized)
146
+ */
147
+ generateFingerprint(occurrence) {
148
+ const parts = [occurrence.error.type];
149
+ if (occurrence.error.stackTrace) {
150
+ const frames = this.extractStackFrames(
151
+ occurrence.error.stackTrace,
152
+ this.options.stackFramesForFingerprint
153
+ );
154
+ parts.push(...frames);
155
+ } else {
156
+ parts.push(this.normalizeMessage(occurrence.error.message));
157
+ }
158
+ return this.simpleHash(parts.join("|"));
159
+ }
160
+ /**
161
+ * Extract and normalize stack frames from a stack trace
162
+ */
163
+ extractStackFrames(stackTrace, count) {
164
+ const lines = stackTrace.split("\n");
165
+ const frames = [];
166
+ for (const line of lines) {
167
+ if (frames.length >= count) break;
168
+ const trimmed = line.trim();
169
+ const nodeMatch = trimmed.match(/^at\s+(.+?)\s+\((.+?):(\d+):\d+\)$/);
170
+ if (nodeMatch) {
171
+ frames.push(`${nodeMatch[1]}@${this.normalizeFilePath(nodeMatch[2])}`);
172
+ continue;
173
+ }
174
+ const anonMatch = trimmed.match(/^at\s+(.+?):(\d+):\d+$/);
175
+ if (anonMatch) {
176
+ frames.push(`anonymous@${this.normalizeFilePath(anonMatch[1])}`);
177
+ continue;
178
+ }
179
+ const browserMatch = trimmed.match(/^(.+?)@(.+?):(\d+):\d+$/);
180
+ if (browserMatch) {
181
+ frames.push(
182
+ `${browserMatch[1]}@${this.normalizeFilePath(browserMatch[2])}`
183
+ );
184
+ continue;
185
+ }
186
+ }
187
+ return frames;
188
+ }
189
+ /**
190
+ * Normalize file path by removing absolute path prefixes and node_modules paths
191
+ */
192
+ normalizeFilePath(filePath) {
193
+ const nodeModulesMatch = filePath.match(
194
+ /node_modules\/(@[^/]+\/[^/]+|[^/]+)/
195
+ );
196
+ if (nodeModulesMatch) {
197
+ return `[npm]/${nodeModulesMatch[1]}`;
198
+ }
199
+ return filePath.replace(/^.*?\/src\//, "src/").replace(/^.*?\/dist\//, "dist/").replace(/^.*?\/lib\//, "lib/").replace(/^file:\/\//, "");
200
+ }
201
+ /**
202
+ * Normalize error message by removing dynamic parts
203
+ */
204
+ normalizeMessage(message) {
205
+ return message.replaceAll(
206
+ /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,
207
+ "[UUID]"
208
+ ).replaceAll(/\b[0-9a-f]{16,}\b/gi, "[ID]").replaceAll(/\b\d+\b/g, "[N]").replaceAll(/"[^"]*"/g, '"[STR]"').replaceAll(/'[^']*'/g, "'[STR]'").slice(0, 200);
209
+ }
210
+ /**
211
+ * Normalize stack trace for display
212
+ */
213
+ normalizeStackTrace(stackTrace) {
214
+ if (!stackTrace) return void 0;
215
+ const lines = stackTrace.split("\n").slice(0, 10);
216
+ return lines.join("\n");
217
+ }
218
+ /**
219
+ * Simple hash function for fingerprinting
220
+ */
221
+ simpleHash(str) {
222
+ let hash = 0;
223
+ for (let i = 0; i < str.length; i++) {
224
+ const char = str.charCodeAt(i);
225
+ hash = (hash << 5) - hash + char;
226
+ hash = hash & hash;
227
+ }
228
+ return Math.abs(hash).toString(16).padStart(8, "0");
229
+ }
230
+ /**
231
+ * Evict the oldest error group
232
+ */
233
+ evictOldestGroup() {
234
+ let oldest = null;
235
+ for (const [fingerprint, group] of this.errorGroups) {
236
+ if (!oldest || group.lastSeen < oldest.lastSeen) {
237
+ oldest = { fingerprint, lastSeen: group.lastSeen };
238
+ }
239
+ }
240
+ if (oldest) {
241
+ this.errorGroups.delete(oldest.fingerprint);
242
+ }
243
+ }
244
+ /**
245
+ * Get all error groups, sorted by most recent
246
+ */
247
+ getErrorGroups() {
248
+ return [...this.errorGroups.values()].sort(
249
+ (a, b) => b.lastSeen - a.lastSeen
250
+ );
251
+ }
252
+ /**
253
+ * Get error groups sorted by count (most frequent first)
254
+ */
255
+ getErrorGroupsByFrequency() {
256
+ return [...this.errorGroups.values()].sort(
257
+ (a, b) => b.count - a.count
258
+ );
259
+ }
260
+ /**
261
+ * Get a specific error group by fingerprint
262
+ */
263
+ getErrorGroup(fingerprint) {
264
+ return this.errorGroups.get(fingerprint);
265
+ }
266
+ /**
267
+ * Get error groups for a specific service
268
+ */
269
+ getErrorGroupsByService(service) {
270
+ return this.getErrorGroups().filter((g) => g.service === service);
271
+ }
272
+ /**
273
+ * Get total error count across all groups
274
+ */
275
+ getTotalErrorCount() {
276
+ let total = 0;
277
+ for (const group of this.errorGroups.values()) {
278
+ total += group.count;
279
+ }
280
+ return total;
281
+ }
282
+ /**
283
+ * Get error statistics
284
+ */
285
+ getStats() {
286
+ const now = Date.now();
287
+ const oneHourAgo = now - 60 * 60 * 1e3;
288
+ let recentErrors = 0;
289
+ const typeCount = /* @__PURE__ */ new Map();
290
+ for (const group of this.errorGroups.values()) {
291
+ if (group.lastSeen > oneHourAgo) {
292
+ recentErrors += group.count;
293
+ }
294
+ typeCount.set(group.type, (typeCount.get(group.type) || 0) + group.count);
295
+ }
296
+ const topErrorTypes = [...typeCount.entries()].map(([type, count]) => ({ type, count })).sort((a, b) => b.count - a.count).slice(0, 5);
297
+ return {
298
+ totalGroups: this.errorGroups.size,
299
+ totalErrors: this.getTotalErrorCount(),
300
+ recentErrors,
301
+ topErrorTypes
302
+ };
303
+ }
304
+ /**
305
+ * Clear all error groups
306
+ */
307
+ clear() {
308
+ this.errorGroups.clear();
309
+ }
310
+ /**
311
+ * Clear old error groups (not seen in given time window)
312
+ */
313
+ clearOlderThan(maxAgeMs) {
314
+ const cutoff = Date.now() - maxAgeMs;
315
+ let cleared = 0;
316
+ for (const [fingerprint, group] of this.errorGroups) {
317
+ if (group.lastSeen < cutoff) {
318
+ this.errorGroups.delete(fingerprint);
319
+ cleared++;
320
+ }
321
+ }
322
+ return cleared;
323
+ }
324
+ };
325
+
326
+ // src/server/telemetry-limits.ts
327
+ var defaultLimit = 100;
328
+ function parseLimit(value) {
329
+ if (!value) return void 0;
330
+ const parsed = Number.parseInt(value, 10);
331
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : void 0;
332
+ }
333
+ function resolveTelemetryLimits(args = {}) {
334
+ const env = args.env ?? process.env;
335
+ const fallback = args.maxHistory ?? defaultLimit;
336
+ return {
337
+ maxTraceCount: args.maxTraceCount ?? parseLimit(env.AUTOTEL_MAX_TRACE_COUNT) ?? fallback,
338
+ maxLogCount: args.maxLogCount ?? parseLimit(env.AUTOTEL_MAX_LOG_COUNT) ?? fallback,
339
+ maxMetricCount: args.maxMetricCount ?? parseLimit(env.AUTOTEL_MAX_METRIC_COUNT) ?? fallback
340
+ };
341
+ }
342
+ function appendWithLimit(items, item, limit) {
343
+ if (limit <= 0) return [];
344
+ const next = [...items, item];
345
+ return next.length > limit ? next.slice(next.length - limit) : next;
346
+ }
347
+ function appendManyWithLimit(items, incoming, limit) {
348
+ if (limit <= 0 || incoming.length === 0) return limit <= 0 ? [] : items;
349
+ const next = [...items, ...incoming];
350
+ return next.length > limit ? next.slice(next.length - limit) : next;
351
+ }
352
+
353
+ // src/server/server.ts
354
+ var DevtoolsServer = class {
355
+ wss;
356
+ clients = /* @__PURE__ */ new Set();
357
+ httpServer;
358
+ traces = [];
359
+ logs = [];
360
+ metrics = [];
361
+ errorAggregator = new ErrorAggregator();
362
+ limits;
363
+ verbose;
364
+ _port;
365
+ constructor(options = {}) {
366
+ this.limits = resolveTelemetryLimits(options);
367
+ this.verbose = options.verbose ?? false;
368
+ this._port = options.port ?? 4318;
369
+ this.httpServer = options.server ?? http.createServer();
370
+ this.wss = new ws.WebSocketServer({ server: this.httpServer, path: options.path ?? "/ws" });
371
+ this.wss.on("connection", (ws) => {
372
+ this.clients.add(ws);
373
+ this.log(`Client connected (${this.clients.size} total)`);
374
+ const data = this.getCurrentData();
375
+ if (data.traces.length > 0 || data.logs.length > 0 || data.errors.length > 0) {
376
+ ws.send(JSON.stringify(data));
377
+ }
378
+ ws.on("close", () => {
379
+ this.clients.delete(ws);
380
+ this.log(`Client disconnected (${this.clients.size} total)`);
381
+ });
382
+ });
383
+ if (!options.server) {
384
+ this.httpServer.listen(this._port, () => {
385
+ const addr = this.httpServer.address();
386
+ if (addr && typeof addr === "object") this._port = addr.port;
387
+ this.log(`WebSocket server listening on port ${this._port}`);
388
+ });
389
+ }
390
+ }
391
+ get port() {
392
+ const addr = this.httpServer.address();
393
+ if (addr && typeof addr === "object") return addr.port;
394
+ return this._port;
395
+ }
396
+ get clientCount() {
397
+ return this.clients.size;
398
+ }
399
+ addTrace(trace) {
400
+ const existing = this.traces.find((t) => t.traceId === trace.traceId);
401
+ if (existing) {
402
+ const existingSpanIds = new Set(existing.spans.map((s) => s.spanId));
403
+ for (const span of trace.spans) {
404
+ if (!existingSpanIds.has(span.spanId)) {
405
+ existing.spans.push(span);
406
+ }
407
+ }
408
+ existing.startTime = Math.min(existing.startTime, trace.startTime);
409
+ existing.endTime = Math.max(existing.endTime, trace.endTime);
410
+ existing.duration = existing.endTime - existing.startTime;
411
+ if (trace.status === "ERROR") existing.status = "ERROR";
412
+ } else {
413
+ this.traces = appendWithLimit(
414
+ this.traces,
415
+ trace,
416
+ this.limits.maxTraceCount
417
+ );
418
+ }
419
+ this.errorAggregator.addErrorsFromTrace(trace);
420
+ this.broadcast({ traces: [trace], metrics: [], logs: [], errors: this.errorAggregator.getErrorGroups() });
421
+ }
422
+ addTraces(traces) {
423
+ for (const trace of traces) this.addTrace(trace);
424
+ }
425
+ addLog(log) {
426
+ this.logs = appendWithLimit(this.logs, log, this.limits.maxLogCount);
427
+ this.broadcast({ traces: [], metrics: [], logs: [log], errors: [] });
428
+ }
429
+ addLogs(logs) {
430
+ this.logs = appendManyWithLimit(this.logs, logs, this.limits.maxLogCount);
431
+ this.broadcast({ traces: [], metrics: [], logs, errors: [] });
432
+ }
433
+ addMetric(metric) {
434
+ this.metrics = appendWithLimit(
435
+ this.metrics,
436
+ metric,
437
+ this.limits.maxMetricCount
438
+ );
439
+ this.broadcast({ traces: [], metrics: [metric], logs: [], errors: [] });
440
+ }
441
+ getCurrentData() {
442
+ return {
443
+ traces: this.traces,
444
+ metrics: this.metrics,
445
+ logs: this.logs,
446
+ errors: this.errorAggregator.getErrorGroups()
447
+ };
448
+ }
449
+ clearData() {
450
+ this.traces = [];
451
+ this.logs = [];
452
+ this.metrics = [];
453
+ this.errorAggregator.clear();
454
+ }
455
+ broadcast(data) {
456
+ const msg = JSON.stringify(data);
457
+ for (const client of this.clients) {
458
+ if (client.readyState === ws.WebSocket.OPEN) {
459
+ client.send(msg);
460
+ }
461
+ }
462
+ }
463
+ log(message) {
464
+ if (this.verbose) console.log(`[autotel-devtools] ${message}`);
465
+ }
466
+ async close() {
467
+ for (const client of this.clients) client.close();
468
+ this.clients.clear();
469
+ this.wss.close();
470
+ await new Promise((resolve2) => this.httpServer.close(() => resolve2()));
471
+ }
472
+ };
473
+
474
+ // src/server/resource-utils.ts
475
+ function getResourceName(resource, fallback = "unknown") {
476
+ if (!resource) return fallback;
477
+ const candidates = [
478
+ resource["service.name"],
479
+ resource["service.namespace"],
480
+ resource["deployment.environment.name"],
481
+ resource["host.name"],
482
+ resource["container.name"],
483
+ resource["process.executable.name"]
484
+ ];
485
+ for (const candidate of candidates) {
486
+ if (typeof candidate === "string" && candidate.trim().length > 0) {
487
+ return candidate;
488
+ }
489
+ }
490
+ return fallback;
491
+ }
492
+
493
+ // src/server/otlp.ts
494
+ function resolveOtlpValue(v) {
495
+ if (!v) return void 0;
496
+ if (v.stringValue !== void 0) return v.stringValue;
497
+ if (v.boolValue !== void 0) return v.boolValue;
498
+ if (v.intValue !== void 0) return typeof v.intValue === "string" ? Number(v.intValue) : v.intValue;
499
+ if (v.doubleValue !== void 0) return v.doubleValue;
500
+ if (v.bytesValue !== void 0) return v.bytesValue;
501
+ if (v.arrayValue?.values) return v.arrayValue.values.map(resolveOtlpValue);
502
+ if (v.kvlistValue?.values) return flattenAttributes(v.kvlistValue.values);
503
+ return void 0;
504
+ }
505
+ function flattenAttributes(attrs) {
506
+ const out = {};
507
+ if (!attrs) return out;
508
+ for (const { key, value } of attrs) {
509
+ out[key] = resolveOtlpValue(value);
510
+ }
511
+ return out;
512
+ }
513
+ function nanoToMs(nano) {
514
+ if (!nano) return 0;
515
+ return Number(BigInt(nano) / 1000000n);
516
+ }
517
+ var SPAN_KIND_MAP = {
518
+ 0: "INTERNAL",
519
+ 1: "INTERNAL",
520
+ 2: "SERVER",
521
+ 3: "CLIENT",
522
+ 4: "PRODUCER",
523
+ 5: "CONSUMER",
524
+ SPAN_KIND_INTERNAL: "INTERNAL",
525
+ SPAN_KIND_SERVER: "SERVER",
526
+ SPAN_KIND_CLIENT: "CLIENT",
527
+ SPAN_KIND_PRODUCER: "PRODUCER",
528
+ SPAN_KIND_CONSUMER: "CONSUMER"
529
+ };
530
+ function normalizeHexId(id) {
531
+ if (!id) return "";
532
+ const isBase64Like = /^[A-Za-z0-9+/=]+$/.test(id) && !/^[0-9a-f]+$/i.test(id);
533
+ const isLikelyBase64Id = isBase64Like && (id.length === 24 || id.length === 28 || id.length === 44 || id.length === 48);
534
+ if (isLikelyBase64Id) {
535
+ try {
536
+ const bytes = Buffer.from(id, "base64");
537
+ return bytes.toString("hex");
538
+ } catch {
539
+ }
540
+ }
541
+ return id;
542
+ }
543
+ function parseOtlpTraces(payload) {
544
+ if (!payload || typeof payload !== "object") return [];
545
+ const { resourceSpans } = payload;
546
+ if (!Array.isArray(resourceSpans) || resourceSpans.length === 0) return [];
547
+ const traceMap = /* @__PURE__ */ new Map();
548
+ for (const rs of resourceSpans) {
549
+ const resourceAttrs = flattenAttributes(rs.resource?.attributes);
550
+ const service = String(resourceAttrs["service.name"] || "unknown");
551
+ const scopeSpans = rs.scopeSpans || [];
552
+ for (const ss of scopeSpans) {
553
+ for (const span of ss.spans || []) {
554
+ const traceId = normalizeHexId(span.traceId);
555
+ if (!traceId) continue;
556
+ const startMs = nanoToMs(span.startTimeUnixNano);
557
+ const endMs = nanoToMs(span.endTimeUnixNano);
558
+ const statusCode = span.status?.code;
559
+ let status = "UNSET";
560
+ if (statusCode === 1 || statusCode === "STATUS_CODE_OK") status = "OK";
561
+ if (statusCode === 2 || statusCode === "STATUS_CODE_ERROR") status = "ERROR";
562
+ const spanData = {
563
+ traceId,
564
+ spanId: normalizeHexId(span.spanId),
565
+ parentSpanId: normalizeHexId(span.parentSpanId) || void 0,
566
+ name: span.name || "unknown",
567
+ kind: SPAN_KIND_MAP[span.kind ?? 0] || "INTERNAL",
568
+ startTime: startMs,
569
+ endTime: endMs,
570
+ duration: endMs - startMs,
571
+ attributes: { ...resourceAttrs, ...flattenAttributes(span.attributes) },
572
+ status: { code: status, message: span.status?.message },
573
+ events: (span.events || []).map((e) => ({
574
+ name: e.name || "",
575
+ timestamp: nanoToMs(e.timeUnixNano),
576
+ attributes: flattenAttributes(e.attributes)
577
+ }))
578
+ };
579
+ const existing = traceMap.get(traceId);
580
+ if (existing) {
581
+ existing.spans.push(spanData);
582
+ } else {
583
+ traceMap.set(traceId, { spans: [spanData], service });
584
+ }
585
+ }
586
+ }
587
+ }
588
+ const traces = [];
589
+ for (const [traceId, { spans, service }] of traceMap) {
590
+ const sorted = spans.sort((a, b) => a.startTime - b.startTime);
591
+ const rootSpan = sorted.find((s) => !s.parentSpanId) || sorted[0];
592
+ const startTime = Math.min(...sorted.map((s) => s.startTime));
593
+ const endTime = Math.max(...sorted.map((s) => s.endTime));
594
+ const hasError = sorted.some((s) => s.status.code === "ERROR");
595
+ traces.push({
596
+ traceId,
597
+ correlationId: traceId.slice(0, 16),
598
+ rootSpan,
599
+ spans: sorted,
600
+ startTime,
601
+ endTime,
602
+ duration: endTime - startTime,
603
+ status: hasError ? "ERROR" : "OK",
604
+ service
605
+ });
606
+ }
607
+ return traces;
608
+ }
609
+ function parseOtlpLogs(payload) {
610
+ if (!payload || typeof payload !== "object") return [];
611
+ const { resourceLogs } = payload;
612
+ if (!Array.isArray(resourceLogs)) return [];
613
+ const logs = [];
614
+ for (const rl of resourceLogs) {
615
+ const resourceAttrs = flattenAttributes(rl.resource?.attributes);
616
+ for (const sl of rl.scopeLogs || []) {
617
+ for (const rec of sl.logRecords || []) {
618
+ const timestamp = nanoToMs(rec.timeUnixNano || rec.observedTimeUnixNano);
619
+ const traceId = normalizeHexId(rec.traceId) || void 0;
620
+ const spanId = normalizeHexId(rec.spanId) || void 0;
621
+ const body = rec.body ? resolveOtlpValue(rec.body) : "";
622
+ logs.push({
623
+ id: `${traceId || "no-trace"}:${spanId || "no-span"}:${timestamp}:${rec.severityNumber || 0}`,
624
+ traceId,
625
+ spanId,
626
+ resourceName: getResourceName(resourceAttrs),
627
+ severityText: rec.severityText,
628
+ severityNumber: rec.severityNumber,
629
+ body: typeof body === "string" ? body : body,
630
+ timestamp,
631
+ attributes: flattenAttributes(rec.attributes),
632
+ resource: resourceAttrs
633
+ });
634
+ }
635
+ }
636
+ }
637
+ return logs;
638
+ }
639
+ function countOtlpMetrics(payload) {
640
+ if (!payload || typeof payload !== "object") return 0;
641
+ const { resourceMetrics } = payload;
642
+ if (!Array.isArray(resourceMetrics)) return 0;
643
+ let count = 0;
644
+ for (const rm of resourceMetrics) {
645
+ for (const sm of rm.scopeMetrics || []) {
646
+ count += (sm.metrics || []).length;
647
+ }
648
+ }
649
+ return count;
650
+ }
651
+ async function readJsonBody(req) {
652
+ return new Promise((resolve2, reject) => {
653
+ const chunks = [];
654
+ req.on("data", (chunk) => chunks.push(chunk));
655
+ req.on("end", () => {
656
+ try {
657
+ resolve2(JSON.parse(Buffer.concat(chunks).toString()));
658
+ } catch {
659
+ reject(new Error("Invalid JSON"));
660
+ }
661
+ });
662
+ req.on("error", reject);
663
+ });
664
+ }
665
+ function sendJson(res, status, data) {
666
+ const body = JSON.stringify(data);
667
+ res.writeHead(status, { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(body) });
668
+ res.end(body);
669
+ }
670
+
671
+ // src/server/http.ts
672
+ function findPackageRoot() {
673
+ let dir = path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))));
674
+ for (let i = 0; i < 5; i++) {
675
+ if (fs.existsSync(path.resolve(dir, "package.json"))) return dir;
676
+ dir = path.dirname(dir);
677
+ }
678
+ return dir;
679
+ }
680
+ var FULLPAGE_HTML = `<!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>autotel-devtools</title><style>*{margin:0;padding:0;box-sizing:border-box}html,body{height:100%;width:100%;overflow:hidden}</style></head><body><script src="/widget.js?mode=fullpage"></script></body></html>`;
681
+ var cachedWidgetJs = null;
682
+ function getWidgetJs() {
683
+ if (!cachedWidgetJs) {
684
+ const pkgRoot = findPackageRoot();
685
+ const candidates = [
686
+ path.resolve(pkgRoot, "dist", "widget.global.js"),
687
+ path.resolve(pkgRoot, "widget.global.js")
688
+ ];
689
+ for (const candidate of candidates) {
690
+ try {
691
+ cachedWidgetJs = fs.readFileSync(candidate, "utf8");
692
+ break;
693
+ } catch {
694
+ }
695
+ }
696
+ if (!cachedWidgetJs) {
697
+ cachedWidgetJs = "// widget bundle not found - run pnpm build first";
698
+ }
699
+ }
700
+ return cachedWidgetJs;
701
+ }
702
+ function attachDevtoolsRoutes(httpServer, devtools) {
703
+ httpServer.on("request", async (req, res) => {
704
+ res.setHeader("Access-Control-Allow-Origin", "*");
705
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
706
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type");
707
+ if (req.method === "OPTIONS") {
708
+ res.writeHead(204);
709
+ res.end();
710
+ return;
711
+ }
712
+ const url = req.url || "/";
713
+ if (req.method === "GET" && url === "/") {
714
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Content-Length": Buffer.byteLength(FULLPAGE_HTML) });
715
+ res.end(FULLPAGE_HTML);
716
+ return;
717
+ }
718
+ if (req.method === "GET" && url.startsWith("/widget.js")) {
719
+ const js = getWidgetJs();
720
+ res.writeHead(200, { "Content-Type": "application/javascript; charset=utf-8", "Content-Length": Buffer.byteLength(js) });
721
+ res.end(js);
722
+ return;
723
+ }
724
+ if (req.method === "GET" && url === "/healthz") {
725
+ sendJson(res, 200, { ok: true, clients: devtools.clientCount });
726
+ return;
727
+ }
728
+ if (req.method === "POST" && url === "/v1/traces") {
729
+ try {
730
+ const payload = await readJsonBody(req);
731
+ const traces = parseOtlpTraces(payload);
732
+ devtools.addTraces(traces);
733
+ sendJson(res, 200, { acceptedTraces: traces.length });
734
+ } catch (e) {
735
+ sendJson(res, 400, { error: "Invalid OTLP JSON", message: e instanceof Error ? e.message : String(e) });
736
+ }
737
+ return;
738
+ }
739
+ if (req.method === "POST" && url === "/v1/logs") {
740
+ try {
741
+ const payload = await readJsonBody(req);
742
+ const logs = parseOtlpLogs(payload);
743
+ devtools.addLogs(logs);
744
+ sendJson(res, 200, { acceptedLogs: logs.length });
745
+ } catch (e) {
746
+ sendJson(res, 400, { error: "Invalid OTLP JSON", message: e instanceof Error ? e.message : String(e) });
747
+ }
748
+ return;
749
+ }
750
+ if (req.method === "POST" && url === "/v1/metrics") {
751
+ try {
752
+ const payload = await readJsonBody(req);
753
+ const count = countOtlpMetrics(payload);
754
+ sendJson(res, 200, { acceptedMetrics: count });
755
+ } catch (e) {
756
+ sendJson(res, 400, { error: "Invalid OTLP JSON", message: e instanceof Error ? e.message : String(e) });
757
+ }
758
+ return;
759
+ }
760
+ sendJson(res, 404, { error: "Not found" });
761
+ });
762
+ }
763
+
764
+ // src/server/exporter.ts
765
+ var DevtoolsSpanExporter = class {
766
+ server;
767
+ serviceName;
768
+ constructor(server, serviceName = "unknown-service") {
769
+ this.server = server;
770
+ this.serviceName = serviceName;
771
+ }
772
+ /**
773
+ * Export spans to the WebSocket server
774
+ */
775
+ async export(spans, resultCallback) {
776
+ resultCallback({ code: 0 });
777
+ Promise.resolve().then(() => {
778
+ try {
779
+ console.log(`[Autotel Exporter] Exporting ${spans.length} span(s)`);
780
+ const traceMap = /* @__PURE__ */ new Map();
781
+ for (const span of spans) {
782
+ const traceId = span.spanContext().traceId;
783
+ if (!traceMap.has(traceId)) {
784
+ traceMap.set(traceId, []);
785
+ }
786
+ traceMap.get(traceId).push(span);
787
+ }
788
+ for (const [traceId, traceSpans] of traceMap) {
789
+ const trace = this.convertToTraceData(traceId, traceSpans);
790
+ console.log(
791
+ `[Autotel Exporter] Adding trace ${traceId.slice(0, 16)} with ${traceSpans.length} spans`
792
+ );
793
+ this.server.addTrace(trace);
794
+ }
795
+ } catch (error) {
796
+ console.error("[Autotel Exporter] Export error:", error);
797
+ }
798
+ });
799
+ }
800
+ /**
801
+ * Shutdown the exporter
802
+ */
803
+ async shutdown() {
804
+ }
805
+ /**
806
+ * Force flush any buffered spans
807
+ */
808
+ async forceFlush() {
809
+ }
810
+ /**
811
+ * Convert OpenTelemetry spans to TraceData
812
+ */
813
+ convertToTraceData(traceId, spans) {
814
+ const spanData = spans.map((span) => this.convertSpan(span));
815
+ const rootSpan = spanData.find((s) => !s.parentSpanId) || spanData[0];
816
+ spanData.sort((a, b) => a.startTime - b.startTime);
817
+ const startTime = Math.min(...spanData.map((s) => s.startTime));
818
+ const endTime = Math.max(...spanData.map((s) => s.endTime));
819
+ const hasError = spanData.some((s) => s.status.code === "ERROR");
820
+ const status = hasError ? "ERROR" : "OK";
821
+ return {
822
+ traceId,
823
+ correlationId: traceId.slice(0, 16),
824
+ // First 16 chars
825
+ rootSpan,
826
+ spans: spanData,
827
+ startTime,
828
+ endTime,
829
+ duration: endTime - startTime,
830
+ status,
831
+ service: this.serviceName
832
+ };
833
+ }
834
+ /**
835
+ * Convert OpenTelemetry span to SpanData
836
+ */
837
+ convertSpan(span) {
838
+ const spanContext = span.spanContext();
839
+ const startTime = span.startTime[0] * 1e3 + span.startTime[1] / 1e6;
840
+ const endTime = span.endTime[0] * 1e3 + span.endTime[1] / 1e6;
841
+ const attributes = {};
842
+ for (const [key, value] of Object.entries(span.attributes)) {
843
+ attributes[key] = value;
844
+ }
845
+ const statusCode = span.status.code;
846
+ let status;
847
+ switch (statusCode) {
848
+ case 0: {
849
+ status = "UNSET";
850
+ break;
851
+ }
852
+ case 1: {
853
+ status = "OK";
854
+ break;
855
+ }
856
+ case 2: {
857
+ status = "ERROR";
858
+ break;
859
+ }
860
+ default: {
861
+ status = "UNSET";
862
+ }
863
+ }
864
+ const events = span.events.map((event) => ({
865
+ name: event.name,
866
+ timestamp: event.time[0] * 1e3 + event.time[1] / 1e6,
867
+ attributes: event.attributes ? Object.fromEntries(Object.entries(event.attributes)) : void 0
868
+ }));
869
+ return {
870
+ traceId: spanContext.traceId,
871
+ spanId: spanContext.spanId,
872
+ parentSpanId: span.parentSpanId,
873
+ name: span.name,
874
+ kind: this.convertSpanKind(span.kind),
875
+ startTime,
876
+ endTime,
877
+ duration: endTime - startTime,
878
+ attributes,
879
+ status: {
880
+ code: status,
881
+ message: span.status.message
882
+ },
883
+ events: events.length > 0 ? events : void 0
884
+ };
885
+ }
886
+ /**
887
+ * Convert OpenTelemetry SpanKind to string
888
+ */
889
+ convertSpanKind(kind) {
890
+ switch (kind) {
891
+ case 0: {
892
+ return "INTERNAL";
893
+ }
894
+ case 1: {
895
+ return "SERVER";
896
+ }
897
+ case 2: {
898
+ return "CLIENT";
899
+ }
900
+ case 3: {
901
+ return "PRODUCER";
902
+ }
903
+ case 4: {
904
+ return "CONSUMER";
905
+ }
906
+ default: {
907
+ return "INTERNAL";
908
+ }
909
+ }
910
+ }
911
+ };
912
+ var defaultTimeout = 5e3;
913
+ function hrTimeToMs(hrTime) {
914
+ return hrTime[0] * 1e3 + hrTime[1] / 1e6;
915
+ }
916
+ function bodyToPayload(body) {
917
+ if (body === void 0) return "";
918
+ if (typeof body === "string") return body;
919
+ if (typeof body === "object" && body !== null) return body;
920
+ return String(body);
921
+ }
922
+ function recordToLogData(record, index) {
923
+ const id = `log-${Date.now()}-${index}-${Math.random().toString(36).slice(2, 9)}`;
924
+ const timestamp = hrTimeToMs(record.hrTime);
925
+ const body = bodyToPayload(record.body);
926
+ const attributes = record.attributes && Object.keys(record.attributes).length > 0 ? record.attributes : void 0;
927
+ const resource = record.resource?.attributes && Object.keys(record.resource.attributes).length > 0 ? record.resource.attributes : void 0;
928
+ const log = {
929
+ id,
930
+ resourceName: getResourceName(resource),
931
+ severityText: record.severityText,
932
+ severityNumber: record.severityNumber,
933
+ body,
934
+ timestamp,
935
+ attributes,
936
+ resource
937
+ };
938
+ if (record.spanContext) {
939
+ log.traceId = record.spanContext.traceId;
940
+ log.spanId = record.spanContext.spanId;
941
+ }
942
+ return log;
943
+ }
944
+ var DevtoolsLogExporter = class {
945
+ endpoint;
946
+ apiKey;
947
+ timeout;
948
+ isShutdown = false;
949
+ constructor(options) {
950
+ this.endpoint = options.endpoint.replace(/\/$/, "");
951
+ this.apiKey = options.apiKey ?? "";
952
+ this.timeout = options.timeout ?? defaultTimeout;
953
+ }
954
+ export(logs, resultCallback) {
955
+ if (this.isShutdown || logs.length === 0) {
956
+ resultCallback({ code: core.ExportResultCode.SUCCESS });
957
+ return;
958
+ }
959
+ const payload = { logs: logs.map((r, i) => recordToLogData(r, i)) };
960
+ const url = `${this.endpoint}/ingest/logs`;
961
+ const headers = {
962
+ "Content-Type": "application/json"
963
+ };
964
+ if (this.apiKey) {
965
+ headers["Authorization"] = `Bearer ${this.apiKey}`;
966
+ }
967
+ const controller = new AbortController();
968
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
969
+ fetch(url, {
970
+ method: "POST",
971
+ headers,
972
+ body: JSON.stringify(payload),
973
+ signal: controller.signal
974
+ }).then((res) => {
975
+ clearTimeout(timeoutId);
976
+ if (!res.ok) {
977
+ throw new Error(`Devtools log ingest failed: ${res.status} ${res.statusText}`);
978
+ }
979
+ resultCallback({ code: core.ExportResultCode.SUCCESS });
980
+ }).catch((err) => {
981
+ clearTimeout(timeoutId);
982
+ resultCallback({
983
+ code: core.ExportResultCode.FAILED,
984
+ error: err instanceof Error ? err : new Error(String(err))
985
+ });
986
+ });
987
+ }
988
+ shutdown() {
989
+ this.isShutdown = true;
990
+ return Promise.resolve();
991
+ }
992
+ };
993
+
994
+ // src/server/remote-exporter.ts
995
+ var DevtoolsRemoteExporter = class {
996
+ options;
997
+ pendingExports = [];
998
+ constructor(options) {
999
+ this.options = {
1000
+ endpoint: options.endpoint.replace(/\/$/, ""),
1001
+ // Remove trailing slash
1002
+ apiKey: options.apiKey ?? "",
1003
+ serviceName: options.serviceName ?? "unknown-service",
1004
+ timeout: options.timeout ?? 5e3,
1005
+ retry: options.retry ?? true,
1006
+ retryCount: options.retryCount ?? 3,
1007
+ retryDelay: options.retryDelay ?? 1e3,
1008
+ verbose: options.verbose ?? false
1009
+ };
1010
+ }
1011
+ /**
1012
+ * Export spans to the remote server
1013
+ */
1014
+ async export(spans, resultCallback) {
1015
+ const exportPromise = this.doExport(spans).then(() => {
1016
+ resultCallback({ code: 0 });
1017
+ }).catch((error) => {
1018
+ this.log(`Export failed: ${error.message}`);
1019
+ resultCallback({ code: 1 });
1020
+ });
1021
+ this.pendingExports.push(exportPromise);
1022
+ exportPromise.finally(() => {
1023
+ const index = this.pendingExports.indexOf(exportPromise);
1024
+ if (index !== -1) {
1025
+ this.pendingExports.splice(index, 1);
1026
+ }
1027
+ });
1028
+ }
1029
+ async doExport(spans) {
1030
+ if (spans.length === 0) return;
1031
+ this.log(`Exporting ${spans.length} span(s) to ${this.options.endpoint}`);
1032
+ const traceMap = /* @__PURE__ */ new Map();
1033
+ for (const span of spans) {
1034
+ const traceId = span.spanContext().traceId;
1035
+ if (!traceMap.has(traceId)) {
1036
+ traceMap.set(traceId, []);
1037
+ }
1038
+ traceMap.get(traceId).push(span);
1039
+ }
1040
+ const traces = [];
1041
+ for (const [traceId, traceSpans] of traceMap) {
1042
+ traces.push(this.convertToTraceData(traceId, traceSpans));
1043
+ }
1044
+ await this.sendWithRetry({ traces });
1045
+ }
1046
+ async sendWithRetry(payload) {
1047
+ let lastError = null;
1048
+ const maxAttempts = this.options.retry ? this.options.retryCount : 1;
1049
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
1050
+ try {
1051
+ await this.send(payload);
1052
+ return;
1053
+ } catch (error) {
1054
+ lastError = error instanceof Error ? error : new Error(String(error));
1055
+ this.log(
1056
+ `Attempt ${attempt}/${maxAttempts} failed: ${lastError.message}`
1057
+ );
1058
+ if (attempt < maxAttempts) {
1059
+ await this.sleep(this.options.retryDelay * attempt);
1060
+ }
1061
+ }
1062
+ }
1063
+ throw lastError || new Error("Export failed");
1064
+ }
1065
+ async send(payload) {
1066
+ const controller = new AbortController();
1067
+ const timeoutId = setTimeout(
1068
+ () => controller.abort(),
1069
+ this.options.timeout
1070
+ );
1071
+ try {
1072
+ const headers = {
1073
+ "Content-Type": "application/json"
1074
+ };
1075
+ if (this.options.apiKey) {
1076
+ headers["Authorization"] = `Bearer ${this.options.apiKey}`;
1077
+ }
1078
+ const response = await fetch(`${this.options.endpoint}/ingest/traces`, {
1079
+ method: "POST",
1080
+ headers,
1081
+ body: JSON.stringify(payload),
1082
+ signal: controller.signal
1083
+ });
1084
+ if (!response.ok) {
1085
+ const text = await response.text();
1086
+ throw new Error(`HTTP ${response.status}: ${text}`);
1087
+ }
1088
+ const result = await response.json();
1089
+ this.log(`Successfully sent ${result.processed} trace(s)`);
1090
+ } finally {
1091
+ clearTimeout(timeoutId);
1092
+ }
1093
+ }
1094
+ /**
1095
+ * Shutdown the exporter, waiting for pending exports
1096
+ */
1097
+ async shutdown() {
1098
+ this.log("Shutting down, waiting for pending exports...");
1099
+ await Promise.allSettled(this.pendingExports);
1100
+ this.log("Shutdown complete");
1101
+ }
1102
+ /**
1103
+ * Force flush pending exports
1104
+ */
1105
+ async forceFlush() {
1106
+ await Promise.allSettled(this.pendingExports);
1107
+ }
1108
+ convertToTraceData(traceId, spans) {
1109
+ const spanData = spans.map((span) => this.convertSpan(span));
1110
+ const rootSpan = spanData.find((s) => !s.parentSpanId) || spanData[0];
1111
+ spanData.sort((a, b) => a.startTime - b.startTime);
1112
+ const startTime = Math.min(...spanData.map((s) => s.startTime));
1113
+ const endTime = Math.max(...spanData.map((s) => s.endTime));
1114
+ const hasError = spanData.some((s) => s.status.code === "ERROR");
1115
+ const status = hasError ? "ERROR" : "OK";
1116
+ return {
1117
+ traceId,
1118
+ correlationId: traceId.slice(0, 16),
1119
+ rootSpan,
1120
+ spans: spanData,
1121
+ startTime,
1122
+ endTime,
1123
+ duration: endTime - startTime,
1124
+ status,
1125
+ service: this.options.serviceName
1126
+ };
1127
+ }
1128
+ convertSpan(span) {
1129
+ const spanContext = span.spanContext();
1130
+ const startTime = span.startTime[0] * 1e3 + span.startTime[1] / 1e6;
1131
+ const endTime = span.endTime[0] * 1e3 + span.endTime[1] / 1e6;
1132
+ const attributes = {};
1133
+ for (const [key, value] of Object.entries(span.attributes)) {
1134
+ attributes[key] = value;
1135
+ }
1136
+ let status;
1137
+ switch (span.status.code) {
1138
+ case 0: {
1139
+ status = "UNSET";
1140
+ break;
1141
+ }
1142
+ case 1: {
1143
+ status = "OK";
1144
+ break;
1145
+ }
1146
+ case 2: {
1147
+ status = "ERROR";
1148
+ break;
1149
+ }
1150
+ default: {
1151
+ status = "UNSET";
1152
+ }
1153
+ }
1154
+ const events = span.events.map((event) => ({
1155
+ name: event.name,
1156
+ timestamp: event.time[0] * 1e3 + event.time[1] / 1e6,
1157
+ attributes: event.attributes ? Object.fromEntries(Object.entries(event.attributes)) : void 0
1158
+ }));
1159
+ return {
1160
+ traceId: spanContext.traceId,
1161
+ spanId: spanContext.spanId,
1162
+ parentSpanId: span.parentSpanId,
1163
+ name: span.name,
1164
+ kind: this.convertSpanKind(span.kind),
1165
+ startTime,
1166
+ endTime,
1167
+ duration: endTime - startTime,
1168
+ attributes,
1169
+ status: {
1170
+ code: status,
1171
+ message: span.status.message
1172
+ },
1173
+ events: events.length > 0 ? events : void 0
1174
+ };
1175
+ }
1176
+ convertSpanKind(kind) {
1177
+ switch (kind) {
1178
+ case 0: {
1179
+ return "INTERNAL";
1180
+ }
1181
+ case 1: {
1182
+ return "SERVER";
1183
+ }
1184
+ case 2: {
1185
+ return "CLIENT";
1186
+ }
1187
+ case 3: {
1188
+ return "PRODUCER";
1189
+ }
1190
+ case 4: {
1191
+ return "CONSUMER";
1192
+ }
1193
+ default: {
1194
+ return "INTERNAL";
1195
+ }
1196
+ }
1197
+ }
1198
+ sleep(ms) {
1199
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
1200
+ }
1201
+ log(message) {
1202
+ if (this.options.verbose) {
1203
+ console.log(`[Devtools Remote Exporter] ${message}`);
1204
+ }
1205
+ }
1206
+ };
1207
+
1208
+ // src/index.ts
1209
+ function createDevtools(options = {}) {
1210
+ const port = options.port ?? 4318;
1211
+ const host = options.host ?? "127.0.0.1";
1212
+ const httpServer = http.createServer();
1213
+ const wsServer = new DevtoolsServer({
1214
+ server: httpServer,
1215
+ verbose: options.verbose,
1216
+ maxHistory: options.maxHistory,
1217
+ maxTraceCount: options.maxTraceCount,
1218
+ maxLogCount: options.maxLogCount,
1219
+ maxMetricCount: options.maxMetricCount
1220
+ });
1221
+ attachDevtoolsRoutes(httpServer, wsServer);
1222
+ httpServer.listen(port, host);
1223
+ const exporter = new DevtoolsSpanExporter(wsServer);
1224
+ return {
1225
+ server: wsServer,
1226
+ httpServer,
1227
+ exporter,
1228
+ port,
1229
+ close: async () => {
1230
+ await wsServer.close();
1231
+ }
1232
+ };
1233
+ }
1234
+
1235
+ exports.DevtoolsLogExporter = DevtoolsLogExporter;
1236
+ exports.DevtoolsRemoteExporter = DevtoolsRemoteExporter;
1237
+ exports.DevtoolsServer = DevtoolsServer;
1238
+ exports.DevtoolsSpanExporter = DevtoolsSpanExporter;
1239
+ exports.ErrorAggregator = ErrorAggregator;
1240
+ exports.createDevtools = createDevtools;
1241
+ //# sourceMappingURL=index.cjs.map
1242
+ //# sourceMappingURL=index.cjs.map