autotel-devtools 8.1.1 → 10.0.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 (63) hide show
  1. package/dist/cli.cjs +108 -1429
  2. package/dist/cli.cjs.map +1 -1
  3. package/dist/cli.d.cts +1 -1
  4. package/dist/cli.d.ts +1 -1
  5. package/dist/cli.js +109 -1422
  6. package/dist/cli.js.map +1 -1
  7. package/dist/error-aggregator-BvNmgn7E.d.ts +120 -0
  8. package/dist/error-aggregator-nnfbpSR7.d.cts +120 -0
  9. package/dist/exporter-1Y3GmLVS.d.cts +182 -0
  10. package/dist/exporter-CZ5HdD3o.d.ts +182 -0
  11. package/dist/genai/index.cjs +650 -537
  12. package/dist/genai/index.cjs.map +1 -1
  13. package/dist/genai/index.d.cts +164 -157
  14. package/dist/genai/index.d.ts +164 -157
  15. package/dist/genai/index.js +649 -536
  16. package/dist/genai/index.js.map +1 -1
  17. package/dist/http-BkkKa9C_.js +1128 -0
  18. package/dist/http-BkkKa9C_.js.map +1 -0
  19. package/dist/http-Yj6iSrMX.cjs +1275 -0
  20. package/dist/http-Yj6iSrMX.cjs.map +1 -0
  21. package/dist/index.cjs +50 -1728
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.d.cts +21 -23
  24. package/dist/index.d.ts +21 -23
  25. package/dist/index.js +44 -1716
  26. package/dist/index.js.map +1 -1
  27. package/dist/listen-BBsxO0wm.cjs +125 -0
  28. package/dist/listen-BBsxO0wm.cjs.map +1 -0
  29. package/dist/listen-DfOCquUq.js +120 -0
  30. package/dist/listen-DfOCquUq.js.map +1 -0
  31. package/dist/resource-utils-B4UVvfnH.js +18 -0
  32. package/dist/resource-utils-B4UVvfnH.js.map +1 -0
  33. package/dist/resource-utils-DjHJB6uc.cjs +24 -0
  34. package/dist/resource-utils-DjHJB6uc.cjs.map +1 -0
  35. package/dist/server/exporter.cjs +135 -159
  36. package/dist/server/exporter.cjs.map +1 -1
  37. package/dist/server/exporter.d.cts +2 -4
  38. package/dist/server/exporter.d.ts +2 -4
  39. package/dist/server/exporter.js +134 -158
  40. package/dist/server/exporter.js.map +1 -1
  41. package/dist/server/index.cjs +29 -1660
  42. package/dist/server/index.d.cts +34 -31
  43. package/dist/server/index.d.ts +34 -31
  44. package/dist/server/index.js +5 -1630
  45. package/dist/server/log-exporter.cjs +75 -102
  46. package/dist/server/log-exporter.cjs.map +1 -1
  47. package/dist/server/log-exporter.d.cts +27 -46
  48. package/dist/server/log-exporter.d.ts +27 -46
  49. package/dist/server/log-exporter.js +74 -100
  50. package/dist/server/log-exporter.js.map +1 -1
  51. package/dist/server/remote-exporter.cjs +171 -213
  52. package/dist/server/remote-exporter.cjs.map +1 -1
  53. package/dist/server/remote-exporter.d.cts +62 -82
  54. package/dist/server/remote-exporter.d.ts +62 -82
  55. package/dist/server/remote-exporter.js +170 -212
  56. package/dist/server/remote-exporter.js.map +1 -1
  57. package/package.json +5 -5
  58. package/dist/error-aggregator-D0Uu5r38.d.ts +0 -147
  59. package/dist/error-aggregator-D1Mr221Y.d.cts +0 -147
  60. package/dist/exporter-De6p4iAD.d.cts +0 -182
  61. package/dist/exporter-De6p4iAD.d.ts +0 -182
  62. package/dist/server/index.cjs.map +0 -1
  63. package/dist/server/index.js.map +0 -1
