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