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/cli.cjs ADDED
@@ -0,0 +1,889 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ var http = require('http');
5
+ var fs = require('fs');
6
+ var path = require('path');
7
+ var url = require('url');
8
+ var ws = require('ws');
9
+
10
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
11
+ // src/server/error-aggregator.ts
12
+ var ErrorAggregator = class {
13
+ errorGroups = /* @__PURE__ */ new Map();
14
+ options;
15
+ constructor(options = {}) {
16
+ this.options = {
17
+ maxGroups: options.maxGroups ?? 100,
18
+ maxAffectedTraces: options.maxAffectedTraces ?? 10,
19
+ maxAffectedSpans: options.maxAffectedSpans ?? 5,
20
+ stackFramesForFingerprint: options.stackFramesForFingerprint ?? 5
21
+ };
22
+ }
23
+ /**
24
+ * Add an error occurrence to the aggregator
25
+ */
26
+ addError(occurrence) {
27
+ const fingerprint = this.generateFingerprint(occurrence);
28
+ const existing = this.errorGroups.get(fingerprint);
29
+ if (existing) {
30
+ existing.count++;
31
+ existing.lastSeen = occurrence.timestamp;
32
+ if (!existing.affectedTraces.includes(occurrence.traceId)) {
33
+ existing.affectedTraces.push(occurrence.traceId);
34
+ if (existing.affectedTraces.length > this.options.maxAffectedTraces) {
35
+ existing.affectedTraces.shift();
36
+ }
37
+ }
38
+ if (!existing.affectedSpans.includes(occurrence.spanName)) {
39
+ existing.affectedSpans.push(occurrence.spanName);
40
+ if (existing.affectedSpans.length > this.options.maxAffectedSpans) {
41
+ existing.affectedSpans.shift();
42
+ }
43
+ }
44
+ return existing;
45
+ }
46
+ const newGroup = {
47
+ fingerprint,
48
+ type: occurrence.error.type,
49
+ message: occurrence.error.message,
50
+ stackTrace: this.normalizeStackTrace(occurrence.error.stackTrace),
51
+ count: 1,
52
+ firstSeen: occurrence.timestamp,
53
+ lastSeen: occurrence.timestamp,
54
+ affectedTraces: [occurrence.traceId],
55
+ affectedSpans: [occurrence.spanName],
56
+ service: occurrence.service,
57
+ attributes: occurrence.attributes
58
+ };
59
+ if (this.errorGroups.size >= this.options.maxGroups) {
60
+ this.evictOldestGroup();
61
+ }
62
+ this.errorGroups.set(fingerprint, newGroup);
63
+ return newGroup;
64
+ }
65
+ /**
66
+ * Extract errors from a trace and add them to the aggregator
67
+ */
68
+ addErrorsFromTrace(trace) {
69
+ const addedGroups = [];
70
+ for (const span of trace.spans) {
71
+ if (span.status.code === "ERROR") {
72
+ const occurrence = this.extractErrorFromSpan(span, trace);
73
+ if (occurrence) {
74
+ const group = this.addError(occurrence);
75
+ addedGroups.push(group);
76
+ }
77
+ }
78
+ }
79
+ return addedGroups;
80
+ }
81
+ /**
82
+ * Extract error occurrence from a span
83
+ */
84
+ extractErrorFromSpan(span, trace) {
85
+ const exceptionEvent = span.events?.find((e) => e.name === "exception");
86
+ const errorType = span.attributes["exception.type"] || span.attributes["error.type"] || exceptionEvent?.attributes?.["exception.type"] || "Error";
87
+ const errorMessage = span.status.message || span.attributes["exception.message"] || span.attributes["error.message"] || "Unknown error";
88
+ const stackTrace = span.attributes["exception.stacktrace"] || span.attributes["exception.stack"] || this.extractStackFromEvents(span);
89
+ return {
90
+ traceId: trace.traceId,
91
+ spanId: span.spanId,
92
+ spanName: span.name,
93
+ service: trace.service,
94
+ timestamp: span.endTime,
95
+ error: {
96
+ type: errorType,
97
+ message: errorMessage,
98
+ stackTrace
99
+ },
100
+ attributes: this.extractRelevantAttributes(span.attributes)
101
+ };
102
+ }
103
+ /**
104
+ * Extract stack trace from span events (exception events)
105
+ */
106
+ extractStackFromEvents(span) {
107
+ if (!span.events) return void 0;
108
+ const exceptionEvent = span.events.find((e) => e.name === "exception");
109
+ if (exceptionEvent?.attributes) {
110
+ return exceptionEvent.attributes["exception.stacktrace"] || exceptionEvent.attributes["exception.stack"];
111
+ }
112
+ return void 0;
113
+ }
114
+ /**
115
+ * Extract relevant attributes for error context
116
+ */
117
+ extractRelevantAttributes(attributes) {
118
+ const relevant = {};
119
+ const keepKeys = [
120
+ "http.method",
121
+ "http.url",
122
+ "http.route",
123
+ "http.status_code",
124
+ "db.system",
125
+ "db.operation",
126
+ "rpc.method",
127
+ "rpc.service",
128
+ "code.function",
129
+ "code.filepath",
130
+ "user.id",
131
+ "operation.name"
132
+ ];
133
+ for (const key of keepKeys) {
134
+ if (key in attributes) {
135
+ relevant[key] = attributes[key];
136
+ }
137
+ }
138
+ return relevant;
139
+ }
140
+ /**
141
+ * Generate a fingerprint for error grouping
142
+ *
143
+ * Uses error type + first N stack frames (normalized)
144
+ */
145
+ generateFingerprint(occurrence) {
146
+ const parts = [occurrence.error.type];
147
+ if (occurrence.error.stackTrace) {
148
+ const frames = this.extractStackFrames(
149
+ occurrence.error.stackTrace,
150
+ this.options.stackFramesForFingerprint
151
+ );
152
+ parts.push(...frames);
153
+ } else {
154
+ parts.push(this.normalizeMessage(occurrence.error.message));
155
+ }
156
+ return this.simpleHash(parts.join("|"));
157
+ }
158
+ /**
159
+ * Extract and normalize stack frames from a stack trace
160
+ */
161
+ extractStackFrames(stackTrace, count) {
162
+ const lines = stackTrace.split("\n");
163
+ const frames = [];
164
+ for (const line of lines) {
165
+ if (frames.length >= count) break;
166
+ const trimmed = line.trim();
167
+ const nodeMatch = trimmed.match(/^at\s+(.+?)\s+\((.+?):(\d+):\d+\)$/);
168
+ if (nodeMatch) {
169
+ frames.push(`${nodeMatch[1]}@${this.normalizeFilePath(nodeMatch[2])}`);
170
+ continue;
171
+ }
172
+ const anonMatch = trimmed.match(/^at\s+(.+?):(\d+):\d+$/);
173
+ if (anonMatch) {
174
+ frames.push(`anonymous@${this.normalizeFilePath(anonMatch[1])}`);
175
+ continue;
176
+ }
177
+ const browserMatch = trimmed.match(/^(.+?)@(.+?):(\d+):\d+$/);
178
+ if (browserMatch) {
179
+ frames.push(
180
+ `${browserMatch[1]}@${this.normalizeFilePath(browserMatch[2])}`
181
+ );
182
+ continue;
183
+ }
184
+ }
185
+ return frames;
186
+ }
187
+ /**
188
+ * Normalize file path by removing absolute path prefixes and node_modules paths
189
+ */
190
+ normalizeFilePath(filePath) {
191
+ const nodeModulesMatch = filePath.match(
192
+ /node_modules\/(@[^/]+\/[^/]+|[^/]+)/
193
+ );
194
+ if (nodeModulesMatch) {
195
+ return `[npm]/${nodeModulesMatch[1]}`;
196
+ }
197
+ return filePath.replace(/^.*?\/src\//, "src/").replace(/^.*?\/dist\//, "dist/").replace(/^.*?\/lib\//, "lib/").replace(/^file:\/\//, "");
198
+ }
199
+ /**
200
+ * Normalize error message by removing dynamic parts
201
+ */
202
+ normalizeMessage(message) {
203
+ return message.replaceAll(
204
+ /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,
205
+ "[UUID]"
206
+ ).replaceAll(/\b[0-9a-f]{16,}\b/gi, "[ID]").replaceAll(/\b\d+\b/g, "[N]").replaceAll(/"[^"]*"/g, '"[STR]"').replaceAll(/'[^']*'/g, "'[STR]'").slice(0, 200);
207
+ }
208
+ /**
209
+ * Normalize stack trace for display
210
+ */
211
+ normalizeStackTrace(stackTrace) {
212
+ if (!stackTrace) return void 0;
213
+ const lines = stackTrace.split("\n").slice(0, 10);
214
+ return lines.join("\n");
215
+ }
216
+ /**
217
+ * Simple hash function for fingerprinting
218
+ */
219
+ simpleHash(str) {
220
+ let hash = 0;
221
+ for (let i = 0; i < str.length; i++) {
222
+ const char = str.charCodeAt(i);
223
+ hash = (hash << 5) - hash + char;
224
+ hash = hash & hash;
225
+ }
226
+ return Math.abs(hash).toString(16).padStart(8, "0");
227
+ }
228
+ /**
229
+ * Evict the oldest error group
230
+ */
231
+ evictOldestGroup() {
232
+ let oldest = null;
233
+ for (const [fingerprint, group] of this.errorGroups) {
234
+ if (!oldest || group.lastSeen < oldest.lastSeen) {
235
+ oldest = { fingerprint, lastSeen: group.lastSeen };
236
+ }
237
+ }
238
+ if (oldest) {
239
+ this.errorGroups.delete(oldest.fingerprint);
240
+ }
241
+ }
242
+ /**
243
+ * Get all error groups, sorted by most recent
244
+ */
245
+ getErrorGroups() {
246
+ return [...this.errorGroups.values()].sort(
247
+ (a, b) => b.lastSeen - a.lastSeen
248
+ );
249
+ }
250
+ /**
251
+ * Get error groups sorted by count (most frequent first)
252
+ */
253
+ getErrorGroupsByFrequency() {
254
+ return [...this.errorGroups.values()].sort(
255
+ (a, b) => b.count - a.count
256
+ );
257
+ }
258
+ /**
259
+ * Get a specific error group by fingerprint
260
+ */
261
+ getErrorGroup(fingerprint) {
262
+ return this.errorGroups.get(fingerprint);
263
+ }
264
+ /**
265
+ * Get error groups for a specific service
266
+ */
267
+ getErrorGroupsByService(service) {
268
+ return this.getErrorGroups().filter((g) => g.service === service);
269
+ }
270
+ /**
271
+ * Get total error count across all groups
272
+ */
273
+ getTotalErrorCount() {
274
+ let total = 0;
275
+ for (const group of this.errorGroups.values()) {
276
+ total += group.count;
277
+ }
278
+ return total;
279
+ }
280
+ /**
281
+ * Get error statistics
282
+ */
283
+ getStats() {
284
+ const now = Date.now();
285
+ const oneHourAgo = now - 60 * 60 * 1e3;
286
+ let recentErrors = 0;
287
+ const typeCount = /* @__PURE__ */ new Map();
288
+ for (const group of this.errorGroups.values()) {
289
+ if (group.lastSeen > oneHourAgo) {
290
+ recentErrors += group.count;
291
+ }
292
+ typeCount.set(group.type, (typeCount.get(group.type) || 0) + group.count);
293
+ }
294
+ const topErrorTypes = [...typeCount.entries()].map(([type, count]) => ({ type, count })).sort((a, b) => b.count - a.count).slice(0, 5);
295
+ return {
296
+ totalGroups: this.errorGroups.size,
297
+ totalErrors: this.getTotalErrorCount(),
298
+ recentErrors,
299
+ topErrorTypes
300
+ };
301
+ }
302
+ /**
303
+ * Clear all error groups
304
+ */
305
+ clear() {
306
+ this.errorGroups.clear();
307
+ }
308
+ /**
309
+ * Clear old error groups (not seen in given time window)
310
+ */
311
+ clearOlderThan(maxAgeMs) {
312
+ const cutoff = Date.now() - maxAgeMs;
313
+ let cleared = 0;
314
+ for (const [fingerprint, group] of this.errorGroups) {
315
+ if (group.lastSeen < cutoff) {
316
+ this.errorGroups.delete(fingerprint);
317
+ cleared++;
318
+ }
319
+ }
320
+ return cleared;
321
+ }
322
+ };
323
+
324
+ // src/server/telemetry-limits.ts
325
+ var defaultLimit = 100;
326
+ function parseLimit(value) {
327
+ if (!value) return void 0;
328
+ const parsed = Number.parseInt(value, 10);
329
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : void 0;
330
+ }
331
+ function resolveTelemetryLimits(args = {}) {
332
+ const env = args.env ?? process.env;
333
+ const fallback = args.maxHistory ?? defaultLimit;
334
+ return {
335
+ maxTraceCount: args.maxTraceCount ?? parseLimit(env.AUTOTEL_MAX_TRACE_COUNT) ?? fallback,
336
+ maxLogCount: args.maxLogCount ?? parseLimit(env.AUTOTEL_MAX_LOG_COUNT) ?? fallback,
337
+ maxMetricCount: args.maxMetricCount ?? parseLimit(env.AUTOTEL_MAX_METRIC_COUNT) ?? fallback
338
+ };
339
+ }
340
+ function appendWithLimit(items, item, limit) {
341
+ if (limit <= 0) return [];
342
+ const next = [...items, item];
343
+ return next.length > limit ? next.slice(next.length - limit) : next;
344
+ }
345
+ function appendManyWithLimit(items, incoming, limit) {
346
+ if (limit <= 0 || incoming.length === 0) return limit <= 0 ? [] : items;
347
+ const next = [...items, ...incoming];
348
+ return next.length > limit ? next.slice(next.length - limit) : next;
349
+ }
350
+
351
+ // src/server/server.ts
352
+ var DevtoolsServer = class {
353
+ wss;
354
+ clients = /* @__PURE__ */ new Set();
355
+ httpServer;
356
+ traces = [];
357
+ logs = [];
358
+ metrics = [];
359
+ errorAggregator = new ErrorAggregator();
360
+ limits;
361
+ verbose;
362
+ _port;
363
+ constructor(options = {}) {
364
+ this.limits = resolveTelemetryLimits(options);
365
+ this.verbose = options.verbose ?? false;
366
+ this._port = options.port ?? 4318;
367
+ this.httpServer = options.server ?? http.createServer();
368
+ this.wss = new ws.WebSocketServer({ server: this.httpServer, path: options.path ?? "/ws" });
369
+ this.wss.on("connection", (ws) => {
370
+ this.clients.add(ws);
371
+ this.log(`Client connected (${this.clients.size} total)`);
372
+ const data = this.getCurrentData();
373
+ if (data.traces.length > 0 || data.logs.length > 0 || data.errors.length > 0) {
374
+ ws.send(JSON.stringify(data));
375
+ }
376
+ ws.on("close", () => {
377
+ this.clients.delete(ws);
378
+ this.log(`Client disconnected (${this.clients.size} total)`);
379
+ });
380
+ });
381
+ if (!options.server) {
382
+ this.httpServer.listen(this._port, () => {
383
+ const addr = this.httpServer.address();
384
+ if (addr && typeof addr === "object") this._port = addr.port;
385
+ this.log(`WebSocket server listening on port ${this._port}`);
386
+ });
387
+ }
388
+ }
389
+ get port() {
390
+ const addr = this.httpServer.address();
391
+ if (addr && typeof addr === "object") return addr.port;
392
+ return this._port;
393
+ }
394
+ get clientCount() {
395
+ return this.clients.size;
396
+ }
397
+ addTrace(trace) {
398
+ const existing = this.traces.find((t) => t.traceId === trace.traceId);
399
+ if (existing) {
400
+ const existingSpanIds = new Set(existing.spans.map((s) => s.spanId));
401
+ for (const span of trace.spans) {
402
+ if (!existingSpanIds.has(span.spanId)) {
403
+ existing.spans.push(span);
404
+ }
405
+ }
406
+ existing.startTime = Math.min(existing.startTime, trace.startTime);
407
+ existing.endTime = Math.max(existing.endTime, trace.endTime);
408
+ existing.duration = existing.endTime - existing.startTime;
409
+ if (trace.status === "ERROR") existing.status = "ERROR";
410
+ } else {
411
+ this.traces = appendWithLimit(
412
+ this.traces,
413
+ trace,
414
+ this.limits.maxTraceCount
415
+ );
416
+ }
417
+ this.errorAggregator.addErrorsFromTrace(trace);
418
+ this.broadcast({ traces: [trace], metrics: [], logs: [], errors: this.errorAggregator.getErrorGroups() });
419
+ }
420
+ addTraces(traces) {
421
+ for (const trace of traces) this.addTrace(trace);
422
+ }
423
+ addLog(log) {
424
+ this.logs = appendWithLimit(this.logs, log, this.limits.maxLogCount);
425
+ this.broadcast({ traces: [], metrics: [], logs: [log], errors: [] });
426
+ }
427
+ addLogs(logs) {
428
+ this.logs = appendManyWithLimit(this.logs, logs, this.limits.maxLogCount);
429
+ this.broadcast({ traces: [], metrics: [], logs, errors: [] });
430
+ }
431
+ addMetric(metric) {
432
+ this.metrics = appendWithLimit(
433
+ this.metrics,
434
+ metric,
435
+ this.limits.maxMetricCount
436
+ );
437
+ this.broadcast({ traces: [], metrics: [metric], logs: [], errors: [] });
438
+ }
439
+ getCurrentData() {
440
+ return {
441
+ traces: this.traces,
442
+ metrics: this.metrics,
443
+ logs: this.logs,
444
+ errors: this.errorAggregator.getErrorGroups()
445
+ };
446
+ }
447
+ clearData() {
448
+ this.traces = [];
449
+ this.logs = [];
450
+ this.metrics = [];
451
+ this.errorAggregator.clear();
452
+ }
453
+ broadcast(data) {
454
+ const msg = JSON.stringify(data);
455
+ for (const client of this.clients) {
456
+ if (client.readyState === ws.WebSocket.OPEN) {
457
+ client.send(msg);
458
+ }
459
+ }
460
+ }
461
+ log(message) {
462
+ if (this.verbose) console.log(`[autotel-devtools] ${message}`);
463
+ }
464
+ async close() {
465
+ for (const client of this.clients) client.close();
466
+ this.clients.clear();
467
+ this.wss.close();
468
+ await new Promise((resolve3) => this.httpServer.close(() => resolve3()));
469
+ }
470
+ };
471
+
472
+ // src/server/resource-utils.ts
473
+ function getResourceName(resource, fallback = "unknown") {
474
+ if (!resource) return fallback;
475
+ const candidates = [
476
+ resource["service.name"],
477
+ resource["service.namespace"],
478
+ resource["deployment.environment.name"],
479
+ resource["host.name"],
480
+ resource["container.name"],
481
+ resource["process.executable.name"]
482
+ ];
483
+ for (const candidate of candidates) {
484
+ if (typeof candidate === "string" && candidate.trim().length > 0) {
485
+ return candidate;
486
+ }
487
+ }
488
+ return fallback;
489
+ }
490
+
491
+ // src/server/otlp.ts
492
+ function resolveOtlpValue(v) {
493
+ if (!v) return void 0;
494
+ if (v.stringValue !== void 0) return v.stringValue;
495
+ if (v.boolValue !== void 0) return v.boolValue;
496
+ if (v.intValue !== void 0) return typeof v.intValue === "string" ? Number(v.intValue) : v.intValue;
497
+ if (v.doubleValue !== void 0) return v.doubleValue;
498
+ if (v.bytesValue !== void 0) return v.bytesValue;
499
+ if (v.arrayValue?.values) return v.arrayValue.values.map(resolveOtlpValue);
500
+ if (v.kvlistValue?.values) return flattenAttributes(v.kvlistValue.values);
501
+ return void 0;
502
+ }
503
+ function flattenAttributes(attrs) {
504
+ const out = {};
505
+ if (!attrs) return out;
506
+ for (const { key, value } of attrs) {
507
+ out[key] = resolveOtlpValue(value);
508
+ }
509
+ return out;
510
+ }
511
+ function nanoToMs(nano) {
512
+ if (!nano) return 0;
513
+ return Number(BigInt(nano) / 1000000n);
514
+ }
515
+ var SPAN_KIND_MAP = {
516
+ 0: "INTERNAL",
517
+ 1: "INTERNAL",
518
+ 2: "SERVER",
519
+ 3: "CLIENT",
520
+ 4: "PRODUCER",
521
+ 5: "CONSUMER",
522
+ SPAN_KIND_INTERNAL: "INTERNAL",
523
+ SPAN_KIND_SERVER: "SERVER",
524
+ SPAN_KIND_CLIENT: "CLIENT",
525
+ SPAN_KIND_PRODUCER: "PRODUCER",
526
+ SPAN_KIND_CONSUMER: "CONSUMER"
527
+ };
528
+ function normalizeHexId(id) {
529
+ if (!id) return "";
530
+ const isBase64Like = /^[A-Za-z0-9+/=]+$/.test(id) && !/^[0-9a-f]+$/i.test(id);
531
+ const isLikelyBase64Id = isBase64Like && (id.length === 24 || id.length === 28 || id.length === 44 || id.length === 48);
532
+ if (isLikelyBase64Id) {
533
+ try {
534
+ const bytes = Buffer.from(id, "base64");
535
+ return bytes.toString("hex");
536
+ } catch {
537
+ }
538
+ }
539
+ return id;
540
+ }
541
+ function parseOtlpTraces(payload) {
542
+ if (!payload || typeof payload !== "object") return [];
543
+ const { resourceSpans } = payload;
544
+ if (!Array.isArray(resourceSpans) || resourceSpans.length === 0) return [];
545
+ const traceMap = /* @__PURE__ */ new Map();
546
+ for (const rs of resourceSpans) {
547
+ const resourceAttrs = flattenAttributes(rs.resource?.attributes);
548
+ const service = String(resourceAttrs["service.name"] || "unknown");
549
+ const scopeSpans = rs.scopeSpans || [];
550
+ for (const ss of scopeSpans) {
551
+ for (const span of ss.spans || []) {
552
+ const traceId = normalizeHexId(span.traceId);
553
+ if (!traceId) continue;
554
+ const startMs = nanoToMs(span.startTimeUnixNano);
555
+ const endMs = nanoToMs(span.endTimeUnixNano);
556
+ const statusCode = span.status?.code;
557
+ let status = "UNSET";
558
+ if (statusCode === 1 || statusCode === "STATUS_CODE_OK") status = "OK";
559
+ if (statusCode === 2 || statusCode === "STATUS_CODE_ERROR") status = "ERROR";
560
+ const spanData = {
561
+ traceId,
562
+ spanId: normalizeHexId(span.spanId),
563
+ parentSpanId: normalizeHexId(span.parentSpanId) || void 0,
564
+ name: span.name || "unknown",
565
+ kind: SPAN_KIND_MAP[span.kind ?? 0] || "INTERNAL",
566
+ startTime: startMs,
567
+ endTime: endMs,
568
+ duration: endMs - startMs,
569
+ attributes: { ...resourceAttrs, ...flattenAttributes(span.attributes) },
570
+ status: { code: status, message: span.status?.message },
571
+ events: (span.events || []).map((e) => ({
572
+ name: e.name || "",
573
+ timestamp: nanoToMs(e.timeUnixNano),
574
+ attributes: flattenAttributes(e.attributes)
575
+ }))
576
+ };
577
+ const existing = traceMap.get(traceId);
578
+ if (existing) {
579
+ existing.spans.push(spanData);
580
+ } else {
581
+ traceMap.set(traceId, { spans: [spanData], service });
582
+ }
583
+ }
584
+ }
585
+ }
586
+ const traces = [];
587
+ for (const [traceId, { spans, service }] of traceMap) {
588
+ const sorted = spans.sort((a, b) => a.startTime - b.startTime);
589
+ const rootSpan = sorted.find((s) => !s.parentSpanId) || sorted[0];
590
+ const startTime = Math.min(...sorted.map((s) => s.startTime));
591
+ const endTime = Math.max(...sorted.map((s) => s.endTime));
592
+ const hasError = sorted.some((s) => s.status.code === "ERROR");
593
+ traces.push({
594
+ traceId,
595
+ correlationId: traceId.slice(0, 16),
596
+ rootSpan,
597
+ spans: sorted,
598
+ startTime,
599
+ endTime,
600
+ duration: endTime - startTime,
601
+ status: hasError ? "ERROR" : "OK",
602
+ service
603
+ });
604
+ }
605
+ return traces;
606
+ }
607
+ function parseOtlpLogs(payload) {
608
+ if (!payload || typeof payload !== "object") return [];
609
+ const { resourceLogs } = payload;
610
+ if (!Array.isArray(resourceLogs)) return [];
611
+ const logs = [];
612
+ for (const rl of resourceLogs) {
613
+ const resourceAttrs = flattenAttributes(rl.resource?.attributes);
614
+ for (const sl of rl.scopeLogs || []) {
615
+ for (const rec of sl.logRecords || []) {
616
+ const timestamp = nanoToMs(rec.timeUnixNano || rec.observedTimeUnixNano);
617
+ const traceId = normalizeHexId(rec.traceId) || void 0;
618
+ const spanId = normalizeHexId(rec.spanId) || void 0;
619
+ const body = rec.body ? resolveOtlpValue(rec.body) : "";
620
+ logs.push({
621
+ id: `${traceId || "no-trace"}:${spanId || "no-span"}:${timestamp}:${rec.severityNumber || 0}`,
622
+ traceId,
623
+ spanId,
624
+ resourceName: getResourceName(resourceAttrs),
625
+ severityText: rec.severityText,
626
+ severityNumber: rec.severityNumber,
627
+ body: typeof body === "string" ? body : body,
628
+ timestamp,
629
+ attributes: flattenAttributes(rec.attributes),
630
+ resource: resourceAttrs
631
+ });
632
+ }
633
+ }
634
+ }
635
+ return logs;
636
+ }
637
+ function countOtlpMetrics(payload) {
638
+ if (!payload || typeof payload !== "object") return 0;
639
+ const { resourceMetrics } = payload;
640
+ if (!Array.isArray(resourceMetrics)) return 0;
641
+ let count = 0;
642
+ for (const rm of resourceMetrics) {
643
+ for (const sm of rm.scopeMetrics || []) {
644
+ count += (sm.metrics || []).length;
645
+ }
646
+ }
647
+ return count;
648
+ }
649
+ async function readJsonBody(req) {
650
+ return new Promise((resolve3, reject) => {
651
+ const chunks = [];
652
+ req.on("data", (chunk) => chunks.push(chunk));
653
+ req.on("end", () => {
654
+ try {
655
+ resolve3(JSON.parse(Buffer.concat(chunks).toString()));
656
+ } catch {
657
+ reject(new Error("Invalid JSON"));
658
+ }
659
+ });
660
+ req.on("error", reject);
661
+ });
662
+ }
663
+ function sendJson(res, status, data) {
664
+ const body = JSON.stringify(data);
665
+ res.writeHead(status, { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(body) });
666
+ res.end(body);
667
+ }
668
+
669
+ // src/server/http.ts
670
+ function findPackageRoot() {
671
+ let dir = path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli.cjs', document.baseURI).href))));
672
+ for (let i = 0; i < 5; i++) {
673
+ if (fs.existsSync(path.resolve(dir, "package.json"))) return dir;
674
+ dir = path.dirname(dir);
675
+ }
676
+ return dir;
677
+ }
678
+ 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>`;
679
+ var cachedWidgetJs = null;
680
+ function getWidgetJs() {
681
+ if (!cachedWidgetJs) {
682
+ const pkgRoot = findPackageRoot();
683
+ const candidates = [
684
+ path.resolve(pkgRoot, "dist", "widget.global.js"),
685
+ path.resolve(pkgRoot, "widget.global.js")
686
+ ];
687
+ for (const candidate of candidates) {
688
+ try {
689
+ cachedWidgetJs = fs.readFileSync(candidate, "utf8");
690
+ break;
691
+ } catch {
692
+ }
693
+ }
694
+ if (!cachedWidgetJs) {
695
+ cachedWidgetJs = "// widget bundle not found - run pnpm build first";
696
+ }
697
+ }
698
+ return cachedWidgetJs;
699
+ }
700
+ function attachDevtoolsRoutes(httpServer, devtools) {
701
+ httpServer.on("request", async (req, res) => {
702
+ res.setHeader("Access-Control-Allow-Origin", "*");
703
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
704
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type");
705
+ if (req.method === "OPTIONS") {
706
+ res.writeHead(204);
707
+ res.end();
708
+ return;
709
+ }
710
+ const url = req.url || "/";
711
+ if (req.method === "GET" && url === "/") {
712
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Content-Length": Buffer.byteLength(FULLPAGE_HTML) });
713
+ res.end(FULLPAGE_HTML);
714
+ return;
715
+ }
716
+ if (req.method === "GET" && url.startsWith("/widget.js")) {
717
+ const js = getWidgetJs();
718
+ res.writeHead(200, { "Content-Type": "application/javascript; charset=utf-8", "Content-Length": Buffer.byteLength(js) });
719
+ res.end(js);
720
+ return;
721
+ }
722
+ if (req.method === "GET" && url === "/healthz") {
723
+ sendJson(res, 200, { ok: true, clients: devtools.clientCount });
724
+ return;
725
+ }
726
+ if (req.method === "POST" && url === "/v1/traces") {
727
+ try {
728
+ const payload = await readJsonBody(req);
729
+ const traces = parseOtlpTraces(payload);
730
+ devtools.addTraces(traces);
731
+ sendJson(res, 200, { acceptedTraces: traces.length });
732
+ } catch (e) {
733
+ sendJson(res, 400, { error: "Invalid OTLP JSON", message: e instanceof Error ? e.message : String(e) });
734
+ }
735
+ return;
736
+ }
737
+ if (req.method === "POST" && url === "/v1/logs") {
738
+ try {
739
+ const payload = await readJsonBody(req);
740
+ const logs = parseOtlpLogs(payload);
741
+ devtools.addLogs(logs);
742
+ sendJson(res, 200, { acceptedLogs: logs.length });
743
+ } catch (e) {
744
+ sendJson(res, 400, { error: "Invalid OTLP JSON", message: e instanceof Error ? e.message : String(e) });
745
+ }
746
+ return;
747
+ }
748
+ if (req.method === "POST" && url === "/v1/metrics") {
749
+ try {
750
+ const payload = await readJsonBody(req);
751
+ const count = countOtlpMetrics(payload);
752
+ sendJson(res, 200, { acceptedMetrics: count });
753
+ } catch (e) {
754
+ sendJson(res, 400, { error: "Invalid OTLP JSON", message: e instanceof Error ? e.message : String(e) });
755
+ }
756
+ return;
757
+ }
758
+ sendJson(res, 404, { error: "Not found" });
759
+ });
760
+ }
761
+
762
+ // src/cli.ts
763
+ function printHelp() {
764
+ process.stdout.write(
765
+ `autotel-devtools - Standalone OTLP receiver with web devtools UI
766
+
767
+ Usage: autotel-devtools [options]
768
+
769
+ Options:
770
+ -p, --port <port> Port to listen on (default: 4318, env: AUTOTEL_DEVTOOLS_PORT)
771
+ -H, --host <host> Host to bind to (default: 127.0.0.1, env: AUTOTEL_DEVTOOLS_HOST)
772
+ -t, --title <title> Dashboard title (env: AUTOTEL_DEVTOOLS_TITLE)
773
+ Env limits: AUTOTEL_MAX_TRACE_COUNT, AUTOTEL_MAX_LOG_COUNT, AUTOTEL_MAX_METRIC_COUNT
774
+ -h, --help Show this help message
775
+ -v, --version Show version number
776
+
777
+ Endpoints:
778
+ GET / Web devtools UI (fullpage)
779
+ GET /widget.js Widget bundle (embed in your app)
780
+ POST /v1/traces Receive OTLP JSON trace data
781
+ POST /v1/logs Receive OTLP JSON log data
782
+ POST /v1/metrics Receive OTLP JSON metric data
783
+ WS /ws WebSocket stream for real-time updates
784
+ GET /healthz Health check
785
+
786
+ Examples:
787
+ npx autotel-devtools
788
+ npx autotel-devtools -p 4319
789
+
790
+ Then point your app:
791
+ OTEL_EXPORTER_OTLP_PROTOCOL=http/json OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 node app.js
792
+
793
+ View in browser:
794
+ http://localhost:4318
795
+
796
+ Or embed widget in your app:
797
+ <script src="http://localhost:4318/widget.js"></script>
798
+
799
+ `
800
+ );
801
+ }
802
+ function printVersion() {
803
+ try {
804
+ const dir = path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli.cjs', document.baseURI).href))));
805
+ const pkgPath = path.resolve(dir, "..", "package.json");
806
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
807
+ process.stdout.write(`${pkg.version}
808
+ `);
809
+ } catch {
810
+ process.stdout.write("unknown\n");
811
+ }
812
+ }
813
+ function parseArgs(argv) {
814
+ const options = {
815
+ port: Number(process.env.AUTOTEL_DEVTOOLS_PORT || 4318),
816
+ host: process.env.AUTOTEL_DEVTOOLS_HOST || "127.0.0.1",
817
+ title: process.env.AUTOTEL_DEVTOOLS_TITLE
818
+ };
819
+ for (let i = 0; i < argv.length; i++) {
820
+ const arg = argv[i];
821
+ const next = argv[i + 1];
822
+ if (arg === "--help" || arg === "-h") {
823
+ printHelp();
824
+ return null;
825
+ }
826
+ if (arg === "--version" || arg === "-v") {
827
+ printVersion();
828
+ return null;
829
+ }
830
+ if ((arg === "--port" || arg === "-p") && next) {
831
+ options.port = Number(next);
832
+ i++;
833
+ continue;
834
+ }
835
+ if ((arg === "--host" || arg === "-H") && next) {
836
+ options.host = next;
837
+ i++;
838
+ continue;
839
+ }
840
+ if ((arg === "--title" || arg === "-t") && next) {
841
+ options.title = next;
842
+ i++;
843
+ continue;
844
+ }
845
+ }
846
+ return options;
847
+ }
848
+ async function main() {
849
+ const options = parseArgs(process.argv.slice(2));
850
+ if (!options) {
851
+ process.exit(0);
852
+ }
853
+ const httpServer = http.createServer();
854
+ const wsServer = new DevtoolsServer({ server: httpServer, verbose: true });
855
+ attachDevtoolsRoutes(httpServer, wsServer);
856
+ httpServer.listen(options.port, options.host, () => {
857
+ const title = options.title || "autotel-devtools";
858
+ process.stdout.write(`
859
+ ${title}
860
+
861
+ `);
862
+ process.stdout.write(` UI: http://${options.host}:${options.port}
863
+ `);
864
+ process.stdout.write(` Widget: <script src="http://${options.host}:${options.port}/widget.js"></script>
865
+ `);
866
+ process.stdout.write(` WebSocket: ws://${options.host}:${options.port}/ws
867
+ `);
868
+ process.stdout.write(` OTLP: http://${options.host}:${options.port}/v1/traces
869
+
870
+ `);
871
+ process.stdout.write(` Set OTEL_EXPORTER_OTLP_PROTOCOL=http/json
872
+ `);
873
+ process.stdout.write(` Set OTEL_EXPORTER_OTLP_ENDPOINT=http://${options.host}:${options.port}
874
+
875
+ `);
876
+ });
877
+ const shutdown = () => {
878
+ wsServer.close().then(() => process.exit(0));
879
+ };
880
+ process.on("SIGINT", shutdown);
881
+ process.on("SIGTERM", shutdown);
882
+ }
883
+ main().catch((error) => {
884
+ process.stderr.write(`[autotel-devtools] failed to start: ${error instanceof Error ? error.message : String(error)}
885
+ `);
886
+ process.exit(1);
887
+ });
888
+ //# sourceMappingURL=cli.cjs.map
889
+ //# sourceMappingURL=cli.cjs.map