package/dist/cli.cjs CHANGED
@@ -1,1443 +1,122 @@
1
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
- var protobuf = require('protobufjs');
10
-
11
- var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
12
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
13
-
14
- var protobuf__default = /*#__PURE__*/_interopDefault(protobuf);
15
-
16
- // src/server/error-aggregator.ts
17
- var ErrorAggregator = class {
18
- errorGroups = /* @__PURE__ */ new Map();
19
- options;
20
- constructor(options = {}) {
21
- this.options = {
22
- maxGroups: options.maxGroups ?? 100,
23
- maxAffectedTraces: options.maxAffectedTraces ?? 10,
24
- maxAffectedSpans: options.maxAffectedSpans ?? 5,
25
- stackFramesForFingerprint: options.stackFramesForFingerprint ?? 5
26
- };
27
- }
28
- /**
29
- * Add an error occurrence to the aggregator
30
- */
31
- addError(occurrence) {
32
- const fingerprint = this.generateFingerprint(occurrence);
33
- const existing = this.errorGroups.get(fingerprint);
34
- if (existing) {
35
- existing.count++;
36
- existing.lastSeen = occurrence.timestamp;
37
- if (!existing.affectedTraces.includes(occurrence.traceId)) {
38
- existing.affectedTraces.push(occurrence.traceId);
39
- if (existing.affectedTraces.length > this.options.maxAffectedTraces) {
40
- existing.affectedTraces.shift();
41
- }
42
- }
43
- if (!existing.affectedSpans.includes(occurrence.spanName)) {
44
- existing.affectedSpans.push(occurrence.spanName);
45
- if (existing.affectedSpans.length > this.options.maxAffectedSpans) {
46
- existing.affectedSpans.shift();
47
- }
48
- }
49
- return existing;
50
- }
51
- const newGroup = {
52
- fingerprint,
53
- type: occurrence.error.type,
54
- message: occurrence.error.message,
55
- stackTrace: this.normalizeStackTrace(occurrence.error.stackTrace),
56
- count: 1,
57
- firstSeen: occurrence.timestamp,
58
- lastSeen: occurrence.timestamp,
59
- affectedTraces: [occurrence.traceId],
60
- affectedSpans: [occurrence.spanName],
61
- service: occurrence.service,
62
- attributes: occurrence.attributes
63
- };
64
- if (this.errorGroups.size >= this.options.maxGroups) {
65
- this.evictOldestGroup();
66
- }
67
- this.errorGroups.set(fingerprint, newGroup);
68
- return newGroup;
69
- }
70
- /**
71
- * Extract errors from a trace and add them to the aggregator
72
- */
73
- addErrorsFromTrace(trace) {
74
- const addedGroups = [];
75
- for (const span of trace.spans) {
76
- if (span.status.code === "ERROR") {
77
- const occurrence = this.extractErrorFromSpan(span, trace);
78
- if (occurrence) {
79
- const group = this.addError(occurrence);
80
- addedGroups.push(group);
81
- }
82
- }
83
- }
84
- return addedGroups;
85
- }
86
- /**
87
- * Extract error occurrence from a span
88
- */
89
- extractErrorFromSpan(span, trace) {
90
- const exceptionEvent = span.events?.find((e) => e.name === "exception");
91
- const errorType = span.attributes["exception.type"] || span.attributes["error.type"] || exceptionEvent?.attributes?.["exception.type"] || "Error";
92
- const errorMessage = span.status.message || span.attributes["exception.message"] || span.attributes["error.message"] || "Unknown error";
93
- const stackTrace = span.attributes["exception.stacktrace"] || span.attributes["exception.stack"] || this.extractStackFromEvents(span);
94
- return {
95
- traceId: trace.traceId,
96
- spanId: span.spanId,
97
- spanName: span.name,
98
- service: trace.service,
99
- timestamp: span.endTime,
100
- error: {
101
- type: errorType,
102
- message: errorMessage,
103
- stackTrace
104
- },
105
- attributes: this.extractRelevantAttributes(span.attributes)
106
- };
107
- }
108
- /**
109
- * Extract stack trace from span events (exception events)
110
- */
111
- extractStackFromEvents(span) {
112
- if (!span.events) return void 0;
113
- const exceptionEvent = span.events.find((e) => e.name === "exception");
114
- if (exceptionEvent?.attributes) {
115
- return exceptionEvent.attributes["exception.stacktrace"] || exceptionEvent.attributes["exception.stack"];
116
- }
117
- return void 0;
118
- }
119
- /**
120
- * Extract relevant attributes for error context
121
- */
122
- extractRelevantAttributes(attributes) {
123
- const relevant = {};
124
- const keepKeys = [
125
- "http.method",
126
- "http.url",
127
- "http.route",
128
- "http.status_code",
129
- "db.system",
130
- "db.operation",
131
- "rpc.method",
132
- "rpc.service",
133
- "code.function",
134
- "code.filepath",
135
- "user.id",
136
- "operation.name"
137
- ];
138
- for (const key of keepKeys) {
139
- if (key in attributes) {
140
- relevant[key] = attributes[key];
141
- }
142
- }
143
- return relevant;
144
- }
145
- /**
146
- * Generate a fingerprint for error grouping
147
- *
148
- * Uses error type + first N stack frames (normalized)
149
- */
150
- generateFingerprint(occurrence) {
151
- const parts = [occurrence.error.type];
152
- if (occurrence.error.stackTrace) {
153
- const frames = this.extractStackFrames(
154
- occurrence.error.stackTrace,
155
- this.options.stackFramesForFingerprint
156
- );
157
- parts.push(...frames);
158
- } else {
159
- parts.push(this.normalizeMessage(occurrence.error.message));
160
- }
161
- return this.simpleHash(parts.join("|"));
162
- }
163
- /**
164
- * Extract and normalize stack frames from a stack trace
165
- */
166
- extractStackFrames(stackTrace, count) {
167
- const lines = stackTrace.split("\n");
168
- const frames = [];
169
- for (const line of lines) {
170
- if (frames.length >= count) break;
171
- const trimmed = line.trim();
172
- const nodeMatch = trimmed.match(/^at\s+(.+?)\s+\((.+?):(\d+):\d+\)$/);
173
- if (nodeMatch) {
174
- frames.push(`${nodeMatch[1]}@${this.normalizeFilePath(nodeMatch[2])}`);
175
- continue;
176
- }
177
- const anonMatch = trimmed.match(/^at\s+(.+?):(\d+):\d+$/);
178
- if (anonMatch) {
179
- frames.push(`anonymous@${this.normalizeFilePath(anonMatch[1])}`);
180
- continue;
181
- }
182
- const browserMatch = trimmed.match(/^(.+?)@(.+?):(\d+):\d+$/);
183
- if (browserMatch) {
184
- frames.push(
185
- `${browserMatch[1]}@${this.normalizeFilePath(browserMatch[2])}`
186
- );
187
- continue;
188
- }
189
- }
190
- return frames;
191
- }
192
- /**
193
- * Normalize file path by removing absolute path prefixes and node_modules paths
194
- */
195
- normalizeFilePath(filePath) {
196
- const nodeModulesMatch = filePath.match(
197
- /node_modules\/(@[^/]+\/[^/]+|[^/]+)/
198
- );
199
- if (nodeModulesMatch) {
200
- return `[npm]/${nodeModulesMatch[1]}`;
201
- }
202
- return filePath.replace(/^.*?\/src\//, "src/").replace(/^.*?\/dist\//, "dist/").replace(/^.*?\/lib\//, "lib/").replace(/^file:\/\//, "");
203
- }
204
- /**
205
- * Normalize error message by removing dynamic parts
206
- */
207
- normalizeMessage(message) {
208
- return message.replaceAll(
209
- /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,
210
- "[UUID]"
211
- ).replaceAll(/\b[0-9a-f]{16,}\b/gi, "[ID]").replaceAll(/\b\d+\b/g, "[N]").replaceAll(/"[^"]*"/g, '"[STR]"').replaceAll(/'[^']*'/g, "'[STR]'").slice(0, 200);
212
- }
213
- /**
214
- * Normalize stack trace for display
215
- */
216
- normalizeStackTrace(stackTrace) {
217
- if (!stackTrace) return void 0;
218
- const lines = stackTrace.split("\n").slice(0, 10);
219
- return lines.join("\n");
220
- }
221
- /**
222
- * Simple hash function for fingerprinting
223
- */
224
- simpleHash(str) {
225
- let hash = 0;
226
- for (let i = 0; i < str.length; i++) {
227
- const char = str.charCodeAt(i);
228
- hash = (hash << 5) - hash + char;
229
- hash = hash & hash;
230
- }
231
- return Math.abs(hash).toString(16).padStart(8, "0");
232
- }
233
- /**
234
- * Evict the oldest error group
235
- */
236
- evictOldestGroup() {
237
- let oldest = null;
238
- for (const [fingerprint, group] of this.errorGroups) {
239
- if (!oldest || group.lastSeen < oldest.lastSeen) {
240
- oldest = { fingerprint, lastSeen: group.lastSeen };
241
- }
242
- }
243
- if (oldest) {
244
- this.errorGroups.delete(oldest.fingerprint);
245
- }
246
- }
247
- /**
248
- * Get all error groups, sorted by most recent
249
- */
250
- getErrorGroups() {
251
- return [...this.errorGroups.values()].sort(
252
- (a, b) => b.lastSeen - a.lastSeen
253
- );
254
- }
255
- /**
256
- * Get error groups sorted by count (most frequent first)
257
- */
258
- getErrorGroupsByFrequency() {
259
- return [...this.errorGroups.values()].sort(
260
- (a, b) => b.count - a.count
261
- );
262
- }
263
- /**
264
- * Get a specific error group by fingerprint
265
- */
266
- getErrorGroup(fingerprint) {
267
- return this.errorGroups.get(fingerprint);
268
- }
269
- /**
270
- * Get error groups for a specific service
271
- */
272
- getErrorGroupsByService(service) {
273
- return this.getErrorGroups().filter((g) => g.service === service);
274
- }
275
- /**
276
- * Get total error count across all groups
277
- */
278
- getTotalErrorCount() {
279
- let total = 0;
280
- for (const group of this.errorGroups.values()) {
281
- total += group.count;
282
- }
283
- return total;
284
- }
285
- /**
286
- * Get error statistics
287
- */
288
- getStats() {
289
- const now = Date.now();
290
- const oneHourAgo = now - 60 * 60 * 1e3;
291
- let recentErrors = 0;
292
- const typeCount = /* @__PURE__ */ new Map();
293
- for (const group of this.errorGroups.values()) {
294
- if (group.lastSeen > oneHourAgo) {
295
- recentErrors += group.count;
296
- }
297
- typeCount.set(group.type, (typeCount.get(group.type) || 0) + group.count);
298
- }
299
- const topErrorTypes = [...typeCount.entries()].map(([type, count]) => ({ type, count })).sort((a, b) => b.count - a.count).slice(0, 5);
300
- return {
301
- totalGroups: this.errorGroups.size,
302
- totalErrors: this.getTotalErrorCount(),
303
- recentErrors,
304
- topErrorTypes
305
- };
306
- }
307
- /**
308
- * Clear all error groups
309
- */
310
- clear() {
311
- this.errorGroups.clear();
312
- }
313
- /**
314
- * Clear old error groups (not seen in given time window)
315
- */
316
- clearOlderThan(maxAgeMs) {
317
- const cutoff = Date.now() - maxAgeMs;
318
- let cleared = 0;
319
- for (const [fingerprint, group] of this.errorGroups) {
320
- if (group.lastSeen < cutoff) {
321
- this.errorGroups.delete(fingerprint);
322
- cleared++;
323
- }
324
- }
325
- return cleared;
326
- }
327
- };
328
-
329
- // src/server/telemetry-limits.ts
330
- var defaultLimit = 100;
331
- function parseLimit(value) {
332
- if (!value) return void 0;
333
- const parsed = Number.parseInt(value, 10);
334
- return Number.isFinite(parsed) && parsed > 0 ? parsed : void 0;
335
- }
336
- function resolveTelemetryLimits(args = {}) {
337
- const env = args.env ?? process.env;
338
- const fallback = args.maxHistory ?? defaultLimit;
339
- return {
340
- maxTraceCount: args.maxTraceCount ?? parseLimit(env.AUTOTEL_MAX_TRACE_COUNT) ?? fallback,
341
- maxLogCount: args.maxLogCount ?? parseLimit(env.AUTOTEL_MAX_LOG_COUNT) ?? fallback,
342
- maxMetricCount: args.maxMetricCount ?? parseLimit(env.AUTOTEL_MAX_METRIC_COUNT) ?? fallback
343
- };
344
- }
345
- function appendWithLimit(items, item, limit) {
346
- if (limit <= 0) return [];
347
- const next = [...items, item];
348
- return next.length > limit ? next.slice(next.length - limit) : next;
349
- }
350
- function appendManyWithLimit(items, incoming, limit) {
351
- if (limit <= 0 || incoming.length === 0) return limit <= 0 ? [] : items;
352
- const next = [...items, ...incoming];
353
- return next.length > limit ? next.slice(next.length - limit) : next;
354
- }
355
-
356
- // src/server/origin-guard.ts
357
- var LOOPBACK_IPV6 = /* @__PURE__ */ new Set(["::1", "0:0:0:0:0:0:0:1"]);
358
- function isLoopbackHostname(hostname) {
359
- const h = hostname.toLowerCase().replace(/^\[|\]$/g, "");
360
- return h === "localhost" || /^127\./.test(h) || LOOPBACK_IPV6.has(h);
361
- }
362
- function hostnameFromHostHeader(host) {
363
- const h = host.trim();
364
- if (h.startsWith("[")) {
365
- const end = h.indexOf("]");
366
- return end > 0 ? h.slice(1, end) : h;
367
- }
368
- const colon = h.indexOf(":");
369
- return colon === -1 ? h : h.slice(0, colon);
370
- }
371
- function hostHeaderIsLoopback(host) {
372
- return isLoopbackHostname(hostnameFromHostHeader(host));
373
- }
374
- function originIsLoopback(origin) {
375
- try {
376
- return isLoopbackHostname(new URL(origin).hostname);
377
- } catch {
378
- return false;
379
- }
380
- }
381
- function allowSensitiveRequest(headers, loopbackOnly) {
382
- const { origin, host } = headers;
383
- if (origin && origin.length > 0 && !originIsLoopback(origin)) return false;
384
- if (loopbackOnly && host && host.length > 0 && !hostHeaderIsLoopback(host)) {
385
- return false;
386
- }
387
- return true;
388
- }
389
-
390
- // src/server/server.ts
391
- var DevtoolsServer = class {
392
- wss;
393
- clients = /* @__PURE__ */ new Set();
394
- httpServer;
395
- traces = [];
396
- logs = [];
397
- metrics = [];
398
- errorAggregator = new ErrorAggregator();
399
- limits;
400
- verbose;
401
- _port;
402
- onData;
403
- constructor(options = {}) {
404
- this.limits = resolveTelemetryLimits(options);
405
- this.verbose = options.verbose ?? false;
406
- this._port = options.port ?? 4318;
407
- this.onData = options.onData;
408
- this.httpServer = options.server ?? http.createServer();
409
- const loopbackOnly = options.host == null || hostHeaderIsLoopback(options.host);
410
- this.wss = new ws.WebSocketServer({
411
- server: this.httpServer,
412
- path: options.path ?? "/ws",
413
- verifyClient: ({ origin, req }) => allowSensitiveRequest({ origin, host: req.headers.host }, loopbackOnly)
414
- });
415
- this.wss.on("error", (err) => {
416
- if (this.httpServer.listening) throw err;
417
- });
418
- this.wss.on("connection", (ws) => {
419
- this.clients.add(ws);
420
- this.log(`Client connected (${this.clients.size} total)`);
421
- const data = this.getCurrentData();
422
- if (data.traces.length > 0 || data.logs.length > 0 || data.errors.length > 0) {
423
- ws.send(JSON.stringify(data));
424
- }
425
- ws.on("close", () => {
426
- this.clients.delete(ws);
427
- this.log(`Client disconnected (${this.clients.size} total)`);
428
- });
429
- });
430
- if (!options.server) {
431
- this.httpServer.listen(this._port, () => {
432
- const addr = this.httpServer.address();
433
- if (addr && typeof addr === "object") this._port = addr.port;
434
- this.log(`WebSocket server listening on port ${this._port}`);
435
- });
436
- }
437
- }
438
- get port() {
439
- const addr = this.httpServer.address();
440
- if (addr && typeof addr === "object") return addr.port;
441
- return this._port;
442
- }
443
- get clientCount() {
444
- return this.clients.size;
445
- }
446
- addTrace(trace) {
447
- const existing = this.traces.find((t) => t.traceId === trace.traceId);
448
- const merged = existing ?? trace;
449
- if (existing) {
450
- const existingSpanIds = new Set(existing.spans.map((s) => s.spanId));
451
- for (const span of trace.spans) {
452
- if (!existingSpanIds.has(span.spanId)) {
453
- existing.spans.push(span);
454
- }
455
- }
456
- existing.startTime = Math.min(existing.startTime, trace.startTime);
457
- existing.endTime = Math.max(existing.endTime, trace.endTime);
458
- existing.duration = existing.endTime - existing.startTime;
459
- if (trace.status === "ERROR") existing.status = "ERROR";
460
- const root = existing.spans.find((s) => !s.parentSpanId);
461
- if (root) {
462
- existing.rootSpan = root;
463
- const rootService = root.attributes?.["service.name"];
464
- if (typeof rootService === "string" && rootService.length > 0) {
465
- existing.service = rootService;
466
- }
467
- }
468
- } else {
469
- this.traces = appendWithLimit(
470
- this.traces,
471
- trace,
472
- this.limits.maxTraceCount
473
- );
474
- }
475
- this.errorAggregator.addErrorsFromTrace(trace);
476
- this.broadcast({ traces: [merged], metrics: [], logs: [], errors: this.errorAggregator.getErrorGroups() });
477
- }
478
- addTraces(traces) {
479
- for (const trace of traces) this.addTrace(trace);
480
- }
481
- // `errors` is full-state on every broadcast (the client replaces, not appends),
482
- // so non-trace broadcasts must echo the current error groups rather than `[]` —
483
- // otherwise a log/metric arriving after an error would wipe it from the UI.
484
- addLog(log) {
485
- this.logs = appendWithLimit(this.logs, log, this.limits.maxLogCount);
486
- this.broadcast({ traces: [], metrics: [], logs: [log], errors: this.errorAggregator.getErrorGroups() });
487
- }
488
- addLogs(logs) {
489
- this.logs = appendManyWithLimit(this.logs, logs, this.limits.maxLogCount);
490
- this.broadcast({ traces: [], metrics: [], logs, errors: this.errorAggregator.getErrorGroups() });
491
- }
492
- addMetric(metric) {
493
- this.metrics = appendWithLimit(
494
- this.metrics,
495
- metric,
496
- this.limits.maxMetricCount
497
- );
498
- this.broadcast({ traces: [], metrics: [metric], logs: [], errors: this.errorAggregator.getErrorGroups() });
499
- }
500
- getCurrentData() {
501
- return {
502
- traces: this.traces,
503
- metrics: this.metrics,
504
- logs: this.logs,
505
- errors: this.errorAggregator.getErrorGroups()
506
- };
507
- }
508
- clearData() {
509
- this.traces = [];
510
- this.logs = [];
511
- this.metrics = [];
512
- this.errorAggregator.clear();
513
- }
514
- broadcast(data) {
515
- const msg = JSON.stringify(data);
516
- for (const client of this.clients) {
517
- if (client.readyState === ws.WebSocket.OPEN) {
518
- client.send(msg);
519
- }
520
- }
521
- if (this.onData) {
522
- try {
523
- this.onData(data);
524
- } catch {
525
- }
526
- }
527
- }
528
- log(message) {
529
- if (this.verbose) console.log(`[autotel-devtools] ${message}`);
530
- }
531
- async close() {
532
- for (const client of this.clients) client.close();
533
- this.clients.clear();
534
- this.wss.close();
535
- await new Promise((resolve3) => this.httpServer.close(() => resolve3()));
536
- }
537
- };
538
-
539
- // src/server/resource-utils.ts
540
- function getResourceName(resource, fallback = "unknown") {
541
- if (!resource) return fallback;
542
- const candidates = [
543
- resource["service.name"],
544
- resource["service.namespace"],
545
- resource["deployment.environment.name"],
546
- resource["host.name"],
547
- resource["container.name"],
548
- resource["process.executable.name"]
549
- ];
550
- for (const candidate of candidates) {
551
- if (typeof candidate === "string" && candidate.trim().length > 0) {
552
- return candidate;
553
- }
554
- }
555
- return fallback;
556
- }
557
-
558
- // src/server/otlp.ts
559
- function resolveOtlpValue(v) {
560
- if (!v) return void 0;
561
- if (v.stringValue !== void 0) return v.stringValue;
562
- if (v.boolValue !== void 0) return v.boolValue;
563
- if (v.intValue !== void 0) return typeof v.intValue === "string" ? Number(v.intValue) : v.intValue;
564
- if (v.doubleValue !== void 0) return v.doubleValue;
565
- if (v.bytesValue !== void 0) return v.bytesValue;
566
- if (v.arrayValue?.values) return v.arrayValue.values.map(resolveOtlpValue);
567
- if (v.kvlistValue?.values) return flattenAttributes(v.kvlistValue.values);
568
- return void 0;
569
- }
570
- function flattenAttributes(attrs) {
571
- const out = {};
572
- if (!attrs) return out;
573
- for (const { key, value } of attrs) {
574
- out[key] = resolveOtlpValue(value);
575
- }
576
- return out;
577
- }
578
- function nanoToMs(nano) {
579
- if (!nano) return 0;
580
- const ns = BigInt(nano);
581
- const ms = ns / 1000000n;
582
- const remNs = ns % 1000000n;
583
- return Number(ms) + Number(remNs) / 1e6;
584
- }
585
- var SPAN_KIND_MAP = {
586
- 0: "INTERNAL",
587
- 1: "INTERNAL",
588
- 2: "SERVER",
589
- 3: "CLIENT",
590
- 4: "PRODUCER",
591
- 5: "CONSUMER",
592
- SPAN_KIND_INTERNAL: "INTERNAL",
593
- SPAN_KIND_SERVER: "SERVER",
594
- SPAN_KIND_CLIENT: "CLIENT",
595
- SPAN_KIND_PRODUCER: "PRODUCER",
596
- SPAN_KIND_CONSUMER: "CONSUMER"
597
- };
598
- function normalizeHexId(id) {
599
- if (!id) return "";
600
- const isBase64Like = /^[A-Za-z0-9+/=]+$/.test(id) && !/^[0-9a-f]+$/i.test(id);
601
- const isLikelyBase64Id = isBase64Like && (id.length === 12 || id.length === 24 || id.length === 28 || id.length === 44 || id.length === 48);
602
- if (isLikelyBase64Id) {
603
- try {
604
- const bytes = Buffer.from(id, "base64");
605
- return bytes.toString("hex");
606
- } catch {
607
- }
608
- }
609
- return id;
610
- }
611
- function parseOtlpTraces(payload) {
612
- if (!payload || typeof payload !== "object") return [];
613
- const { resourceSpans } = payload;
614
- if (!Array.isArray(resourceSpans) || resourceSpans.length === 0) return [];
615
- const traceMap = /* @__PURE__ */ new Map();
616
- for (const rs of resourceSpans) {
617
- const resourceAttrs = flattenAttributes(rs.resource?.attributes);
618
- const service = String(resourceAttrs["service.name"] || "unknown");
619
- const scopeSpans = rs.scopeSpans || [];
620
- for (const ss of scopeSpans) {
621
- const scope = ss.scope?.name ? { name: ss.scope.name, version: ss.scope.version || void 0 } : void 0;
622
- for (const span of ss.spans || []) {
623
- const traceId = normalizeHexId(span.traceId);
624
- if (!traceId) continue;
625
- const startMs = nanoToMs(span.startTimeUnixNano);
626
- const endMs = nanoToMs(span.endTimeUnixNano);
627
- const statusCode = span.status?.code;
628
- let status = "UNSET";
629
- if (statusCode === 1 || statusCode === "STATUS_CODE_OK") status = "OK";
630
- if (statusCode === 2 || statusCode === "STATUS_CODE_ERROR") status = "ERROR";
631
- const spanData = {
632
- traceId,
633
- spanId: normalizeHexId(span.spanId),
634
- parentSpanId: normalizeHexId(span.parentSpanId) || void 0,
635
- name: span.name || "unknown",
636
- kind: SPAN_KIND_MAP[span.kind ?? 0] || "INTERNAL",
637
- startTime: startMs,
638
- endTime: endMs,
639
- duration: endMs - startMs,
640
- attributes: { ...resourceAttrs, ...flattenAttributes(span.attributes) },
641
- status: { code: status, message: span.status?.message },
642
- events: (span.events || []).map((e) => ({
643
- name: e.name || "",
644
- timestamp: nanoToMs(e.timeUnixNano),
645
- attributes: flattenAttributes(e.attributes)
646
- })),
647
- links: (span.links || []).map((l) => ({
648
- traceId: normalizeHexId(l.traceId),
649
- spanId: normalizeHexId(l.spanId),
650
- attributes: flattenAttributes(l.attributes)
651
- })),
652
- scope
653
- };
654
- const existing = traceMap.get(traceId);
655
- if (existing) {
656
- existing.spans.push(spanData);
657
- } else {
658
- traceMap.set(traceId, { spans: [spanData], service });
659
- }
660
- }
661
- }
662
- }
663
- const traces = [];
664
- for (const [traceId, { spans, service }] of traceMap) {
665
- const sorted = spans.sort((a, b) => a.startTime - b.startTime);
666
- const rootSpan = sorted.find((s) => !s.parentSpanId) || sorted[0];
667
- const startTime = Math.min(...sorted.map((s) => s.startTime));
668
- const endTime = Math.max(...sorted.map((s) => s.endTime));
669
- const hasError = sorted.some((s) => s.status.code === "ERROR");
670
- traces.push({
671
- traceId,
672
- correlationId: traceId.slice(0, 16),
673
- rootSpan,
674
- spans: sorted,
675
- startTime,
676
- endTime,
677
- duration: endTime - startTime,
678
- status: hasError ? "ERROR" : "OK",
679
- service
680
- });
681
- }
682
- return traces;
683
- }
684
- function parseOtlpLogs(payload) {
685
- if (!payload || typeof payload !== "object") return [];
686
- const { resourceLogs } = payload;
687
- if (!Array.isArray(resourceLogs)) return [];
688
- const logs = [];
689
- for (const rl of resourceLogs) {
690
- const resourceAttrs = flattenAttributes(rl.resource?.attributes);
691
- for (const sl of rl.scopeLogs || []) {
692
- for (const rec of sl.logRecords || []) {
693
- const timestamp = nanoToMs(rec.timeUnixNano || rec.observedTimeUnixNano);
694
- const traceId = normalizeHexId(rec.traceId) || void 0;
695
- const spanId = normalizeHexId(rec.spanId) || void 0;
696
- const body = rec.body ? resolveOtlpValue(rec.body) : "";
697
- logs.push({
698
- id: `${traceId || "no-trace"}:${spanId || "no-span"}:${timestamp}:${rec.severityNumber || 0}`,
699
- traceId,
700
- spanId,
701
- resourceName: getResourceName(resourceAttrs),
702
- severityText: rec.severityText,
703
- severityNumber: rec.severityNumber,
704
- body: typeof body === "string" ? body : body,
705
- timestamp,
706
- attributes: flattenAttributes(rec.attributes),
707
- resource: resourceAttrs
708
- });
709
- }
710
- }
711
- }
712
- return logs;
713
- }
714
- function countOtlpMetrics(payload) {
715
- if (!payload || typeof payload !== "object") return 0;
716
- const { resourceMetrics } = payload;
717
- if (!Array.isArray(resourceMetrics)) return 0;
718
- let count = 0;
719
- for (const rm of resourceMetrics) {
720
- for (const sm of rm.scopeMetrics || []) {
721
- count += (sm.metrics || []).length;
722
- }
723
- }
724
- return count;
725
- }
726
- async function readJsonBody(req) {
727
- return new Promise((resolve3, reject) => {
728
- const chunks = [];
729
- req.on("data", (chunk) => chunks.push(chunk));
730
- req.on("end", () => {
731
- try {
732
- resolve3(JSON.parse(Buffer.concat(chunks).toString()));
733
- } catch {
734
- reject(new Error("Invalid JSON"));
735
- }
736
- });
737
- req.on("error", reject);
738
- });
739
- }
740
- async function readRawBody(req) {
741
- return new Promise((resolve3, reject) => {
742
- const chunks = [];
743
- req.on("data", (chunk) => chunks.push(chunk));
744
- req.on("end", () => resolve3(Buffer.concat(chunks)));
745
- req.on("error", reject);
746
- });
747
- }
748
- function isProtobufContentType(contentType) {
749
- if (!contentType) return false;
750
- const value = contentType.toLowerCase();
751
- return value.includes("application/x-protobuf") || value.includes("application/protobuf");
752
- }
753
- function sendJson(res, status, data) {
754
- const body = JSON.stringify(data);
755
- res.writeHead(status, { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(body) });
756
- res.end(body);
757
- }
758
- var COMMON_PROTO = `
759
- syntax = "proto3";
760
- package opentelemetry.proto.common.v1;
761
-
762
- message AnyValue {
763
- oneof value {
764
- string string_value = 1;
765
- bool bool_value = 2;
766
- int64 int_value = 3;
767
- double double_value = 4;
768
- ArrayValue array_value = 5;
769
- KeyValueList kvlist_value = 6;
770
- bytes bytes_value = 7;
771
- }
772
- }
773
- message ArrayValue { repeated AnyValue values = 1; }
774
- message KeyValueList { repeated KeyValue values = 1; }
775
- message KeyValue {
776
- string key = 1;
777
- AnyValue value = 2;
778
- }
779
- message InstrumentationScope {
780
- string name = 1;
781
- string version = 2;
782
- repeated KeyValue attributes = 3;
783
- uint32 dropped_attributes_count = 4;
784
- }
785
- `;
786
- var RESOURCE_PROTO = `
787
- syntax = "proto3";
788
- package opentelemetry.proto.resource.v1;
789
-
790
- message Resource {
791
- repeated opentelemetry.proto.common.v1.KeyValue attributes = 1;
792
- uint32 dropped_attributes_count = 2;
793
- }
794
- `;
795
- var TRACE_PROTO = `
796
- syntax = "proto3";
797
- package opentelemetry.proto.trace.v1;
798
-
799
- message ResourceSpans {
800
- opentelemetry.proto.resource.v1.Resource resource = 1;
801
- repeated ScopeSpans scope_spans = 2;
802
- string schema_url = 3;
803
- }
804
- message ScopeSpans {
805
- opentelemetry.proto.common.v1.InstrumentationScope scope = 1;
806
- repeated Span spans = 2;
807
- string schema_url = 3;
808
- }
809
- message Span {
810
- bytes trace_id = 1;
811
- bytes span_id = 2;
812
- string trace_state = 3;
813
- bytes parent_span_id = 4;
814
- fixed32 flags = 16;
815
- string name = 5;
816
- SpanKind kind = 6;
817
- fixed64 start_time_unix_nano = 7;
818
- fixed64 end_time_unix_nano = 8;
819
- repeated opentelemetry.proto.common.v1.KeyValue attributes = 9;
820
- uint32 dropped_attributes_count = 10;
821
- repeated Event events = 11;
822
- uint32 dropped_events_count = 12;
823
- repeated Link links = 13;
824
- uint32 dropped_links_count = 14;
825
- Status status = 15;
826
-
827
- enum SpanKind {
828
- SPAN_KIND_UNSPECIFIED = 0;
829
- SPAN_KIND_INTERNAL = 1;
830
- SPAN_KIND_SERVER = 2;
831
- SPAN_KIND_CLIENT = 3;
832
- SPAN_KIND_PRODUCER = 4;
833
- SPAN_KIND_CONSUMER = 5;
834
- }
835
- message Event {
836
- fixed64 time_unix_nano = 1;
837
- string name = 2;
838
- repeated opentelemetry.proto.common.v1.KeyValue attributes = 3;
839
- uint32 dropped_attributes_count = 4;
840
- }
841
- message Link {
842
- bytes trace_id = 1;
843
- bytes span_id = 2;
844
- string trace_state = 3;
845
- repeated opentelemetry.proto.common.v1.KeyValue attributes = 4;
846
- uint32 dropped_attributes_count = 5;
847
- fixed32 flags = 6;
848
- }
849
- }
850
- message Status {
851
- reserved 1;
852
- string message = 2;
853
- StatusCode code = 3;
854
-
855
- enum StatusCode {
856
- STATUS_CODE_UNSET = 0;
857
- STATUS_CODE_OK = 1;
858
- STATUS_CODE_ERROR = 2;
859
- }
860
- }
861
- message ExportTraceServiceRequest {
862
- repeated ResourceSpans resource_spans = 1;
863
- }
864
- `;
865
- var LOGS_PROTO = `
866
- syntax = "proto3";
867
- package opentelemetry.proto.logs.v1;
868
-
869
- enum SeverityNumber {
870
- SEVERITY_NUMBER_UNSPECIFIED = 0;
871
- SEVERITY_NUMBER_TRACE = 1;
872
- SEVERITY_NUMBER_TRACE2 = 2;
873
- SEVERITY_NUMBER_TRACE3 = 3;
874
- SEVERITY_NUMBER_TRACE4 = 4;
875
- SEVERITY_NUMBER_DEBUG = 5;
876
- SEVERITY_NUMBER_DEBUG2 = 6;
877
- SEVERITY_NUMBER_DEBUG3 = 7;
878
- SEVERITY_NUMBER_DEBUG4 = 8;
879
- SEVERITY_NUMBER_INFO = 9;
880
- SEVERITY_NUMBER_INFO2 = 10;
881
- SEVERITY_NUMBER_INFO3 = 11;
882
- SEVERITY_NUMBER_INFO4 = 12;
883
- SEVERITY_NUMBER_WARN = 13;
884
- SEVERITY_NUMBER_WARN2 = 14;
885
- SEVERITY_NUMBER_WARN3 = 15;
886
- SEVERITY_NUMBER_WARN4 = 16;
887
- SEVERITY_NUMBER_ERROR = 17;
888
- SEVERITY_NUMBER_ERROR2 = 18;
889
- SEVERITY_NUMBER_ERROR3 = 19;
890
- SEVERITY_NUMBER_ERROR4 = 20;
891
- SEVERITY_NUMBER_FATAL = 21;
892
- SEVERITY_NUMBER_FATAL2 = 22;
893
- SEVERITY_NUMBER_FATAL3 = 23;
894
- SEVERITY_NUMBER_FATAL4 = 24;
895
- }
896
- message ResourceLogs {
897
- opentelemetry.proto.resource.v1.Resource resource = 1;
898
- repeated ScopeLogs scope_logs = 2;
899
- string schema_url = 3;
900
- }
901
- message ScopeLogs {
902
- opentelemetry.proto.common.v1.InstrumentationScope scope = 1;
903
- repeated LogRecord log_records = 2;
904
- string schema_url = 3;
905
- }
906
- message LogRecord {
907
- reserved 4;
908
- fixed64 time_unix_nano = 1;
909
- fixed64 observed_time_unix_nano = 11;
910
- SeverityNumber severity_number = 2;
911
- string severity_text = 3;
912
- opentelemetry.proto.common.v1.AnyValue body = 5;
913
- repeated opentelemetry.proto.common.v1.KeyValue attributes = 6;
914
- uint32 dropped_attributes_count = 7;
915
- fixed32 flags = 8;
916
- bytes trace_id = 9;
917
- bytes span_id = 10;
918
- }
919
- message ExportLogsServiceRequest {
920
- repeated ResourceLogs resource_logs = 1;
921
- }
922
- `;
923
- var METRICS_PROTO = `
924
- syntax = "proto3";
925
- package opentelemetry.proto.metrics.v1;
926
-
927
- message ResourceMetrics {
928
- opentelemetry.proto.resource.v1.Resource resource = 1;
929
- repeated ScopeMetrics scope_metrics = 2;
930
- string schema_url = 3;
931
- }
932
- message ScopeMetrics {
933
- opentelemetry.proto.common.v1.InstrumentationScope scope = 1;
934
- repeated Metric metrics = 2;
935
- string schema_url = 3;
936
- }
937
- message Metric {
938
- string name = 1;
939
- string description = 2;
940
- string unit = 3;
941
- }
942
- message ExportMetricsServiceRequest {
943
- repeated ResourceMetrics resource_metrics = 1;
944
- }
945
- `;
946
- var TO_OBJECT_OPTIONS = {
947
- longs: String,
948
- bytes: String,
949
- defaults: false
950
- };
951
- var cachedRoot = null;
952
- function getRoot() {
953
- if (cachedRoot) return cachedRoot;
954
- const root = new protobuf__default.default.Root();
955
- for (const source of [COMMON_PROTO, RESOURCE_PROTO, TRACE_PROTO, LOGS_PROTO, METRICS_PROTO]) {
956
- protobuf__default.default.parse(source, root, { keepCase: false });
957
- }
958
- root.resolveAll();
959
- cachedRoot = root;
960
- return root;
961
- }
962
- function decodeRequest(typeName, body) {
963
- const messageType = getRoot().lookupType(typeName);
964
- const message = messageType.decode(body);
965
- return messageType.toObject(message, TO_OBJECT_OPTIONS);
966
- }
967
- function decodeOtlpTraceRequest(body) {
968
- return decodeRequest("opentelemetry.proto.trace.v1.ExportTraceServiceRequest", body);
969
- }
970
- function decodeOtlpLogsRequest(body) {
971
- return decodeRequest("opentelemetry.proto.logs.v1.ExportLogsServiceRequest", body);
972
- }
973
- function decodeOtlpMetricsRequest(body) {
974
- return decodeRequest("opentelemetry.proto.metrics.v1.ExportMetricsServiceRequest", body);
975
- }
976
-
977
- // src/server/identity.ts
978
- var DEVTOOLS_IDENTITY = "autotel-devtools";
979
- async function probePortHolder(host, port, timeoutMs = 500) {
980
- const authority = host.includes(":") ? `[${host}]` : host;
981
- const controller = new AbortController();
982
- const timer = setTimeout(() => controller.abort(), timeoutMs);
983
- try {
984
- const res = await fetch(`http://${authority}:${port}/healthz`, {
985
- signal: controller.signal
986
- });
987
- if (res.headers.get("x-autotel-devtools")) return "autotel-devtools";
988
- try {
989
- const body = await res.json();
990
- if (body && body.service === DEVTOOLS_IDENTITY) return "autotel-devtools";
991
- } catch {
992
- }
993
- return "foreign";
994
- } catch {
995
- return "none";
996
- } finally {
997
- clearTimeout(timer);
998
- }
999
- }
1000
-
1001
- // src/server/http.ts
1002
- function sendOtlpError(res, req, e) {
1003
- sendJson(res, 400, {
1004
- error: "Invalid OTLP payload",
1005
- message: e instanceof Error ? e.message : String(e),
1006
- contentType: req.headers["content-type"] ?? null
1007
- });
1008
- }
1009
- var PROTOBUF_DECODERS = {
1010
- traces: decodeOtlpTraceRequest,
1011
- logs: decodeOtlpLogsRequest,
1012
- metrics: decodeOtlpMetricsRequest
1013
- };
1014
- async function readOtlpPayload(req, signal) {
1015
- if (isProtobufContentType(req.headers["content-type"])) {
1016
- return PROTOBUF_DECODERS[signal](await readRawBody(req));
1017
- }
1018
- return readJsonBody(req);
1019
- }
1020
- function findPackageRoot() {
1021
- 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))));
1022
- for (let i = 0; i < 5; i++) {
1023
- if (fs.existsSync(path.resolve(dir, "package.json"))) return dir;
1024
- dir = path.dirname(dir);
1025
- }
1026
- return dir;
1027
- }
1028
- var DEVTOOLS_FAVICON_SVG = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="#0f172a"/><text x="32" y="41" text-anchor="middle" font-size="32">\u{1F6F0}\uFE0F</text></svg>';
1029
- 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><link rel="icon" href="/favicon.svg" type="image/svg+xml"><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>`;
1030
- var cachedVersion = null;
1031
- function getVersion() {
1032
- if (cachedVersion !== null) return cachedVersion;
1033
- let version = "unknown";
1034
- try {
1035
- const pkg = JSON.parse(fs.readFileSync(path.resolve(findPackageRoot(), "package.json"), "utf8"));
1036
- if (typeof pkg.version === "string") version = pkg.version;
1037
- } catch {
1038
- }
1039
- cachedVersion = version;
1040
- return version;
1041
- }
1042
- var cachedWidgetJs = null;
1043
- function getWidgetJs() {
1044
- if (!cachedWidgetJs) {
1045
- const pkgRoot = findPackageRoot();
1046
- const candidates = [
1047
- path.resolve(pkgRoot, "dist", "widget.global.js"),
1048
- path.resolve(pkgRoot, "widget.global.js")
1049
- ];
1050
- for (const candidate of candidates) {
1051
- try {
1052
- cachedWidgetJs = fs.readFileSync(candidate, "utf8");
1053
- break;
1054
- } catch {
1055
- }
1056
- }
1057
- if (!cachedWidgetJs) {
1058
- cachedWidgetJs = "// widget bundle not found - run pnpm build first";
1059
- }
1060
- }
1061
- return cachedWidgetJs;
1062
- }
1063
- function attachDevtoolsRoutes(httpServer, devtools, options = {}) {
1064
- const loopbackOnly = options.loopbackOnly ?? true;
1065
- httpServer.on("request", async (req, res) => {
1066
- if (req.headers.upgrade?.toLowerCase() === "websocket") return;
1067
- res.setHeader("Access-Control-Allow-Origin", "*");
1068
- res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
1069
- res.setHeader("Access-Control-Allow-Headers", "Content-Type");
1070
- res.setHeader("x-autotel-devtools", getVersion());
1071
- res.setHeader("Access-Control-Expose-Headers", "x-autotel-devtools");
1072
- if (req.method === "OPTIONS") {
1073
- res.writeHead(204);
1074
- res.end();
1075
- return;
1076
- }
1077
- const url = req.url || "/";
1078
- if (req.method === "GET" && url === "/") {
1079
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Content-Length": Buffer.byteLength(FULLPAGE_HTML) });
1080
- res.end(FULLPAGE_HTML);
1081
- return;
1082
- }
1083
- if (req.method === "GET" && url.startsWith("/widget.js")) {
1084
- const js = getWidgetJs();
1085
- res.writeHead(200, { "Content-Type": "application/javascript; charset=utf-8", "Content-Length": Buffer.byteLength(js) });
1086
- res.end(js);
1087
- return;
1088
- }
1089
- if (req.method === "GET" && (url === "/favicon.svg" || url === "/favicon.ico")) {
1090
- res.writeHead(200, {
1091
- "Content-Type": "image/svg+xml; charset=utf-8",
1092
- "Cache-Control": "public, max-age=86400",
1093
- "Content-Length": Buffer.byteLength(DEVTOOLS_FAVICON_SVG)
1094
- });
1095
- res.end(DEVTOOLS_FAVICON_SVG);
1096
- return;
1097
- }
1098
- if (req.method === "GET" && url === "/healthz") {
1099
- sendJson(res, 200, {
1100
- ok: true,
1101
- service: DEVTOOLS_IDENTITY,
1102
- version: getVersion(),
1103
- clients: devtools.clientCount
1104
- });
1105
- return;
1106
- }
1107
- if (req.method === "GET" && url === "/v1/traces") {
1108
- if (!allowSensitiveRequest(req.headers, loopbackOnly)) {
1109
- sendJson(res, 403, { error: "Forbidden" });
1110
- return;
1111
- }
1112
- const data = devtools.getCurrentData();
1113
- sendJson(res, 200, { traces: data.traces, count: data.traces.length });
1114
- return;
1115
- }
1116
- if (req.method === "DELETE" && url === "/v1/traces") {
1117
- if (!allowSensitiveRequest(req.headers, loopbackOnly)) {
1118
- sendJson(res, 403, { error: "Forbidden" });
1119
- return;
1120
- }
1121
- devtools.clearData();
1122
- sendJson(res, 200, { cleared: true });
1123
- return;
1124
- }
1125
- if (req.method === "POST" && url === "/v1/traces") {
1126
- try {
1127
- const payload = await readOtlpPayload(req, "traces");
1128
- const traces = parseOtlpTraces(payload);
1129
- devtools.addTraces(traces);
1130
- sendJson(res, 200, { acceptedTraces: traces.length });
1131
- } catch (e) {
1132
- sendOtlpError(res, req, e);
1133
- }
1134
- return;
1135
- }
1136
- if (req.method === "POST" && url === "/v1/logs") {
1137
- try {
1138
- const payload = await readOtlpPayload(req, "logs");
1139
- const logs = parseOtlpLogs(payload);
1140
- devtools.addLogs(logs);
1141
- sendJson(res, 200, { acceptedLogs: logs.length });
1142
- } catch (e) {
1143
- sendOtlpError(res, req, e);
1144
- }
1145
- return;
1146
- }
1147
- if (req.method === "POST" && url === "/v1/metrics") {
1148
- try {
1149
- const payload = await readOtlpPayload(req, "metrics");
1150
- const count = countOtlpMetrics(payload);
1151
- sendJson(res, 200, { acceptedMetrics: count });
1152
- } catch (e) {
1153
- sendOtlpError(res, req, e);
1154
- }
1155
- return;
1156
- }
1157
- sendJson(res, 404, { error: "Not found" });
1158
- });
1159
- }
1160
- var LOOPBACK = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1"]);
1161
- var DEFAULT_MAX_PORT_TRIES = 20;
1162
- function formatAddress(host, port) {
1163
- return host.includes(":") ? `[${host}]:${port}` : `${host}:${port}`;
1164
- }
1165
- function listenLoopbackDualStack(args) {
1166
- const { primary, port, host, attachSecondary, maxTries } = args;
1167
- const maxAttempts = Math.max(1, maxTries ?? DEFAULT_MAX_PORT_TRIES);
1168
- let sibling;
1169
- const ready = new Promise(
1170
- (resolve3, reject) => {
1171
- const addresses = [];
1172
- const warnings = [];
1173
- const primaryHost = host === "localhost" ? "127.0.0.1" : host;
1174
- let candidate = port;
1175
- let attempt = 0;
1176
- const bindFailed = (atPort, msg) => reject(
1177
- new Error(`could not bind ${formatAddress(primaryHost, atPort)}: ${msg}`)
1178
- );
1179
- const onError = (e) => {
1180
- if (e.code !== "EADDRINUSE") return bindFailed(candidate, e.message);
1181
- if (++attempt >= maxAttempts) {
1182
- reject(
1183
- new Error(
1184
- `could not bind ${formatAddress(primaryHost, port)}: ${maxAttempts} consecutive ports in use`
1185
- )
1186
- );
1187
- return;
1188
- }
1189
- candidate++;
1190
- listen();
1191
- };
1192
- const onListening = () => {
1193
- primary.removeListener("error", onError);
1194
- if (candidate !== port) {
1195
- warnings.push(`port ${port} was busy; using ${candidate} instead`);
1196
- }
1197
- const addr = primary.address();
1198
- const resolvedPort = addr && typeof addr === "object" ? addr.port : candidate;
1199
- addresses.push(formatAddress(primaryHost, resolvedPort));
1200
- if (!LOOPBACK.has(host)) {
1201
- resolve3({ addresses, port: resolvedPort, warnings });
1202
- return;
1203
- }
1204
- const siblingHost = primaryHost === "::1" ? "127.0.0.1" : "::1";
1205
- const s = http.createServer();
1206
- attachSecondary(s);
1207
- const onSiblingError = (se) => {
1208
- s.close();
1209
- warnings.push(
1210
- `could not also bind ${formatAddress(siblingHost, resolvedPort)} (${se.message}); clients using the ${siblingHost === "::1" ? "IPv6" : "IPv4"} form of "localhost" may not connect.`
1211
- );
1212
- resolve3({ addresses, port: resolvedPort, warnings });
1213
- };
1214
- s.once("error", onSiblingError);
1215
- s.listen(resolvedPort, siblingHost, () => {
1216
- s.off("error", onSiblingError);
1217
- sibling = s;
1218
- addresses.push(formatAddress(siblingHost, resolvedPort));
1219
- resolve3({ addresses, port: resolvedPort, warnings });
1220
- });
1221
- };
1222
- const listen = () => {
1223
- try {
1224
- primary.listen(candidate, primaryHost);
1225
- } catch (e) {
1226
- primary.removeListener("error", onError);
1227
- primary.removeListener("listening", onListening);
1228
- bindFailed(candidate, e.message);
1229
- }
1230
- };
1231
- primary.on("error", onError);
1232
- primary.once("listening", onListening);
1233
- listen();
1234
- }
1235
- );
1236
- return {
1237
- ready,
1238
- closeSibling: () => new Promise((res) => {
1239
- if (!sibling) return res();
1240
- sibling.close(() => res());
1241
- })
1242
- };
1243
- }
1244
-
1245
- // src/cli.ts
2
+ const require_http = require('./http-Yj6iSrMX.cjs');
3
+ const require_listen = require('./listen-BBsxO0wm.cjs');
4
+ let node_http = require("node:http");
5
+ let node_fs = require("node:fs");
6
+ let node_path = require("node:path");
7
+ let node_url = require("node:url");
8
+
9
+ //#region src/cli.ts
1246
10
  function printHelp() {
1247
- process.stdout.write(
1248
- `autotel-devtools - Standalone OTLP receiver with web devtools UI
1249
-
1250
- Usage: autotel-devtools [port] [options]
1251
-
1252
- Arguments:
1253
- port Port to listen on (shorthand for --port; must be a positive integer)
1254
-
1255
- Options:
1256
- -p, --port <port> Port to listen on (default: 4318, env: AUTOTEL_DEVTOOLS_PORT).
1257
- If the port is taken, the next free port is used and a warning is shown.
1258
- -H, --host <host> Host to bind to (default: 127.0.0.1, env: AUTOTEL_DEVTOOLS_HOST)
1259
- -t, --title <title> Dashboard title (env: AUTOTEL_DEVTOOLS_TITLE)
1260
- Env limits: AUTOTEL_MAX_TRACE_COUNT, AUTOTEL_MAX_LOG_COUNT, AUTOTEL_MAX_METRIC_COUNT
1261
- -h, --help Show this help message
1262
- -v, --version Show version number
1263
-
1264
- Endpoints:
1265
- GET / Web devtools UI (fullpage)
1266
- GET /widget.js Widget bundle (embed in your app)
1267
- POST /v1/traces Receive OTLP JSON trace data
1268
- GET /v1/traces Read back received traces (verify ingestion in tests)
1269
- DELETE /v1/traces Clear captured telemetry (test reset)
1270
- POST /v1/logs Receive OTLP JSON log data
1271
- POST /v1/metrics Receive OTLP JSON metric data
1272
- WS /ws WebSocket stream for real-time updates
1273
- GET /healthz Health check
1274
-
1275
- Examples:
1276
- npx autotel-devtools
1277
- npx autotel-devtools 4319
1278
- npx autotel-devtools -p 4319 -H 0.0.0.0
1279
-
1280
- Then point your app:
1281
- OTEL_EXPORTER_OTLP_PROTOCOL=http/json OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 node app.js
1282
-
1283
- View in browser:
1284
- http://localhost:4318
1285
-
1286
- Or embed widget in your app:
1287
- <script src="http://localhost:4318/widget.js"></script>
1288
-
1289
- `
1290
- );
11
+ process.stdout.write("autotel-devtools - Standalone OTLP receiver with web devtools UI\n\nUsage: autotel-devtools [port] [options]\n\nArguments:\n port Port to listen on (shorthand for --port; must be a positive integer)\n\nOptions:\n -p, --port <port> Port to listen on (default: 4318, env: AUTOTEL_DEVTOOLS_PORT).\n If the port is taken, the next free port is used and a warning is shown.\n -H, --host <host> Host to bind to (default: 127.0.0.1, env: AUTOTEL_DEVTOOLS_HOST)\n -t, --title <title> Dashboard title (env: AUTOTEL_DEVTOOLS_TITLE)\n Env limits: AUTOTEL_MAX_TRACE_COUNT, AUTOTEL_MAX_LOG_COUNT, AUTOTEL_MAX_METRIC_COUNT\n -h, --help Show this help message\n -v, --version Show version number\n\nEndpoints:\n GET / Web devtools UI (fullpage)\n GET /widget.js Widget bundle (embed in your app)\n POST /v1/traces Receive OTLP JSON trace data\n GET /v1/traces Read back received traces (verify ingestion in tests)\n DELETE /v1/traces Clear captured telemetry (test reset)\n POST /v1/logs Receive OTLP JSON log data\n POST /v1/metrics Receive OTLP JSON metric data\n WS /ws WebSocket stream for real-time updates\n GET /healthz Health check\n\nExamples:\n npx autotel-devtools\n npx autotel-devtools 4319\n npx autotel-devtools -p 4319 -H 0.0.0.0\n\nThen point your app:\n OTEL_EXPORTER_OTLP_PROTOCOL=http/json OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 node app.js\n\nView in browser:\n http://localhost:4318\n\nOr embed widget in your app:\n <script src=\"http://localhost:4318/widget.js\"><\/script>\n\n");
1291
12
  }
1292
13
  function printVersion() {
1293
- try {
1294
- 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))));
1295
- const pkgPath = path.resolve(dir, "..", "package.json");
1296
- const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
1297
- process.stdout.write(`${pkg.version}
1298
- `);
1299
- } catch {
1300
- process.stdout.write("unknown\n");
1301
- }
14
+ try {
15
+ const pkgPath = (0, node_path.resolve)((0, node_path.dirname)((0, node_url.fileURLToPath)(require("url").pathToFileURL(__filename).href)), "..", "package.json");
16
+ const pkg = JSON.parse((0, node_fs.readFileSync)(pkgPath, "utf8"));
17
+ process.stdout.write(`${pkg.version}\n`);
18
+ } catch {
19
+ process.stdout.write("unknown\n");
20
+ }
1302
21
  }
1303
22
  function parseArgs(argv) {
1304
- const options = {
1305
- port: parsePort(process.env.AUTOTEL_DEVTOOLS_PORT || "4318"),
1306
- host: process.env.AUTOTEL_DEVTOOLS_HOST || "127.0.0.1",
1307
- title: process.env.AUTOTEL_DEVTOOLS_TITLE
1308
- };
1309
- let portWasExplicit = false;
1310
- let positionalPortConsumed = false;
1311
- for (let i = 0; i < argv.length; i++) {
1312
- const arg = argv[i];
1313
- const next = argv[i + 1];
1314
- if (arg === "--help" || arg === "-h") {
1315
- printHelp();
1316
- return null;
1317
- }
1318
- if (arg === "--version" || arg === "-v") {
1319
- printVersion();
1320
- return null;
1321
- }
1322
- if ((arg === "--port" || arg === "-p") && next) {
1323
- options.port = parsePort(next);
1324
- portWasExplicit = true;
1325
- i++;
1326
- continue;
1327
- }
1328
- if ((arg === "--host" || arg === "-H") && next) {
1329
- options.host = next;
1330
- i++;
1331
- continue;
1332
- }
1333
- if ((arg === "--title" || arg === "-t") && next) {
1334
- options.title = next;
1335
- i++;
1336
- continue;
1337
- }
1338
- if (/^\d+$/.test(arg) && !positionalPortConsumed) {
1339
- if (!portWasExplicit) options.port = parsePort(arg);
1340
- positionalPortConsumed = true;
1341
- continue;
1342
- }
1343
- }
1344
- return options;
23
+ const options = {
24
+ port: parsePort(process.env.AUTOTEL_DEVTOOLS_PORT || "4318"),
25
+ host: process.env.AUTOTEL_DEVTOOLS_HOST || "127.0.0.1",
26
+ title: process.env.AUTOTEL_DEVTOOLS_TITLE
27
+ };
28
+ let portWasExplicit = false;
29
+ let positionalPortConsumed = false;
30
+ for (let i = 0; i < argv.length; i++) {
31
+ const arg = argv[i];
32
+ const next = argv[i + 1];
33
+ if (arg === "--help" || arg === "-h") {
34
+ printHelp();
35
+ return null;
36
+ }
37
+ if (arg === "--version" || arg === "-v") {
38
+ printVersion();
39
+ return null;
40
+ }
41
+ if ((arg === "--port" || arg === "-p") && next) {
42
+ options.port = parsePort(next);
43
+ portWasExplicit = true;
44
+ i++;
45
+ continue;
46
+ }
47
+ if ((arg === "--host" || arg === "-H") && next) {
48
+ options.host = next;
49
+ i++;
50
+ continue;
51
+ }
52
+ if ((arg === "--title" || arg === "-t") && next) {
53
+ options.title = next;
54
+ i++;
55
+ continue;
56
+ }
57
+ if (/^\d+$/.test(arg) && !positionalPortConsumed) {
58
+ if (!portWasExplicit) options.port = parsePort(arg);
59
+ positionalPortConsumed = true;
60
+ continue;
61
+ }
62
+ }
63
+ return options;
1345
64
  }
1346
65
  function parsePort(value) {
1347
- const n = Number(value);
1348
- if (!Number.isInteger(n) || n < 0 || n > 65535) {
1349
- process.stderr.write(`[autotel-devtools] invalid port: ${value}
1350
- `);
1351
- process.exit(2);
1352
- }
1353
- return n;
66
+ const n = Number(value);
67
+ if (!Number.isInteger(n) || n < 0 || n > 65535) {
68
+ process.stderr.write(`[autotel-devtools] invalid port: ${value}\n`);
69
+ process.exit(2);
70
+ }
71
+ return n;
1354
72
  }
1355
73
  async function main() {
1356
- const options = parseArgs(process.argv.slice(2));
1357
- if (!options) {
1358
- process.exit(0);
1359
- }
1360
- const httpServer = http.createServer();
1361
- const loopbackOnly = hostHeaderIsLoopback(options.host);
1362
- const wsServer = new DevtoolsServer({ server: httpServer, host: options.host, verbose: true });
1363
- attachDevtoolsRoutes(httpServer, wsServer, { loopbackOnly });
1364
- const listeners = listenLoopbackDualStack({
1365
- primary: httpServer,
1366
- port: options.port,
1367
- host: options.host,
1368
- attachSecondary: (s) => attachDevtoolsRoutes(s, wsServer, { loopbackOnly })
1369
- });
1370
- const { addresses, warnings, port: boundPort } = await listeners.ready;
1371
- if (boundPort !== options.port) {
1372
- const holder = await probePortHolder(options.host, options.port);
1373
- if (holder === "autotel-devtools") {
1374
- warnings.push(
1375
- `another autotel-devtools is already running on port ${options.port}; this instance is on ${boundPort}. Use the existing one, or stop it and restart here.`
1376
- );
1377
- } else {
1378
- warnings.push(
1379
- `port ${options.port} is held by another process that is NOT autotel-devtools. Anything exporting OTLP to :${options.port} is reaching that process, not this devtools. Point your exporter at :${boundPort}, or free :${options.port} and restart.`
1380
- );
1381
- }
1382
- }
1383
- const uiBase = `http://${options.host === "localhost" ? "127.0.0.1" : options.host}:${boundPort}`;
1384
- const title = options.title || "autotel-devtools";
1385
- process.stdout.write(`
1386
- ${title}
1387
-
1388
- `);
1389
- process.stdout.write(` Listening: ${addresses.join(" + ")}
1390
- `);
1391
- process.stdout.write(` UI: ${uiBase} (open in a browser)
1392
- `);
1393
- process.stdout.write(` OTLP: ${uiBase}/v1/traces
1394
- `);
1395
- process.stdout.write(` WebSocket: ${uiBase.replace("http", "ws")}/ws
1396
-
1397
- `);
1398
- process.stdout.write(
1399
- ` Embed in your app \u2014 paste into your HTML; a floating panel appears automatically:
1400
- `
1401
- );
1402
- process.stdout.write(` <script src="${uiBase}/widget.js"></script>
1403
-
1404
- `);
1405
- process.stdout.write(
1406
- ` full screen instead: <script src="${uiBase}/widget.js?mode=fullpage"></script>
1407
- `
1408
- );
1409
- process.stdout.write(
1410
- ` choose where it goes: add <autotel-devtools></autotel-devtools> to your markup
1411
-
1412
- `
1413
- );
1414
- process.stdout.write(` Or point any OTLP exporter at this receiver:
1415
- `);
1416
- process.stdout.write(` OTEL_EXPORTER_OTLP_PROTOCOL=http/json
1417
- `);
1418
- process.stdout.write(` OTEL_EXPORTER_OTLP_ENDPOINT=${uiBase}
1419
-
1420
- `);
1421
- process.stdout.write(` Verify ingestion: curl -s ${uiBase}/v1/traces
1422
-
1423
- `);
1424
- for (const w of warnings) {
1425
- process.stdout.write(` \u26A0 ${w}
1426
- `);
1427
- }
1428
- if (warnings.length > 0) process.stdout.write("\n");
1429
- const shutdown = () => {
1430
- Promise.all([wsServer.close(), listeners.closeSibling()]).then(
1431
- () => process.exit(0)
1432
- );
1433
- };
1434
- process.on("SIGINT", shutdown);
1435
- process.on("SIGTERM", shutdown);
74
+ const options = parseArgs(process.argv.slice(2));
75
+ if (!options) process.exit(0);
76
+ const httpServer = (0, node_http.createServer)();
77
+ const loopbackOnly = require_http.hostHeaderIsLoopback(options.host);
78
+ const wsServer = new require_http.DevtoolsServer({
79
+ server: httpServer,
80
+ host: options.host,
81
+ verbose: true
82
+ });
83
+ require_http.attachDevtoolsRoutes(httpServer, wsServer, { loopbackOnly });
84
+ const listeners = require_listen.listenLoopbackDualStack({
85
+ primary: httpServer,
86
+ port: options.port,
87
+ host: options.host,
88
+ attachSecondary: (s) => require_http.attachDevtoolsRoutes(s, wsServer, { loopbackOnly })
89
+ });
90
+ const { addresses, warnings, port: boundPort } = await listeners.ready;
91
+ if (boundPort !== options.port) if (await require_http.probePortHolder(options.host, options.port) === "autotel-devtools") warnings.push(`another autotel-devtools is already running on port ${options.port}; this instance is on ${boundPort}. Use the existing one, or stop it and restart here.`);
92
+ else warnings.push(`port ${options.port} is held by another process that is NOT autotel-devtools. Anything exporting OTLP to :${options.port} is reaching that process, not this devtools. Point your exporter at :${boundPort}, or free :${options.port} and restart.`);
93
+ const uiBase = `http://${options.host === "localhost" ? "127.0.0.1" : options.host}:${boundPort}`;
94
+ const title = options.title || "autotel-devtools";
95
+ process.stdout.write(`\n ${title}\n\n`);
96
+ process.stdout.write(` Listening: ${addresses.join(" + ")}\n`);
97
+ process.stdout.write(` UI: ${uiBase} (open in a browser)\n`);
98
+ process.stdout.write(` OTLP: ${uiBase}/v1/traces\n`);
99
+ process.stdout.write(` WebSocket: ${uiBase.replace("http", "ws")}/ws\n\n`);
100
+ process.stdout.write(` Embed in your app — paste into your HTML; a floating panel appears automatically:\n`);
101
+ process.stdout.write(` <script src="${uiBase}/widget.js"><\/script>\n\n`);
102
+ process.stdout.write(` full screen instead: <script src="${uiBase}/widget.js?mode=fullpage"><\/script>\n`);
103
+ process.stdout.write(` choose where it goes: add <autotel-devtools></autotel-devtools> to your markup\n\n`);
104
+ process.stdout.write(` Or point any OTLP exporter at this receiver:\n`);
105
+ process.stdout.write(` OTEL_EXPORTER_OTLP_PROTOCOL=http/json\n`);
106
+ process.stdout.write(` OTEL_EXPORTER_OTLP_ENDPOINT=${uiBase}\n\n`);
107
+ process.stdout.write(` Verify ingestion: curl -s ${uiBase}/v1/traces\n\n`);
108
+ for (const w of warnings) process.stdout.write(` ⚠ ${w}\n`);
109
+ if (warnings.length > 0) process.stdout.write("\n");
110
+ const shutdown = () => {
111
+ Promise.all([wsServer.close(), listeners.closeSibling()]).then(() => process.exit(0));
112
+ };
113
+ process.on("SIGINT", shutdown);
114
+ process.on("SIGTERM", shutdown);
1436
115
  }
1437
116
  main().catch((error) => {
1438
- process.stderr.write(`[autotel-devtools] failed to start: ${error instanceof Error ? error.message : String(error)}
1439
- `);
1440
- process.exit(1);
117
+ process.stderr.write(`[autotel-devtools] failed to start: ${error instanceof Error ? error.message : String(error)}\n`);
118
+ process.exit(1);
1441
119
  });
1442
- //# sourceMappingURL=cli.cjs.map
120
+
121
+ //#endregion
1443
122
  //# sourceMappingURL=cli.cjs.map